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.
6 #include "cryptopp/sha.h"
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;
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;
49 map<uint256, int> mapRequestCount;
50 CCriticalSection cs_mapRequestCount;
52 map<string, string> mapAddressBook;
53 CCriticalSection cs_mapAddressBook;
55 vector<unsigned char> vchDefaultKey;
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 //////////////////////////////////////////////////////////////////////////////
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()
95 throw runtime_error("GenerateNewKey() : AddKey failed");
96 return key.GetPubKey();
102 //////////////////////////////////////////////////////////////////////////////
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;
117 wtx.nTimeReceived = GetAdjustedTime();
119 bool fUpdated = false;
123 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
125 wtx.hashBlock = wtxIn.hashBlock;
128 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
130 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
131 wtx.nIndex = wtxIn.nIndex;
134 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
136 wtx.fFromMe = wtxIn.fFromMe;
139 if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
141 wtx.fSpent = wtxIn.fSpent;
147 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
150 if (fInsertedNew || fUpdated)
151 if (!wtx.WriteToDisk())
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)
162 vchDefaultKey = GetKeyFromKeyPool();
163 walletdb.WriteDefaultKey(vchDefaultKey);
164 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
169 vWalletUpdated.push_back(hash);
177 bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
179 if (tx.IsMine() || mapWallet.count(tx.GetHash()))
182 // Get merkle branch if transaction was found in a block
184 wtx.SetMerkleBranch(pblock);
185 return AddToWallet(wtx);
190 bool AddToWalletIfFromMe(const CTransaction& tx, const CBlock* pblock)
192 if (tx.IsFromMe() || mapWallet.count(tx.GetHash()))
195 // Get merkle branch if transaction was found in a block
197 wtx.SetMerkleBranch(pblock);
198 return AddToWallet(wtx);
203 bool EraseFromWallet(uint256 hash)
205 CRITICAL_BLOCK(cs_mapWallet)
207 if (mapWallet.erase(hash))
208 CWalletDB().EraseTx(hash);
213 void WalletUpdateSpent(const COutPoint& prevout)
215 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
216 // Update the wallet spent flag if it doesn't know due to wallet.dat being
217 // restored from backup or the user making copies of wallet.dat.
218 CRITICAL_BLOCK(cs_mapWallet)
220 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
221 if (mi != mapWallet.end())
223 CWalletTx& wtx = (*mi).second;
224 if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
226 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
229 vWalletUpdated.push_back(prevout.hash);
242 //////////////////////////////////////////////////////////////////////////////
244 // mapOrphanTransactions
247 void AddOrphanTx(const CDataStream& vMsg)
250 CDataStream(vMsg) >> tx;
251 uint256 hash = tx.GetHash();
252 if (mapOrphanTransactions.count(hash))
254 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
255 foreach(const CTxIn& txin, tx.vin)
256 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
259 void EraseOrphanTx(uint256 hash)
261 if (!mapOrphanTransactions.count(hash))
263 const CDataStream* pvMsg = mapOrphanTransactions[hash];
265 CDataStream(*pvMsg) >> tx;
266 foreach(const CTxIn& txin, tx.vin)
268 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
269 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
271 if ((*mi).second == pvMsg)
272 mapOrphanTransactionsByPrev.erase(mi++);
278 mapOrphanTransactions.erase(hash);
288 //////////////////////////////////////////////////////////////////////////////
293 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
296 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
298 if (!ReadFromDisk(txindexRet.pos))
300 if (prevout.n >= vout.size())
308 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
311 return ReadFromDisk(txdb, prevout, txindex);
314 bool CTransaction::ReadFromDisk(COutPoint prevout)
318 return ReadFromDisk(txdb, prevout, txindex);
321 bool CTxIn::IsMine() const
323 CRITICAL_BLOCK(cs_mapWallet)
325 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
326 if (mi != mapWallet.end())
328 const CWalletTx& prev = (*mi).second;
329 if (prevout.n < prev.vout.size())
330 if (prev.vout[prevout.n].IsMine())
337 int64 CTxIn::GetDebit() const
339 CRITICAL_BLOCK(cs_mapWallet)
341 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
342 if (mi != mapWallet.end())
344 const CWalletTx& prev = (*mi).second;
345 if (prevout.n < prev.vout.size())
346 if (prev.vout[prevout.n].IsMine())
347 return prev.vout[prevout.n].nValue;
353 int64 CWalletTx::GetTxTime() const
355 if (!fTimeReceivedIsTxTime && hashBlock != 0)
357 // If we did not receive the transaction directly, we rely on the block's
358 // time to figure out when it happened. We use the median over a range
359 // of blocks to try to filter out inaccurate block times.
360 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
361 if (mi != mapBlockIndex.end())
363 CBlockIndex* pindex = (*mi).second;
365 return pindex->GetMedianTime();
368 return nTimeReceived;
371 int CWalletTx::GetRequestCount() const
373 // Returns -1 if it wasn't being tracked
375 CRITICAL_BLOCK(cs_mapRequestCount)
382 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
383 if (mi != mapRequestCount.end())
384 nRequests = (*mi).second;
389 // Did anyone request this transaction?
390 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
391 if (mi != mapRequestCount.end())
393 nRequests = (*mi).second;
395 // How about the block it's in?
396 if (nRequests == 0 && hashBlock != 0)
398 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
399 if (mi != mapRequestCount.end())
400 nRequests = (*mi).second;
402 nRequests = 1; // If it's in someone else's block it must have got out
410 void CWalletTx::GetAmounts(int64& nGenerated, list<pair<string, int64> >& listReceived,
411 list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
413 nGenerated = nFee = 0;
414 listReceived.clear();
416 strSentAccount = strFromAccount;
420 if (GetDepthInMainChain() >= COINBASE_MATURITY)
421 nGenerated = GetCredit();
426 int64 nDebit = GetDebit();
427 if (nDebit > 0) // debit>0 means we signed/sent this transaction
429 int64 nValueOut = GetValueOut();
430 nFee = nDebit - nValueOut;
433 // Sent/received. Standard client will never generate a send-to-multiple-recipients,
434 // but non-standard clients might (so return a list of address/amount pairs)
435 foreach(const CTxOut& txout, vout)
439 vector<unsigned char> vchPubKey;
440 if (ExtractHash160(txout.scriptPubKey, hash160))
441 address = Hash160ToAddress(hash160);
442 else if (ExtractPubKey(txout.scriptPubKey, false, vchPubKey))
443 address = PubKeyToAddress(vchPubKey);
445 address = " unknown "; // some type of weird non-standard transaction?
447 if (nDebit > 0 && txout.IsChange())
451 listSent.push_back(make_pair(address, txout.nValue));
454 listReceived.push_back(make_pair(address, txout.nValue));
459 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
460 int64& nSent, int64& nFee) const
462 nGenerated = nReceived = nSent = nFee = 0;
464 int64 allGenerated, allFee;
465 allGenerated = allFee = 0;
466 string strSentAccount;
467 list<pair<string, int64> > listReceived;
468 list<pair<string, int64> > listSent;
469 GetAmounts(allGenerated, listReceived, listSent, allFee, strSentAccount);
471 if (strAccount == "")
472 nGenerated = allGenerated;
473 if (strAccount == strSentAccount)
475 foreach(const PAIRTYPE(string,int64)& s, listSent)
479 CRITICAL_BLOCK(cs_mapAddressBook)
481 foreach(const PAIRTYPE(string,int64)& r, listReceived)
482 if (mapAddressBook.count(r.first) && mapAddressBook[r.first] == strAccount)
483 nReceived += r.second;
489 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
501 // Load the block this tx is in
503 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
505 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
510 // Update the tx's hashBlock
511 hashBlock = pblock->GetHash();
513 // Locate the transaction
514 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
515 if (pblock->vtx[nIndex] == *(CTransaction*)this)
517 if (nIndex == pblock->vtx.size())
519 vMerkleBranch.clear();
521 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
525 // Fill in merkle branch
526 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
529 // Is the tx in a block that's in the main chain
530 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
531 if (mi == mapBlockIndex.end())
533 CBlockIndex* pindex = (*mi).second;
534 if (!pindex || !pindex->IsInMainChain())
537 return pindexBest->nHeight - pindex->nHeight + 1;
542 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
546 const int COPY_DEPTH = 3;
547 if (SetMerkleBranch() < COPY_DEPTH)
549 vector<uint256> vWorkQueue;
550 foreach(const CTxIn& txin, vin)
551 vWorkQueue.push_back(txin.prevout.hash);
553 // This critsect is OK because txdb is already open
554 CRITICAL_BLOCK(cs_mapWallet)
556 map<uint256, const CMerkleTx*> mapWalletPrev;
557 set<uint256> setAlreadyDone;
558 for (int i = 0; i < vWorkQueue.size(); i++)
560 uint256 hash = vWorkQueue[i];
561 if (setAlreadyDone.count(hash))
563 setAlreadyDone.insert(hash);
566 if (mapWallet.count(hash))
568 tx = mapWallet[hash];
569 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
570 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
572 else if (mapWalletPrev.count(hash))
574 tx = *mapWalletPrev[hash];
576 else if (!fClient && txdb.ReadDiskTx(hash, tx))
582 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
586 int nDepth = tx.SetMerkleBranch();
587 vtxPrev.push_back(tx);
589 if (nDepth < COPY_DEPTH)
590 foreach(const CTxIn& txin, tx.vin)
591 vWorkQueue.push_back(txin.prevout.hash);
596 reverse(vtxPrev.begin(), vtxPrev.end());
609 bool CTransaction::CheckTransaction() const
611 // Basic checks that don't depend on any context
612 if (vin.empty() || vout.empty())
613 return error("CTransaction::CheckTransaction() : vin or vout empty");
616 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
617 return error("CTransaction::CheckTransaction() : size limits failed");
619 // Check for negative or overflow output values
621 foreach(const CTxOut& txout, vout)
623 if (txout.nValue < 0)
624 return error("CTransaction::CheckTransaction() : txout.nValue negative");
625 if (txout.nValue > MAX_MONEY)
626 return error("CTransaction::CheckTransaction() : txout.nValue too high");
627 nValueOut += txout.nValue;
628 if (!MoneyRange(nValueOut))
629 return error("CTransaction::CheckTransaction() : txout total out of range");
634 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
635 return error("CTransaction::CheckTransaction() : coinbase script size");
639 foreach(const CTxIn& txin, vin)
640 if (txin.prevout.IsNull())
641 return error("CTransaction::CheckTransaction() : prevout is null");
647 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
650 *pfMissingInputs = false;
652 if (!CheckTransaction())
653 return error("AcceptToMemoryPool() : CheckTransaction failed");
655 // Coinbase is only valid in a block, not as a loose transaction
657 return error("AcceptToMemoryPool() : coinbase as individual tx");
659 // To help v0.1.5 clients who would see it as a negative number
660 if ((int64)nLockTime > INT_MAX)
661 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
664 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
665 if (GetSigOpCount() > 2 || nSize < 100)
666 return error("AcceptToMemoryPool() : nonstandard transaction");
668 // Rather not work on nonstandard transactions
670 return error("AcceptToMemoryPool() : nonstandard transaction type");
672 // Do we already have it?
673 uint256 hash = GetHash();
674 CRITICAL_BLOCK(cs_mapTransactions)
675 if (mapTransactions.count(hash))
678 if (txdb.ContainsTx(hash))
681 // Check for conflicts with in-memory transactions
682 CTransaction* ptxOld = NULL;
683 for (int i = 0; i < vin.size(); i++)
685 COutPoint outpoint = vin[i].prevout;
686 if (mapNextTx.count(outpoint))
688 // Disable replacement feature for now
691 // Allow replacing with a newer version of the same transaction
694 ptxOld = mapNextTx[outpoint].ptx;
695 if (ptxOld->IsFinal())
697 if (!IsNewerThan(*ptxOld))
699 for (int i = 0; i < vin.size(); i++)
701 COutPoint outpoint = vin[i].prevout;
702 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
711 // Check against previous transactions
712 map<uint256, CTxIndex> mapUnused;
714 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
717 *pfMissingInputs = true;
718 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
721 // Don't accept it if it can't get into a block
722 if (nFees < GetMinFee(1000))
723 return error("AcceptToMemoryPool() : not enough fees");
725 // Limit free transactions per 10 minutes
726 if (nFees < CENT && GetBoolArg("-limitfreerelay"))
728 static int64 nNextReset;
729 static int64 nFreeCount;
730 if (GetTime() > nNextReset)
732 nNextReset = GetTime() + 10 * 60;
735 if (nFreeCount > 150000 && !IsFromMe())
736 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
741 // Store transaction in memory
742 CRITICAL_BLOCK(cs_mapTransactions)
746 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
747 ptxOld->RemoveFromMemoryPool();
749 AddToMemoryPoolUnchecked();
752 ///// are we sure this is ok when loading transactions or restoring block txes
753 // If updated, erase old tx from wallet
755 EraseFromWallet(ptxOld->GetHash());
757 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
762 bool CTransaction::AddToMemoryPoolUnchecked()
764 // Add to memory pool without checking anything. Don't call this directly,
765 // call AcceptToMemoryPool to properly check the transaction first.
766 CRITICAL_BLOCK(cs_mapTransactions)
768 uint256 hash = GetHash();
769 mapTransactions[hash] = *this;
770 for (int i = 0; i < vin.size(); i++)
771 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
772 nTransactionsUpdated++;
778 bool CTransaction::RemoveFromMemoryPool()
780 // Remove transaction from memory pool
781 CRITICAL_BLOCK(cs_mapTransactions)
783 foreach(const CTxIn& txin, vin)
784 mapNextTx.erase(txin.prevout);
785 mapTransactions.erase(GetHash());
786 nTransactionsUpdated++;
796 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
798 if (hashBlock == 0 || nIndex == -1)
801 // Find the block it claims to be in
802 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
803 if (mi == mapBlockIndex.end())
805 CBlockIndex* pindex = (*mi).second;
806 if (!pindex || !pindex->IsInMainChain())
809 // Make sure the merkle branch connects to this block
810 if (!fMerkleVerified)
812 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
814 fMerkleVerified = true;
817 nHeightRet = pindex->nHeight;
818 return pindexBest->nHeight - pindex->nHeight + 1;
822 int CMerkleTx::GetBlocksToMaturity() const
826 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
830 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
834 if (!IsInMainChain() && !ClientConnectInputs())
836 return CTransaction::AcceptToMemoryPool(txdb, false);
840 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
846 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
848 CRITICAL_BLOCK(cs_mapTransactions)
850 // Add previous supporting transactions first
851 foreach(CMerkleTx& tx, vtxPrev)
853 if (!tx.IsCoinBase())
855 uint256 hash = tx.GetHash();
856 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
857 tx.AcceptToMemoryPool(txdb, fCheckInputs);
860 return AcceptToMemoryPool(txdb, fCheckInputs);
865 int ScanForWalletTransactions(CBlockIndex* pindexStart)
869 CBlockIndex* pindex = pindexStart;
870 CRITICAL_BLOCK(cs_mapWallet)
875 block.ReadFromDisk(pindex, true);
876 foreach(CTransaction& tx, block.vtx)
878 uint256 hash = tx.GetHash();
879 if (mapWallet.count(hash)) continue;
880 AddToWalletIfMine(tx, &block);
881 if (mapWallet.count(hash))
884 printf("Added missing RECEIVE %s\n", hash.ToString().c_str());
887 AddToWalletIfFromMe(tx, &block);
888 if (mapWallet.count(hash))
891 printf("Added missing SEND %s\n", hash.ToString().c_str());
895 pindex = pindex->pnext;
901 void ReacceptWalletTransactions()
905 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
908 vector<CDiskTxPos> vMissingTx;
909 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
911 CWalletTx& wtx = item.second;
912 if (wtx.fSpent && wtx.IsCoinBase())
916 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
918 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
921 if (txindex.vSpent.size() != wtx.vout.size())
923 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
926 for (int i = 0; i < txindex.vSpent.size(); i++)
928 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
931 vMissingTx.push_back(txindex.vSpent[i]);
936 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
943 // Reaccept any txes of ours that aren't already in a block
944 if (!wtx.IsCoinBase())
945 wtx.AcceptWalletTransaction(txdb, false);
948 if (!vMissingTx.empty())
950 // TODO: optimize this to scan just part of the block chain?
951 if (ScanForWalletTransactions(pindexGenesisBlock))
952 fRepeat = true; // Found missing transactions: re-do Reaccept.
958 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
960 foreach(const CMerkleTx& tx, vtxPrev)
962 if (!tx.IsCoinBase())
964 uint256 hash = tx.GetHash();
965 if (!txdb.ContainsTx(hash))
966 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
971 uint256 hash = GetHash();
972 if (!txdb.ContainsTx(hash))
974 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
975 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
980 void ResendWalletTransactions()
982 // Do this infrequently and randomly to avoid giving away
983 // that these are our transactions.
984 static int64 nNextTime;
985 if (GetTime() < nNextTime)
987 bool fFirst = (nNextTime == 0);
988 nNextTime = GetTime() + GetRand(30 * 60);
992 // Only do it if there's been a new block since last time
993 static int64 nLastTime;
994 if (nTimeBestReceived < nLastTime)
996 nLastTime = GetTime();
998 // Rebroadcast any of our txes that aren't in a block yet
999 printf("ResendWalletTransactions()\n");
1001 CRITICAL_BLOCK(cs_mapWallet)
1003 // Sort them in chronological order
1004 multimap<unsigned int, CWalletTx*> mapSorted;
1005 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1007 CWalletTx& wtx = item.second;
1008 // Don't rebroadcast until it's had plenty of time that
1009 // it should have gotten in already by now.
1010 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1011 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1013 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1015 CWalletTx& wtx = *item.second;
1016 wtx.RelayWalletTransaction(txdb);
1030 //////////////////////////////////////////////////////////////////////////////
1032 // CBlock and CBlockIndex
1035 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1037 if (!fReadTransactions)
1039 *this = pindex->GetBlockHeader();
1042 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
1044 if (GetHash() != pindex->GetBlockHash())
1045 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1049 uint256 GetOrphanRoot(const CBlock* pblock)
1051 // Work back to the first block in the orphan chain
1052 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1053 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1054 return pblock->GetHash();
1057 int64 GetBlockValue(int nHeight, int64 nFees)
1059 int64 nSubsidy = 50 * COIN;
1061 // Subsidy is cut in half every 4 years
1062 nSubsidy >>= (nHeight / 210000);
1064 return nSubsidy + nFees;
1067 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
1069 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1070 const int64 nTargetSpacing = 10 * 60;
1071 const int64 nInterval = nTargetTimespan / nTargetSpacing;
1074 if (pindexLast == NULL)
1075 return bnProofOfWorkLimit.GetCompact();
1077 // Only change once per interval
1078 if ((pindexLast->nHeight+1) % nInterval != 0)
1079 return pindexLast->nBits;
1081 // Go back by what we want to be 14 days worth of blocks
1082 const CBlockIndex* pindexFirst = pindexLast;
1083 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1084 pindexFirst = pindexFirst->pprev;
1085 assert(pindexFirst);
1087 // Limit adjustment step
1088 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1089 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1090 if (nActualTimespan < nTargetTimespan/4)
1091 nActualTimespan = nTargetTimespan/4;
1092 if (nActualTimespan > nTargetTimespan*4)
1093 nActualTimespan = nTargetTimespan*4;
1097 bnNew.SetCompact(pindexLast->nBits);
1098 bnNew *= nActualTimespan;
1099 bnNew /= nTargetTimespan;
1101 if (bnNew > bnProofOfWorkLimit)
1102 bnNew = bnProofOfWorkLimit;
1105 printf("GetNextWorkRequired RETARGET\n");
1106 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1107 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1108 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1110 return bnNew.GetCompact();
1113 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1116 bnTarget.SetCompact(nBits);
1119 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1120 return error("CheckProofOfWork() : nBits below minimum work");
1122 // Check proof of work matches claimed amount
1123 if (hash > bnTarget.getuint256())
1124 return error("CheckProofOfWork() : hash doesn't match nBits");
1129 bool IsInitialBlockDownload()
1131 if (pindexBest == NULL || (!fTestNet && nBestHeight < 74000))
1133 static int64 nLastUpdate;
1134 static CBlockIndex* pindexLastBest;
1135 if (pindexBest != pindexLastBest)
1137 pindexLastBest = pindexBest;
1138 nLastUpdate = GetTime();
1140 return (GetTime() - nLastUpdate < 10 &&
1141 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1144 void InvalidChainFound(CBlockIndex* pindexNew)
1146 if (pindexNew->bnChainWork > bnBestInvalidWork)
1148 bnBestInvalidWork = pindexNew->bnChainWork;
1149 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
1152 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());
1153 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1154 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1155 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1168 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1170 // Relinquish previous transactions' spent pointers
1173 foreach(const CTxIn& txin, vin)
1175 COutPoint prevout = txin.prevout;
1177 // Get prev txindex from disk
1179 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1180 return error("DisconnectInputs() : ReadTxIndex failed");
1182 if (prevout.n >= txindex.vSpent.size())
1183 return error("DisconnectInputs() : prevout.n out of range");
1185 // Mark outpoint as not spent
1186 txindex.vSpent[prevout.n].SetNull();
1189 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1190 return error("DisconnectInputs() : UpdateTxIndex failed");
1194 // Remove transaction from index
1195 if (!txdb.EraseTxIndex(*this))
1196 return error("DisconnectInputs() : EraseTxPos failed");
1202 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1203 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1205 // Take over previous transactions' spent pointers
1209 for (int i = 0; i < vin.size(); i++)
1211 COutPoint prevout = vin[i].prevout;
1216 if (fMiner && mapTestPool.count(prevout.hash))
1218 // Get txindex from current proposed changes
1219 txindex = mapTestPool[prevout.hash];
1223 // Read txindex from txdb
1224 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1226 if (!fFound && (fBlock || fMiner))
1227 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());
1230 CTransaction txPrev;
1231 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1233 // Get prev tx from single transactions in memory
1234 CRITICAL_BLOCK(cs_mapTransactions)
1236 if (!mapTransactions.count(prevout.hash))
1237 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1238 txPrev = mapTransactions[prevout.hash];
1241 txindex.vSpent.resize(txPrev.vout.size());
1245 // Get prev tx from disk
1246 if (!txPrev.ReadFromDisk(txindex.pos))
1247 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1250 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1251 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());
1253 // If prev is coinbase, check that it's matured
1254 if (txPrev.IsCoinBase())
1255 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1256 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1257 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1260 if (!VerifySignature(txPrev, *this, i))
1261 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1263 // Check for conflicts
1264 if (!txindex.vSpent[prevout.n].IsNull())
1265 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());
1267 // Check for negative or overflow input values
1268 nValueIn += txPrev.vout[prevout.n].nValue;
1269 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1270 return error("ConnectInputs() : txin values out of range");
1272 // Mark outpoints as spent
1273 txindex.vSpent[prevout.n] = posThisTx;
1278 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1279 return error("ConnectInputs() : UpdateTxIndex failed");
1283 mapTestPool[prevout.hash] = txindex;
1287 if (nValueIn < GetValueOut())
1288 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1290 // Tally transaction fees
1291 int64 nTxFee = nValueIn - GetValueOut();
1293 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1294 if (nTxFee < nMinFee)
1297 if (!MoneyRange(nFees))
1298 return error("ConnectInputs() : nFees out of range");
1303 // Add transaction to disk index
1304 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1305 return error("ConnectInputs() : AddTxPos failed");
1309 // Add transaction to test pool
1310 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1317 bool CTransaction::ClientConnectInputs()
1322 // Take over previous transactions' spent pointers
1323 CRITICAL_BLOCK(cs_mapTransactions)
1326 for (int i = 0; i < vin.size(); i++)
1328 // Get prev tx from single transactions in memory
1329 COutPoint prevout = vin[i].prevout;
1330 if (!mapTransactions.count(prevout.hash))
1332 CTransaction& txPrev = mapTransactions[prevout.hash];
1334 if (prevout.n >= txPrev.vout.size())
1338 if (!VerifySignature(txPrev, *this, i))
1339 return error("ConnectInputs() : VerifySignature failed");
1341 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1342 ///// this has to go away now that posNext is gone
1343 // // Check for conflicts
1344 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1345 // return error("ConnectInputs() : prev tx already used");
1347 // // Flag outpoints as used
1348 // txPrev.vout[prevout.n].posNext = posThisTx;
1350 nValueIn += txPrev.vout[prevout.n].nValue;
1352 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1353 return error("ClientConnectInputs() : txin values out of range");
1355 if (GetValueOut() > nValueIn)
1365 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1367 // Disconnect in reverse order
1368 for (int i = vtx.size()-1; i >= 0; i--)
1369 if (!vtx[i].DisconnectInputs(txdb))
1372 // Update block index on disk without changing it in memory.
1373 // The memory index structure will be changed after the db commits.
1376 CDiskBlockIndex blockindexPrev(pindex->pprev);
1377 blockindexPrev.hashNext = 0;
1378 if (!txdb.WriteBlockIndex(blockindexPrev))
1379 return error("DisconnectBlock() : WriteBlockIndex failed");
1385 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1387 // Check it again in case a previous version let a bad block in
1391 //// issue here: it doesn't know the version
1392 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1394 map<uint256, CTxIndex> mapUnused;
1396 foreach(CTransaction& tx, vtx)
1398 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1399 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1401 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1405 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1408 // Update block index on disk without changing it in memory.
1409 // The memory index structure will be changed after the db commits.
1412 CDiskBlockIndex blockindexPrev(pindex->pprev);
1413 blockindexPrev.hashNext = pindex->GetBlockHash();
1414 if (!txdb.WriteBlockIndex(blockindexPrev))
1415 return error("ConnectBlock() : WriteBlockIndex failed");
1418 // Watch for transactions paying to me
1419 foreach(CTransaction& tx, vtx)
1420 AddToWalletIfMine(tx, this);
1425 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1427 printf("REORGANIZE\n");
1430 CBlockIndex* pfork = pindexBest;
1431 CBlockIndex* plonger = pindexNew;
1432 while (pfork != plonger)
1434 while (plonger->nHeight > pfork->nHeight)
1435 if (!(plonger = plonger->pprev))
1436 return error("Reorganize() : plonger->pprev is null");
1437 if (pfork == plonger)
1439 if (!(pfork = pfork->pprev))
1440 return error("Reorganize() : pfork->pprev is null");
1443 // List of what to disconnect
1444 vector<CBlockIndex*> vDisconnect;
1445 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1446 vDisconnect.push_back(pindex);
1448 // List of what to connect
1449 vector<CBlockIndex*> vConnect;
1450 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1451 vConnect.push_back(pindex);
1452 reverse(vConnect.begin(), vConnect.end());
1454 // Disconnect shorter branch
1455 vector<CTransaction> vResurrect;
1456 foreach(CBlockIndex* pindex, vDisconnect)
1459 if (!block.ReadFromDisk(pindex))
1460 return error("Reorganize() : ReadFromDisk for disconnect failed");
1461 if (!block.DisconnectBlock(txdb, pindex))
1462 return error("Reorganize() : DisconnectBlock failed");
1464 // Queue memory transactions to resurrect
1465 foreach(const CTransaction& tx, block.vtx)
1466 if (!tx.IsCoinBase())
1467 vResurrect.push_back(tx);
1470 // Connect longer branch
1471 vector<CTransaction> vDelete;
1472 for (int i = 0; i < vConnect.size(); i++)
1474 CBlockIndex* pindex = vConnect[i];
1476 if (!block.ReadFromDisk(pindex))
1477 return error("Reorganize() : ReadFromDisk for connect failed");
1478 if (!block.ConnectBlock(txdb, pindex))
1482 return error("Reorganize() : ConnectBlock failed");
1485 // Queue memory transactions to delete
1486 foreach(const CTransaction& tx, block.vtx)
1487 vDelete.push_back(tx);
1489 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1490 return error("Reorganize() : WriteHashBestChain failed");
1492 // Make sure it's successfully written to disk before changing memory structure
1493 if (!txdb.TxnCommit())
1494 return error("Reorganize() : TxnCommit failed");
1496 // Disconnect shorter branch
1497 foreach(CBlockIndex* pindex, vDisconnect)
1499 pindex->pprev->pnext = NULL;
1501 // Connect longer branch
1502 foreach(CBlockIndex* pindex, vConnect)
1504 pindex->pprev->pnext = pindex;
1506 // Resurrect memory transactions that were in the disconnected branch
1507 foreach(CTransaction& tx, vResurrect)
1508 tx.AcceptToMemoryPool(txdb, false);
1510 // Delete redundant memory transactions that are in the connected branch
1511 foreach(CTransaction& tx, vDelete)
1512 tx.RemoveFromMemoryPool();
1518 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1520 uint256 hash = GetHash();
1523 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1525 txdb.WriteHashBestChain(hash);
1526 if (!txdb.TxnCommit())
1527 return error("SetBestChain() : TxnCommit failed");
1528 pindexGenesisBlock = pindexNew;
1530 else if (hashPrevBlock == hashBestChain)
1532 // Adding to current best branch
1533 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1536 InvalidChainFound(pindexNew);
1537 return error("SetBestChain() : ConnectBlock failed");
1539 if (!txdb.TxnCommit())
1540 return error("SetBestChain() : TxnCommit failed");
1542 // Add to current best branch
1543 pindexNew->pprev->pnext = pindexNew;
1545 // Delete redundant memory transactions
1546 foreach(CTransaction& tx, vtx)
1547 tx.RemoveFromMemoryPool();
1552 if (!Reorganize(txdb, pindexNew))
1555 InvalidChainFound(pindexNew);
1556 return error("SetBestChain() : Reorganize failed");
1561 hashBestChain = hash;
1562 pindexBest = pindexNew;
1563 nBestHeight = pindexBest->nHeight;
1564 bnBestChainWork = pindexNew->bnChainWork;
1565 nTimeBestReceived = GetTime();
1566 nTransactionsUpdated++;
1567 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1573 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1575 // Check for duplicate
1576 uint256 hash = GetHash();
1577 if (mapBlockIndex.count(hash))
1578 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1580 // Construct new block index object
1581 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1583 return error("AddToBlockIndex() : new CBlockIndex failed");
1584 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1585 pindexNew->phashBlock = &((*mi).first);
1586 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1587 if (miPrev != mapBlockIndex.end())
1589 pindexNew->pprev = (*miPrev).second;
1590 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1592 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1596 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1597 if (!txdb.TxnCommit())
1601 if (pindexNew->bnChainWork > bnBestChainWork)
1602 if (!SetBestChain(txdb, pindexNew))
1607 if (pindexNew == pindexBest)
1609 // Notify UI to display prev block's coinbase if it was ours
1610 static uint256 hashPrevBestCoinBase;
1611 CRITICAL_BLOCK(cs_mapWallet)
1612 vWalletUpdated.push_back(hashPrevBestCoinBase);
1613 hashPrevBestCoinBase = vtx[0].GetHash();
1623 bool CBlock::CheckBlock() const
1625 // These are checks that are independent of context
1626 // that can be verified before saving an orphan block.
1629 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1630 return error("CheckBlock() : size limits failed");
1632 // Check proof of work matches claimed amount
1633 if (!CheckProofOfWork(GetHash(), nBits))
1634 return error("CheckBlock() : proof of work failed");
1637 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1638 return error("CheckBlock() : block timestamp too far in the future");
1640 // First transaction must be coinbase, the rest must not be
1641 if (vtx.empty() || !vtx[0].IsCoinBase())
1642 return error("CheckBlock() : first tx is not coinbase");
1643 for (int i = 1; i < vtx.size(); i++)
1644 if (vtx[i].IsCoinBase())
1645 return error("CheckBlock() : more than one coinbase");
1647 // Check transactions
1648 foreach(const CTransaction& tx, vtx)
1649 if (!tx.CheckTransaction())
1650 return error("CheckBlock() : CheckTransaction failed");
1652 // Check that it's not full of nonstandard transactions
1653 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1654 return error("CheckBlock() : too many nonstandard transactions");
1657 if (hashMerkleRoot != BuildMerkleTree())
1658 return error("CheckBlock() : hashMerkleRoot mismatch");
1663 bool CBlock::AcceptBlock()
1665 // Check for duplicate
1666 uint256 hash = GetHash();
1667 if (mapBlockIndex.count(hash))
1668 return error("AcceptBlock() : block already in mapBlockIndex");
1670 // Get prev block index
1671 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1672 if (mi == mapBlockIndex.end())
1673 return error("AcceptBlock() : prev block not found");
1674 CBlockIndex* pindexPrev = (*mi).second;
1675 int nHeight = pindexPrev->nHeight+1;
1677 // Check proof of work
1678 if (nBits != GetNextWorkRequired(pindexPrev))
1679 return error("AcceptBlock() : incorrect proof of work");
1681 // Check timestamp against prev
1682 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1683 return error("AcceptBlock() : block's timestamp is too early");
1685 // Check that all transactions are finalized
1686 foreach(const CTransaction& tx, vtx)
1687 if (!tx.IsFinal(nHeight, GetBlockTime()))
1688 return error("AcceptBlock() : contains a non-final transaction");
1690 // Check that the block chain matches the known block chain up to a checkpoint
1692 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1693 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1694 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1695 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1696 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))
1697 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1699 // Write block to history file
1700 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1701 return error("AcceptBlock() : out of disk space");
1702 unsigned int nFile = -1;
1703 unsigned int nBlockPos = 0;
1704 if (!WriteToDisk(nFile, nBlockPos))
1705 return error("AcceptBlock() : WriteToDisk failed");
1706 if (!AddToBlockIndex(nFile, nBlockPos))
1707 return error("AcceptBlock() : AddToBlockIndex failed");
1709 // Relay inventory, but don't relay old inventory during initial block download
1710 if (hashBestChain == hash)
1711 CRITICAL_BLOCK(cs_vNodes)
1712 foreach(CNode* pnode, vNodes)
1713 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1714 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1719 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1721 // Check for duplicate
1722 uint256 hash = pblock->GetHash();
1723 if (mapBlockIndex.count(hash))
1724 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1725 if (mapOrphanBlocks.count(hash))
1726 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1728 // Preliminary checks
1729 if (!pblock->CheckBlock())
1730 return error("ProcessBlock() : CheckBlock FAILED");
1732 // If don't already have its previous block, shunt it off to holding area until we get it
1733 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1735 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1736 CBlock* pblock2 = new CBlock(*pblock);
1737 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1738 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1740 // Ask this guy to fill in what we're missing
1742 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1747 if (!pblock->AcceptBlock())
1748 return error("ProcessBlock() : AcceptBlock FAILED");
1750 // Recursively process any orphan blocks that depended on this one
1751 vector<uint256> vWorkQueue;
1752 vWorkQueue.push_back(hash);
1753 for (int i = 0; i < vWorkQueue.size(); i++)
1755 uint256 hashPrev = vWorkQueue[i];
1756 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1757 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1760 CBlock* pblockOrphan = (*mi).second;
1761 if (pblockOrphan->AcceptBlock())
1762 vWorkQueue.push_back(pblockOrphan->GetHash());
1763 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1764 delete pblockOrphan;
1766 mapOrphanBlocksByPrev.erase(hashPrev);
1769 printf("ProcessBlock: ACCEPTED\n");
1780 template<typename Stream>
1781 bool ScanMessageStart(Stream& s)
1783 // Scan ahead to the next pchMessageStart, which should normally be immediately
1784 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1786 short prevmask = s.exceptions(0);
1787 const char* p = BEGIN(pchMessageStart);
1797 s.exceptions(prevmask);
1801 p = BEGIN(pchMessageStart);
1804 if (++p == END(pchMessageStart))
1807 s.exceptions(prevmask);
1816 s.exceptions(prevmask);
1821 bool CheckDiskSpace(uint64 nAdditionalBytes)
1823 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1825 // Check for 15MB because database could create another 10MB log file at any time
1826 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1829 string strMessage = _("Warning: Disk space is low ");
1830 strMiscWarning = strMessage;
1831 printf("*** %s\n", strMessage.c_str());
1832 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1833 CreateThread(Shutdown, NULL);
1839 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1843 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1846 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1848 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1857 static unsigned int nCurrentBlockFile = 1;
1859 FILE* AppendBlockFile(unsigned int& nFileRet)
1864 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1867 if (fseek(file, 0, SEEK_END) != 0)
1869 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1870 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1872 nFileRet = nCurrentBlockFile;
1876 nCurrentBlockFile++;
1880 bool LoadBlockIndex(bool fAllowNew)
1884 hashGenesisBlock = uint256("0x0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110");
1885 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1886 pchMessageStart[0] = 0xfa;
1887 pchMessageStart[1] = 0xbf;
1888 pchMessageStart[2] = 0xb5;
1889 pchMessageStart[3] = 0xda;
1896 if (!txdb.LoadBlockIndex())
1901 // Init with genesis block
1903 if (mapBlockIndex.empty())
1909 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1910 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1911 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1912 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1913 // vMerkleTree: 4a5e1e
1916 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1918 txNew.vin.resize(1);
1919 txNew.vout.resize(1);
1920 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1921 txNew.vout[0].nValue = 50 * COIN;
1922 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1924 block.vtx.push_back(txNew);
1925 block.hashPrevBlock = 0;
1926 block.hashMerkleRoot = block.BuildMerkleTree();
1928 block.nTime = 1231006505;
1929 block.nBits = 0x1d00ffff;
1930 block.nNonce = 2083236893;
1934 block.nTime = 1279232055;
1935 block.nBits = 0x1d07fff8;
1936 block.nNonce = 81622180;
1940 printf("%s\n", block.GetHash().ToString().c_str());
1941 printf("%s\n", hashGenesisBlock.ToString().c_str());
1942 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1943 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1945 assert(block.GetHash() == hashGenesisBlock);
1947 // Start new block file
1949 unsigned int nBlockPos;
1950 if (!block.WriteToDisk(nFile, nBlockPos))
1951 return error("LoadBlockIndex() : writing genesis block to disk failed");
1952 if (!block.AddToBlockIndex(nFile, nBlockPos))
1953 return error("LoadBlockIndex() : genesis block not accepted");
1961 void PrintBlockTree()
1963 // precompute tree structure
1964 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1965 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1967 CBlockIndex* pindex = (*mi).second;
1968 mapNext[pindex->pprev].push_back(pindex);
1970 //while (rand() % 3 == 0)
1971 // mapNext[pindex->pprev].push_back(pindex);
1974 vector<pair<int, CBlockIndex*> > vStack;
1975 vStack.push_back(make_pair(0, pindexGenesisBlock));
1978 while (!vStack.empty())
1980 int nCol = vStack.back().first;
1981 CBlockIndex* pindex = vStack.back().second;
1984 // print split or gap
1985 if (nCol > nPrevCol)
1987 for (int i = 0; i < nCol-1; i++)
1991 else if (nCol < nPrevCol)
1993 for (int i = 0; i < nCol; i++)
2000 for (int i = 0; i < nCol; i++)
2005 block.ReadFromDisk(pindex);
2006 printf("%d (%u,%u) %s %s tx %d",
2010 block.GetHash().ToString().substr(0,20).c_str(),
2011 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2014 CRITICAL_BLOCK(cs_mapWallet)
2016 if (mapWallet.count(block.vtx[0].GetHash()))
2018 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2019 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2025 // put the main timechain first
2026 vector<CBlockIndex*>& vNext = mapNext[pindex];
2027 for (int i = 0; i < vNext.size(); i++)
2029 if (vNext[i]->pnext)
2031 swap(vNext[0], vNext[i]);
2037 for (int i = 0; i < vNext.size(); i++)
2038 vStack.push_back(make_pair(nCol+i, vNext[i]));
2051 //////////////////////////////////////////////////////////////////////////////
2056 map<uint256, CAlert> mapAlerts;
2057 CCriticalSection cs_mapAlerts;
2059 string GetWarnings(string strFor)
2062 string strStatusBar;
2064 if (GetBoolArg("-testsafemode"))
2067 // Misc warnings like out of disk space and clock is wrong
2068 if (strMiscWarning != "")
2071 strStatusBar = strMiscWarning;
2074 // Longer invalid proof-of-work chain
2075 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2078 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2082 CRITICAL_BLOCK(cs_mapAlerts)
2084 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2086 const CAlert& alert = item.second;
2087 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2089 nPriority = alert.nPriority;
2090 strStatusBar = alert.strStatusBar;
2095 if (strFor == "statusbar")
2096 return strStatusBar;
2097 else if (strFor == "rpc")
2099 assert(("GetWarnings() : invalid parameter", false));
2103 bool CAlert::ProcessAlert()
2105 if (!CheckSignature())
2110 CRITICAL_BLOCK(cs_mapAlerts)
2112 // Cancel previous alerts
2113 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2115 const CAlert& alert = (*mi).second;
2118 printf("cancelling alert %d\n", alert.nID);
2119 mapAlerts.erase(mi++);
2121 else if (!alert.IsInEffect())
2123 printf("expiring alert %d\n", alert.nID);
2124 mapAlerts.erase(mi++);
2130 // Check if this alert has been cancelled
2131 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2133 const CAlert& alert = item.second;
2134 if (alert.Cancels(*this))
2136 printf("alert already cancelled by %d\n", alert.nID);
2142 mapAlerts.insert(make_pair(GetHash(), *this));
2145 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2157 //////////////////////////////////////////////////////////////////////////////
2163 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
2167 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2168 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2170 // Don't know what it is, just say we already got one
2177 // The message start string is designed to be unlikely to occur in normal data.
2178 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2179 // a large 4-byte int at any alignment.
2180 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2183 bool ProcessMessages(CNode* pfrom)
2185 CDataStream& vRecv = pfrom->vRecv;
2189 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2193 // (4) message start
2202 // Scan for message start
2203 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2204 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2205 if (vRecv.end() - pstart < nHeaderSize)
2207 if (vRecv.size() > nHeaderSize)
2209 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2210 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2214 if (pstart - vRecv.begin() > 0)
2215 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2216 vRecv.erase(vRecv.begin(), pstart);
2219 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2224 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2227 string strCommand = hdr.GetCommand();
2230 unsigned int nMessageSize = hdr.nMessageSize;
2231 if (nMessageSize > MAX_SIZE)
2233 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2236 if (nMessageSize > vRecv.size())
2238 // Rewind and wait for rest of message
2239 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2244 if (vRecv.GetVersion() >= 209)
2246 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2247 unsigned int nChecksum = 0;
2248 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2249 if (nChecksum != hdr.nChecksum)
2251 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2252 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2257 // Copy message to its own buffer
2258 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2259 vRecv.ignore(nMessageSize);
2265 CRITICAL_BLOCK(cs_main)
2266 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2270 catch (std::ios_base::failure& e)
2272 if (strstr(e.what(), "end of data"))
2274 // Allow exceptions from underlength message on vRecv
2275 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());
2277 else if (strstr(e.what(), "size too large"))
2279 // Allow exceptions from overlong size
2280 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2284 PrintExceptionContinue(&e, "ProcessMessage()");
2287 catch (std::exception& e) {
2288 PrintExceptionContinue(&e, "ProcessMessage()");
2290 PrintExceptionContinue(NULL, "ProcessMessage()");
2294 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2304 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2306 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2307 RandAddSeedPerfmon();
2309 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2310 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2311 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2313 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2321 if (strCommand == "version")
2323 // Each connection can only send one version message
2324 if (pfrom->nVersion != 0)
2331 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2332 if (pfrom->nVersion == 10300)
2333 pfrom->nVersion = 300;
2334 if (pfrom->nVersion >= 106 && !vRecv.empty())
2335 vRecv >> addrFrom >> nNonce;
2336 if (pfrom->nVersion >= 106 && !vRecv.empty())
2337 vRecv >> pfrom->strSubVer;
2338 if (pfrom->nVersion >= 209 && !vRecv.empty())
2339 vRecv >> pfrom->nStartingHeight;
2341 if (pfrom->nVersion == 0)
2344 // Disconnect if we connected to ourself
2345 if (nNonce == nLocalHostNonce && nNonce > 1)
2347 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2348 pfrom->fDisconnect = true;
2352 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2354 AddTimeData(pfrom->addr.ip, nTime);
2357 if (pfrom->nVersion >= 209)
2358 pfrom->PushMessage("verack");
2359 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2360 if (pfrom->nVersion < 209)
2361 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2363 if (!pfrom->fInbound)
2365 // Advertise our address
2366 if (addrLocalHost.IsRoutable() && !fUseProxy)
2368 CAddress addr(addrLocalHost);
2369 addr.nTime = GetAdjustedTime();
2370 pfrom->PushAddress(addr);
2373 // Get recent addresses
2374 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2376 pfrom->PushMessage("getaddr");
2377 pfrom->fGetAddr = true;
2381 // Ask the first connected node for block updates
2382 static int nAskedForBlocks;
2383 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2386 pfrom->PushGetBlocks(pindexBest, uint256(0));
2390 CRITICAL_BLOCK(cs_mapAlerts)
2391 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2392 item.second.RelayTo(pfrom);
2394 pfrom->fSuccessfullyConnected = true;
2396 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2400 else if (pfrom->nVersion == 0)
2402 // Must have a version message before anything else
2407 else if (strCommand == "verack")
2409 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2413 else if (strCommand == "addr")
2415 vector<CAddress> vAddr;
2418 // Don't want addr from older versions unless seeding
2419 if (pfrom->nVersion < 209)
2421 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2423 if (vAddr.size() > 1000)
2424 return error("message addr size() = %d", vAddr.size());
2426 // Store the new addresses
2427 int64 nNow = GetAdjustedTime();
2428 int64 nSince = nNow - 10 * 60;
2429 foreach(CAddress& addr, vAddr)
2433 // ignore IPv6 for now, since it isn't implemented anyway
2436 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2437 addr.nTime = nNow - 5 * 24 * 60 * 60;
2438 AddAddress(addr, 2 * 60 * 60);
2439 pfrom->AddAddressKnown(addr);
2440 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2442 // Relay to a limited number of other nodes
2443 CRITICAL_BLOCK(cs_vNodes)
2445 // Use deterministic randomness to send to the same nodes for 24 hours
2446 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2447 static uint256 hashSalt;
2449 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2450 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2451 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2452 multimap<uint256, CNode*> mapMix;
2453 foreach(CNode* pnode, vNodes)
2455 if (pnode->nVersion < 31402)
2457 unsigned int nPointer;
2458 memcpy(&nPointer, &pnode, sizeof(nPointer));
2459 uint256 hashKey = hashRand ^ nPointer;
2460 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2461 mapMix.insert(make_pair(hashKey, pnode));
2463 int nRelayNodes = 2;
2464 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2465 ((*mi).second)->PushAddress(addr);
2469 if (vAddr.size() < 1000)
2470 pfrom->fGetAddr = false;
2474 else if (strCommand == "inv")
2478 if (vInv.size() > 50000)
2479 return error("message inv size() = %d", vInv.size());
2482 foreach(const CInv& inv, vInv)
2486 pfrom->AddInventoryKnown(inv);
2488 bool fAlreadyHave = AlreadyHave(txdb, inv);
2489 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2493 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2494 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2496 // Track requests for our stuff
2497 CRITICAL_BLOCK(cs_mapRequestCount)
2499 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2500 if (mi != mapRequestCount.end())
2507 else if (strCommand == "getdata")
2511 if (vInv.size() > 50000)
2512 return error("message getdata size() = %d", vInv.size());
2514 foreach(const CInv& inv, vInv)
2518 printf("received getdata for: %s\n", inv.ToString().c_str());
2520 if (inv.type == MSG_BLOCK)
2522 // Send block from disk
2523 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2524 if (mi != mapBlockIndex.end())
2527 block.ReadFromDisk((*mi).second);
2528 pfrom->PushMessage("block", block);
2530 // Trigger them to send a getblocks request for the next batch of inventory
2531 if (inv.hash == pfrom->hashContinue)
2533 // Bypass PushInventory, this must send even if redundant,
2534 // and we want it right after the last block so they don't
2535 // wait for other stuff first.
2537 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2538 pfrom->PushMessage("inv", vInv);
2539 pfrom->hashContinue = 0;
2543 else if (inv.IsKnownType())
2545 // Send stream from relay memory
2546 CRITICAL_BLOCK(cs_mapRelay)
2548 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2549 if (mi != mapRelay.end())
2550 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2554 // Track requests for our stuff
2555 CRITICAL_BLOCK(cs_mapRequestCount)
2557 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2558 if (mi != mapRequestCount.end())
2565 else if (strCommand == "getblocks")
2567 CBlockLocator locator;
2569 vRecv >> locator >> hashStop;
2571 // Find the last block the caller has in the main chain
2572 CBlockIndex* pindex = locator.GetBlockIndex();
2574 // Send the rest of the chain
2576 pindex = pindex->pnext;
2577 int nLimit = 500 + locator.GetDistanceBack();
2578 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2579 for (; pindex; pindex = pindex->pnext)
2581 if (pindex->GetBlockHash() == hashStop)
2583 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2586 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2589 // When this block is requested, we'll send an inv that'll make them
2590 // getblocks the next batch of inventory.
2591 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2592 pfrom->hashContinue = pindex->GetBlockHash();
2599 else if (strCommand == "getheaders")
2601 CBlockLocator locator;
2603 vRecv >> locator >> hashStop;
2605 CBlockIndex* pindex = NULL;
2606 if (locator.IsNull())
2608 // If locator is null, return the hashStop block
2609 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2610 if (mi == mapBlockIndex.end())
2612 pindex = (*mi).second;
2616 // Find the last block the caller has in the main chain
2617 pindex = locator.GetBlockIndex();
2619 pindex = pindex->pnext;
2622 vector<CBlock> vHeaders;
2623 int nLimit = 2000 + locator.GetDistanceBack();
2624 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2625 for (; pindex; pindex = pindex->pnext)
2627 vHeaders.push_back(pindex->GetBlockHeader());
2628 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2631 pfrom->PushMessage("headers", vHeaders);
2635 else if (strCommand == "tx")
2637 vector<uint256> vWorkQueue;
2638 CDataStream vMsg(vRecv);
2642 CInv inv(MSG_TX, tx.GetHash());
2643 pfrom->AddInventoryKnown(inv);
2645 bool fMissingInputs = false;
2646 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2648 AddToWalletIfMine(tx, NULL);
2649 RelayMessage(inv, vMsg);
2650 mapAlreadyAskedFor.erase(inv);
2651 vWorkQueue.push_back(inv.hash);
2653 // Recursively process any orphan transactions that depended on this one
2654 for (int i = 0; i < vWorkQueue.size(); i++)
2656 uint256 hashPrev = vWorkQueue[i];
2657 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2658 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2661 const CDataStream& vMsg = *((*mi).second);
2663 CDataStream(vMsg) >> tx;
2664 CInv inv(MSG_TX, tx.GetHash());
2666 if (tx.AcceptToMemoryPool(true))
2668 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2669 AddToWalletIfMine(tx, NULL);
2670 RelayMessage(inv, vMsg);
2671 mapAlreadyAskedFor.erase(inv);
2672 vWorkQueue.push_back(inv.hash);
2677 foreach(uint256 hash, vWorkQueue)
2678 EraseOrphanTx(hash);
2680 else if (fMissingInputs)
2682 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2688 else if (strCommand == "block")
2693 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2696 CInv inv(MSG_BLOCK, block.GetHash());
2697 pfrom->AddInventoryKnown(inv);
2699 if (ProcessBlock(pfrom, &block))
2700 mapAlreadyAskedFor.erase(inv);
2704 else if (strCommand == "getaddr")
2706 // Nodes rebroadcast an addr every 24 hours
2707 pfrom->vAddrToSend.clear();
2708 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2709 CRITICAL_BLOCK(cs_mapAddresses)
2711 unsigned int nCount = 0;
2712 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2714 const CAddress& addr = item.second;
2715 if (addr.nTime > nSince)
2718 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2720 const CAddress& addr = item.second;
2721 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2722 pfrom->PushAddress(addr);
2728 else if (strCommand == "checkorder")
2733 if (!GetBoolArg("-allowreceivebyip"))
2735 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2742 /// we have a chance to check the order here
2744 // Keep giving the same key to the same ip until they use it
2745 if (!mapReuseKey.count(pfrom->addr.ip))
2746 mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();
2748 // Send back approval of order and pubkey to use
2749 CScript scriptPubKey;
2750 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2751 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2755 else if (strCommand == "submitorder")
2760 if (!GetBoolArg("-allowreceivebyip"))
2762 pfrom->PushMessage("reply", hashReply, (int)2);
2768 wtxNew.fFromMe = false;
2771 if (!wtxNew.AcceptWalletTransaction())
2773 pfrom->PushMessage("reply", hashReply, (int)1);
2774 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2776 wtxNew.fTimeReceivedIsTxTime = true;
2777 AddToWallet(wtxNew);
2778 wtxNew.RelayWalletTransaction();
2779 mapReuseKey.erase(pfrom->addr.ip);
2781 // Send back confirmation
2782 pfrom->PushMessage("reply", hashReply, (int)0);
2786 else if (strCommand == "reply")
2791 CRequestTracker tracker;
2792 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2794 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2795 if (mi != pfrom->mapRequests.end())
2797 tracker = (*mi).second;
2798 pfrom->mapRequests.erase(mi);
2801 if (!tracker.IsNull())
2802 tracker.fn(tracker.param1, vRecv);
2806 else if (strCommand == "ping")
2811 else if (strCommand == "alert")
2816 if (alert.ProcessAlert())
2819 pfrom->setKnown.insert(alert.GetHash());
2820 CRITICAL_BLOCK(cs_vNodes)
2821 foreach(CNode* pnode, vNodes)
2822 alert.RelayTo(pnode);
2829 // Ignore unknown commands for extensibility
2833 // Update the last seen time for this node's address
2834 if (pfrom->fNetworkNode)
2835 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2836 AddressCurrentlyConnected(pfrom->addr);
2850 bool SendMessages(CNode* pto, bool fSendTrickle)
2852 CRITICAL_BLOCK(cs_main)
2854 // Don't send anything until we get their version message
2855 if (pto->nVersion == 0)
2859 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2860 pto->PushMessage("ping");
2862 // Resend wallet transactions that haven't gotten in a block yet
2863 ResendWalletTransactions();
2865 // Address refresh broadcast
2866 static int64 nLastRebroadcast;
2867 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2869 nLastRebroadcast = GetTime();
2870 CRITICAL_BLOCK(cs_vNodes)
2872 foreach(CNode* pnode, vNodes)
2874 // Periodically clear setAddrKnown to allow refresh broadcasts
2875 pnode->setAddrKnown.clear();
2877 // Rebroadcast our address
2878 if (addrLocalHost.IsRoutable() && !fUseProxy)
2880 CAddress addr(addrLocalHost);
2881 addr.nTime = GetAdjustedTime();
2882 pnode->PushAddress(addr);
2888 // Clear out old addresses periodically so it's not too much work at once
2889 static int64 nLastClear;
2890 if (nLastClear == 0)
2891 nLastClear = GetTime();
2892 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2894 nLastClear = GetTime();
2895 CRITICAL_BLOCK(cs_mapAddresses)
2898 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2899 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2900 mi != mapAddresses.end();)
2902 const CAddress& addr = (*mi).second;
2903 if (addr.nTime < nSince)
2905 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2907 addrdb.EraseAddress(addr);
2908 mapAddresses.erase(mi++);
2922 vector<CAddress> vAddr;
2923 vAddr.reserve(pto->vAddrToSend.size());
2924 foreach(const CAddress& addr, pto->vAddrToSend)
2926 // returns true if wasn't already contained in the set
2927 if (pto->setAddrKnown.insert(addr).second)
2929 vAddr.push_back(addr);
2930 // receiver rejects addr messages larger than 1000
2931 if (vAddr.size() >= 1000)
2933 pto->PushMessage("addr", vAddr);
2938 pto->vAddrToSend.clear();
2940 pto->PushMessage("addr", vAddr);
2945 // Message: inventory
2948 vector<CInv> vInvWait;
2949 CRITICAL_BLOCK(pto->cs_inventory)
2951 vInv.reserve(pto->vInventoryToSend.size());
2952 vInvWait.reserve(pto->vInventoryToSend.size());
2953 foreach(const CInv& inv, pto->vInventoryToSend)
2955 if (pto->setInventoryKnown.count(inv))
2958 // trickle out tx inv to protect privacy
2959 if (inv.type == MSG_TX && !fSendTrickle)
2961 // 1/4 of tx invs blast to all immediately
2962 static uint256 hashSalt;
2964 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2965 uint256 hashRand = inv.hash ^ hashSalt;
2966 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2967 bool fTrickleWait = ((hashRand & 3) != 0);
2969 // always trickle our own transactions
2972 TRY_CRITICAL_BLOCK(cs_mapWallet)
2974 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2975 if (mi != mapWallet.end())
2977 CWalletTx& wtx = (*mi).second;
2979 fTrickleWait = true;
2986 vInvWait.push_back(inv);
2991 // returns true if wasn't already contained in the set
2992 if (pto->setInventoryKnown.insert(inv).second)
2994 vInv.push_back(inv);
2995 if (vInv.size() >= 1000)
2997 pto->PushMessage("inv", vInv);
3002 pto->vInventoryToSend = vInvWait;
3005 pto->PushMessage("inv", vInv);
3011 vector<CInv> vGetData;
3012 int64 nNow = GetTime() * 1000000;
3014 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3016 const CInv& inv = (*pto->mapAskFor.begin()).second;
3017 if (!AlreadyHave(txdb, inv))
3019 printf("sending getdata: %s\n", inv.ToString().c_str());
3020 vGetData.push_back(inv);
3021 if (vGetData.size() >= 1000)
3023 pto->PushMessage("getdata", vGetData);
3027 pto->mapAskFor.erase(pto->mapAskFor.begin());
3029 if (!vGetData.empty())
3030 pto->PushMessage("getdata", vGetData);
3049 //////////////////////////////////////////////////////////////////////////////
3054 void GenerateBitcoins(bool fGenerate)
3056 if (fGenerateBitcoins != fGenerate)
3058 fGenerateBitcoins = fGenerate;
3059 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3062 if (fGenerateBitcoins)
3064 int nProcessors = boost::thread::hardware_concurrency();
3065 printf("%d processors\n", nProcessors);
3066 if (nProcessors < 1)
3068 if (fLimitProcessors && nProcessors > nLimitProcessors)
3069 nProcessors = nLimitProcessors;
3070 int nAddThreads = nProcessors - vnThreadsRunning[3];
3071 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3072 for (int i = 0; i < nAddThreads; i++)
3074 if (!CreateThread(ThreadBitcoinMiner, NULL))
3075 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3081 void ThreadBitcoinMiner(void* parg)
3085 vnThreadsRunning[3]++;
3087 vnThreadsRunning[3]--;
3089 catch (std::exception& e) {
3090 vnThreadsRunning[3]--;
3091 PrintException(&e, "ThreadBitcoinMiner()");
3093 vnThreadsRunning[3]--;
3094 PrintException(NULL, "ThreadBitcoinMiner()");
3096 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3098 if (vnThreadsRunning[3] == 0)
3100 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3103 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
3104 void CallCPUID(int in, int& aret, int& cret)
3108 "mov %2, %%eax; " // in into eax
3110 "mov %%eax, %0;" // eax into a
3111 "mov %%ecx, %1;" // ecx into c
3112 :"=r"(a),"=r"(c) /* output */
3113 :"r"(in) /* input */
3114 :"%eax","%ecx" /* clobbered register */
3120 bool Detect128BitSSE2()
3123 CallCPUID(0, a, nBrand);
3124 bool fIntel = (nBrand == 0x6c65746e); // ntel
3125 bool fAMD = (nBrand == 0x444d4163); // cAMD
3129 unsigned int nStepping : 4;
3130 unsigned int nModel : 4;
3131 unsigned int nFamily : 4;
3132 unsigned int nProcessorType : 2;
3133 unsigned int nUnused : 2;
3134 unsigned int nExtendedModel : 4;
3135 unsigned int nExtendedFamily : 8;
3139 memcpy(&cpu, &a, sizeof(cpu));
3140 int nFamily = cpu.nExtendedFamily + cpu.nFamily;
3141 int nModel = cpu.nExtendedModel*16 + cpu.nModel;
3143 // We need Intel Nehalem or AMD K10 or better for 128bit SSE2
3144 // Nehalem = i3/i5/i7 and some Xeon
3145 // K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II
3146 // Intel Core i5 family 6, model 26 or 30
3147 // Intel Core i7 family 6, model 26 or 30
3148 // Intel Core i3 family 6, model 37
3149 // AMD Phenom family 16, model 10
3150 bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >= 60026) ||
3151 (fAMD && nFamily * 10000 + nModel >= 160010));
3153 // AMD reports a lower model number in 64-bit mode
3154 if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)
3157 static bool fPrinted;
3161 printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);
3166 bool Detect128BitSSE2() { return false; }
3169 int FormatHashBlocks(void* pbuffer, unsigned int len)
3171 unsigned char* pdata = (unsigned char*)pbuffer;
3172 unsigned int blocks = 1 + ((len + 8) / 64);
3173 unsigned char* pend = pdata + 64 * blocks;
3174 memset(pdata + len, 0, 64 * blocks - len);
3176 unsigned int bits = len * 8;
3177 pend[-1] = (bits >> 0) & 0xff;
3178 pend[-2] = (bits >> 8) & 0xff;
3179 pend[-3] = (bits >> 16) & 0xff;
3180 pend[-4] = (bits >> 24) & 0xff;
3184 using CryptoPP::ByteReverse;
3186 static const unsigned int pSHA256InitState[8] =
3187 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3189 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3191 memcpy(pstate, pinit, 32);
3192 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
3196 // ScanHash scans nonces looking for a hash with at least some zero bits.
3197 // It operates on big endian data. Caller does the byte reversing.
3198 // All input buffers are 16-byte aligned. nNonce is usually preserved
3199 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3200 // the block is rebuilt and nNonce starts over at zero.
3202 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3204 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3208 // Hash pdata using pmidstate as the starting state into
3209 // preformatted buffer phash1, then hash phash1 into phash
3211 SHA256Transform(phash1, pdata, pmidstate);
3212 SHA256Transform(phash, phash1, pSHA256InitState);
3214 // Return the nonce if the hash has at least some zero bits,
3215 // caller will check if it has enough to reach the target
3216 if (((unsigned short*)phash)[14] == 0)
3219 // If nothing found after trying for a while, return -1
3220 if ((nNonce & 0xffff) == 0)
3222 nHashesDone = 0xffff+1;
3228 extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);
3236 set<uint256> setDependsOn;
3239 COrphan(CTransaction* ptxIn)
3247 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3248 foreach(uint256 hash, setDependsOn)
3249 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3254 CBlock* CreateNewBlock(CReserveKey& reservekey)
3256 CBlockIndex* pindexPrev = pindexBest;
3259 auto_ptr<CBlock> pblock(new CBlock());
3263 // Create coinbase tx
3265 txNew.vin.resize(1);
3266 txNew.vin[0].prevout.SetNull();
3267 txNew.vout.resize(1);
3268 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3270 // Add our coinbase tx as first transaction
3271 pblock->vtx.push_back(txNew);
3273 // Collect memory pool transactions into the block
3275 CRITICAL_BLOCK(cs_main)
3276 CRITICAL_BLOCK(cs_mapTransactions)
3280 // Priority order to process transactions
3281 list<COrphan> vOrphan; // list memory doesn't move
3282 map<uint256, vector<COrphan*> > mapDependers;
3283 multimap<double, CTransaction*> mapPriority;
3284 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3286 CTransaction& tx = (*mi).second;
3287 if (tx.IsCoinBase() || !tx.IsFinal())
3290 COrphan* porphan = NULL;
3291 double dPriority = 0;
3292 foreach(const CTxIn& txin, tx.vin)
3294 // Read prev transaction
3295 CTransaction txPrev;
3297 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3299 // Has to wait for dependencies
3302 // Use list for automatic deletion
3303 vOrphan.push_back(COrphan(&tx));
3304 porphan = &vOrphan.back();
3306 mapDependers[txin.prevout.hash].push_back(porphan);
3307 porphan->setDependsOn.insert(txin.prevout.hash);
3310 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3312 // Read block header
3315 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
3317 map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(block.GetHash());
3318 if (it != mapBlockIndex.end())
3320 CBlockIndex* pindex = (*it).second;
3321 if (pindex->IsInMainChain())
3322 nConf = 1 + nBestHeight - pindex->nHeight;
3326 dPriority += (double)nValueIn * nConf;
3328 if (fDebug && GetBoolArg("-printpriority"))
3329 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3332 // Priority is sum(valuein * age) / txsize
3333 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3336 porphan->dPriority = dPriority;
3338 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3340 if (fDebug && GetBoolArg("-printpriority"))
3342 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3349 // Collect transactions into block
3350 map<uint256, CTxIndex> mapTestPool;
3351 uint64 nBlockSize = 1000;
3352 int nBlockSigOps = 100;
3353 while (!mapPriority.empty())
3355 // Take highest priority transaction off priority queue
3356 double dPriority = -(*mapPriority.begin()).first;
3357 CTransaction& tx = *(*mapPriority.begin()).second;
3358 mapPriority.erase(mapPriority.begin());
3361 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3362 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3364 int nTxSigOps = tx.GetSigOpCount();
3365 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3368 // Transaction fee required depends on block size
3369 bool fAllowFree = (nBlockSize + nTxSize < 4000 || dPriority > COIN * 144 / 250);
3370 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
3372 // Connecting shouldn't fail due to dependency on other memory pool transactions
3373 // because we're already processing them in order of dependency
3374 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3375 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3377 swap(mapTestPool, mapTestPoolTmp);
3380 pblock->vtx.push_back(tx);
3381 nBlockSize += nTxSize;
3382 nBlockSigOps += nTxSigOps;
3384 // Add transactions that depend on this one to the priority queue
3385 uint256 hash = tx.GetHash();
3386 if (mapDependers.count(hash))
3388 foreach(COrphan* porphan, mapDependers[hash])
3390 if (!porphan->setDependsOn.empty())
3392 porphan->setDependsOn.erase(hash);
3393 if (porphan->setDependsOn.empty())
3394 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3400 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3403 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3404 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3405 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3406 pblock->nBits = GetNextWorkRequired(pindexPrev);
3409 return pblock.release();
3413 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
3415 // Update nExtraNonce
3416 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3417 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3422 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
3423 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3427 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3430 // Prebuild hash buffers
3437 uint256 hashPrevBlock;
3438 uint256 hashMerkleRoot;
3441 unsigned int nNonce;
3444 unsigned char pchPadding0[64];
3446 unsigned char pchPadding1[64];
3449 memset(&tmp, 0, sizeof(tmp));
3451 tmp.block.nVersion = pblock->nVersion;
3452 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3453 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3454 tmp.block.nTime = pblock->nTime;
3455 tmp.block.nBits = pblock->nBits;
3456 tmp.block.nNonce = pblock->nNonce;
3458 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3459 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3461 // Byte swap all the input buffer
3462 for (int i = 0; i < sizeof(tmp)/4; i++)
3463 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3465 // Precalc the first half of the first hash, which stays constant
3466 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3468 memcpy(pdata, &tmp.block, 128);
3469 memcpy(phash1, &tmp.hash1, 64);
3473 bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
3475 uint256 hash = pblock->GetHash();
3476 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3478 if (hash > hashTarget)
3482 printf("BitcoinMiner:\n");
3483 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3485 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3486 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3489 CRITICAL_BLOCK(cs_main)
3491 if (pblock->hashPrevBlock != hashBestChain)
3492 return error("BitcoinMiner : generated block is stale");
3494 // Remove key from key pool
3495 reservekey.KeepKey();
3497 // Track how many getdata requests this block gets
3498 CRITICAL_BLOCK(cs_mapRequestCount)
3499 mapRequestCount[pblock->GetHash()] = 0;
3501 // Process this block the same as if we had received it from another node
3502 if (!ProcessBlock(NULL, pblock))
3503 return error("BitcoinMiner : ProcessBlock, block not accepted");
3513 printf("BitcoinMiner started\n");
3514 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3515 bool f4WaySSE2 = Detect128BitSSE2();
3516 if (mapArgs.count("-4way"))
3517 f4WaySSE2 = GetBoolArg(mapArgs["-4way"]);
3519 // Each thread has its own key and counter
3520 CReserveKey reservekey;
3521 unsigned int nExtraNonce = 0;
3522 int64 nPrevTime = 0;
3524 while (fGenerateBitcoins)
3526 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3530 while (vNodes.empty() || IsInitialBlockDownload())
3535 if (!fGenerateBitcoins)
3543 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3544 CBlockIndex* pindexPrev = pindexBest;
3546 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3549 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
3551 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3555 // Prebuild hash buffers
3557 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3558 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3559 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3561 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3563 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3564 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3570 int64 nStart = GetTime();
3571 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3573 uint256& hash = *alignup<16>(hashbuf);
3576 unsigned int nHashesDone = 0;
3577 unsigned int nNonceFound;
3581 // tcatm's 4-way 128-bit SSE2 SHA-256
3582 nNonceFound = ScanHash_4WaySSE2(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
3586 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
3588 // Check if something found
3589 if (nNonceFound != -1)
3591 for (int i = 0; i < sizeof(hash)/4; i++)
3592 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3594 if (hash <= hashTarget)
3597 pblock->nNonce = ByteReverse(nNonceFound);
3598 assert(hash == pblock->GetHash());
3600 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3601 CheckWork(pblock.get(), reservekey);
3602 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3608 static int64 nHashCounter;
3609 if (nHPSTimerStart == 0)
3611 nHPSTimerStart = GetTimeMillis();
3615 nHashCounter += nHashesDone;
3616 if (GetTimeMillis() - nHPSTimerStart > 4000)
3618 static CCriticalSection cs;
3621 if (GetTimeMillis() - nHPSTimerStart > 4000)
3623 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3624 nHPSTimerStart = GetTimeMillis();
3626 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3627 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3628 static int64 nLogTime;
3629 if (GetTime() - nLogTime > 30 * 60)
3631 nLogTime = GetTime();
3632 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3633 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3639 // Check for stop or if block needs to be rebuilt
3642 if (!fGenerateBitcoins)
3644 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3648 if (nBlockNonce >= 0xffff0000)
3650 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3652 if (pindexPrev != pindexBest)
3655 // Update nTime every few seconds
3656 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3657 nBlockTime = ByteReverse(pblock->nTime);
3679 //////////////////////////////////////////////////////////////////////////////
3687 int64 nStart = GetTimeMillis();
3690 CRITICAL_BLOCK(cs_mapWallet)
3692 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3694 CWalletTx* pcoin = &(*it).second;
3695 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3697 nTotal += pcoin->GetCredit();
3701 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3706 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<CWalletTx*>& setCoinsRet)
3708 setCoinsRet.clear();
3710 // List of values less than target
3711 int64 nLowestLarger = INT64_MAX;
3712 CWalletTx* pcoinLowestLarger = NULL;
3713 vector<pair<int64, CWalletTx*> > vValue;
3714 int64 nTotalLower = 0;
3716 CRITICAL_BLOCK(cs_mapWallet)
3718 vector<CWalletTx*> vCoins;
3719 vCoins.reserve(mapWallet.size());
3720 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3721 vCoins.push_back(&(*it).second);
3722 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3724 foreach(CWalletTx* pcoin, vCoins)
3726 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3729 int nDepth = pcoin->GetDepthInMainChain();
3730 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
3733 int64 n = pcoin->GetCredit();
3736 if (n < nTargetValue)
3738 vValue.push_back(make_pair(n, pcoin));
3741 else if (n == nTargetValue)
3743 setCoinsRet.insert(pcoin);
3746 else if (n < nLowestLarger)
3749 pcoinLowestLarger = pcoin;
3754 if (nTotalLower < nTargetValue)
3756 if (pcoinLowestLarger == NULL)
3758 setCoinsRet.insert(pcoinLowestLarger);
3762 // Solve subset sum by stochastic approximation
3763 sort(vValue.rbegin(), vValue.rend());
3764 vector<char> vfIncluded;
3765 vector<char> vfBest(vValue.size(), true);
3766 int64 nBest = nTotalLower;
3768 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3770 vfIncluded.assign(vValue.size(), false);
3772 bool fReachedTarget = false;
3773 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3775 for (int i = 0; i < vValue.size(); i++)
3777 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3779 nTotal += vValue[i].first;
3780 vfIncluded[i] = true;
3781 if (nTotal >= nTargetValue)
3783 fReachedTarget = true;
3787 vfBest = vfIncluded;
3789 nTotal -= vValue[i].first;
3790 vfIncluded[i] = false;
3797 // If the next larger is still closer, return it
3798 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
3799 setCoinsRet.insert(pcoinLowestLarger);
3802 for (int i = 0; i < vValue.size(); i++)
3804 setCoinsRet.insert(vValue[i].second);
3807 printf("SelectCoins() best subset: ");
3808 for (int i = 0; i < vValue.size(); i++)
3810 printf("%s ", FormatMoney(vValue[i].first).c_str());
3811 printf("total %s\n", FormatMoney(nBest).c_str());
3817 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
3819 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet) ||
3820 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet) ||
3821 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet));
3827 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3829 CRITICAL_BLOCK(cs_main)
3831 // txdb must be opened before the mapWallet lock
3833 CRITICAL_BLOCK(cs_mapWallet)
3835 nFeeRet = nTransactionFee;
3839 wtxNew.vout.clear();
3840 wtxNew.fFromMe = true;
3843 int64 nValueOut = nValue;
3844 int64 nTotalValue = nValue + nFeeRet;
3846 // Choose coins to use
3847 set<CWalletTx*> setCoins;
3848 if (!SelectCoins(nTotalValue, setCoins))
3851 foreach(CWalletTx* pcoin, setCoins)
3852 nValueIn += pcoin->GetCredit();
3854 // Fill a vout to the payee
3855 bool fChangeFirst = GetRand(2);
3857 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3859 // Fill a vout back to self with any change
3860 int64 nChange = nValueIn - nTotalValue;
3861 if (nChange >= CENT)
3863 // Note: We use a new key here to keep it from being obvious which side is the change.
3864 // The drawback is that by not reusing a previous key, the change may be lost if a
3865 // backup is restored, if the backup doesn't have the new private key for the change.
3866 // If we reused the old key, it would be possible to add code to look for and
3867 // rediscover unknown transactions that were written with keys of ours to recover
3868 // post-backup change.
3870 // Reserve a new key pair from key pool
3871 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3872 assert(mapKeys.count(vchPubKey));
3874 // Fill a vout to ourself, using same address type as the payment
3875 CScript scriptChange;
3876 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3877 scriptChange.SetBitcoinAddress(vchPubKey);
3879 scriptChange << vchPubKey << OP_CHECKSIG;
3880 wtxNew.vout.push_back(CTxOut(nChange, scriptChange));
3883 reservekey.ReturnKey();
3885 // Fill a vout to the payee
3887 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3890 foreach(CWalletTx* pcoin, setCoins)
3891 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3892 if (pcoin->vout[nOut].IsMine())
3893 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3897 foreach(CWalletTx* pcoin, setCoins)
3898 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3899 if (pcoin->vout[nOut].IsMine())
3900 if (!SignSignature(*pcoin, wtxNew, nIn++))
3904 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
3905 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
3908 // Check that enough fee is included
3909 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
3910 int64 nMinFee = wtxNew.GetMinFee();
3911 if (nFeeRet < max(nPayFee, nMinFee))
3913 nFeeRet = max(nPayFee, nMinFee);
3917 // Fill vtxPrev by copying from previous transactions vtxPrev
3918 wtxNew.AddSupportingTransactions(txdb);
3919 wtxNew.fTimeReceivedIsTxTime = true;
3928 // Call after CreateTransaction unless you want to abort
3929 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3931 CRITICAL_BLOCK(cs_main)
3933 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3934 CRITICAL_BLOCK(cs_mapWallet)
3936 // This is only to keep the database open to defeat the auto-flush for the
3937 // duration of this scope. This is the only place where this optimization
3938 // maybe makes sense; please don't do it anywhere else.
3939 CWalletDB walletdb("r");
3941 // Take key pair from key pool so it won't be used again
3942 reservekey.KeepKey();
3944 // Add tx to wallet, because if it has change it's also ours,
3945 // otherwise just for transaction history.
3946 AddToWallet(wtxNew);
3948 // Mark old coins as spent
3949 set<CWalletTx*> setCoins;
3950 foreach(const CTxIn& txin, wtxNew.vin)
3951 setCoins.insert(&mapWallet[txin.prevout.hash]);
3952 foreach(CWalletTx* pcoin, setCoins)
3954 pcoin->fSpent = true;
3955 pcoin->WriteToDisk();
3956 vWalletUpdated.push_back(pcoin->GetHash());
3960 // Track how many getdata requests our transaction gets
3961 CRITICAL_BLOCK(cs_mapRequestCount)
3962 mapRequestCount[wtxNew.GetHash()] = 0;
3965 if (!wtxNew.AcceptToMemoryPool())
3967 // This must not fail. The transaction has already been signed and recorded.
3968 printf("CommitTransaction() : Error: Transaction not valid");
3971 wtxNew.RelayWalletTransaction();
3980 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3982 CRITICAL_BLOCK(cs_main)
3984 CReserveKey reservekey;
3986 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
3989 if (nValue + nFeeRequired > GetBalance())
3990 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3992 strError = _("Error: Transaction creation failed ");
3993 printf("SendMoney() : %s", strError.c_str());
3997 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
4000 if (!CommitTransaction(wtxNew, reservekey))
4001 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.");
4009 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
4013 return _("Invalid amount");
4014 if (nValue + nTransactionFee > GetBalance())
4015 return _("Insufficient funds");
4017 // Parse bitcoin address
4018 CScript scriptPubKey;
4019 if (!scriptPubKey.SetBitcoinAddress(strAddress))
4020 return _("Invalid bitcoin address");
4022 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);