Merge remote branch 'refs/remotes/svn/trunk' into svn
[bitcoinplatinum.git] / main.cpp
blob2d950eefb5a6e03de041c47237c11f4aa016dcde
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #include "headers.h"
6 #include "cryptopp/sha.h"
13 // Global state
16 CCriticalSection cs_main;
18 map<uint256, CTransaction> mapTransactions;
19 CCriticalSection cs_mapTransactions;
20 unsigned int nTransactionsUpdated = 0;
21 map<COutPoint, CInPoint> mapNextTx;
23 map<uint256, CBlockIndex*> mapBlockIndex;
24 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
25 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
26 CBlockIndex* pindexGenesisBlock = NULL;
27 int nBestHeight = -1;
28 CBigNum bnBestChainWork = 0;
29 CBigNum bnBestInvalidWork = 0;
30 uint256 hashBestChain = 0;
31 CBlockIndex* pindexBest = NULL;
32 int64 nTimeBestReceived = 0;
34 map<uint256, CBlock*> mapOrphanBlocks;
35 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
37 map<uint256, CDataStream*> mapOrphanTransactions;
38 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
40 map<uint256, CWalletTx> mapWallet;
41 vector<uint256> vWalletUpdated;
42 CCriticalSection cs_mapWallet;
44 map<vector<unsigned char>, CPrivKey> mapKeys;
45 map<uint160, vector<unsigned char> > mapPubKeys;
46 CCriticalSection cs_mapKeys;
47 CKey keyUser;
49 map<uint256, int> mapRequestCount;
50 CCriticalSection cs_mapRequestCount;
52 map<string, string> mapAddressBook;
53 CCriticalSection cs_mapAddressBook;
55 vector<unsigned char> vchDefaultKey;
57 double dHashesPerSec;
58 int64 nHPSTimerStart;
60 // Settings
61 int fGenerateBitcoins = false;
62 int64 nTransactionFee = 0;
63 CAddress addrIncoming;
64 int fLimitProcessors = false;
65 int nLimitProcessors = 1;
66 int fMinimizeToTray = true;
67 int fMinimizeOnClose = true;
74 //////////////////////////////////////////////////////////////////////////////
76 // mapKeys
79 bool AddKey(const CKey& key)
81 CRITICAL_BLOCK(cs_mapKeys)
83 mapKeys[key.GetPubKey()] = key.GetPrivKey();
84 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
86 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
89 vector<unsigned char> GenerateNewKey()
91 RandAddSeedPerfmon();
92 CKey key;
93 key.MakeNewKey();
94 if (!AddKey(key))
95 throw runtime_error("GenerateNewKey() : AddKey failed");
96 return key.GetPubKey();
102 //////////////////////////////////////////////////////////////////////////////
104 // mapWallet
107 bool AddToWallet(const CWalletTx& wtxIn)
109 uint256 hash = wtxIn.GetHash();
110 CRITICAL_BLOCK(cs_mapWallet)
112 // Inserts only if not already there, returns tx inserted or tx found
113 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
114 CWalletTx& wtx = (*ret.first).second;
115 bool fInsertedNew = ret.second;
116 if (fInsertedNew)
117 wtx.nTimeReceived = GetAdjustedTime();
119 bool fUpdated = false;
120 if (!fInsertedNew)
122 // Merge
123 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
125 wtx.hashBlock = wtxIn.hashBlock;
126 fUpdated = true;
128 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
130 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
131 wtx.nIndex = wtxIn.nIndex;
132 fUpdated = true;
134 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
136 wtx.fFromMe = wtxIn.fFromMe;
137 fUpdated = true;
139 if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
141 wtx.fSpent = wtxIn.fSpent;
142 fUpdated = true;
146 //// debug print
147 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
149 // Write to disk
150 if (fInsertedNew || fUpdated)
151 if (!wtx.WriteToDisk())
152 return false;
154 // If default receiving address gets used, replace it with a new one
155 CScript scriptDefaultKey;
156 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
157 foreach(const CTxOut& txout, wtx.vout)
159 if (txout.scriptPubKey == scriptDefaultKey)
161 CWalletDB walletdb;
162 vchDefaultKey = walletdb.GetKeyFromKeyPool();
163 walletdb.WriteDefaultKey(vchDefaultKey);
164 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
168 // Notify UI
169 vWalletUpdated.push_back(hash);
172 // Refresh UI
173 MainFrameRepaint();
174 return true;
177 bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
179 if (tx.IsMine() || mapWallet.count(tx.GetHash()))
181 CWalletTx wtx(tx);
182 // Get merkle branch if transaction was found in a block
183 if (pblock)
184 wtx.SetMerkleBranch(pblock);
185 return AddToWallet(wtx);
187 return true;
190 bool EraseFromWallet(uint256 hash)
192 CRITICAL_BLOCK(cs_mapWallet)
194 if (mapWallet.erase(hash))
195 CWalletDB().EraseTx(hash);
197 return true;
200 void WalletUpdateSpent(const COutPoint& prevout)
202 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
203 // Update the wallet spent flag if it doesn't know due to wallet.dat being
204 // restored from backup or the user making copies of wallet.dat.
205 CRITICAL_BLOCK(cs_mapWallet)
207 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
208 if (mi != mapWallet.end())
210 CWalletTx& wtx = (*mi).second;
211 if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
213 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
214 wtx.fSpent = true;
215 wtx.WriteToDisk();
216 vWalletUpdated.push_back(prevout.hash);
229 //////////////////////////////////////////////////////////////////////////////
231 // mapOrphanTransactions
234 void AddOrphanTx(const CDataStream& vMsg)
236 CTransaction tx;
237 CDataStream(vMsg) >> tx;
238 uint256 hash = tx.GetHash();
239 if (mapOrphanTransactions.count(hash))
240 return;
241 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
242 foreach(const CTxIn& txin, tx.vin)
243 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
246 void EraseOrphanTx(uint256 hash)
248 if (!mapOrphanTransactions.count(hash))
249 return;
250 const CDataStream* pvMsg = mapOrphanTransactions[hash];
251 CTransaction tx;
252 CDataStream(*pvMsg) >> tx;
253 foreach(const CTxIn& txin, tx.vin)
255 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
256 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
258 if ((*mi).second == pvMsg)
259 mapOrphanTransactionsByPrev.erase(mi++);
260 else
261 mi++;
264 delete pvMsg;
265 mapOrphanTransactions.erase(hash);
275 //////////////////////////////////////////////////////////////////////////////
277 // CTransaction
280 bool CTxIn::IsMine() const
282 CRITICAL_BLOCK(cs_mapWallet)
284 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
285 if (mi != mapWallet.end())
287 const CWalletTx& prev = (*mi).second;
288 if (prevout.n < prev.vout.size())
289 if (prev.vout[prevout.n].IsMine())
290 return true;
293 return false;
296 int64 CTxIn::GetDebit() const
298 CRITICAL_BLOCK(cs_mapWallet)
300 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
301 if (mi != mapWallet.end())
303 const CWalletTx& prev = (*mi).second;
304 if (prevout.n < prev.vout.size())
305 if (prev.vout[prevout.n].IsMine())
306 return prev.vout[prevout.n].nValue;
309 return 0;
312 int64 CWalletTx::GetTxTime() const
314 if (!fTimeReceivedIsTxTime && hashBlock != 0)
316 // If we did not receive the transaction directly, we rely on the block's
317 // time to figure out when it happened. We use the median over a range
318 // of blocks to try to filter out inaccurate block times.
319 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
320 if (mi != mapBlockIndex.end())
322 CBlockIndex* pindex = (*mi).second;
323 if (pindex)
324 return pindex->GetMedianTime();
327 return nTimeReceived;
330 int CWalletTx::GetRequestCount() const
332 // Returns -1 if it wasn't being tracked
333 int nRequests = -1;
334 CRITICAL_BLOCK(cs_mapRequestCount)
336 if (IsCoinBase())
338 // Generated block
339 if (hashBlock != 0)
341 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
342 if (mi != mapRequestCount.end())
343 nRequests = (*mi).second;
346 else
348 // Did anyone request this transaction?
349 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
350 if (mi != mapRequestCount.end())
352 nRequests = (*mi).second;
354 // How about the block it's in?
355 if (nRequests == 0 && hashBlock != 0)
357 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
358 if (mi != mapRequestCount.end())
359 nRequests = (*mi).second;
360 else
361 nRequests = 1; // If it's in someone else's block it must have got out
366 return nRequests;
372 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
374 if (fClient)
376 if (hashBlock == 0)
377 return 0;
379 else
381 CBlock blockTmp;
382 if (pblock == NULL)
384 // Load the block this tx is in
385 CTxIndex txindex;
386 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
387 return 0;
388 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
389 return 0;
390 pblock = &blockTmp;
393 // Update the tx's hashBlock
394 hashBlock = pblock->GetHash();
396 // Locate the transaction
397 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
398 if (pblock->vtx[nIndex] == *(CTransaction*)this)
399 break;
400 if (nIndex == pblock->vtx.size())
402 vMerkleBranch.clear();
403 nIndex = -1;
404 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
405 return 0;
408 // Fill in merkle branch
409 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
412 // Is the tx in a block that's in the main chain
413 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
414 if (mi == mapBlockIndex.end())
415 return 0;
416 CBlockIndex* pindex = (*mi).second;
417 if (!pindex || !pindex->IsInMainChain())
418 return 0;
420 return pindexBest->nHeight - pindex->nHeight + 1;
425 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
427 vtxPrev.clear();
429 const int COPY_DEPTH = 3;
430 if (SetMerkleBranch() < COPY_DEPTH)
432 vector<uint256> vWorkQueue;
433 foreach(const CTxIn& txin, vin)
434 vWorkQueue.push_back(txin.prevout.hash);
436 // This critsect is OK because txdb is already open
437 CRITICAL_BLOCK(cs_mapWallet)
439 map<uint256, const CMerkleTx*> mapWalletPrev;
440 set<uint256> setAlreadyDone;
441 for (int i = 0; i < vWorkQueue.size(); i++)
443 uint256 hash = vWorkQueue[i];
444 if (setAlreadyDone.count(hash))
445 continue;
446 setAlreadyDone.insert(hash);
448 CMerkleTx tx;
449 if (mapWallet.count(hash))
451 tx = mapWallet[hash];
452 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
453 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
455 else if (mapWalletPrev.count(hash))
457 tx = *mapWalletPrev[hash];
459 else if (!fClient && txdb.ReadDiskTx(hash, tx))
463 else
465 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
466 continue;
469 int nDepth = tx.SetMerkleBranch();
470 vtxPrev.push_back(tx);
472 if (nDepth < COPY_DEPTH)
473 foreach(const CTxIn& txin, tx.vin)
474 vWorkQueue.push_back(txin.prevout.hash);
479 reverse(vtxPrev.begin(), vtxPrev.end());
492 bool CTransaction::CheckTransaction() const
494 // Basic checks that don't depend on any context
495 if (vin.empty() || vout.empty())
496 return error("CTransaction::CheckTransaction() : vin or vout empty");
498 // Size limits
499 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
500 return error("CTransaction::CheckTransaction() : size limits failed");
502 // Check for negative or overflow output values
503 int64 nValueOut = 0;
504 foreach(const CTxOut& txout, vout)
506 if (txout.nValue < 0)
507 return error("CTransaction::CheckTransaction() : txout.nValue negative");
508 if (txout.nValue > MAX_MONEY)
509 return error("CTransaction::CheckTransaction() : txout.nValue too high");
510 nValueOut += txout.nValue;
511 if (!MoneyRange(nValueOut))
512 return error("CTransaction::CheckTransaction() : txout total out of range");
515 if (IsCoinBase())
517 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
518 return error("CTransaction::CheckTransaction() : coinbase script size");
520 else
522 foreach(const CTxIn& txin, vin)
523 if (txin.prevout.IsNull())
524 return error("CTransaction::CheckTransaction() : prevout is null");
527 return true;
530 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
532 if (pfMissingInputs)
533 *pfMissingInputs = false;
535 if (!CheckTransaction())
536 return error("AcceptToMemoryPool() : CheckTransaction failed");
538 // Coinbase is only valid in a block, not as a loose transaction
539 if (IsCoinBase())
540 return error("AcceptToMemoryPool() : coinbase as individual tx");
542 // To help v0.1.5 clients who would see it as a negative number
543 if ((int64)nLockTime > INT_MAX)
544 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
546 // Rather not work on nonstandard transactions
547 if (GetSigOpCount() > 2 || ::GetSerializeSize(*this, SER_NETWORK) < 100)
548 return error("AcceptToMemoryPool() : nonstandard transaction");
550 // Do we already have it?
551 uint256 hash = GetHash();
552 CRITICAL_BLOCK(cs_mapTransactions)
553 if (mapTransactions.count(hash))
554 return false;
555 if (fCheckInputs)
556 if (txdb.ContainsTx(hash))
557 return false;
559 // Check for conflicts with in-memory transactions
560 CTransaction* ptxOld = NULL;
561 for (int i = 0; i < vin.size(); i++)
563 COutPoint outpoint = vin[i].prevout;
564 if (mapNextTx.count(outpoint))
566 // Disable replacement feature for now
567 return false;
569 // Allow replacing with a newer version of the same transaction
570 if (i != 0)
571 return false;
572 ptxOld = mapNextTx[outpoint].ptx;
573 if (!IsNewerThan(*ptxOld))
574 return false;
575 for (int i = 0; i < vin.size(); i++)
577 COutPoint outpoint = vin[i].prevout;
578 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
579 return false;
581 break;
585 // Check against previous transactions
586 map<uint256, CTxIndex> mapUnused;
587 int64 nFees = 0;
588 if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
590 if (pfMissingInputs)
591 *pfMissingInputs = true;
592 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
595 // Store transaction in memory
596 CRITICAL_BLOCK(cs_mapTransactions)
598 if (ptxOld)
600 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
601 ptxOld->RemoveFromMemoryPool();
603 AddToMemoryPoolUnchecked();
606 ///// are we sure this is ok when loading transactions or restoring block txes
607 // If updated, erase old tx from wallet
608 if (ptxOld)
609 EraseFromWallet(ptxOld->GetHash());
611 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
612 return true;
616 bool CTransaction::AddToMemoryPoolUnchecked()
618 // Add to memory pool without checking anything. Don't call this directly,
619 // call AcceptToMemoryPool to properly check the transaction first.
620 CRITICAL_BLOCK(cs_mapTransactions)
622 uint256 hash = GetHash();
623 mapTransactions[hash] = *this;
624 for (int i = 0; i < vin.size(); i++)
625 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
626 nTransactionsUpdated++;
628 return true;
632 bool CTransaction::RemoveFromMemoryPool()
634 // Remove transaction from memory pool
635 CRITICAL_BLOCK(cs_mapTransactions)
637 foreach(const CTxIn& txin, vin)
638 mapNextTx.erase(txin.prevout);
639 mapTransactions.erase(GetHash());
640 nTransactionsUpdated++;
642 return true;
650 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
652 if (hashBlock == 0 || nIndex == -1)
653 return 0;
655 // Find the block it claims to be in
656 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
657 if (mi == mapBlockIndex.end())
658 return 0;
659 CBlockIndex* pindex = (*mi).second;
660 if (!pindex || !pindex->IsInMainChain())
661 return 0;
663 // Make sure the merkle branch connects to this block
664 if (!fMerkleVerified)
666 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
667 return 0;
668 fMerkleVerified = true;
671 nHeightRet = pindex->nHeight;
672 return pindexBest->nHeight - pindex->nHeight + 1;
676 int CMerkleTx::GetBlocksToMaturity() const
678 if (!IsCoinBase())
679 return 0;
680 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
684 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
686 if (fClient)
688 if (!IsInMainChain() && !ClientConnectInputs())
689 return false;
690 return CTransaction::AcceptToMemoryPool(txdb, false);
692 else
694 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
700 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
702 CRITICAL_BLOCK(cs_mapTransactions)
704 // Add previous supporting transactions first
705 foreach(CMerkleTx& tx, vtxPrev)
707 if (!tx.IsCoinBase())
709 uint256 hash = tx.GetHash();
710 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
711 tx.AcceptToMemoryPool(txdb, fCheckInputs);
714 return AcceptToMemoryPool(txdb, fCheckInputs);
716 return false;
719 void ReacceptWalletTransactions()
721 CTxDB txdb("r");
722 CRITICAL_BLOCK(cs_mapWallet)
724 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
726 CWalletTx& wtx = item.second;
727 if (wtx.fSpent && wtx.IsCoinBase())
728 continue;
730 CTxIndex txindex;
731 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
733 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
734 if (!wtx.fSpent)
736 if (txindex.vSpent.size() != wtx.vout.size())
738 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
739 continue;
741 for (int i = 0; i < txindex.vSpent.size(); i++)
743 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
745 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
746 wtx.fSpent = true;
747 wtx.WriteToDisk();
748 break;
753 else
755 // Reaccept any txes of ours that aren't already in a block
756 if (!wtx.IsCoinBase())
757 wtx.AcceptWalletTransaction(txdb, false);
764 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
766 foreach(const CMerkleTx& tx, vtxPrev)
768 if (!tx.IsCoinBase())
770 uint256 hash = tx.GetHash();
771 if (!txdb.ContainsTx(hash))
772 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
775 if (!IsCoinBase())
777 uint256 hash = GetHash();
778 if (!txdb.ContainsTx(hash))
780 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
781 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
786 void ResendWalletTransactions()
788 // Do this infrequently and randomly to avoid giving away
789 // that these are our transactions.
790 static int64 nNextTime;
791 if (GetTime() < nNextTime)
792 return;
793 bool fFirst = (nNextTime == 0);
794 nNextTime = GetTime() + GetRand(30 * 60);
795 if (fFirst)
796 return;
798 // Only do it if there's been a new block since last time
799 static int64 nLastTime;
800 if (nTimeBestReceived < nLastTime)
801 return;
802 nLastTime = GetTime();
804 // Rebroadcast any of our txes that aren't in a block yet
805 printf("ResendWalletTransactions()\n");
806 CTxDB txdb("r");
807 CRITICAL_BLOCK(cs_mapWallet)
809 // Sort them in chronological order
810 multimap<unsigned int, CWalletTx*> mapSorted;
811 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
813 CWalletTx& wtx = item.second;
814 // Don't rebroadcast until it's had plenty of time that
815 // it should have gotten in already by now.
816 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
817 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
819 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
821 CWalletTx& wtx = *item.second;
822 wtx.RelayWalletTransaction(txdb);
836 //////////////////////////////////////////////////////////////////////////////
838 // CBlock and CBlockIndex
841 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
843 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
844 return false;
845 if (GetHash() != pindex->GetBlockHash())
846 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
847 return true;
850 uint256 GetOrphanRoot(const CBlock* pblock)
852 // Work back to the first block in the orphan chain
853 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
854 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
855 return pblock->GetHash();
858 int64 GetBlockValue(int nHeight, int64 nFees)
860 int64 nSubsidy = 50 * COIN;
862 // Subsidy is cut in half every 4 years
863 nSubsidy >>= (nHeight / 210000);
865 return nSubsidy + nFees;
868 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
870 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
871 const int64 nTargetSpacing = 10 * 60;
872 const int64 nInterval = nTargetTimespan / nTargetSpacing;
874 // Genesis block
875 if (pindexLast == NULL)
876 return bnProofOfWorkLimit.GetCompact();
878 // Only change once per interval
879 if ((pindexLast->nHeight+1) % nInterval != 0)
880 return pindexLast->nBits;
882 // Go back by what we want to be 14 days worth of blocks
883 const CBlockIndex* pindexFirst = pindexLast;
884 for (int i = 0; pindexFirst && i < nInterval-1; i++)
885 pindexFirst = pindexFirst->pprev;
886 assert(pindexFirst);
888 // Limit adjustment step
889 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
890 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
891 if (nActualTimespan < nTargetTimespan/4)
892 nActualTimespan = nTargetTimespan/4;
893 if (nActualTimespan > nTargetTimespan*4)
894 nActualTimespan = nTargetTimespan*4;
896 // Retarget
897 CBigNum bnNew;
898 bnNew.SetCompact(pindexLast->nBits);
899 bnNew *= nActualTimespan;
900 bnNew /= nTargetTimespan;
902 if (bnNew > bnProofOfWorkLimit)
903 bnNew = bnProofOfWorkLimit;
905 /// debug print
906 printf("GetNextWorkRequired RETARGET\n");
907 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
908 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
909 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
911 return bnNew.GetCompact();
914 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
916 CBigNum bnTarget;
917 bnTarget.SetCompact(nBits);
919 // Check range
920 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
921 return error("CheckProofOfWork() : nBits below minimum work");
923 // Check proof of work matches claimed amount
924 if (hash > bnTarget.getuint256())
925 return error("CheckProofOfWork() : hash doesn't match nBits");
927 return true;
930 bool IsInitialBlockDownload()
932 if (pindexBest == NULL)
933 return true;
934 static int64 nLastUpdate;
935 static CBlockIndex* pindexLastBest;
936 if (pindexBest != pindexLastBest)
938 pindexLastBest = pindexBest;
939 nLastUpdate = GetTime();
941 return (GetTime() - nLastUpdate < 10 &&
942 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
945 void InvalidChainFound(CBlockIndex* pindexNew)
947 if (pindexNew->bnChainWork > bnBestInvalidWork)
949 bnBestInvalidWork = pindexNew->bnChainWork;
950 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
951 MainFrameRepaint();
953 printf("InvalidChainFound: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
954 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
955 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
956 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
969 bool CTransaction::DisconnectInputs(CTxDB& txdb)
971 // Relinquish previous transactions' spent pointers
972 if (!IsCoinBase())
974 foreach(const CTxIn& txin, vin)
976 COutPoint prevout = txin.prevout;
978 // Get prev txindex from disk
979 CTxIndex txindex;
980 if (!txdb.ReadTxIndex(prevout.hash, txindex))
981 return error("DisconnectInputs() : ReadTxIndex failed");
983 if (prevout.n >= txindex.vSpent.size())
984 return error("DisconnectInputs() : prevout.n out of range");
986 // Mark outpoint as not spent
987 txindex.vSpent[prevout.n].SetNull();
989 // Write back
990 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
991 return error("DisconnectInputs() : UpdateTxIndex failed");
995 // Remove transaction from index
996 if (!txdb.EraseTxIndex(*this))
997 return error("DisconnectInputs() : EraseTxPos failed");
999 return true;
1003 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1004 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1006 // Take over previous transactions' spent pointers
1007 if (!IsCoinBase())
1009 int64 nValueIn = 0;
1010 for (int i = 0; i < vin.size(); i++)
1012 COutPoint prevout = vin[i].prevout;
1014 // Read txindex
1015 CTxIndex txindex;
1016 bool fFound = true;
1017 if (fMiner && mapTestPool.count(prevout.hash))
1019 // Get txindex from current proposed changes
1020 txindex = mapTestPool[prevout.hash];
1022 else
1024 // Read txindex from txdb
1025 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1027 if (!fFound && (fBlock || fMiner))
1028 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1030 // Read txPrev
1031 CTransaction txPrev;
1032 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1034 // Get prev tx from single transactions in memory
1035 CRITICAL_BLOCK(cs_mapTransactions)
1037 if (!mapTransactions.count(prevout.hash))
1038 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1039 txPrev = mapTransactions[prevout.hash];
1041 if (!fFound)
1042 txindex.vSpent.resize(txPrev.vout.size());
1044 else
1046 // Get prev tx from disk
1047 if (!txPrev.ReadFromDisk(txindex.pos))
1048 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1051 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1052 return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str());
1054 // If prev is coinbase, check that it's matured
1055 if (txPrev.IsCoinBase())
1056 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1057 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1058 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1060 // Verify signature
1061 if (!VerifySignature(txPrev, *this, i))
1062 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1064 // Check for conflicts
1065 if (!txindex.vSpent[prevout.n].IsNull())
1066 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
1068 // Check for negative or overflow input values
1069 nValueIn += txPrev.vout[prevout.n].nValue;
1070 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1071 return error("ConnectInputs() : txin values out of range");
1073 // Mark outpoints as spent
1074 txindex.vSpent[prevout.n] = posThisTx;
1076 // Write back
1077 if (fBlock)
1079 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1080 return error("ConnectInputs() : UpdateTxIndex failed");
1082 else if (fMiner)
1084 mapTestPool[prevout.hash] = txindex;
1088 if (nValueIn < GetValueOut())
1089 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1091 // Tally transaction fees
1092 int64 nTxFee = nValueIn - GetValueOut();
1093 if (nTxFee < 0)
1094 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1095 if (nTxFee < nMinFee)
1096 return false;
1097 nFees += nTxFee;
1098 if (!MoneyRange(nFees))
1099 return error("ConnectInputs() : nFees out of range");
1102 if (fBlock)
1104 // Add transaction to disk index
1105 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1106 return error("ConnectInputs() : AddTxPos failed");
1108 else if (fMiner)
1110 // Add transaction to test pool
1111 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1114 return true;
1118 bool CTransaction::ClientConnectInputs()
1120 if (IsCoinBase())
1121 return false;
1123 // Take over previous transactions' spent pointers
1124 CRITICAL_BLOCK(cs_mapTransactions)
1126 int64 nValueIn = 0;
1127 for (int i = 0; i < vin.size(); i++)
1129 // Get prev tx from single transactions in memory
1130 COutPoint prevout = vin[i].prevout;
1131 if (!mapTransactions.count(prevout.hash))
1132 return false;
1133 CTransaction& txPrev = mapTransactions[prevout.hash];
1135 if (prevout.n >= txPrev.vout.size())
1136 return false;
1138 // Verify signature
1139 if (!VerifySignature(txPrev, *this, i))
1140 return error("ConnectInputs() : VerifySignature failed");
1142 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1143 ///// this has to go away now that posNext is gone
1144 // // Check for conflicts
1145 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1146 // return error("ConnectInputs() : prev tx already used");
1148 // // Flag outpoints as used
1149 // txPrev.vout[prevout.n].posNext = posThisTx;
1151 nValueIn += txPrev.vout[prevout.n].nValue;
1153 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1154 return error("ClientConnectInputs() : txin values out of range");
1156 if (GetValueOut() > nValueIn)
1157 return false;
1160 return true;
1166 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1168 // Disconnect in reverse order
1169 for (int i = vtx.size()-1; i >= 0; i--)
1170 if (!vtx[i].DisconnectInputs(txdb))
1171 return false;
1173 // Update block index on disk without changing it in memory.
1174 // The memory index structure will be changed after the db commits.
1175 if (pindex->pprev)
1177 CDiskBlockIndex blockindexPrev(pindex->pprev);
1178 blockindexPrev.hashNext = 0;
1179 if (!txdb.WriteBlockIndex(blockindexPrev))
1180 return error("DisconnectBlock() : WriteBlockIndex failed");
1183 return true;
1186 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1188 // Check it again in case a previous version let a bad block in
1189 if (!CheckBlock())
1190 return false;
1192 //// issue here: it doesn't know the version
1193 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1195 map<uint256, CTxIndex> mapUnused;
1196 int64 nFees = 0;
1197 foreach(CTransaction& tx, vtx)
1199 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1200 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1202 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1203 return false;
1206 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1207 return false;
1209 // Update block index on disk without changing it in memory.
1210 // The memory index structure will be changed after the db commits.
1211 if (pindex->pprev)
1213 CDiskBlockIndex blockindexPrev(pindex->pprev);
1214 blockindexPrev.hashNext = pindex->GetBlockHash();
1215 if (!txdb.WriteBlockIndex(blockindexPrev))
1216 return error("ConnectBlock() : WriteBlockIndex failed");
1219 // Watch for transactions paying to me
1220 foreach(CTransaction& tx, vtx)
1221 AddToWalletIfMine(tx, this);
1223 return true;
1228 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1230 printf("REORGANIZE\n");
1232 // Find the fork
1233 CBlockIndex* pfork = pindexBest;
1234 CBlockIndex* plonger = pindexNew;
1235 while (pfork != plonger)
1237 while (plonger->nHeight > pfork->nHeight)
1238 if (!(plonger = plonger->pprev))
1239 return error("Reorganize() : plonger->pprev is null");
1240 if (pfork == plonger)
1241 break;
1242 if (!(pfork = pfork->pprev))
1243 return error("Reorganize() : pfork->pprev is null");
1246 // List of what to disconnect
1247 vector<CBlockIndex*> vDisconnect;
1248 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1249 vDisconnect.push_back(pindex);
1251 // List of what to connect
1252 vector<CBlockIndex*> vConnect;
1253 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1254 vConnect.push_back(pindex);
1255 reverse(vConnect.begin(), vConnect.end());
1257 // Disconnect shorter branch
1258 vector<CTransaction> vResurrect;
1259 foreach(CBlockIndex* pindex, vDisconnect)
1261 CBlock block;
1262 if (!block.ReadFromDisk(pindex))
1263 return error("Reorganize() : ReadFromDisk for disconnect failed");
1264 if (!block.DisconnectBlock(txdb, pindex))
1265 return error("Reorganize() : DisconnectBlock failed");
1267 // Queue memory transactions to resurrect
1268 foreach(const CTransaction& tx, block.vtx)
1269 if (!tx.IsCoinBase())
1270 vResurrect.push_back(tx);
1273 // Connect longer branch
1274 vector<CTransaction> vDelete;
1275 for (int i = 0; i < vConnect.size(); i++)
1277 CBlockIndex* pindex = vConnect[i];
1278 CBlock block;
1279 if (!block.ReadFromDisk(pindex))
1280 return error("Reorganize() : ReadFromDisk for connect failed");
1281 if (!block.ConnectBlock(txdb, pindex))
1283 // Invalid block
1284 txdb.TxnAbort();
1285 return error("Reorganize() : ConnectBlock failed");
1288 // Queue memory transactions to delete
1289 foreach(const CTransaction& tx, block.vtx)
1290 vDelete.push_back(tx);
1292 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1293 return error("Reorganize() : WriteHashBestChain failed");
1295 // Make sure it's successfully written to disk before changing memory structure
1296 if (!txdb.TxnCommit())
1297 return error("Reorganize() : TxnCommit failed");
1299 // Disconnect shorter branch
1300 foreach(CBlockIndex* pindex, vDisconnect)
1301 if (pindex->pprev)
1302 pindex->pprev->pnext = NULL;
1304 // Connect longer branch
1305 foreach(CBlockIndex* pindex, vConnect)
1306 if (pindex->pprev)
1307 pindex->pprev->pnext = pindex;
1309 // Resurrect memory transactions that were in the disconnected branch
1310 foreach(CTransaction& tx, vResurrect)
1311 tx.AcceptToMemoryPool(txdb, false);
1313 // Delete redundant memory transactions that are in the connected branch
1314 foreach(CTransaction& tx, vDelete)
1315 tx.RemoveFromMemoryPool();
1317 return true;
1321 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1323 uint256 hash = GetHash();
1325 txdb.TxnBegin();
1326 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1328 txdb.WriteHashBestChain(hash);
1329 if (!txdb.TxnCommit())
1330 return error("SetBestChain() : TxnCommit failed");
1331 pindexGenesisBlock = pindexNew;
1333 else if (hashPrevBlock == hashBestChain)
1335 // Adding to current best branch
1336 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1338 txdb.TxnAbort();
1339 InvalidChainFound(pindexNew);
1340 return error("SetBestChain() : ConnectBlock failed");
1342 if (!txdb.TxnCommit())
1343 return error("SetBestChain() : TxnCommit failed");
1345 // Add to current best branch
1346 pindexNew->pprev->pnext = pindexNew;
1348 // Delete redundant memory transactions
1349 foreach(CTransaction& tx, vtx)
1350 tx.RemoveFromMemoryPool();
1352 else
1354 // New best branch
1355 if (!Reorganize(txdb, pindexNew))
1357 txdb.TxnAbort();
1358 InvalidChainFound(pindexNew);
1359 return error("SetBestChain() : Reorganize failed");
1363 // New best block
1364 hashBestChain = hash;
1365 pindexBest = pindexNew;
1366 nBestHeight = pindexBest->nHeight;
1367 bnBestChainWork = pindexNew->bnChainWork;
1368 nTimeBestReceived = GetTime();
1369 nTransactionsUpdated++;
1370 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1372 return true;
1376 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1378 // Check for duplicate
1379 uint256 hash = GetHash();
1380 if (mapBlockIndex.count(hash))
1381 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1383 // Construct new block index object
1384 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1385 if (!pindexNew)
1386 return error("AddToBlockIndex() : new CBlockIndex failed");
1387 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1388 pindexNew->phashBlock = &((*mi).first);
1389 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1390 if (miPrev != mapBlockIndex.end())
1392 pindexNew->pprev = (*miPrev).second;
1393 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1395 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1397 CTxDB txdb;
1398 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1400 // New best
1401 if (pindexNew->bnChainWork > bnBestChainWork)
1402 if (!SetBestChain(txdb, pindexNew))
1403 return false;
1405 txdb.Close();
1407 if (pindexNew == pindexBest)
1409 // Notify UI to display prev block's coinbase if it was ours
1410 static uint256 hashPrevBestCoinBase;
1411 CRITICAL_BLOCK(cs_mapWallet)
1412 vWalletUpdated.push_back(hashPrevBestCoinBase);
1413 hashPrevBestCoinBase = vtx[0].GetHash();
1416 MainFrameRepaint();
1417 return true;
1423 bool CBlock::CheckBlock() const
1425 // These are checks that are independent of context
1426 // that can be verified before saving an orphan block.
1428 // Size limits
1429 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1430 return error("CheckBlock() : size limits failed");
1432 // Check proof of work matches claimed amount
1433 if (!CheckProofOfWork(GetHash(), nBits))
1434 return error("CheckBlock() : proof of work failed");
1436 // Check timestamp
1437 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1438 return error("CheckBlock() : block timestamp too far in the future");
1440 // First transaction must be coinbase, the rest must not be
1441 if (vtx.empty() || !vtx[0].IsCoinBase())
1442 return error("CheckBlock() : first tx is not coinbase");
1443 for (int i = 1; i < vtx.size(); i++)
1444 if (vtx[i].IsCoinBase())
1445 return error("CheckBlock() : more than one coinbase");
1447 // Check transactions
1448 foreach(const CTransaction& tx, vtx)
1449 if (!tx.CheckTransaction())
1450 return error("CheckBlock() : CheckTransaction failed");
1452 // Check that it's not full of nonstandard transactions
1453 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1454 return error("CheckBlock() : too many nonstandard transactions");
1456 // Check merkleroot
1457 if (hashMerkleRoot != BuildMerkleTree())
1458 return error("CheckBlock() : hashMerkleRoot mismatch");
1460 return true;
1463 bool CBlock::AcceptBlock()
1465 // Check for duplicate
1466 uint256 hash = GetHash();
1467 if (mapBlockIndex.count(hash))
1468 return error("AcceptBlock() : block already in mapBlockIndex");
1470 // Get prev block index
1471 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1472 if (mi == mapBlockIndex.end())
1473 return error("AcceptBlock() : prev block not found");
1474 CBlockIndex* pindexPrev = (*mi).second;
1475 int nHeight = pindexPrev->nHeight+1;
1477 // Check proof of work
1478 if (nBits != GetNextWorkRequired(pindexPrev))
1479 return error("AcceptBlock() : incorrect proof of work");
1481 // Check timestamp against prev
1482 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1483 return error("AcceptBlock() : block's timestamp is too early");
1485 // Check that all transactions are finalized
1486 foreach(const CTransaction& tx, vtx)
1487 if (!tx.IsFinal(nHeight, GetBlockTime()))
1488 return error("AcceptBlock() : contains a non-final transaction");
1490 // Check that the block chain matches the known block chain up to a checkpoint
1491 if (!fTestNet)
1492 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1493 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1494 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1495 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1496 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))
1497 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1499 // Write block to history file
1500 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1501 return error("AcceptBlock() : out of disk space");
1502 unsigned int nFile;
1503 unsigned int nBlockPos;
1504 if (!WriteToDisk(!fClient, nFile, nBlockPos))
1505 return error("AcceptBlock() : WriteToDisk failed");
1506 if (!AddToBlockIndex(nFile, nBlockPos))
1507 return error("AcceptBlock() : AddToBlockIndex failed");
1509 // Relay inventory, but don't relay old inventory during initial block download
1510 if (hashBestChain == hash)
1511 CRITICAL_BLOCK(cs_vNodes)
1512 foreach(CNode* pnode, vNodes)
1513 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1514 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1516 return true;
1519 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1521 // Check for duplicate
1522 uint256 hash = pblock->GetHash();
1523 if (mapBlockIndex.count(hash))
1524 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1525 if (mapOrphanBlocks.count(hash))
1526 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1528 // Preliminary checks
1529 if (!pblock->CheckBlock())
1531 delete pblock;
1532 return error("ProcessBlock() : CheckBlock FAILED");
1535 // If don't already have its previous block, shunt it off to holding area until we get it
1536 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1538 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1539 mapOrphanBlocks.insert(make_pair(hash, pblock));
1540 mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));
1542 // Ask this guy to fill in what we're missing
1543 if (pfrom)
1544 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));
1545 return true;
1548 // Store to disk
1549 if (!pblock->AcceptBlock())
1551 delete pblock;
1552 return error("ProcessBlock() : AcceptBlock FAILED");
1554 delete pblock;
1556 // Recursively process any orphan blocks that depended on this one
1557 vector<uint256> vWorkQueue;
1558 vWorkQueue.push_back(hash);
1559 for (int i = 0; i < vWorkQueue.size(); i++)
1561 uint256 hashPrev = vWorkQueue[i];
1562 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1563 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1564 ++mi)
1566 CBlock* pblockOrphan = (*mi).second;
1567 if (pblockOrphan->AcceptBlock())
1568 vWorkQueue.push_back(pblockOrphan->GetHash());
1569 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1570 delete pblockOrphan;
1572 mapOrphanBlocksByPrev.erase(hashPrev);
1575 printf("ProcessBlock: ACCEPTED\n");
1576 return true;
1586 template<typename Stream>
1587 bool ScanMessageStart(Stream& s)
1589 // Scan ahead to the next pchMessageStart, which should normally be immediately
1590 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1591 s.clear(0);
1592 short prevmask = s.exceptions(0);
1593 const char* p = BEGIN(pchMessageStart);
1596 loop
1598 char c;
1599 s.read(&c, 1);
1600 if (s.fail())
1602 s.clear(0);
1603 s.exceptions(prevmask);
1604 return false;
1606 if (*p != c)
1607 p = BEGIN(pchMessageStart);
1608 if (*p == c)
1610 if (++p == END(pchMessageStart))
1612 s.clear(0);
1613 s.exceptions(prevmask);
1614 return true;
1619 catch (...)
1621 s.clear(0);
1622 s.exceptions(prevmask);
1623 return false;
1627 bool CheckDiskSpace(uint64 nAdditionalBytes)
1629 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1631 // Check for 15MB because database could create another 10MB log file at any time
1632 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1634 fShutdown = true;
1635 string strMessage = _("Warning: Disk space is low ");
1636 strMiscWarning = strMessage;
1637 printf("*** %s\n", strMessage.c_str());
1638 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1639 CreateThread(Shutdown, NULL);
1640 return false;
1642 return true;
1645 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1647 if (nFile == -1)
1648 return NULL;
1649 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1650 if (!file)
1651 return NULL;
1652 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1654 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1656 fclose(file);
1657 return NULL;
1660 return file;
1663 static unsigned int nCurrentBlockFile = 1;
1665 FILE* AppendBlockFile(unsigned int& nFileRet)
1667 nFileRet = 0;
1668 loop
1670 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1671 if (!file)
1672 return NULL;
1673 if (fseek(file, 0, SEEK_END) != 0)
1674 return NULL;
1675 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1676 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1678 nFileRet = nCurrentBlockFile;
1679 return file;
1681 fclose(file);
1682 nCurrentBlockFile++;
1686 bool LoadBlockIndex(bool fAllowNew)
1688 if (fTestNet)
1690 hashGenesisBlock = uint256("0x0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110");
1691 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1692 pchMessageStart[0] = 0xfa;
1693 pchMessageStart[1] = 0xbf;
1694 pchMessageStart[2] = 0xb5;
1695 pchMessageStart[3] = 0xda;
1699 // Load block index
1701 CTxDB txdb("cr");
1702 if (!txdb.LoadBlockIndex())
1703 return false;
1704 txdb.Close();
1707 // Init with genesis block
1709 if (mapBlockIndex.empty())
1711 if (!fAllowNew)
1712 return false;
1714 // Genesis Block:
1715 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1716 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1717 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1718 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1719 // vMerkleTree: 4a5e1e
1721 // Genesis block
1722 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1723 CTransaction txNew;
1724 txNew.vin.resize(1);
1725 txNew.vout.resize(1);
1726 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1727 txNew.vout[0].nValue = 50 * COIN;
1728 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1729 CBlock block;
1730 block.vtx.push_back(txNew);
1731 block.hashPrevBlock = 0;
1732 block.hashMerkleRoot = block.BuildMerkleTree();
1733 block.nVersion = 1;
1734 block.nTime = 1231006505;
1735 block.nBits = 0x1d00ffff;
1736 block.nNonce = 2083236893;
1738 if (fTestNet)
1740 block.nTime = 1279232055;
1741 block.nBits = 0x1d07fff8;
1742 block.nNonce = 81622180;
1745 //// debug print
1746 printf("%s\n", block.GetHash().ToString().c_str());
1747 printf("%s\n", hashGenesisBlock.ToString().c_str());
1748 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1749 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1750 block.print();
1751 assert(block.GetHash() == hashGenesisBlock);
1753 // Start new block file
1754 unsigned int nFile;
1755 unsigned int nBlockPos;
1756 if (!block.WriteToDisk(!fClient, nFile, nBlockPos))
1757 return error("LoadBlockIndex() : writing genesis block to disk failed");
1758 if (!block.AddToBlockIndex(nFile, nBlockPos))
1759 return error("LoadBlockIndex() : genesis block not accepted");
1762 return true;
1767 void PrintBlockTree()
1769 // precompute tree structure
1770 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1771 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1773 CBlockIndex* pindex = (*mi).second;
1774 mapNext[pindex->pprev].push_back(pindex);
1775 // test
1776 //while (rand() % 3 == 0)
1777 // mapNext[pindex->pprev].push_back(pindex);
1780 vector<pair<int, CBlockIndex*> > vStack;
1781 vStack.push_back(make_pair(0, pindexGenesisBlock));
1783 int nPrevCol = 0;
1784 while (!vStack.empty())
1786 int nCol = vStack.back().first;
1787 CBlockIndex* pindex = vStack.back().second;
1788 vStack.pop_back();
1790 // print split or gap
1791 if (nCol > nPrevCol)
1793 for (int i = 0; i < nCol-1; i++)
1794 printf("| ");
1795 printf("|\\\n");
1797 else if (nCol < nPrevCol)
1799 for (int i = 0; i < nCol; i++)
1800 printf("| ");
1801 printf("|\n");
1803 nPrevCol = nCol;
1805 // print columns
1806 for (int i = 0; i < nCol; i++)
1807 printf("| ");
1809 // print item
1810 CBlock block;
1811 block.ReadFromDisk(pindex);
1812 printf("%d (%u,%u) %s %s tx %d",
1813 pindex->nHeight,
1814 pindex->nFile,
1815 pindex->nBlockPos,
1816 block.GetHash().ToString().substr(0,20).c_str(),
1817 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1818 block.vtx.size());
1820 CRITICAL_BLOCK(cs_mapWallet)
1822 if (mapWallet.count(block.vtx[0].GetHash()))
1824 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1825 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1828 printf("\n");
1831 // put the main timechain first
1832 vector<CBlockIndex*>& vNext = mapNext[pindex];
1833 for (int i = 0; i < vNext.size(); i++)
1835 if (vNext[i]->pnext)
1837 swap(vNext[0], vNext[i]);
1838 break;
1842 // iterate children
1843 for (int i = 0; i < vNext.size(); i++)
1844 vStack.push_back(make_pair(nCol+i, vNext[i]));
1857 //////////////////////////////////////////////////////////////////////////////
1859 // CAlert
1862 map<uint256, CAlert> mapAlerts;
1863 CCriticalSection cs_mapAlerts;
1865 string GetWarnings(string strFor)
1867 int nPriority = 0;
1868 string strStatusBar;
1869 string strRPC;
1870 if (mapArgs.count("-testsafemode"))
1871 strRPC = "test";
1873 // Misc warnings like out of disk space and clock is wrong
1874 if (strMiscWarning != "")
1876 nPriority = 1000;
1877 strStatusBar = strMiscWarning;
1880 // Longer invalid proof-of-work chain
1881 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1883 nPriority = 2000;
1884 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1887 // Alerts
1888 CRITICAL_BLOCK(cs_mapAlerts)
1890 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1892 const CAlert& alert = item.second;
1893 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1895 nPriority = alert.nPriority;
1896 strStatusBar = alert.strStatusBar;
1897 strRPC = alert.strRPCError;
1902 if (strFor == "statusbar")
1903 return strStatusBar;
1904 else if (strFor == "rpc")
1905 return strRPC;
1906 assert(("GetWarnings() : invalid parameter", false));
1907 return "error";
1910 bool CAlert::ProcessAlert()
1912 if (!CheckSignature())
1913 return false;
1914 if (!IsInEffect())
1915 return false;
1917 CRITICAL_BLOCK(cs_mapAlerts)
1919 // Cancel previous alerts
1920 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1922 const CAlert& alert = (*mi).second;
1923 if (Cancels(alert))
1925 printf("cancelling alert %d\n", alert.nID);
1926 mapAlerts.erase(mi++);
1928 else if (!alert.IsInEffect())
1930 printf("expiring alert %d\n", alert.nID);
1931 mapAlerts.erase(mi++);
1933 else
1934 mi++;
1937 // Check if this alert has been cancelled
1938 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1940 const CAlert& alert = item.second;
1941 if (alert.Cancels(*this))
1943 printf("alert already cancelled by %d\n", alert.nID);
1944 return false;
1948 // Add to mapAlerts
1949 mapAlerts.insert(make_pair(GetHash(), *this));
1952 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1953 MainFrameRepaint();
1954 return true;
1964 //////////////////////////////////////////////////////////////////////////////
1966 // Messages
1970 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
1972 switch (inv.type)
1974 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1975 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1977 // Don't know what it is, just say we already got one
1978 return true;
1984 // The message start string is designed to be unlikely to occur in normal data.
1985 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1986 // a large 4-byte int at any alignment.
1987 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1990 bool ProcessMessages(CNode* pfrom)
1992 CDataStream& vRecv = pfrom->vRecv;
1993 if (vRecv.empty())
1994 return true;
1995 //if (fDebug)
1996 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
1999 // Message format
2000 // (4) message start
2001 // (12) command
2002 // (4) size
2003 // (4) checksum
2004 // (x) data
2007 loop
2009 // Scan for message start
2010 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2011 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2012 if (vRecv.end() - pstart < nHeaderSize)
2014 if (vRecv.size() > nHeaderSize)
2016 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2017 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2019 break;
2021 if (pstart - vRecv.begin() > 0)
2022 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2023 vRecv.erase(vRecv.begin(), pstart);
2025 // Read header
2026 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2027 CMessageHeader hdr;
2028 vRecv >> hdr;
2029 if (!hdr.IsValid())
2031 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2032 continue;
2034 string strCommand = hdr.GetCommand();
2036 // Message size
2037 unsigned int nMessageSize = hdr.nMessageSize;
2038 if (nMessageSize > MAX_SIZE)
2040 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2041 continue;
2043 if (nMessageSize > vRecv.size())
2045 // Rewind and wait for rest of message
2046 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2047 break;
2050 // Checksum
2051 if (vRecv.GetVersion() >= 209)
2053 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2054 unsigned int nChecksum = 0;
2055 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2056 if (nChecksum != hdr.nChecksum)
2058 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2059 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2060 continue;
2064 // Copy message to its own buffer
2065 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2066 vRecv.ignore(nMessageSize);
2068 // Process message
2069 bool fRet = false;
2072 CRITICAL_BLOCK(cs_main)
2073 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2074 if (fShutdown)
2075 return true;
2077 catch (std::ios_base::failure& e)
2079 if (strstr(e.what(), "end of data"))
2081 // Allow exceptions from underlength message on vRecv
2082 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
2084 else if (strstr(e.what(), "size too large"))
2086 // Allow exceptions from overlong size
2087 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2089 else
2091 PrintExceptionContinue(&e, "ProcessMessage()");
2094 catch (std::exception& e) {
2095 PrintExceptionContinue(&e, "ProcessMessage()");
2096 } catch (...) {
2097 PrintExceptionContinue(NULL, "ProcessMessage()");
2100 if (!fRet)
2101 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2104 vRecv.Compact();
2105 return true;
2111 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2113 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2114 RandAddSeedPerfmon();
2115 if (fDebug)
2116 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2117 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2118 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2120 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2121 return true;
2128 if (strCommand == "version")
2130 // Each connection can only send one version message
2131 if (pfrom->nVersion != 0)
2132 return false;
2134 int64 nTime;
2135 CAddress addrMe;
2136 CAddress addrFrom;
2137 uint64 nNonce = 1;
2138 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2139 if (pfrom->nVersion == 10300)
2140 pfrom->nVersion = 300;
2141 if (pfrom->nVersion >= 106 && !vRecv.empty())
2142 vRecv >> addrFrom >> nNonce;
2143 if (pfrom->nVersion >= 106 && !vRecv.empty())
2144 vRecv >> pfrom->strSubVer;
2145 if (pfrom->nVersion >= 209 && !vRecv.empty())
2146 vRecv >> pfrom->nStartingHeight;
2148 if (pfrom->nVersion == 0)
2149 return false;
2151 // Disconnect if we connected to ourself
2152 if (nNonce == nLocalHostNonce && nNonce > 1)
2154 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2155 pfrom->fDisconnect = true;
2156 return true;
2159 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2160 if (pfrom->fClient)
2162 pfrom->vSend.nType |= SER_BLOCKHEADERONLY;
2163 pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;
2166 AddTimeData(pfrom->addr.ip, nTime);
2168 // Change version
2169 if (pfrom->nVersion >= 209)
2170 pfrom->PushMessage("verack");
2171 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2172 if (pfrom->nVersion < 209)
2173 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2175 // Ask the first connected node for block updates
2176 static int nAskedForBlocks;
2177 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2179 nAskedForBlocks++;
2180 pfrom->PushGetBlocks(pindexBest, uint256(0));
2183 // Relay alerts
2184 CRITICAL_BLOCK(cs_mapAlerts)
2185 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2186 item.second.RelayTo(pfrom);
2188 pfrom->fSuccessfullyConnected = true;
2190 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2194 else if (pfrom->nVersion == 0)
2196 // Must have a version message before anything else
2197 return false;
2201 else if (strCommand == "verack")
2203 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2207 else if (strCommand == "addr")
2209 vector<CAddress> vAddr;
2210 vRecv >> vAddr;
2211 if (pfrom->nVersion < 200) // don't want addresses from 0.1.5
2212 return true;
2213 if (pfrom->nVersion < 209 && mapAddresses.size() > 1000) // don't want addr from 0.2.0 unless seeding
2214 return true;
2215 if (vAddr.size() > 1000)
2216 return error("message addr size() = %d", vAddr.size());
2218 // Store the new addresses
2219 foreach(CAddress& addr, vAddr)
2221 if (fShutdown)
2222 return true;
2223 // ignore IPv6 for now, since it isn't implemented anyway
2224 if (!addr.IsIPv4())
2225 continue;
2226 addr.nTime = GetAdjustedTime() - 2 * 60 * 60;
2227 if (pfrom->fGetAddr || vAddr.size() > 10)
2228 addr.nTime -= 5 * 24 * 60 * 60;
2229 AddAddress(addr);
2230 pfrom->AddAddressKnown(addr);
2231 if (!pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2233 // Relay to a limited number of other nodes
2234 CRITICAL_BLOCK(cs_vNodes)
2236 // Use deterministic randomness to send to the same nodes for 24 hours
2237 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2238 static uint256 hashSalt;
2239 if (hashSalt == 0)
2240 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2241 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2242 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2243 multimap<uint256, CNode*> mapMix;
2244 foreach(CNode* pnode, vNodes)
2246 unsigned int nPointer;
2247 memcpy(&nPointer, &pnode, sizeof(nPointer));
2248 uint256 hashKey = hashRand ^ nPointer;
2249 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2250 mapMix.insert(make_pair(hashKey, pnode));
2252 int nRelayNodes = 2;
2253 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2254 ((*mi).second)->PushAddress(addr);
2258 if (vAddr.size() < 1000)
2259 pfrom->fGetAddr = false;
2263 else if (strCommand == "inv")
2265 vector<CInv> vInv;
2266 vRecv >> vInv;
2267 if (vInv.size() > 50000)
2268 return error("message inv size() = %d", vInv.size());
2270 CTxDB txdb("r");
2271 foreach(const CInv& inv, vInv)
2273 if (fShutdown)
2274 return true;
2275 pfrom->AddInventoryKnown(inv);
2277 bool fAlreadyHave = AlreadyHave(txdb, inv);
2278 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2280 if (!fAlreadyHave)
2281 pfrom->AskFor(inv);
2282 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2283 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2285 // Track requests for our stuff
2286 CRITICAL_BLOCK(cs_mapRequestCount)
2288 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2289 if (mi != mapRequestCount.end())
2290 (*mi).second++;
2296 else if (strCommand == "getdata")
2298 vector<CInv> vInv;
2299 vRecv >> vInv;
2300 if (vInv.size() > 50000)
2301 return error("message getdata size() = %d", vInv.size());
2303 foreach(const CInv& inv, vInv)
2305 if (fShutdown)
2306 return true;
2307 printf("received getdata for: %s\n", inv.ToString().c_str());
2309 if (inv.type == MSG_BLOCK)
2311 // Send block from disk
2312 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2313 if (mi != mapBlockIndex.end())
2315 //// could optimize this to send header straight from blockindex for client
2316 CBlock block;
2317 block.ReadFromDisk((*mi).second, !pfrom->fClient);
2318 pfrom->PushMessage("block", block);
2320 // Trigger them to send a getblocks request for the next batch of inventory
2321 if (inv.hash == pfrom->hashContinue)
2323 // Bypass PushInventory, this must send even if redundant,
2324 // and we want it right after the last block so they don't
2325 // wait for other stuff first.
2326 vector<CInv> vInv;
2327 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2328 pfrom->PushMessage("inv", vInv);
2329 pfrom->hashContinue = 0;
2333 else if (inv.IsKnownType())
2335 // Send stream from relay memory
2336 CRITICAL_BLOCK(cs_mapRelay)
2338 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2339 if (mi != mapRelay.end())
2340 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2344 // Track requests for our stuff
2345 CRITICAL_BLOCK(cs_mapRequestCount)
2347 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2348 if (mi != mapRequestCount.end())
2349 (*mi).second++;
2355 else if (strCommand == "getblocks")
2357 CBlockLocator locator;
2358 uint256 hashStop;
2359 vRecv >> locator >> hashStop;
2361 // Find the first block the caller has in the main chain
2362 CBlockIndex* pindex = locator.GetBlockIndex();
2364 // Send the rest of the chain
2365 if (pindex)
2366 pindex = pindex->pnext;
2367 int nLimit = 500 + locator.GetDistanceBack();
2368 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2369 for (; pindex; pindex = pindex->pnext)
2371 if (pindex->GetBlockHash() == hashStop)
2373 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2374 break;
2376 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2377 if (--nLimit <= 0)
2379 // When this block is requested, we'll send an inv that'll make them
2380 // getblocks the next batch of inventory.
2381 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2382 pfrom->hashContinue = pindex->GetBlockHash();
2383 break;
2389 else if (strCommand == "tx")
2391 vector<uint256> vWorkQueue;
2392 CDataStream vMsg(vRecv);
2393 CTransaction tx;
2394 vRecv >> tx;
2396 CInv inv(MSG_TX, tx.GetHash());
2397 pfrom->AddInventoryKnown(inv);
2399 bool fMissingInputs = false;
2400 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2402 AddToWalletIfMine(tx, NULL);
2403 RelayMessage(inv, vMsg);
2404 mapAlreadyAskedFor.erase(inv);
2405 vWorkQueue.push_back(inv.hash);
2407 // Recursively process any orphan transactions that depended on this one
2408 for (int i = 0; i < vWorkQueue.size(); i++)
2410 uint256 hashPrev = vWorkQueue[i];
2411 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2412 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2413 ++mi)
2415 const CDataStream& vMsg = *((*mi).second);
2416 CTransaction tx;
2417 CDataStream(vMsg) >> tx;
2418 CInv inv(MSG_TX, tx.GetHash());
2420 if (tx.AcceptToMemoryPool(true))
2422 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2423 AddToWalletIfMine(tx, NULL);
2424 RelayMessage(inv, vMsg);
2425 mapAlreadyAskedFor.erase(inv);
2426 vWorkQueue.push_back(inv.hash);
2431 foreach(uint256 hash, vWorkQueue)
2432 EraseOrphanTx(hash);
2434 else if (fMissingInputs)
2436 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2437 AddOrphanTx(vMsg);
2442 else if (strCommand == "block")
2444 auto_ptr<CBlock> pblock(new CBlock);
2445 vRecv >> *pblock;
2447 //// debug print
2448 printf("received block %s\n", pblock->GetHash().ToString().substr(0,20).c_str());
2449 // pblock->print();
2451 CInv inv(MSG_BLOCK, pblock->GetHash());
2452 pfrom->AddInventoryKnown(inv);
2454 if (ProcessBlock(pfrom, pblock.release()))
2455 mapAlreadyAskedFor.erase(inv);
2459 else if (strCommand == "getaddr")
2461 // Nodes rebroadcast an addr every 24 hours
2462 pfrom->vAddrToSend.clear();
2463 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2464 CRITICAL_BLOCK(cs_mapAddresses)
2466 unsigned int nCount = 0;
2467 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2469 const CAddress& addr = item.second;
2470 if (addr.nTime > nSince)
2471 nCount++;
2473 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2475 const CAddress& addr = item.second;
2476 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2477 pfrom->PushAddress(addr);
2483 else if (strCommand == "checkorder")
2485 uint256 hashReply;
2486 CWalletTx order;
2487 vRecv >> hashReply >> order;
2489 if (!mapArgs.count("-allowreceivebyip") || mapArgs["-allowreceivebyip"] == "0")
2491 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2492 return true;
2495 /// we have a chance to check the order here
2497 // Keep giving the same key to the same ip until they use it
2498 if (!mapReuseKey.count(pfrom->addr.ip))
2499 mapReuseKey[pfrom->addr.ip] = CWalletDB().GetKeyFromKeyPool();
2501 // Send back approval of order and pubkey to use
2502 CScript scriptPubKey;
2503 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2504 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2508 else if (strCommand == "submitorder")
2510 uint256 hashReply;
2511 CWalletTx wtxNew;
2512 vRecv >> hashReply >> wtxNew;
2513 wtxNew.fFromMe = false;
2515 if (!mapArgs.count("-allowreceivebyip") || mapArgs["-allowreceivebyip"] == "0")
2517 pfrom->PushMessage("reply", hashReply, (int)2);
2518 return true;
2521 // Broadcast
2522 if (!wtxNew.AcceptWalletTransaction())
2524 pfrom->PushMessage("reply", hashReply, (int)1);
2525 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2527 wtxNew.fTimeReceivedIsTxTime = true;
2528 AddToWallet(wtxNew);
2529 wtxNew.RelayWalletTransaction();
2530 mapReuseKey.erase(pfrom->addr.ip);
2532 // Send back confirmation
2533 pfrom->PushMessage("reply", hashReply, (int)0);
2537 else if (strCommand == "reply")
2539 uint256 hashReply;
2540 vRecv >> hashReply;
2542 CRequestTracker tracker;
2543 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2545 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2546 if (mi != pfrom->mapRequests.end())
2548 tracker = (*mi).second;
2549 pfrom->mapRequests.erase(mi);
2552 if (!tracker.IsNull())
2553 tracker.fn(tracker.param1, vRecv);
2557 else if (strCommand == "ping")
2562 else if (strCommand == "alert")
2564 CAlert alert;
2565 vRecv >> alert;
2567 if (alert.ProcessAlert())
2569 // Relay
2570 pfrom->setKnown.insert(alert.GetHash());
2571 CRITICAL_BLOCK(cs_vNodes)
2572 foreach(CNode* pnode, vNodes)
2573 alert.RelayTo(pnode);
2578 else
2580 // Ignore unknown commands for extensibility
2584 // Update the last seen time for this node's address
2585 if (pfrom->fNetworkNode)
2586 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2587 AddressCurrentlyConnected(pfrom->addr);
2590 return true;
2601 bool SendMessages(CNode* pto, bool fSendTrickle)
2603 CRITICAL_BLOCK(cs_main)
2605 // Don't send anything until we get their version message
2606 if (pto->nVersion == 0)
2607 return true;
2609 // Keep-alive ping
2610 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2611 pto->PushMessage("ping");
2613 // Address refresh broadcast
2614 static int64 nLastRebroadcast;
2615 if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours
2617 nLastRebroadcast = GetTime();
2618 CRITICAL_BLOCK(cs_vNodes)
2620 foreach(CNode* pnode, vNodes)
2622 // Periodically clear setAddrKnown to allow refresh broadcasts
2623 pnode->setAddrKnown.clear();
2625 // Rebroadcast our address
2626 if (addrLocalHost.IsRoutable() && !fUseProxy)
2627 pnode->PushAddress(addrLocalHost);
2632 // Resend wallet transactions that haven't gotten in a block yet
2633 ResendWalletTransactions();
2637 // Message: addr
2639 if (fSendTrickle)
2641 vector<CAddress> vAddr;
2642 vAddr.reserve(pto->vAddrToSend.size());
2643 foreach(const CAddress& addr, pto->vAddrToSend)
2645 // returns true if wasn't already contained in the set
2646 if (pto->setAddrKnown.insert(addr).second)
2648 vAddr.push_back(addr);
2649 // receiver rejects addr messages larger than 1000
2650 if (vAddr.size() >= 1000)
2652 pto->PushMessage("addr", vAddr);
2653 vAddr.clear();
2657 pto->vAddrToSend.clear();
2658 if (!vAddr.empty())
2659 pto->PushMessage("addr", vAddr);
2664 // Message: inventory
2666 vector<CInv> vInv;
2667 vector<CInv> vInvWait;
2668 CRITICAL_BLOCK(pto->cs_inventory)
2670 vInv.reserve(pto->vInventoryToSend.size());
2671 vInvWait.reserve(pto->vInventoryToSend.size());
2672 foreach(const CInv& inv, pto->vInventoryToSend)
2674 if (pto->setInventoryKnown.count(inv))
2675 continue;
2677 // trickle out tx inv to protect privacy
2678 if (inv.type == MSG_TX && !fSendTrickle)
2680 // 1/4 of tx invs blast to all immediately
2681 static uint256 hashSalt;
2682 if (hashSalt == 0)
2683 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2684 uint256 hashRand = inv.hash ^ hashSalt;
2685 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2686 bool fTrickleWait = ((hashRand & 3) != 0);
2688 // always trickle our own transactions
2689 if (!fTrickleWait)
2691 TRY_CRITICAL_BLOCK(cs_mapWallet)
2693 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2694 if (mi != mapWallet.end())
2696 CWalletTx& wtx = (*mi).second;
2697 if (wtx.fFromMe)
2698 fTrickleWait = true;
2703 if (fTrickleWait)
2705 vInvWait.push_back(inv);
2706 continue;
2710 // returns true if wasn't already contained in the set
2711 if (pto->setInventoryKnown.insert(inv).second)
2713 vInv.push_back(inv);
2714 if (vInv.size() >= 1000)
2716 pto->PushMessage("inv", vInv);
2717 vInv.clear();
2721 pto->vInventoryToSend = vInvWait;
2723 if (!vInv.empty())
2724 pto->PushMessage("inv", vInv);
2728 // Message: getdata
2730 vector<CInv> vGetData;
2731 int64 nNow = GetTime() * 1000000;
2732 CTxDB txdb("r");
2733 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2735 const CInv& inv = (*pto->mapAskFor.begin()).second;
2736 if (!AlreadyHave(txdb, inv))
2738 printf("sending getdata: %s\n", inv.ToString().c_str());
2739 vGetData.push_back(inv);
2740 if (vGetData.size() >= 1000)
2742 pto->PushMessage("getdata", vGetData);
2743 vGetData.clear();
2746 pto->mapAskFor.erase(pto->mapAskFor.begin());
2748 if (!vGetData.empty())
2749 pto->PushMessage("getdata", vGetData);
2752 return true;
2768 //////////////////////////////////////////////////////////////////////////////
2770 // BitcoinMiner
2773 void GenerateBitcoins(bool fGenerate)
2775 if (fGenerateBitcoins != fGenerate)
2777 fGenerateBitcoins = fGenerate;
2778 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2779 MainFrameRepaint();
2781 if (fGenerateBitcoins)
2783 int nProcessors = boost::thread::hardware_concurrency();
2784 printf("%d processors\n", nProcessors);
2785 if (nProcessors < 1)
2786 nProcessors = 1;
2787 if (fLimitProcessors && nProcessors > nLimitProcessors)
2788 nProcessors = nLimitProcessors;
2789 int nAddThreads = nProcessors - vnThreadsRunning[3];
2790 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2791 for (int i = 0; i < nAddThreads; i++)
2793 if (!CreateThread(ThreadBitcoinMiner, NULL))
2794 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2795 Sleep(10);
2800 void ThreadBitcoinMiner(void* parg)
2804 vnThreadsRunning[3]++;
2805 BitcoinMiner();
2806 vnThreadsRunning[3]--;
2808 catch (std::exception& e) {
2809 vnThreadsRunning[3]--;
2810 PrintException(&e, "ThreadBitcoinMiner()");
2811 } catch (...) {
2812 vnThreadsRunning[3]--;
2813 PrintException(NULL, "ThreadBitcoinMiner()");
2815 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
2816 nHPSTimerStart = 0;
2817 if (vnThreadsRunning[3] == 0)
2818 dHashesPerSec = 0;
2819 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2822 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
2823 void CallCPUID(int in, int& aret, int& cret)
2825 int a, c;
2826 asm (
2827 "mov %2, %%eax; " // in into eax
2828 "cpuid;"
2829 "mov %%eax, %0;" // eax into a
2830 "mov %%ecx, %1;" // eax into c
2831 :"=r"(a),"=r"(c) /* output */
2832 :"r"(in) /* input */
2833 :"%eax","%ecx" /* clobbered register */
2835 aret = a;
2836 cret = c;
2839 bool Detect128BitSSE2()
2841 int a, c, nBrand;
2842 CallCPUID(0, a, nBrand);
2843 bool fIntel = (nBrand == 0x6c65746e); // ntel
2844 bool fAMD = (nBrand == 0x444d4163); // cAMD
2846 struct
2848 unsigned int nStepping : 4;
2849 unsigned int nModel : 4;
2850 unsigned int nFamily : 4;
2851 unsigned int nProcessorType : 2;
2852 unsigned int nUnused : 2;
2853 unsigned int nExtendedModel : 4;
2854 unsigned int nExtendedFamily : 8;
2856 cpu;
2857 CallCPUID(1, a, c);
2858 memcpy(&cpu, &a, sizeof(cpu));
2859 int nFamily = cpu.nExtendedFamily + cpu.nFamily;
2860 int nModel = cpu.nExtendedModel*16 + cpu.nModel;
2862 // We need Intel Nehalem or AMD K10 or better for 128bit SSE2
2863 // Nehalem = i3/i5/i7 and some Xeon
2864 // K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II
2865 // Intel Core i5 family 6, model 26 or 30
2866 // Intel Core i7 family 6, model 26 or 30
2867 // Intel Core i3 family 6, model 37
2868 // AMD Phenom family 16, model 10
2869 bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >= 60026) ||
2870 (fAMD && nFamily * 10000 + nModel >= 160010));
2872 // AMD reports a lower model number in 64-bit mode
2873 if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)
2874 fUseSSE2 = true;
2876 static bool fPrinted;
2877 if (!fPrinted)
2879 fPrinted = true;
2880 printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);
2882 return fUseSSE2;
2884 #else
2885 bool Detect128BitSSE2() { return false; }
2886 #endif
2888 int FormatHashBlocks(void* pbuffer, unsigned int len)
2890 unsigned char* pdata = (unsigned char*)pbuffer;
2891 unsigned int blocks = 1 + ((len + 8) / 64);
2892 unsigned char* pend = pdata + 64 * blocks;
2893 memset(pdata + len, 0, 64 * blocks - len);
2894 pdata[len] = 0x80;
2895 unsigned int bits = len * 8;
2896 pend[-1] = (bits >> 0) & 0xff;
2897 pend[-2] = (bits >> 8) & 0xff;
2898 pend[-3] = (bits >> 16) & 0xff;
2899 pend[-4] = (bits >> 24) & 0xff;
2900 return blocks;
2903 using CryptoPP::ByteReverse;
2905 static const unsigned int pSHA256InitState[8] =
2906 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2908 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2910 memcpy(pstate, pinit, 32);
2911 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2915 // ScanHash scans nonces looking for a hash with at least some zero bits.
2916 // It operates on big endian data. Caller does the byte reversing.
2917 // All input buffers are 16-byte aligned. nNonce is usually preserved
2918 // between calls, but periodically or if nNonce is above 0xff000000,
2919 // the block is rebuilt and nNonce starts over at zero.
2921 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone)
2923 unsigned int& nNonce = *(unsigned int*)(pblock + 12);
2924 for (;;)
2926 // Crypto++ SHA-256
2927 // Hash pblock using pmidstate as the starting state into
2928 // preformatted buffer phash1, then hash phash1 into phash
2929 nNonce++;
2930 SHA256Transform(phash1, pblock, pmidstate);
2931 SHA256Transform(phash, phash1, pSHA256InitState);
2933 // Return the nonce if the hash has at least some zero bits,
2934 // caller will check if it has enough to reach the target
2935 if (((unsigned short*)phash)[14] == 0)
2936 return nNonce;
2938 // If nothing found after trying for a while, return -1
2939 if ((nNonce & 0xffff) == 0)
2941 nHashesDone = 0xffff+1;
2942 return -1;
2947 extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);
2952 void BitcoinMiner()
2954 printf("BitcoinMiner started\n");
2955 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2956 bool f4WaySSE2 = Detect128BitSSE2();
2957 if (mapArgs.count("-4way"))
2958 f4WaySSE2 = (mapArgs["-4way"] != "0");
2960 CReserveKey reservekey;
2961 unsigned int nExtraNonce = 0;
2962 int64 nPrevTime = 0;
2963 while (fGenerateBitcoins)
2965 if (AffinityBugWorkaround(ThreadBitcoinMiner))
2966 return;
2967 if (fShutdown)
2968 return;
2969 while (vNodes.empty() || IsInitialBlockDownload())
2971 Sleep(1000);
2972 if (fShutdown)
2973 return;
2974 if (!fGenerateBitcoins)
2975 return;
2978 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2979 CBlockIndex* pindexPrev = pindexBest;
2980 unsigned int nBits = GetNextWorkRequired(pindexPrev);
2984 // Create coinbase tx
2986 CTransaction txNew;
2987 txNew.vin.resize(1);
2988 txNew.vin[0].prevout.SetNull();
2989 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2990 if (nNow > nPrevTime+1 && ++nExtraNonce >= 0x7f)
2992 nExtraNonce = 1;
2993 nPrevTime = nNow;
2995 txNew.vin[0].scriptSig << nBits << CBigNum(nExtraNonce);
2996 txNew.vout.resize(1);
2997 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3001 // Create new block
3003 auto_ptr<CBlock> pblock(new CBlock());
3004 if (!pblock.get())
3005 return;
3007 // Add our coinbase tx as first transaction
3008 pblock->vtx.push_back(txNew);
3010 // Collect memory pool transactions into the block
3011 int64 nFees = 0;
3012 CRITICAL_BLOCK(cs_main)
3013 CRITICAL_BLOCK(cs_mapTransactions)
3015 CTxDB txdb("r");
3016 map<uint256, CTxIndex> mapTestPool;
3017 vector<char> vfAlreadyAdded(mapTransactions.size());
3018 uint64 nBlockSize = 1000;
3019 int nBlockSigOps = 100;
3020 bool fFoundSomething = true;
3021 while (fFoundSomething)
3023 fFoundSomething = false;
3024 unsigned int n = 0;
3025 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)
3027 if (vfAlreadyAdded[n])
3028 continue;
3029 CTransaction& tx = (*mi).second;
3030 if (tx.IsCoinBase() || !tx.IsFinal())
3031 continue;
3032 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3033 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3034 continue;
3035 int nTxSigOps = tx.GetSigOpCount();
3036 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3037 continue;
3039 // Transaction fee based on block size
3040 int64 nMinFee = tx.GetMinFee(nBlockSize);
3042 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3043 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3044 continue;
3045 swap(mapTestPool, mapTestPoolTmp);
3047 pblock->vtx.push_back(tx);
3048 nBlockSize += nTxSize;
3049 nBlockSigOps += nTxSigOps;
3050 vfAlreadyAdded[n] = true;
3051 fFoundSomething = true;
3055 pblock->nBits = nBits;
3056 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3057 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3061 // Prebuild hash buffer
3063 struct tmpworkspace
3065 struct unnamed2
3067 int nVersion;
3068 uint256 hashPrevBlock;
3069 uint256 hashMerkleRoot;
3070 unsigned int nTime;
3071 unsigned int nBits;
3072 unsigned int nNonce;
3074 block;
3075 unsigned char pchPadding0[64];
3076 uint256 hash1;
3077 unsigned char pchPadding1[64];
3079 char tmpbuf[sizeof(tmpworkspace)+16];
3080 tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);
3082 tmp.block.nVersion = pblock->nVersion;
3083 tmp.block.hashPrevBlock = pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3084 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3085 tmp.block.nTime = pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3086 tmp.block.nBits = pblock->nBits = nBits;
3087 tmp.block.nNonce = pblock->nNonce = 0;
3089 unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3090 unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3092 // Byte swap all the input buffer
3093 for (int i = 0; i < sizeof(tmp)/4; i++)
3094 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3096 // Precalc the first half of the first hash, which stays constant
3097 uint256 midstatebuf[2];
3098 uint256& midstate = *alignup<16>(midstatebuf);
3099 SHA256Transform(&midstate, &tmp.block, pSHA256InitState);
3103 // Search
3105 int64 nStart = GetTime();
3106 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3107 uint256 hashbuf[2];
3108 uint256& hash = *alignup<16>(hashbuf);
3109 loop
3111 unsigned int nHashesDone = 0;
3112 unsigned int nNonceFound;
3114 #ifdef FOURWAYSSE2
3115 if (f4WaySSE2)
3116 // tcatm's 4-way 128-bit SSE2 SHA-256
3117 nNonceFound = ScanHash_4WaySSE2((char*)&midstate, (char*)&tmp.block + 64, (char*)&tmp.hash1, (char*)&hash, nHashesDone);
3118 else
3119 #endif
3120 // Crypto++ SHA-256
3121 nNonceFound = ScanHash_CryptoPP((char*)&midstate, (char*)&tmp.block + 64, (char*)&tmp.hash1, (char*)&hash, nHashesDone);
3123 // Check if something found
3124 if (nNonceFound != -1)
3126 for (int i = 0; i < sizeof(hash)/4; i++)
3127 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3129 if (hash <= hashTarget)
3131 // Found a solution
3132 pblock->nNonce = ByteReverse(nNonceFound);
3133 assert(hash == pblock->GetHash());
3135 //// debug print
3136 printf("BitcoinMiner:\n");
3137 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3138 pblock->print();
3139 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3140 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3142 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3143 CRITICAL_BLOCK(cs_main)
3145 if (pindexPrev == pindexBest)
3147 // Remove key from key pool
3148 reservekey.KeepKey();
3150 // Track how many getdata requests this block gets
3151 CRITICAL_BLOCK(cs_mapRequestCount)
3152 mapRequestCount[pblock->GetHash()] = 0;
3154 // Process this block the same as if we had received it from another node
3155 if (!ProcessBlock(NULL, pblock.release()))
3156 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
3159 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3161 Sleep(500);
3162 break;
3166 // Meter hashes/sec
3167 static int64 nHashCounter;
3168 if (nHPSTimerStart == 0)
3170 nHPSTimerStart = GetTimeMillis();
3171 nHashCounter = 0;
3173 else
3174 nHashCounter += nHashesDone;
3175 if (GetTimeMillis() - nHPSTimerStart > 4000)
3177 static CCriticalSection cs;
3178 CRITICAL_BLOCK(cs)
3180 if (GetTimeMillis() - nHPSTimerStart > 4000)
3182 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3183 nHPSTimerStart = GetTimeMillis();
3184 nHashCounter = 0;
3185 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3186 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3187 static int64 nLogTime;
3188 if (GetTime() - nLogTime > 30 * 60)
3190 nLogTime = GetTime();
3191 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3192 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3198 // Check for stop or if block needs to be rebuilt
3199 if (fShutdown)
3200 return;
3201 if (!fGenerateBitcoins)
3202 return;
3203 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3204 return;
3205 if (vNodes.empty())
3206 break;
3207 if (tmp.block.nNonce >= 0xff000000)
3208 break;
3209 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3210 break;
3211 if (pindexPrev != pindexBest)
3212 break;
3214 // Update nTime every few seconds
3215 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3216 tmp.block.nTime = ByteReverse(pblock->nTime);
3238 //////////////////////////////////////////////////////////////////////////////
3240 // Actions
3244 int64 GetBalance()
3246 int64 nStart = GetTimeMillis();
3248 int64 nTotal = 0;
3249 CRITICAL_BLOCK(cs_mapWallet)
3251 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3253 CWalletTx* pcoin = &(*it).second;
3254 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3255 continue;
3256 nTotal += pcoin->GetCredit(true);
3260 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3261 return nTotal;
3265 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
3267 setCoinsRet.clear();
3269 // List of values less than target
3270 int64 nLowestLarger = INT64_MAX;
3271 CWalletTx* pcoinLowestLarger = NULL;
3272 vector<pair<int64, CWalletTx*> > vValue;
3273 int64 nTotalLower = 0;
3275 CRITICAL_BLOCK(cs_mapWallet)
3277 vector<CWalletTx*> vCoins;
3278 vCoins.reserve(mapWallet.size());
3279 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3280 vCoins.push_back(&(*it).second);
3281 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3283 foreach(CWalletTx* pcoin, vCoins)
3285 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3286 continue;
3287 int64 n = pcoin->GetCredit();
3288 if (n <= 0)
3289 continue;
3290 if (n < nTargetValue)
3292 vValue.push_back(make_pair(n, pcoin));
3293 nTotalLower += n;
3295 else if (n == nTargetValue)
3297 setCoinsRet.insert(pcoin);
3298 return true;
3300 else if (n < nLowestLarger)
3302 nLowestLarger = n;
3303 pcoinLowestLarger = pcoin;
3308 if (nTotalLower < nTargetValue)
3310 if (pcoinLowestLarger == NULL)
3311 return false;
3312 setCoinsRet.insert(pcoinLowestLarger);
3313 return true;
3316 // Solve subset sum by stochastic approximation
3317 sort(vValue.rbegin(), vValue.rend());
3318 vector<char> vfIncluded;
3319 vector<char> vfBest(vValue.size(), true);
3320 int64 nBest = nTotalLower;
3322 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3324 vfIncluded.assign(vValue.size(), false);
3325 int64 nTotal = 0;
3326 bool fReachedTarget = false;
3327 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3329 for (int i = 0; i < vValue.size(); i++)
3331 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3333 nTotal += vValue[i].first;
3334 vfIncluded[i] = true;
3335 if (nTotal >= nTargetValue)
3337 fReachedTarget = true;
3338 if (nTotal < nBest)
3340 nBest = nTotal;
3341 vfBest = vfIncluded;
3343 nTotal -= vValue[i].first;
3344 vfIncluded[i] = false;
3351 // If the next larger is still closer, return it
3352 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
3353 setCoinsRet.insert(pcoinLowestLarger);
3354 else
3356 for (int i = 0; i < vValue.size(); i++)
3357 if (vfBest[i])
3358 setCoinsRet.insert(vValue[i].second);
3360 //// debug print
3361 printf("SelectCoins() best subset: ");
3362 for (int i = 0; i < vValue.size(); i++)
3363 if (vfBest[i])
3364 printf("%s ", FormatMoney(vValue[i].first).c_str());
3365 printf("total %s\n", FormatMoney(nBest).c_str());
3368 return true;
3374 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRequiredRet)
3376 nFeeRequiredRet = 0;
3377 CRITICAL_BLOCK(cs_main)
3379 // txdb must be opened before the mapWallet lock
3380 CTxDB txdb("r");
3381 CRITICAL_BLOCK(cs_mapWallet)
3383 int64 nFee = nTransactionFee;
3384 loop
3386 wtxNew.vin.clear();
3387 wtxNew.vout.clear();
3388 wtxNew.fFromMe = true;
3389 if (nValue < 0)
3390 return false;
3391 int64 nValueOut = nValue;
3392 int64 nTotalValue = nValue + nFee;
3394 // Choose coins to use
3395 set<CWalletTx*> setCoins;
3396 if (!SelectCoins(nTotalValue, setCoins))
3397 return false;
3398 int64 nValueIn = 0;
3399 foreach(CWalletTx* pcoin, setCoins)
3400 nValueIn += pcoin->GetCredit();
3402 // Fill a vout to the payee
3403 bool fChangeFirst = GetRand(2);
3404 if (!fChangeFirst)
3405 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3407 // Fill a vout back to self with any change
3408 int64 nChange = nValueIn - nTotalValue;
3409 if (nChange >= CENT)
3411 // Note: We use a new key here to keep it from being obvious which side is the change.
3412 // The drawback is that by not reusing a previous key, the change may be lost if a
3413 // backup is restored, if the backup doesn't have the new private key for the change.
3414 // If we reused the old key, it would be possible to add code to look for and
3415 // rediscover unknown transactions that were written with keys of ours to recover
3416 // post-backup change.
3418 // Reserve a new key pair from key pool
3419 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3420 assert(mapKeys.count(vchPubKey));
3422 // Fill a vout to ourself, using same address type as the payment
3423 CScript scriptChange;
3424 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3425 scriptChange.SetBitcoinAddress(vchPubKey);
3426 else
3427 scriptChange << vchPubKey << OP_CHECKSIG;
3428 wtxNew.vout.push_back(CTxOut(nChange, scriptChange));
3430 else
3431 reservekey.ReturnKey();
3433 // Fill a vout to the payee
3434 if (fChangeFirst)
3435 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3437 // Fill vin
3438 foreach(CWalletTx* pcoin, setCoins)
3439 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3440 if (pcoin->vout[nOut].IsMine())
3441 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3443 // Sign
3444 int nIn = 0;
3445 foreach(CWalletTx* pcoin, setCoins)
3446 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3447 if (pcoin->vout[nOut].IsMine())
3448 if (!SignSignature(*pcoin, wtxNew, nIn++))
3449 return false;
3451 // Limit size
3452 if (::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK) >= MAX_BLOCK_SIZE_GEN/5)
3453 return false;
3455 // Check that enough fee is included
3456 if (nFee < wtxNew.GetMinFee())
3458 nFee = nFeeRequiredRet = wtxNew.GetMinFee();
3459 continue;
3462 // Fill vtxPrev by copying from previous transactions vtxPrev
3463 wtxNew.AddSupportingTransactions(txdb);
3464 wtxNew.fTimeReceivedIsTxTime = true;
3466 break;
3470 return true;
3473 // Call after CreateTransaction unless you want to abort
3474 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3476 CRITICAL_BLOCK(cs_main)
3478 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3479 CRITICAL_BLOCK(cs_mapWallet)
3481 // This is only to keep the database open to defeat the auto-flush for the
3482 // duration of this scope. This is the only place where this optimization
3483 // maybe makes sense; please don't do it anywhere else.
3484 CWalletDB walletdb("r");
3486 // Take key pair from key pool so it won't be used again
3487 reservekey.KeepKey();
3489 // Add tx to wallet, because if it has change it's also ours,
3490 // otherwise just for transaction history.
3491 AddToWallet(wtxNew);
3493 // Mark old coins as spent
3494 set<CWalletTx*> setCoins;
3495 foreach(const CTxIn& txin, wtxNew.vin)
3496 setCoins.insert(&mapWallet[txin.prevout.hash]);
3497 foreach(CWalletTx* pcoin, setCoins)
3499 pcoin->fSpent = true;
3500 pcoin->WriteToDisk();
3501 vWalletUpdated.push_back(pcoin->GetHash());
3505 // Track how many getdata requests our transaction gets
3506 CRITICAL_BLOCK(cs_mapRequestCount)
3507 mapRequestCount[wtxNew.GetHash()] = 0;
3509 // Broadcast
3510 if (!wtxNew.AcceptToMemoryPool())
3512 // This must not fail. The transaction has already been signed and recorded.
3513 printf("CommitTransaction() : Error: Transaction not valid");
3514 return false;
3516 wtxNew.RelayWalletTransaction();
3518 MainFrameRepaint();
3519 return true;
3525 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3527 CRITICAL_BLOCK(cs_main)
3529 CReserveKey reservekey;
3530 int64 nFeeRequired;
3531 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
3533 string strError;
3534 if (nValue + nFeeRequired > GetBalance())
3535 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3536 else
3537 strError = _("Error: Transaction creation failed ");
3538 printf("SendMoney() : %s", strError.c_str());
3539 return strError;
3542 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3543 return "ABORTED";
3545 if (!CommitTransaction(wtxNew, reservekey))
3546 return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
3548 MainFrameRepaint();
3549 return "";
3554 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3556 // Check amount
3557 if (nValue <= 0)
3558 return _("Invalid amount");
3559 if (nValue + nTransactionFee > GetBalance())
3560 return _("Insufficient funds");
3562 // Parse bitcoin address
3563 CScript scriptPubKey;
3564 if (!scriptPubKey.SetBitcoinAddress(strAddress))
3565 return _("Invalid bitcoin address");
3567 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);