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);
446 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
447 this->GetHash().ToString().c_str());
448 address = " unknown ";
451 // Don't report 'change' txouts
452 if (nDebit > 0 && txout.IsChange())
456 listSent.push_back(make_pair(address, txout.nValue));
459 listReceived.push_back(make_pair(address, txout.nValue));
464 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
465 int64& nSent, int64& nFee) const
467 nGenerated = nReceived = nSent = nFee = 0;
469 int64 allGenerated, allFee;
470 allGenerated = allFee = 0;
471 string strSentAccount;
472 list<pair<string, int64> > listReceived;
473 list<pair<string, int64> > listSent;
474 GetAmounts(allGenerated, listReceived, listSent, allFee, strSentAccount);
476 if (strAccount == "")
477 nGenerated = allGenerated;
478 if (strAccount == strSentAccount)
480 foreach(const PAIRTYPE(string,int64)& s, listSent)
484 CRITICAL_BLOCK(cs_mapAddressBook)
486 foreach(const PAIRTYPE(string,int64)& r, listReceived)
488 if (mapAddressBook.count(r.first))
490 if (mapAddressBook[r.first] == strAccount)
492 nReceived += r.second;
495 else if (strAccount.empty())
497 nReceived += r.second;
505 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
517 // Load the block this tx is in
519 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
521 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
526 // Update the tx's hashBlock
527 hashBlock = pblock->GetHash();
529 // Locate the transaction
530 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
531 if (pblock->vtx[nIndex] == *(CTransaction*)this)
533 if (nIndex == pblock->vtx.size())
535 vMerkleBranch.clear();
537 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
541 // Fill in merkle branch
542 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
545 // Is the tx in a block that's in the main chain
546 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
547 if (mi == mapBlockIndex.end())
549 CBlockIndex* pindex = (*mi).second;
550 if (!pindex || !pindex->IsInMainChain())
553 return pindexBest->nHeight - pindex->nHeight + 1;
558 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
562 const int COPY_DEPTH = 3;
563 if (SetMerkleBranch() < COPY_DEPTH)
565 vector<uint256> vWorkQueue;
566 foreach(const CTxIn& txin, vin)
567 vWorkQueue.push_back(txin.prevout.hash);
569 // This critsect is OK because txdb is already open
570 CRITICAL_BLOCK(cs_mapWallet)
572 map<uint256, const CMerkleTx*> mapWalletPrev;
573 set<uint256> setAlreadyDone;
574 for (int i = 0; i < vWorkQueue.size(); i++)
576 uint256 hash = vWorkQueue[i];
577 if (setAlreadyDone.count(hash))
579 setAlreadyDone.insert(hash);
582 if (mapWallet.count(hash))
584 tx = mapWallet[hash];
585 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
586 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
588 else if (mapWalletPrev.count(hash))
590 tx = *mapWalletPrev[hash];
592 else if (!fClient && txdb.ReadDiskTx(hash, tx))
598 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
602 int nDepth = tx.SetMerkleBranch();
603 vtxPrev.push_back(tx);
605 if (nDepth < COPY_DEPTH)
606 foreach(const CTxIn& txin, tx.vin)
607 vWorkQueue.push_back(txin.prevout.hash);
612 reverse(vtxPrev.begin(), vtxPrev.end());
625 bool CTransaction::CheckTransaction() const
627 // Basic checks that don't depend on any context
628 if (vin.empty() || vout.empty())
629 return error("CTransaction::CheckTransaction() : vin or vout empty");
632 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
633 return error("CTransaction::CheckTransaction() : size limits failed");
635 // Check for negative or overflow output values
637 foreach(const CTxOut& txout, vout)
639 if (txout.nValue < 0)
640 return error("CTransaction::CheckTransaction() : txout.nValue negative");
641 if (txout.nValue > MAX_MONEY)
642 return error("CTransaction::CheckTransaction() : txout.nValue too high");
643 nValueOut += txout.nValue;
644 if (!MoneyRange(nValueOut))
645 return error("CTransaction::CheckTransaction() : txout total out of range");
650 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
651 return error("CTransaction::CheckTransaction() : coinbase script size");
655 foreach(const CTxIn& txin, vin)
656 if (txin.prevout.IsNull())
657 return error("CTransaction::CheckTransaction() : prevout is null");
663 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
666 *pfMissingInputs = false;
668 if (!CheckTransaction())
669 return error("AcceptToMemoryPool() : CheckTransaction failed");
671 // Coinbase is only valid in a block, not as a loose transaction
673 return error("AcceptToMemoryPool() : coinbase as individual tx");
675 // To help v0.1.5 clients who would see it as a negative number
676 if ((int64)nLockTime > INT_MAX)
677 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
680 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
681 if (GetSigOpCount() > 2 || nSize < 100)
682 return error("AcceptToMemoryPool() : nonstandard transaction");
684 // Rather not work on nonstandard transactions
686 return error("AcceptToMemoryPool() : nonstandard transaction type");
688 // Do we already have it?
689 uint256 hash = GetHash();
690 CRITICAL_BLOCK(cs_mapTransactions)
691 if (mapTransactions.count(hash))
694 if (txdb.ContainsTx(hash))
697 // Check for conflicts with in-memory transactions
698 CTransaction* ptxOld = NULL;
699 for (int i = 0; i < vin.size(); i++)
701 COutPoint outpoint = vin[i].prevout;
702 if (mapNextTx.count(outpoint))
704 // Disable replacement feature for now
707 // Allow replacing with a newer version of the same transaction
710 ptxOld = mapNextTx[outpoint].ptx;
711 if (ptxOld->IsFinal())
713 if (!IsNewerThan(*ptxOld))
715 for (int i = 0; i < vin.size(); i++)
717 COutPoint outpoint = vin[i].prevout;
718 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
727 // Check against previous transactions
728 map<uint256, CTxIndex> mapUnused;
730 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
733 *pfMissingInputs = true;
734 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
737 // Don't accept it if it can't get into a block
738 if (nFees < GetMinFee(1000))
739 return error("AcceptToMemoryPool() : not enough fees");
741 // Limit free transactions per 10 minutes
742 if (nFees < CENT && GetBoolArg("-limitfreerelay"))
744 static int64 nNextReset;
745 static int64 nFreeCount;
746 if (GetTime() > nNextReset)
748 nNextReset = GetTime() + 10 * 60;
751 if (nFreeCount > 150000 && !IsFromMe())
752 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
757 // Store transaction in memory
758 CRITICAL_BLOCK(cs_mapTransactions)
762 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
763 ptxOld->RemoveFromMemoryPool();
765 AddToMemoryPoolUnchecked();
768 ///// are we sure this is ok when loading transactions or restoring block txes
769 // If updated, erase old tx from wallet
771 EraseFromWallet(ptxOld->GetHash());
773 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
778 bool CTransaction::AddToMemoryPoolUnchecked()
780 // Add to memory pool without checking anything. Don't call this directly,
781 // call AcceptToMemoryPool to properly check the transaction first.
782 CRITICAL_BLOCK(cs_mapTransactions)
784 uint256 hash = GetHash();
785 mapTransactions[hash] = *this;
786 for (int i = 0; i < vin.size(); i++)
787 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
788 nTransactionsUpdated++;
794 bool CTransaction::RemoveFromMemoryPool()
796 // Remove transaction from memory pool
797 CRITICAL_BLOCK(cs_mapTransactions)
799 foreach(const CTxIn& txin, vin)
800 mapNextTx.erase(txin.prevout);
801 mapTransactions.erase(GetHash());
802 nTransactionsUpdated++;
812 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
814 if (hashBlock == 0 || nIndex == -1)
817 // Find the block it claims to be in
818 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
819 if (mi == mapBlockIndex.end())
821 CBlockIndex* pindex = (*mi).second;
822 if (!pindex || !pindex->IsInMainChain())
825 // Make sure the merkle branch connects to this block
826 if (!fMerkleVerified)
828 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
830 fMerkleVerified = true;
833 nHeightRet = pindex->nHeight;
834 return pindexBest->nHeight - pindex->nHeight + 1;
838 int CMerkleTx::GetBlocksToMaturity() const
842 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
846 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
850 if (!IsInMainChain() && !ClientConnectInputs())
852 return CTransaction::AcceptToMemoryPool(txdb, false);
856 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
862 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
864 CRITICAL_BLOCK(cs_mapTransactions)
866 // Add previous supporting transactions first
867 foreach(CMerkleTx& tx, vtxPrev)
869 if (!tx.IsCoinBase())
871 uint256 hash = tx.GetHash();
872 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
873 tx.AcceptToMemoryPool(txdb, fCheckInputs);
876 return AcceptToMemoryPool(txdb, fCheckInputs);
881 int ScanForWalletTransactions(CBlockIndex* pindexStart)
885 CBlockIndex* pindex = pindexStart;
886 CRITICAL_BLOCK(cs_mapWallet)
891 block.ReadFromDisk(pindex, true);
892 foreach(CTransaction& tx, block.vtx)
894 uint256 hash = tx.GetHash();
895 if (mapWallet.count(hash)) continue;
896 AddToWalletIfMine(tx, &block);
897 if (mapWallet.count(hash))
900 printf("Added missing RECEIVE %s\n", hash.ToString().c_str());
903 AddToWalletIfFromMe(tx, &block);
904 if (mapWallet.count(hash))
907 printf("Added missing SEND %s\n", hash.ToString().c_str());
911 pindex = pindex->pnext;
917 void ReacceptWalletTransactions()
921 while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
924 vector<CDiskTxPos> vMissingTx;
925 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
927 CWalletTx& wtx = item.second;
928 if (wtx.fSpent && wtx.IsCoinBase())
932 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
934 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
937 if (txindex.vSpent.size() != wtx.vout.size())
939 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
942 for (int i = 0; i < txindex.vSpent.size(); i++)
944 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
947 vMissingTx.push_back(txindex.vSpent[i]);
952 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
959 // Reaccept any txes of ours that aren't already in a block
960 if (!wtx.IsCoinBase())
961 wtx.AcceptWalletTransaction(txdb, false);
964 if (!vMissingTx.empty())
966 // TODO: optimize this to scan just part of the block chain?
967 if (ScanForWalletTransactions(pindexGenesisBlock))
968 fRepeat = true; // Found missing transactions: re-do Reaccept.
974 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
976 foreach(const CMerkleTx& tx, vtxPrev)
978 if (!tx.IsCoinBase())
980 uint256 hash = tx.GetHash();
981 if (!txdb.ContainsTx(hash))
982 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
987 uint256 hash = GetHash();
988 if (!txdb.ContainsTx(hash))
990 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
991 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
996 void ResendWalletTransactions()
998 // Do this infrequently and randomly to avoid giving away
999 // that these are our transactions.
1000 static int64 nNextTime;
1001 if (GetTime() < nNextTime)
1003 bool fFirst = (nNextTime == 0);
1004 nNextTime = GetTime() + GetRand(30 * 60);
1008 // Only do it if there's been a new block since last time
1009 static int64 nLastTime;
1010 if (nTimeBestReceived < nLastTime)
1012 nLastTime = GetTime();
1014 // Rebroadcast any of our txes that aren't in a block yet
1015 printf("ResendWalletTransactions()\n");
1017 CRITICAL_BLOCK(cs_mapWallet)
1019 // Sort them in chronological order
1020 multimap<unsigned int, CWalletTx*> mapSorted;
1021 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1023 CWalletTx& wtx = item.second;
1024 // Don't rebroadcast until it's had plenty of time that
1025 // it should have gotten in already by now.
1026 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1027 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1029 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1031 CWalletTx& wtx = *item.second;
1032 wtx.RelayWalletTransaction(txdb);
1046 //////////////////////////////////////////////////////////////////////////////
1048 // CBlock and CBlockIndex
1051 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1053 if (!fReadTransactions)
1055 *this = pindex->GetBlockHeader();
1058 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
1060 if (GetHash() != pindex->GetBlockHash())
1061 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1065 uint256 GetOrphanRoot(const CBlock* pblock)
1067 // Work back to the first block in the orphan chain
1068 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1069 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1070 return pblock->GetHash();
1073 int64 GetBlockValue(int nHeight, int64 nFees)
1075 int64 nSubsidy = 50 * COIN;
1077 // Subsidy is cut in half every 4 years
1078 nSubsidy >>= (nHeight / 210000);
1080 return nSubsidy + nFees;
1083 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
1085 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1086 const int64 nTargetSpacing = 10 * 60;
1087 const int64 nInterval = nTargetTimespan / nTargetSpacing;
1090 if (pindexLast == NULL)
1091 return bnProofOfWorkLimit.GetCompact();
1093 // Only change once per interval
1094 if ((pindexLast->nHeight+1) % nInterval != 0)
1095 return pindexLast->nBits;
1097 // Go back by what we want to be 14 days worth of blocks
1098 const CBlockIndex* pindexFirst = pindexLast;
1099 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1100 pindexFirst = pindexFirst->pprev;
1101 assert(pindexFirst);
1103 // Limit adjustment step
1104 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1105 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1106 if (nActualTimespan < nTargetTimespan/4)
1107 nActualTimespan = nTargetTimespan/4;
1108 if (nActualTimespan > nTargetTimespan*4)
1109 nActualTimespan = nTargetTimespan*4;
1113 bnNew.SetCompact(pindexLast->nBits);
1114 bnNew *= nActualTimespan;
1115 bnNew /= nTargetTimespan;
1117 if (bnNew > bnProofOfWorkLimit)
1118 bnNew = bnProofOfWorkLimit;
1121 printf("GetNextWorkRequired RETARGET\n");
1122 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1123 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1124 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1126 return bnNew.GetCompact();
1129 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1132 bnTarget.SetCompact(nBits);
1135 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1136 return error("CheckProofOfWork() : nBits below minimum work");
1138 // Check proof of work matches claimed amount
1139 if (hash > bnTarget.getuint256())
1140 return error("CheckProofOfWork() : hash doesn't match nBits");
1145 bool IsInitialBlockDownload()
1147 if (pindexBest == NULL || (!fTestNet && nBestHeight < 74000))
1149 static int64 nLastUpdate;
1150 static CBlockIndex* pindexLastBest;
1151 if (pindexBest != pindexLastBest)
1153 pindexLastBest = pindexBest;
1154 nLastUpdate = GetTime();
1156 return (GetTime() - nLastUpdate < 10 &&
1157 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1160 void InvalidChainFound(CBlockIndex* pindexNew)
1162 if (pindexNew->bnChainWork > bnBestInvalidWork)
1164 bnBestInvalidWork = pindexNew->bnChainWork;
1165 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
1168 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());
1169 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1170 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1171 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1184 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1186 // Relinquish previous transactions' spent pointers
1189 foreach(const CTxIn& txin, vin)
1191 COutPoint prevout = txin.prevout;
1193 // Get prev txindex from disk
1195 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1196 return error("DisconnectInputs() : ReadTxIndex failed");
1198 if (prevout.n >= txindex.vSpent.size())
1199 return error("DisconnectInputs() : prevout.n out of range");
1201 // Mark outpoint as not spent
1202 txindex.vSpent[prevout.n].SetNull();
1205 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1206 return error("DisconnectInputs() : UpdateTxIndex failed");
1210 // Remove transaction from index
1211 if (!txdb.EraseTxIndex(*this))
1212 return error("DisconnectInputs() : EraseTxPos failed");
1218 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1219 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1221 // Take over previous transactions' spent pointers
1225 for (int i = 0; i < vin.size(); i++)
1227 COutPoint prevout = vin[i].prevout;
1232 if (fMiner && mapTestPool.count(prevout.hash))
1234 // Get txindex from current proposed changes
1235 txindex = mapTestPool[prevout.hash];
1239 // Read txindex from txdb
1240 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1242 if (!fFound && (fBlock || fMiner))
1243 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());
1246 CTransaction txPrev;
1247 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1249 // Get prev tx from single transactions in memory
1250 CRITICAL_BLOCK(cs_mapTransactions)
1252 if (!mapTransactions.count(prevout.hash))
1253 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1254 txPrev = mapTransactions[prevout.hash];
1257 txindex.vSpent.resize(txPrev.vout.size());
1261 // Get prev tx from disk
1262 if (!txPrev.ReadFromDisk(txindex.pos))
1263 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1266 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1267 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());
1269 // If prev is coinbase, check that it's matured
1270 if (txPrev.IsCoinBase())
1271 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1272 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1273 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1276 if (!VerifySignature(txPrev, *this, i))
1277 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1279 // Check for conflicts
1280 if (!txindex.vSpent[prevout.n].IsNull())
1281 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());
1283 // Check for negative or overflow input values
1284 nValueIn += txPrev.vout[prevout.n].nValue;
1285 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1286 return error("ConnectInputs() : txin values out of range");
1288 // Mark outpoints as spent
1289 txindex.vSpent[prevout.n] = posThisTx;
1294 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1295 return error("ConnectInputs() : UpdateTxIndex failed");
1299 mapTestPool[prevout.hash] = txindex;
1303 if (nValueIn < GetValueOut())
1304 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1306 // Tally transaction fees
1307 int64 nTxFee = nValueIn - GetValueOut();
1309 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1310 if (nTxFee < nMinFee)
1313 if (!MoneyRange(nFees))
1314 return error("ConnectInputs() : nFees out of range");
1319 // Add transaction to disk index
1320 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1321 return error("ConnectInputs() : AddTxPos failed");
1325 // Add transaction to test pool
1326 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1333 bool CTransaction::ClientConnectInputs()
1338 // Take over previous transactions' spent pointers
1339 CRITICAL_BLOCK(cs_mapTransactions)
1342 for (int i = 0; i < vin.size(); i++)
1344 // Get prev tx from single transactions in memory
1345 COutPoint prevout = vin[i].prevout;
1346 if (!mapTransactions.count(prevout.hash))
1348 CTransaction& txPrev = mapTransactions[prevout.hash];
1350 if (prevout.n >= txPrev.vout.size())
1354 if (!VerifySignature(txPrev, *this, i))
1355 return error("ConnectInputs() : VerifySignature failed");
1357 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1358 ///// this has to go away now that posNext is gone
1359 // // Check for conflicts
1360 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1361 // return error("ConnectInputs() : prev tx already used");
1363 // // Flag outpoints as used
1364 // txPrev.vout[prevout.n].posNext = posThisTx;
1366 nValueIn += txPrev.vout[prevout.n].nValue;
1368 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1369 return error("ClientConnectInputs() : txin values out of range");
1371 if (GetValueOut() > nValueIn)
1381 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1383 // Disconnect in reverse order
1384 for (int i = vtx.size()-1; i >= 0; i--)
1385 if (!vtx[i].DisconnectInputs(txdb))
1388 // Update block index on disk without changing it in memory.
1389 // The memory index structure will be changed after the db commits.
1392 CDiskBlockIndex blockindexPrev(pindex->pprev);
1393 blockindexPrev.hashNext = 0;
1394 if (!txdb.WriteBlockIndex(blockindexPrev))
1395 return error("DisconnectBlock() : WriteBlockIndex failed");
1401 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1403 // Check it again in case a previous version let a bad block in
1407 //// issue here: it doesn't know the version
1408 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1410 map<uint256, CTxIndex> mapUnused;
1412 foreach(CTransaction& tx, vtx)
1414 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1415 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1417 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1421 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1424 // Update block index on disk without changing it in memory.
1425 // The memory index structure will be changed after the db commits.
1428 CDiskBlockIndex blockindexPrev(pindex->pprev);
1429 blockindexPrev.hashNext = pindex->GetBlockHash();
1430 if (!txdb.WriteBlockIndex(blockindexPrev))
1431 return error("ConnectBlock() : WriteBlockIndex failed");
1434 // Watch for transactions paying to me
1435 foreach(CTransaction& tx, vtx)
1436 AddToWalletIfMine(tx, this);
1441 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1443 printf("REORGANIZE\n");
1446 CBlockIndex* pfork = pindexBest;
1447 CBlockIndex* plonger = pindexNew;
1448 while (pfork != plonger)
1450 while (plonger->nHeight > pfork->nHeight)
1451 if (!(plonger = plonger->pprev))
1452 return error("Reorganize() : plonger->pprev is null");
1453 if (pfork == plonger)
1455 if (!(pfork = pfork->pprev))
1456 return error("Reorganize() : pfork->pprev is null");
1459 // List of what to disconnect
1460 vector<CBlockIndex*> vDisconnect;
1461 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1462 vDisconnect.push_back(pindex);
1464 // List of what to connect
1465 vector<CBlockIndex*> vConnect;
1466 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1467 vConnect.push_back(pindex);
1468 reverse(vConnect.begin(), vConnect.end());
1470 // Disconnect shorter branch
1471 vector<CTransaction> vResurrect;
1472 foreach(CBlockIndex* pindex, vDisconnect)
1475 if (!block.ReadFromDisk(pindex))
1476 return error("Reorganize() : ReadFromDisk for disconnect failed");
1477 if (!block.DisconnectBlock(txdb, pindex))
1478 return error("Reorganize() : DisconnectBlock failed");
1480 // Queue memory transactions to resurrect
1481 foreach(const CTransaction& tx, block.vtx)
1482 if (!tx.IsCoinBase())
1483 vResurrect.push_back(tx);
1486 // Connect longer branch
1487 vector<CTransaction> vDelete;
1488 for (int i = 0; i < vConnect.size(); i++)
1490 CBlockIndex* pindex = vConnect[i];
1492 if (!block.ReadFromDisk(pindex))
1493 return error("Reorganize() : ReadFromDisk for connect failed");
1494 if (!block.ConnectBlock(txdb, pindex))
1498 return error("Reorganize() : ConnectBlock failed");
1501 // Queue memory transactions to delete
1502 foreach(const CTransaction& tx, block.vtx)
1503 vDelete.push_back(tx);
1505 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1506 return error("Reorganize() : WriteHashBestChain failed");
1508 // Make sure it's successfully written to disk before changing memory structure
1509 if (!txdb.TxnCommit())
1510 return error("Reorganize() : TxnCommit failed");
1512 // Disconnect shorter branch
1513 foreach(CBlockIndex* pindex, vDisconnect)
1515 pindex->pprev->pnext = NULL;
1517 // Connect longer branch
1518 foreach(CBlockIndex* pindex, vConnect)
1520 pindex->pprev->pnext = pindex;
1522 // Resurrect memory transactions that were in the disconnected branch
1523 foreach(CTransaction& tx, vResurrect)
1524 tx.AcceptToMemoryPool(txdb, false);
1526 // Delete redundant memory transactions that are in the connected branch
1527 foreach(CTransaction& tx, vDelete)
1528 tx.RemoveFromMemoryPool();
1534 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1536 uint256 hash = GetHash();
1539 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1541 txdb.WriteHashBestChain(hash);
1542 if (!txdb.TxnCommit())
1543 return error("SetBestChain() : TxnCommit failed");
1544 pindexGenesisBlock = pindexNew;
1546 else if (hashPrevBlock == hashBestChain)
1548 // Adding to current best branch
1549 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1552 InvalidChainFound(pindexNew);
1553 return error("SetBestChain() : ConnectBlock failed");
1555 if (!txdb.TxnCommit())
1556 return error("SetBestChain() : TxnCommit failed");
1558 // Add to current best branch
1559 pindexNew->pprev->pnext = pindexNew;
1561 // Delete redundant memory transactions
1562 foreach(CTransaction& tx, vtx)
1563 tx.RemoveFromMemoryPool();
1568 if (!Reorganize(txdb, pindexNew))
1571 InvalidChainFound(pindexNew);
1572 return error("SetBestChain() : Reorganize failed");
1577 hashBestChain = hash;
1578 pindexBest = pindexNew;
1579 nBestHeight = pindexBest->nHeight;
1580 bnBestChainWork = pindexNew->bnChainWork;
1581 nTimeBestReceived = GetTime();
1582 nTransactionsUpdated++;
1583 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1589 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1591 // Check for duplicate
1592 uint256 hash = GetHash();
1593 if (mapBlockIndex.count(hash))
1594 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1596 // Construct new block index object
1597 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1599 return error("AddToBlockIndex() : new CBlockIndex failed");
1600 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1601 pindexNew->phashBlock = &((*mi).first);
1602 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1603 if (miPrev != mapBlockIndex.end())
1605 pindexNew->pprev = (*miPrev).second;
1606 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1608 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1612 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1613 if (!txdb.TxnCommit())
1617 if (pindexNew->bnChainWork > bnBestChainWork)
1618 if (!SetBestChain(txdb, pindexNew))
1623 if (pindexNew == pindexBest)
1625 // Notify UI to display prev block's coinbase if it was ours
1626 static uint256 hashPrevBestCoinBase;
1627 CRITICAL_BLOCK(cs_mapWallet)
1628 vWalletUpdated.push_back(hashPrevBestCoinBase);
1629 hashPrevBestCoinBase = vtx[0].GetHash();
1639 bool CBlock::CheckBlock() const
1641 // These are checks that are independent of context
1642 // that can be verified before saving an orphan block.
1645 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1646 return error("CheckBlock() : size limits failed");
1648 // Check proof of work matches claimed amount
1649 if (!CheckProofOfWork(GetHash(), nBits))
1650 return error("CheckBlock() : proof of work failed");
1653 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1654 return error("CheckBlock() : block timestamp too far in the future");
1656 // First transaction must be coinbase, the rest must not be
1657 if (vtx.empty() || !vtx[0].IsCoinBase())
1658 return error("CheckBlock() : first tx is not coinbase");
1659 for (int i = 1; i < vtx.size(); i++)
1660 if (vtx[i].IsCoinBase())
1661 return error("CheckBlock() : more than one coinbase");
1663 // Check transactions
1664 foreach(const CTransaction& tx, vtx)
1665 if (!tx.CheckTransaction())
1666 return error("CheckBlock() : CheckTransaction failed");
1668 // Check that it's not full of nonstandard transactions
1669 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1670 return error("CheckBlock() : too many nonstandard transactions");
1673 if (hashMerkleRoot != BuildMerkleTree())
1674 return error("CheckBlock() : hashMerkleRoot mismatch");
1679 bool CBlock::AcceptBlock()
1681 // Check for duplicate
1682 uint256 hash = GetHash();
1683 if (mapBlockIndex.count(hash))
1684 return error("AcceptBlock() : block already in mapBlockIndex");
1686 // Get prev block index
1687 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1688 if (mi == mapBlockIndex.end())
1689 return error("AcceptBlock() : prev block not found");
1690 CBlockIndex* pindexPrev = (*mi).second;
1691 int nHeight = pindexPrev->nHeight+1;
1693 // Check proof of work
1694 if (nBits != GetNextWorkRequired(pindexPrev))
1695 return error("AcceptBlock() : incorrect proof of work");
1697 // Check timestamp against prev
1698 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1699 return error("AcceptBlock() : block's timestamp is too early");
1701 // Check that all transactions are finalized
1702 foreach(const CTransaction& tx, vtx)
1703 if (!tx.IsFinal(nHeight, GetBlockTime()))
1704 return error("AcceptBlock() : contains a non-final transaction");
1706 // Check that the block chain matches the known block chain up to a checkpoint
1708 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1709 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1710 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1711 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1712 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))
1713 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1715 // Write block to history file
1716 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1717 return error("AcceptBlock() : out of disk space");
1718 unsigned int nFile = -1;
1719 unsigned int nBlockPos = 0;
1720 if (!WriteToDisk(nFile, nBlockPos))
1721 return error("AcceptBlock() : WriteToDisk failed");
1722 if (!AddToBlockIndex(nFile, nBlockPos))
1723 return error("AcceptBlock() : AddToBlockIndex failed");
1725 // Relay inventory, but don't relay old inventory during initial block download
1726 if (hashBestChain == hash)
1727 CRITICAL_BLOCK(cs_vNodes)
1728 foreach(CNode* pnode, vNodes)
1729 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1730 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1735 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1737 // Check for duplicate
1738 uint256 hash = pblock->GetHash();
1739 if (mapBlockIndex.count(hash))
1740 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1741 if (mapOrphanBlocks.count(hash))
1742 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1744 // Preliminary checks
1745 if (!pblock->CheckBlock())
1746 return error("ProcessBlock() : CheckBlock FAILED");
1748 // If don't already have its previous block, shunt it off to holding area until we get it
1749 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1751 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1752 CBlock* pblock2 = new CBlock(*pblock);
1753 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1754 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1756 // Ask this guy to fill in what we're missing
1758 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1763 if (!pblock->AcceptBlock())
1764 return error("ProcessBlock() : AcceptBlock FAILED");
1766 // Recursively process any orphan blocks that depended on this one
1767 vector<uint256> vWorkQueue;
1768 vWorkQueue.push_back(hash);
1769 for (int i = 0; i < vWorkQueue.size(); i++)
1771 uint256 hashPrev = vWorkQueue[i];
1772 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1773 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1776 CBlock* pblockOrphan = (*mi).second;
1777 if (pblockOrphan->AcceptBlock())
1778 vWorkQueue.push_back(pblockOrphan->GetHash());
1779 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1780 delete pblockOrphan;
1782 mapOrphanBlocksByPrev.erase(hashPrev);
1785 printf("ProcessBlock: ACCEPTED\n");
1796 template<typename Stream>
1797 bool ScanMessageStart(Stream& s)
1799 // Scan ahead to the next pchMessageStart, which should normally be immediately
1800 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1802 short prevmask = s.exceptions(0);
1803 const char* p = BEGIN(pchMessageStart);
1813 s.exceptions(prevmask);
1817 p = BEGIN(pchMessageStart);
1820 if (++p == END(pchMessageStart))
1823 s.exceptions(prevmask);
1832 s.exceptions(prevmask);
1837 bool CheckDiskSpace(uint64 nAdditionalBytes)
1839 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1841 // Check for 15MB because database could create another 10MB log file at any time
1842 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1845 string strMessage = _("Warning: Disk space is low ");
1846 strMiscWarning = strMessage;
1847 printf("*** %s\n", strMessage.c_str());
1848 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1849 CreateThread(Shutdown, NULL);
1855 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1859 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1862 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1864 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1873 static unsigned int nCurrentBlockFile = 1;
1875 FILE* AppendBlockFile(unsigned int& nFileRet)
1880 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1883 if (fseek(file, 0, SEEK_END) != 0)
1885 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1886 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1888 nFileRet = nCurrentBlockFile;
1892 nCurrentBlockFile++;
1896 bool LoadBlockIndex(bool fAllowNew)
1900 hashGenesisBlock = uint256("0x0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110");
1901 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1902 pchMessageStart[0] = 0xfa;
1903 pchMessageStart[1] = 0xbf;
1904 pchMessageStart[2] = 0xb5;
1905 pchMessageStart[3] = 0xda;
1912 if (!txdb.LoadBlockIndex())
1917 // Init with genesis block
1919 if (mapBlockIndex.empty())
1925 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1926 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1927 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1928 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1929 // vMerkleTree: 4a5e1e
1932 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1934 txNew.vin.resize(1);
1935 txNew.vout.resize(1);
1936 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1937 txNew.vout[0].nValue = 50 * COIN;
1938 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1940 block.vtx.push_back(txNew);
1941 block.hashPrevBlock = 0;
1942 block.hashMerkleRoot = block.BuildMerkleTree();
1944 block.nTime = 1231006505;
1945 block.nBits = 0x1d00ffff;
1946 block.nNonce = 2083236893;
1950 block.nTime = 1279232055;
1951 block.nBits = 0x1d07fff8;
1952 block.nNonce = 81622180;
1956 printf("%s\n", block.GetHash().ToString().c_str());
1957 printf("%s\n", hashGenesisBlock.ToString().c_str());
1958 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1959 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1961 assert(block.GetHash() == hashGenesisBlock);
1963 // Start new block file
1965 unsigned int nBlockPos;
1966 if (!block.WriteToDisk(nFile, nBlockPos))
1967 return error("LoadBlockIndex() : writing genesis block to disk failed");
1968 if (!block.AddToBlockIndex(nFile, nBlockPos))
1969 return error("LoadBlockIndex() : genesis block not accepted");
1977 void PrintBlockTree()
1979 // precompute tree structure
1980 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1981 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1983 CBlockIndex* pindex = (*mi).second;
1984 mapNext[pindex->pprev].push_back(pindex);
1986 //while (rand() % 3 == 0)
1987 // mapNext[pindex->pprev].push_back(pindex);
1990 vector<pair<int, CBlockIndex*> > vStack;
1991 vStack.push_back(make_pair(0, pindexGenesisBlock));
1994 while (!vStack.empty())
1996 int nCol = vStack.back().first;
1997 CBlockIndex* pindex = vStack.back().second;
2000 // print split or gap
2001 if (nCol > nPrevCol)
2003 for (int i = 0; i < nCol-1; i++)
2007 else if (nCol < nPrevCol)
2009 for (int i = 0; i < nCol; i++)
2016 for (int i = 0; i < nCol; i++)
2021 block.ReadFromDisk(pindex);
2022 printf("%d (%u,%u) %s %s tx %d",
2026 block.GetHash().ToString().substr(0,20).c_str(),
2027 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2030 CRITICAL_BLOCK(cs_mapWallet)
2032 if (mapWallet.count(block.vtx[0].GetHash()))
2034 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2035 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2041 // put the main timechain first
2042 vector<CBlockIndex*>& vNext = mapNext[pindex];
2043 for (int i = 0; i < vNext.size(); i++)
2045 if (vNext[i]->pnext)
2047 swap(vNext[0], vNext[i]);
2053 for (int i = 0; i < vNext.size(); i++)
2054 vStack.push_back(make_pair(nCol+i, vNext[i]));
2067 //////////////////////////////////////////////////////////////////////////////
2072 map<uint256, CAlert> mapAlerts;
2073 CCriticalSection cs_mapAlerts;
2075 string GetWarnings(string strFor)
2078 string strStatusBar;
2080 if (GetBoolArg("-testsafemode"))
2083 // Misc warnings like out of disk space and clock is wrong
2084 if (strMiscWarning != "")
2087 strStatusBar = strMiscWarning;
2090 // Longer invalid proof-of-work chain
2091 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2094 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2098 CRITICAL_BLOCK(cs_mapAlerts)
2100 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2102 const CAlert& alert = item.second;
2103 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2105 nPriority = alert.nPriority;
2106 strStatusBar = alert.strStatusBar;
2111 if (strFor == "statusbar")
2112 return strStatusBar;
2113 else if (strFor == "rpc")
2115 assert(("GetWarnings() : invalid parameter", false));
2119 bool CAlert::ProcessAlert()
2121 if (!CheckSignature())
2126 CRITICAL_BLOCK(cs_mapAlerts)
2128 // Cancel previous alerts
2129 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2131 const CAlert& alert = (*mi).second;
2134 printf("cancelling alert %d\n", alert.nID);
2135 mapAlerts.erase(mi++);
2137 else if (!alert.IsInEffect())
2139 printf("expiring alert %d\n", alert.nID);
2140 mapAlerts.erase(mi++);
2146 // Check if this alert has been cancelled
2147 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2149 const CAlert& alert = item.second;
2150 if (alert.Cancels(*this))
2152 printf("alert already cancelled by %d\n", alert.nID);
2158 mapAlerts.insert(make_pair(GetHash(), *this));
2161 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2173 //////////////////////////////////////////////////////////////////////////////
2179 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
2183 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2184 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2186 // Don't know what it is, just say we already got one
2193 // The message start string is designed to be unlikely to occur in normal data.
2194 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2195 // a large 4-byte int at any alignment.
2196 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2199 bool ProcessMessages(CNode* pfrom)
2201 CDataStream& vRecv = pfrom->vRecv;
2205 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2209 // (4) message start
2218 // Scan for message start
2219 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2220 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2221 if (vRecv.end() - pstart < nHeaderSize)
2223 if (vRecv.size() > nHeaderSize)
2225 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2226 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2230 if (pstart - vRecv.begin() > 0)
2231 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2232 vRecv.erase(vRecv.begin(), pstart);
2235 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2240 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2243 string strCommand = hdr.GetCommand();
2246 unsigned int nMessageSize = hdr.nMessageSize;
2247 if (nMessageSize > MAX_SIZE)
2249 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2252 if (nMessageSize > vRecv.size())
2254 // Rewind and wait for rest of message
2255 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2260 if (vRecv.GetVersion() >= 209)
2262 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2263 unsigned int nChecksum = 0;
2264 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2265 if (nChecksum != hdr.nChecksum)
2267 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2268 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2273 // Copy message to its own buffer
2274 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2275 vRecv.ignore(nMessageSize);
2281 CRITICAL_BLOCK(cs_main)
2282 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2286 catch (std::ios_base::failure& e)
2288 if (strstr(e.what(), "end of data"))
2290 // Allow exceptions from underlength message on vRecv
2291 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());
2293 else if (strstr(e.what(), "size too large"))
2295 // Allow exceptions from overlong size
2296 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2300 PrintExceptionContinue(&e, "ProcessMessage()");
2303 catch (std::exception& e) {
2304 PrintExceptionContinue(&e, "ProcessMessage()");
2306 PrintExceptionContinue(NULL, "ProcessMessage()");
2310 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2320 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2322 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2323 RandAddSeedPerfmon();
2325 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2326 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2327 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2329 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2337 if (strCommand == "version")
2339 // Each connection can only send one version message
2340 if (pfrom->nVersion != 0)
2347 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2348 if (pfrom->nVersion == 10300)
2349 pfrom->nVersion = 300;
2350 if (pfrom->nVersion >= 106 && !vRecv.empty())
2351 vRecv >> addrFrom >> nNonce;
2352 if (pfrom->nVersion >= 106 && !vRecv.empty())
2353 vRecv >> pfrom->strSubVer;
2354 if (pfrom->nVersion >= 209 && !vRecv.empty())
2355 vRecv >> pfrom->nStartingHeight;
2357 if (pfrom->nVersion == 0)
2360 // Disconnect if we connected to ourself
2361 if (nNonce == nLocalHostNonce && nNonce > 1)
2363 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2364 pfrom->fDisconnect = true;
2368 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2370 AddTimeData(pfrom->addr.ip, nTime);
2373 if (pfrom->nVersion >= 209)
2374 pfrom->PushMessage("verack");
2375 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2376 if (pfrom->nVersion < 209)
2377 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2379 if (!pfrom->fInbound)
2381 // Advertise our address
2382 if (addrLocalHost.IsRoutable() && !fUseProxy)
2384 CAddress addr(addrLocalHost);
2385 addr.nTime = GetAdjustedTime();
2386 pfrom->PushAddress(addr);
2389 // Get recent addresses
2390 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2392 pfrom->PushMessage("getaddr");
2393 pfrom->fGetAddr = true;
2397 // Ask the first connected node for block updates
2398 static int nAskedForBlocks;
2399 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2402 pfrom->PushGetBlocks(pindexBest, uint256(0));
2406 CRITICAL_BLOCK(cs_mapAlerts)
2407 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2408 item.second.RelayTo(pfrom);
2410 pfrom->fSuccessfullyConnected = true;
2412 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2416 else if (pfrom->nVersion == 0)
2418 // Must have a version message before anything else
2423 else if (strCommand == "verack")
2425 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2429 else if (strCommand == "addr")
2431 vector<CAddress> vAddr;
2434 // Don't want addr from older versions unless seeding
2435 if (pfrom->nVersion < 209)
2437 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2439 if (vAddr.size() > 1000)
2440 return error("message addr size() = %d", vAddr.size());
2442 // Store the new addresses
2443 int64 nNow = GetAdjustedTime();
2444 int64 nSince = nNow - 10 * 60;
2445 foreach(CAddress& addr, vAddr)
2449 // ignore IPv6 for now, since it isn't implemented anyway
2452 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2453 addr.nTime = nNow - 5 * 24 * 60 * 60;
2454 AddAddress(addr, 2 * 60 * 60);
2455 pfrom->AddAddressKnown(addr);
2456 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2458 // Relay to a limited number of other nodes
2459 CRITICAL_BLOCK(cs_vNodes)
2461 // Use deterministic randomness to send to the same nodes for 24 hours
2462 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2463 static uint256 hashSalt;
2465 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2466 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2467 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2468 multimap<uint256, CNode*> mapMix;
2469 foreach(CNode* pnode, vNodes)
2471 if (pnode->nVersion < 31402)
2473 unsigned int nPointer;
2474 memcpy(&nPointer, &pnode, sizeof(nPointer));
2475 uint256 hashKey = hashRand ^ nPointer;
2476 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2477 mapMix.insert(make_pair(hashKey, pnode));
2479 int nRelayNodes = 2;
2480 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2481 ((*mi).second)->PushAddress(addr);
2485 if (vAddr.size() < 1000)
2486 pfrom->fGetAddr = false;
2490 else if (strCommand == "inv")
2494 if (vInv.size() > 50000)
2495 return error("message inv size() = %d", vInv.size());
2498 foreach(const CInv& inv, vInv)
2502 pfrom->AddInventoryKnown(inv);
2504 bool fAlreadyHave = AlreadyHave(txdb, inv);
2505 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2509 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2510 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2512 // Track requests for our stuff
2513 CRITICAL_BLOCK(cs_mapRequestCount)
2515 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2516 if (mi != mapRequestCount.end())
2523 else if (strCommand == "getdata")
2527 if (vInv.size() > 50000)
2528 return error("message getdata size() = %d", vInv.size());
2530 foreach(const CInv& inv, vInv)
2534 printf("received getdata for: %s\n", inv.ToString().c_str());
2536 if (inv.type == MSG_BLOCK)
2538 // Send block from disk
2539 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2540 if (mi != mapBlockIndex.end())
2543 block.ReadFromDisk((*mi).second);
2544 pfrom->PushMessage("block", block);
2546 // Trigger them to send a getblocks request for the next batch of inventory
2547 if (inv.hash == pfrom->hashContinue)
2549 // Bypass PushInventory, this must send even if redundant,
2550 // and we want it right after the last block so they don't
2551 // wait for other stuff first.
2553 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2554 pfrom->PushMessage("inv", vInv);
2555 pfrom->hashContinue = 0;
2559 else if (inv.IsKnownType())
2561 // Send stream from relay memory
2562 CRITICAL_BLOCK(cs_mapRelay)
2564 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2565 if (mi != mapRelay.end())
2566 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2570 // Track requests for our stuff
2571 CRITICAL_BLOCK(cs_mapRequestCount)
2573 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2574 if (mi != mapRequestCount.end())
2581 else if (strCommand == "getblocks")
2583 CBlockLocator locator;
2585 vRecv >> locator >> hashStop;
2587 // Find the last block the caller has in the main chain
2588 CBlockIndex* pindex = locator.GetBlockIndex();
2590 // Send the rest of the chain
2592 pindex = pindex->pnext;
2593 int nLimit = 500 + locator.GetDistanceBack();
2594 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2595 for (; pindex; pindex = pindex->pnext)
2597 if (pindex->GetBlockHash() == hashStop)
2599 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2602 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2605 // When this block is requested, we'll send an inv that'll make them
2606 // getblocks the next batch of inventory.
2607 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2608 pfrom->hashContinue = pindex->GetBlockHash();
2615 else if (strCommand == "getheaders")
2617 CBlockLocator locator;
2619 vRecv >> locator >> hashStop;
2621 CBlockIndex* pindex = NULL;
2622 if (locator.IsNull())
2624 // If locator is null, return the hashStop block
2625 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2626 if (mi == mapBlockIndex.end())
2628 pindex = (*mi).second;
2632 // Find the last block the caller has in the main chain
2633 pindex = locator.GetBlockIndex();
2635 pindex = pindex->pnext;
2638 vector<CBlock> vHeaders;
2639 int nLimit = 2000 + locator.GetDistanceBack();
2640 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2641 for (; pindex; pindex = pindex->pnext)
2643 vHeaders.push_back(pindex->GetBlockHeader());
2644 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2647 pfrom->PushMessage("headers", vHeaders);
2651 else if (strCommand == "tx")
2653 vector<uint256> vWorkQueue;
2654 CDataStream vMsg(vRecv);
2658 CInv inv(MSG_TX, tx.GetHash());
2659 pfrom->AddInventoryKnown(inv);
2661 bool fMissingInputs = false;
2662 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2664 AddToWalletIfMine(tx, NULL);
2665 RelayMessage(inv, vMsg);
2666 mapAlreadyAskedFor.erase(inv);
2667 vWorkQueue.push_back(inv.hash);
2669 // Recursively process any orphan transactions that depended on this one
2670 for (int i = 0; i < vWorkQueue.size(); i++)
2672 uint256 hashPrev = vWorkQueue[i];
2673 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2674 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2677 const CDataStream& vMsg = *((*mi).second);
2679 CDataStream(vMsg) >> tx;
2680 CInv inv(MSG_TX, tx.GetHash());
2682 if (tx.AcceptToMemoryPool(true))
2684 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2685 AddToWalletIfMine(tx, NULL);
2686 RelayMessage(inv, vMsg);
2687 mapAlreadyAskedFor.erase(inv);
2688 vWorkQueue.push_back(inv.hash);
2693 foreach(uint256 hash, vWorkQueue)
2694 EraseOrphanTx(hash);
2696 else if (fMissingInputs)
2698 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2704 else if (strCommand == "block")
2709 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2712 CInv inv(MSG_BLOCK, block.GetHash());
2713 pfrom->AddInventoryKnown(inv);
2715 if (ProcessBlock(pfrom, &block))
2716 mapAlreadyAskedFor.erase(inv);
2720 else if (strCommand == "getaddr")
2722 // Nodes rebroadcast an addr every 24 hours
2723 pfrom->vAddrToSend.clear();
2724 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2725 CRITICAL_BLOCK(cs_mapAddresses)
2727 unsigned int nCount = 0;
2728 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2730 const CAddress& addr = item.second;
2731 if (addr.nTime > nSince)
2734 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2736 const CAddress& addr = item.second;
2737 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2738 pfrom->PushAddress(addr);
2744 else if (strCommand == "checkorder")
2749 if (!GetBoolArg("-allowreceivebyip"))
2751 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2758 /// we have a chance to check the order here
2760 // Keep giving the same key to the same ip until they use it
2761 if (!mapReuseKey.count(pfrom->addr.ip))
2762 mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();
2764 // Send back approval of order and pubkey to use
2765 CScript scriptPubKey;
2766 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2767 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2771 else if (strCommand == "submitorder")
2776 if (!GetBoolArg("-allowreceivebyip"))
2778 pfrom->PushMessage("reply", hashReply, (int)2);
2784 wtxNew.fFromMe = false;
2787 if (!wtxNew.AcceptWalletTransaction())
2789 pfrom->PushMessage("reply", hashReply, (int)1);
2790 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2792 wtxNew.fTimeReceivedIsTxTime = true;
2793 AddToWallet(wtxNew);
2794 wtxNew.RelayWalletTransaction();
2795 mapReuseKey.erase(pfrom->addr.ip);
2797 // Send back confirmation
2798 pfrom->PushMessage("reply", hashReply, (int)0);
2802 else if (strCommand == "reply")
2807 CRequestTracker tracker;
2808 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2810 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2811 if (mi != pfrom->mapRequests.end())
2813 tracker = (*mi).second;
2814 pfrom->mapRequests.erase(mi);
2817 if (!tracker.IsNull())
2818 tracker.fn(tracker.param1, vRecv);
2822 else if (strCommand == "ping")
2827 else if (strCommand == "alert")
2832 if (alert.ProcessAlert())
2835 pfrom->setKnown.insert(alert.GetHash());
2836 CRITICAL_BLOCK(cs_vNodes)
2837 foreach(CNode* pnode, vNodes)
2838 alert.RelayTo(pnode);
2845 // Ignore unknown commands for extensibility
2849 // Update the last seen time for this node's address
2850 if (pfrom->fNetworkNode)
2851 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2852 AddressCurrentlyConnected(pfrom->addr);
2866 bool SendMessages(CNode* pto, bool fSendTrickle)
2868 CRITICAL_BLOCK(cs_main)
2870 // Don't send anything until we get their version message
2871 if (pto->nVersion == 0)
2875 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2876 pto->PushMessage("ping");
2878 // Resend wallet transactions that haven't gotten in a block yet
2879 ResendWalletTransactions();
2881 // Address refresh broadcast
2882 static int64 nLastRebroadcast;
2883 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2885 nLastRebroadcast = GetTime();
2886 CRITICAL_BLOCK(cs_vNodes)
2888 foreach(CNode* pnode, vNodes)
2890 // Periodically clear setAddrKnown to allow refresh broadcasts
2891 pnode->setAddrKnown.clear();
2893 // Rebroadcast our address
2894 if (addrLocalHost.IsRoutable() && !fUseProxy)
2896 CAddress addr(addrLocalHost);
2897 addr.nTime = GetAdjustedTime();
2898 pnode->PushAddress(addr);
2904 // Clear out old addresses periodically so it's not too much work at once
2905 static int64 nLastClear;
2906 if (nLastClear == 0)
2907 nLastClear = GetTime();
2908 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2910 nLastClear = GetTime();
2911 CRITICAL_BLOCK(cs_mapAddresses)
2914 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2915 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2916 mi != mapAddresses.end();)
2918 const CAddress& addr = (*mi).second;
2919 if (addr.nTime < nSince)
2921 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2923 addrdb.EraseAddress(addr);
2924 mapAddresses.erase(mi++);
2938 vector<CAddress> vAddr;
2939 vAddr.reserve(pto->vAddrToSend.size());
2940 foreach(const CAddress& addr, pto->vAddrToSend)
2942 // returns true if wasn't already contained in the set
2943 if (pto->setAddrKnown.insert(addr).second)
2945 vAddr.push_back(addr);
2946 // receiver rejects addr messages larger than 1000
2947 if (vAddr.size() >= 1000)
2949 pto->PushMessage("addr", vAddr);
2954 pto->vAddrToSend.clear();
2956 pto->PushMessage("addr", vAddr);
2961 // Message: inventory
2964 vector<CInv> vInvWait;
2965 CRITICAL_BLOCK(pto->cs_inventory)
2967 vInv.reserve(pto->vInventoryToSend.size());
2968 vInvWait.reserve(pto->vInventoryToSend.size());
2969 foreach(const CInv& inv, pto->vInventoryToSend)
2971 if (pto->setInventoryKnown.count(inv))
2974 // trickle out tx inv to protect privacy
2975 if (inv.type == MSG_TX && !fSendTrickle)
2977 // 1/4 of tx invs blast to all immediately
2978 static uint256 hashSalt;
2980 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2981 uint256 hashRand = inv.hash ^ hashSalt;
2982 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2983 bool fTrickleWait = ((hashRand & 3) != 0);
2985 // always trickle our own transactions
2988 TRY_CRITICAL_BLOCK(cs_mapWallet)
2990 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2991 if (mi != mapWallet.end())
2993 CWalletTx& wtx = (*mi).second;
2995 fTrickleWait = true;
3002 vInvWait.push_back(inv);
3007 // returns true if wasn't already contained in the set
3008 if (pto->setInventoryKnown.insert(inv).second)
3010 vInv.push_back(inv);
3011 if (vInv.size() >= 1000)
3013 pto->PushMessage("inv", vInv);
3018 pto->vInventoryToSend = vInvWait;
3021 pto->PushMessage("inv", vInv);
3027 vector<CInv> vGetData;
3028 int64 nNow = GetTime() * 1000000;
3030 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3032 const CInv& inv = (*pto->mapAskFor.begin()).second;
3033 if (!AlreadyHave(txdb, inv))
3035 printf("sending getdata: %s\n", inv.ToString().c_str());
3036 vGetData.push_back(inv);
3037 if (vGetData.size() >= 1000)
3039 pto->PushMessage("getdata", vGetData);
3043 pto->mapAskFor.erase(pto->mapAskFor.begin());
3045 if (!vGetData.empty())
3046 pto->PushMessage("getdata", vGetData);
3065 //////////////////////////////////////////////////////////////////////////////
3070 void GenerateBitcoins(bool fGenerate)
3072 if (fGenerateBitcoins != fGenerate)
3074 fGenerateBitcoins = fGenerate;
3075 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3078 if (fGenerateBitcoins)
3080 int nProcessors = boost::thread::hardware_concurrency();
3081 printf("%d processors\n", nProcessors);
3082 if (nProcessors < 1)
3084 if (fLimitProcessors && nProcessors > nLimitProcessors)
3085 nProcessors = nLimitProcessors;
3086 int nAddThreads = nProcessors - vnThreadsRunning[3];
3087 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3088 for (int i = 0; i < nAddThreads; i++)
3090 if (!CreateThread(ThreadBitcoinMiner, NULL))
3091 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3097 void ThreadBitcoinMiner(void* parg)
3101 vnThreadsRunning[3]++;
3103 vnThreadsRunning[3]--;
3105 catch (std::exception& e) {
3106 vnThreadsRunning[3]--;
3107 PrintException(&e, "ThreadBitcoinMiner()");
3109 vnThreadsRunning[3]--;
3110 PrintException(NULL, "ThreadBitcoinMiner()");
3112 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3114 if (vnThreadsRunning[3] == 0)
3116 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3119 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
3120 void CallCPUID(int in, int& aret, int& cret)
3124 "mov %2, %%eax; " // in into eax
3126 "mov %%eax, %0;" // eax into a
3127 "mov %%ecx, %1;" // ecx into c
3128 :"=r"(a),"=r"(c) /* output */
3129 :"r"(in) /* input */
3130 :"%eax","%ebx","%ecx","%edx" /* clobbered register */
3136 bool Detect128BitSSE2()
3139 CallCPUID(0, a, nBrand);
3140 bool fIntel = (nBrand == 0x6c65746e); // ntel
3141 bool fAMD = (nBrand == 0x444d4163); // cAMD
3145 unsigned int nStepping : 4;
3146 unsigned int nModel : 4;
3147 unsigned int nFamily : 4;
3148 unsigned int nProcessorType : 2;
3149 unsigned int nUnused : 2;
3150 unsigned int nExtendedModel : 4;
3151 unsigned int nExtendedFamily : 8;
3155 memcpy(&cpu, &a, sizeof(cpu));
3156 int nFamily = cpu.nExtendedFamily + cpu.nFamily;
3157 int nModel = cpu.nExtendedModel*16 + cpu.nModel;
3159 // We need Intel Nehalem or AMD K10 or better for 128bit SSE2
3160 // Nehalem = i3/i5/i7 and some Xeon
3161 // K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II
3162 // Intel Core i5 family 6, model 26 or 30
3163 // Intel Core i7 family 6, model 26 or 30
3164 // Intel Core i3 family 6, model 37
3165 // AMD Phenom family 16, model 10
3166 bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >= 60026) ||
3167 (fAMD && nFamily * 10000 + nModel >= 160010));
3169 // AMD reports a lower model number in 64-bit mode
3170 if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)
3173 static bool fPrinted;
3177 printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);
3182 bool Detect128BitSSE2() { return false; }
3185 int FormatHashBlocks(void* pbuffer, unsigned int len)
3187 unsigned char* pdata = (unsigned char*)pbuffer;
3188 unsigned int blocks = 1 + ((len + 8) / 64);
3189 unsigned char* pend = pdata + 64 * blocks;
3190 memset(pdata + len, 0, 64 * blocks - len);
3192 unsigned int bits = len * 8;
3193 pend[-1] = (bits >> 0) & 0xff;
3194 pend[-2] = (bits >> 8) & 0xff;
3195 pend[-3] = (bits >> 16) & 0xff;
3196 pend[-4] = (bits >> 24) & 0xff;
3200 using CryptoPP::ByteReverse;
3202 static const unsigned int pSHA256InitState[8] =
3203 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3205 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3207 memcpy(pstate, pinit, 32);
3208 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
3212 // ScanHash scans nonces looking for a hash with at least some zero bits.
3213 // It operates on big endian data. Caller does the byte reversing.
3214 // All input buffers are 16-byte aligned. nNonce is usually preserved
3215 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3216 // the block is rebuilt and nNonce starts over at zero.
3218 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3220 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3224 // Hash pdata using pmidstate as the starting state into
3225 // preformatted buffer phash1, then hash phash1 into phash
3227 SHA256Transform(phash1, pdata, pmidstate);
3228 SHA256Transform(phash, phash1, pSHA256InitState);
3230 // Return the nonce if the hash has at least some zero bits,
3231 // caller will check if it has enough to reach the target
3232 if (((unsigned short*)phash)[14] == 0)
3235 // If nothing found after trying for a while, return -1
3236 if ((nNonce & 0xffff) == 0)
3238 nHashesDone = 0xffff+1;
3244 extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);
3252 set<uint256> setDependsOn;
3255 COrphan(CTransaction* ptxIn)
3263 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3264 foreach(uint256 hash, setDependsOn)
3265 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3270 CBlock* CreateNewBlock(CReserveKey& reservekey)
3272 CBlockIndex* pindexPrev = pindexBest;
3275 auto_ptr<CBlock> pblock(new CBlock());
3279 // Create coinbase tx
3281 txNew.vin.resize(1);
3282 txNew.vin[0].prevout.SetNull();
3283 txNew.vout.resize(1);
3284 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3286 // Add our coinbase tx as first transaction
3287 pblock->vtx.push_back(txNew);
3289 // Collect memory pool transactions into the block
3291 CRITICAL_BLOCK(cs_main)
3292 CRITICAL_BLOCK(cs_mapTransactions)
3296 // Priority order to process transactions
3297 list<COrphan> vOrphan; // list memory doesn't move
3298 map<uint256, vector<COrphan*> > mapDependers;
3299 multimap<double, CTransaction*> mapPriority;
3300 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3302 CTransaction& tx = (*mi).second;
3303 if (tx.IsCoinBase() || !tx.IsFinal())
3306 COrphan* porphan = NULL;
3307 double dPriority = 0;
3308 foreach(const CTxIn& txin, tx.vin)
3310 // Read prev transaction
3311 CTransaction txPrev;
3313 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3315 // Has to wait for dependencies
3318 // Use list for automatic deletion
3319 vOrphan.push_back(COrphan(&tx));
3320 porphan = &vOrphan.back();
3322 mapDependers[txin.prevout.hash].push_back(porphan);
3323 porphan->setDependsOn.insert(txin.prevout.hash);
3326 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3328 // Read block header
3331 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
3333 map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(block.GetHash());
3334 if (it != mapBlockIndex.end())
3336 CBlockIndex* pindex = (*it).second;
3337 if (pindex->IsInMainChain())
3338 nConf = 1 + nBestHeight - pindex->nHeight;
3342 dPriority += (double)nValueIn * nConf;
3344 if (fDebug && GetBoolArg("-printpriority"))
3345 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3348 // Priority is sum(valuein * age) / txsize
3349 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3352 porphan->dPriority = dPriority;
3354 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3356 if (fDebug && GetBoolArg("-printpriority"))
3358 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3365 // Collect transactions into block
3366 map<uint256, CTxIndex> mapTestPool;
3367 uint64 nBlockSize = 1000;
3368 int nBlockSigOps = 100;
3369 while (!mapPriority.empty())
3371 // Take highest priority transaction off priority queue
3372 double dPriority = -(*mapPriority.begin()).first;
3373 CTransaction& tx = *(*mapPriority.begin()).second;
3374 mapPriority.erase(mapPriority.begin());
3377 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3378 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3380 int nTxSigOps = tx.GetSigOpCount();
3381 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3384 // Transaction fee required depends on block size
3385 bool fAllowFree = (nBlockSize + nTxSize < 4000 || dPriority > COIN * 144 / 250);
3386 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
3388 // Connecting shouldn't fail due to dependency on other memory pool transactions
3389 // because we're already processing them in order of dependency
3390 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3391 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3393 swap(mapTestPool, mapTestPoolTmp);
3396 pblock->vtx.push_back(tx);
3397 nBlockSize += nTxSize;
3398 nBlockSigOps += nTxSigOps;
3400 // Add transactions that depend on this one to the priority queue
3401 uint256 hash = tx.GetHash();
3402 if (mapDependers.count(hash))
3404 foreach(COrphan* porphan, mapDependers[hash])
3406 if (!porphan->setDependsOn.empty())
3408 porphan->setDependsOn.erase(hash);
3409 if (porphan->setDependsOn.empty())
3410 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3416 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3419 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3420 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3421 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3422 pblock->nBits = GetNextWorkRequired(pindexPrev);
3425 return pblock.release();
3429 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
3431 // Update nExtraNonce
3432 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3433 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3438 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
3439 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3443 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3446 // Prebuild hash buffers
3453 uint256 hashPrevBlock;
3454 uint256 hashMerkleRoot;
3457 unsigned int nNonce;
3460 unsigned char pchPadding0[64];
3462 unsigned char pchPadding1[64];
3465 memset(&tmp, 0, sizeof(tmp));
3467 tmp.block.nVersion = pblock->nVersion;
3468 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3469 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3470 tmp.block.nTime = pblock->nTime;
3471 tmp.block.nBits = pblock->nBits;
3472 tmp.block.nNonce = pblock->nNonce;
3474 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3475 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3477 // Byte swap all the input buffer
3478 for (int i = 0; i < sizeof(tmp)/4; i++)
3479 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3481 // Precalc the first half of the first hash, which stays constant
3482 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3484 memcpy(pdata, &tmp.block, 128);
3485 memcpy(phash1, &tmp.hash1, 64);
3489 bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
3491 uint256 hash = pblock->GetHash();
3492 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3494 if (hash > hashTarget)
3498 printf("BitcoinMiner:\n");
3499 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3501 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3502 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3505 CRITICAL_BLOCK(cs_main)
3507 if (pblock->hashPrevBlock != hashBestChain)
3508 return error("BitcoinMiner : generated block is stale");
3510 // Remove key from key pool
3511 reservekey.KeepKey();
3513 // Track how many getdata requests this block gets
3514 CRITICAL_BLOCK(cs_mapRequestCount)
3515 mapRequestCount[pblock->GetHash()] = 0;
3517 // Process this block the same as if we had received it from another node
3518 if (!ProcessBlock(NULL, pblock))
3519 return error("BitcoinMiner : ProcessBlock, block not accepted");
3529 printf("BitcoinMiner started\n");
3530 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3531 bool f4WaySSE2 = Detect128BitSSE2();
3532 if (mapArgs.count("-4way"))
3533 f4WaySSE2 = GetBoolArg("-4way");
3535 // Each thread has its own key and counter
3536 CReserveKey reservekey;
3537 unsigned int nExtraNonce = 0;
3538 int64 nPrevTime = 0;
3540 while (fGenerateBitcoins)
3542 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3546 while (vNodes.empty() || IsInitialBlockDownload())
3551 if (!fGenerateBitcoins)
3559 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3560 CBlockIndex* pindexPrev = pindexBest;
3562 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3565 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
3567 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3571 // Prebuild hash buffers
3573 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3574 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3575 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3577 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3579 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3580 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3586 int64 nStart = GetTime();
3587 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3589 uint256& hash = *alignup<16>(hashbuf);
3592 unsigned int nHashesDone = 0;
3593 unsigned int nNonceFound;
3597 // tcatm's 4-way 128-bit SSE2 SHA-256
3598 nNonceFound = ScanHash_4WaySSE2(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
3602 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
3604 // Check if something found
3605 if (nNonceFound != -1)
3607 for (int i = 0; i < sizeof(hash)/4; i++)
3608 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3610 if (hash <= hashTarget)
3613 pblock->nNonce = ByteReverse(nNonceFound);
3614 assert(hash == pblock->GetHash());
3616 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3617 CheckWork(pblock.get(), reservekey);
3618 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3624 static int64 nHashCounter;
3625 if (nHPSTimerStart == 0)
3627 nHPSTimerStart = GetTimeMillis();
3631 nHashCounter += nHashesDone;
3632 if (GetTimeMillis() - nHPSTimerStart > 4000)
3634 static CCriticalSection cs;
3637 if (GetTimeMillis() - nHPSTimerStart > 4000)
3639 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3640 nHPSTimerStart = GetTimeMillis();
3642 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3643 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3644 static int64 nLogTime;
3645 if (GetTime() - nLogTime > 30 * 60)
3647 nLogTime = GetTime();
3648 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3649 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3655 // Check for stop or if block needs to be rebuilt
3658 if (!fGenerateBitcoins)
3660 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3664 if (nBlockNonce >= 0xffff0000)
3666 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3668 if (pindexPrev != pindexBest)
3671 // Update nTime every few seconds
3672 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3673 nBlockTime = ByteReverse(pblock->nTime);
3695 //////////////////////////////////////////////////////////////////////////////
3703 int64 nStart = GetTimeMillis();
3706 CRITICAL_BLOCK(cs_mapWallet)
3708 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3710 CWalletTx* pcoin = &(*it).second;
3711 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3713 nTotal += pcoin->GetCredit();
3717 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3722 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<CWalletTx*>& setCoinsRet)
3724 setCoinsRet.clear();
3726 // List of values less than target
3727 int64 nLowestLarger = INT64_MAX;
3728 CWalletTx* pcoinLowestLarger = NULL;
3729 vector<pair<int64, CWalletTx*> > vValue;
3730 int64 nTotalLower = 0;
3732 CRITICAL_BLOCK(cs_mapWallet)
3734 vector<CWalletTx*> vCoins;
3735 vCoins.reserve(mapWallet.size());
3736 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3737 vCoins.push_back(&(*it).second);
3738 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3740 foreach(CWalletTx* pcoin, vCoins)
3742 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3745 int nDepth = pcoin->GetDepthInMainChain();
3746 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
3749 int64 n = pcoin->GetCredit();
3752 if (n < nTargetValue)
3754 vValue.push_back(make_pair(n, pcoin));
3757 else if (n == nTargetValue)
3759 setCoinsRet.insert(pcoin);
3762 else if (n < nLowestLarger)
3765 pcoinLowestLarger = pcoin;
3770 if (nTotalLower < nTargetValue)
3772 if (pcoinLowestLarger == NULL)
3774 setCoinsRet.insert(pcoinLowestLarger);
3778 // Solve subset sum by stochastic approximation
3779 sort(vValue.rbegin(), vValue.rend());
3780 vector<char> vfIncluded;
3781 vector<char> vfBest(vValue.size(), true);
3782 int64 nBest = nTotalLower;
3784 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3786 vfIncluded.assign(vValue.size(), false);
3788 bool fReachedTarget = false;
3789 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3791 for (int i = 0; i < vValue.size(); i++)
3793 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3795 nTotal += vValue[i].first;
3796 vfIncluded[i] = true;
3797 if (nTotal >= nTargetValue)
3799 fReachedTarget = true;
3803 vfBest = vfIncluded;
3805 nTotal -= vValue[i].first;
3806 vfIncluded[i] = false;
3813 // If the next larger is still closer, return it
3814 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
3815 setCoinsRet.insert(pcoinLowestLarger);
3818 for (int i = 0; i < vValue.size(); i++)
3820 setCoinsRet.insert(vValue[i].second);
3823 printf("SelectCoins() best subset: ");
3824 for (int i = 0; i < vValue.size(); i++)
3826 printf("%s ", FormatMoney(vValue[i].first).c_str());
3827 printf("total %s\n", FormatMoney(nBest).c_str());
3833 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
3835 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet) ||
3836 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet) ||
3837 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet));
3843 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3845 CRITICAL_BLOCK(cs_main)
3847 // txdb must be opened before the mapWallet lock
3849 CRITICAL_BLOCK(cs_mapWallet)
3851 nFeeRet = nTransactionFee;
3855 wtxNew.vout.clear();
3856 wtxNew.fFromMe = true;
3859 int64 nValueOut = nValue;
3860 int64 nTotalValue = nValue + nFeeRet;
3862 // Choose coins to use
3863 set<CWalletTx*> setCoins;
3864 if (!SelectCoins(nTotalValue, setCoins))
3867 foreach(CWalletTx* pcoin, setCoins)
3868 nValueIn += pcoin->GetCredit();
3870 // Fill a vout to the payee
3871 bool fChangeFirst = GetRand(2);
3873 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3875 // Fill a vout back to self with any change
3876 int64 nChange = nValueIn - nTotalValue;
3877 if (nChange >= CENT)
3879 // Note: We use a new key here to keep it from being obvious which side is the change.
3880 // The drawback is that by not reusing a previous key, the change may be lost if a
3881 // backup is restored, if the backup doesn't have the new private key for the change.
3882 // If we reused the old key, it would be possible to add code to look for and
3883 // rediscover unknown transactions that were written with keys of ours to recover
3884 // post-backup change.
3886 // Reserve a new key pair from key pool
3887 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3888 assert(mapKeys.count(vchPubKey));
3890 // Fill a vout to ourself, using same address type as the payment
3891 CScript scriptChange;
3892 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3893 scriptChange.SetBitcoinAddress(vchPubKey);
3895 scriptChange << vchPubKey << OP_CHECKSIG;
3896 wtxNew.vout.push_back(CTxOut(nChange, scriptChange));
3899 reservekey.ReturnKey();
3901 // Fill a vout to the payee
3903 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3906 foreach(CWalletTx* pcoin, setCoins)
3907 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3908 if (pcoin->vout[nOut].IsMine())
3909 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3913 foreach(CWalletTx* pcoin, setCoins)
3914 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3915 if (pcoin->vout[nOut].IsMine())
3916 if (!SignSignature(*pcoin, wtxNew, nIn++))
3920 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
3921 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
3924 // Check that enough fee is included
3925 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
3926 int64 nMinFee = wtxNew.GetMinFee();
3927 if (nFeeRet < max(nPayFee, nMinFee))
3929 nFeeRet = max(nPayFee, nMinFee);
3933 // Fill vtxPrev by copying from previous transactions vtxPrev
3934 wtxNew.AddSupportingTransactions(txdb);
3935 wtxNew.fTimeReceivedIsTxTime = true;
3944 // Call after CreateTransaction unless you want to abort
3945 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3947 CRITICAL_BLOCK(cs_main)
3949 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3950 CRITICAL_BLOCK(cs_mapWallet)
3952 // This is only to keep the database open to defeat the auto-flush for the
3953 // duration of this scope. This is the only place where this optimization
3954 // maybe makes sense; please don't do it anywhere else.
3955 CWalletDB walletdb("r");
3957 // Take key pair from key pool so it won't be used again
3958 reservekey.KeepKey();
3960 // Add tx to wallet, because if it has change it's also ours,
3961 // otherwise just for transaction history.
3962 AddToWallet(wtxNew);
3964 // Mark old coins as spent
3965 set<CWalletTx*> setCoins;
3966 foreach(const CTxIn& txin, wtxNew.vin)
3967 setCoins.insert(&mapWallet[txin.prevout.hash]);
3968 foreach(CWalletTx* pcoin, setCoins)
3970 pcoin->fSpent = true;
3971 pcoin->WriteToDisk();
3972 vWalletUpdated.push_back(pcoin->GetHash());
3976 // Track how many getdata requests our transaction gets
3977 CRITICAL_BLOCK(cs_mapRequestCount)
3978 mapRequestCount[wtxNew.GetHash()] = 0;
3981 if (!wtxNew.AcceptToMemoryPool())
3983 // This must not fail. The transaction has already been signed and recorded.
3984 printf("CommitTransaction() : Error: Transaction not valid");
3987 wtxNew.RelayWalletTransaction();
3996 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3998 CRITICAL_BLOCK(cs_main)
4000 CReserveKey reservekey;
4002 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
4005 if (nValue + nFeeRequired > GetBalance())
4006 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
4008 strError = _("Error: Transaction creation failed ");
4009 printf("SendMoney() : %s", strError.c_str());
4013 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
4016 if (!CommitTransaction(wtxNew, reservekey))
4017 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.");
4025 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
4029 return _("Invalid amount");
4030 if (nValue + nTransactionFee > GetBalance())
4031 return _("Insufficient funds");
4033 // Parse bitcoin address
4034 CScript scriptPubKey;
4035 if (!scriptPubKey.SetBitcoinAddress(strAddress))
4036 return _("Invalid bitcoin address");
4038 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);