1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #include "checkpoints.h"
9 #include "ui_interface.h"
10 #include <boost/algorithm/string/replace.hpp>
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
15 using namespace boost;
21 CCriticalSection cs_setpwalletRegistered;
22 set<CWallet*> setpwalletRegistered;
24 CCriticalSection cs_main;
27 unsigned int nTransactionsUpdated = 0;
29 map<uint256, CBlockIndex*> mapBlockIndex;
30 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
31 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
32 CBlockIndex* pindexGenesisBlock = NULL;
34 CBigNum bnBestChainWork = 0;
35 CBigNum bnBestInvalidWork = 0;
36 uint256 hashBestChain = 0;
37 CBlockIndex* pindexBest = NULL;
38 int64 nTimeBestReceived = 0;
40 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
42 map<uint256, CBlock*> mapOrphanBlocks;
43 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
45 map<uint256, CDataStream*> mapOrphanTransactions;
46 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
48 // Constant stuff for coinbase transactions we create:
49 CScript COINBASE_FLAGS;
51 const string strMessageMagic = "Bitcoin Signed Message:\n";
57 int64 nTransactionFee = 0;
61 //////////////////////////////////////////////////////////////////////////////
63 // dispatching functions
66 // These functions dispatch to one or all registered wallets
69 void RegisterWallet(CWallet* pwalletIn)
72 LOCK(cs_setpwalletRegistered);
73 setpwalletRegistered.insert(pwalletIn);
77 void UnregisterWallet(CWallet* pwalletIn)
80 LOCK(cs_setpwalletRegistered);
81 setpwalletRegistered.erase(pwalletIn);
85 // check whether the passed transaction is from us
86 bool static IsFromMe(CTransaction& tx)
88 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
89 if (pwallet->IsFromMe(tx))
94 // get the wallet transaction with the given hash (if it exists)
95 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
97 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
98 if (pwallet->GetTransaction(hashTx,wtx))
103 // erases transaction with the given hash from all wallets
104 void static EraseFromWallets(uint256 hash)
106 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
107 pwallet->EraseFromWallet(hash);
110 // make sure all wallets know about the given transaction, in the given block
111 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
113 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
114 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
117 // notify wallets about a new best chain
118 void static SetBestChain(const CBlockLocator& loc)
120 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
121 pwallet->SetBestChain(loc);
124 // notify wallets about an updated transaction
125 void static UpdatedTransaction(const uint256& hashTx)
127 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
128 pwallet->UpdatedTransaction(hashTx);
132 void static PrintWallets(const CBlock& block)
134 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
135 pwallet->PrintWallet(block);
138 // notify wallets about an incoming inventory (for request counts)
139 void static Inventory(const uint256& hash)
141 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
142 pwallet->Inventory(hash);
145 // ask wallets to resend their transactions
146 void static ResendWalletTransactions()
148 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
149 pwallet->ResendWalletTransactions();
158 //////////////////////////////////////////////////////////////////////////////
160 // mapOrphanTransactions
163 void AddOrphanTx(const CDataStream& vMsg)
166 CDataStream(vMsg) >> tx;
167 uint256 hash = tx.GetHash();
168 if (mapOrphanTransactions.count(hash))
171 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
172 BOOST_FOREACH(const CTxIn& txin, tx.vin)
173 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
176 void static EraseOrphanTx(uint256 hash)
178 if (!mapOrphanTransactions.count(hash))
180 const CDataStream* pvMsg = mapOrphanTransactions[hash];
182 CDataStream(*pvMsg) >> tx;
183 BOOST_FOREACH(const CTxIn& txin, tx.vin)
185 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
186 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
188 if ((*mi).second == pvMsg)
189 mapOrphanTransactionsByPrev.erase(mi++);
195 mapOrphanTransactions.erase(hash);
198 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
200 unsigned int nEvicted = 0;
201 while (mapOrphanTransactions.size() > nMaxOrphans)
203 // Evict a random orphan:
204 std::vector<unsigned char> randbytes(32);
205 RAND_bytes(&randbytes[0], 32);
206 uint256 randomhash(randbytes);
207 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
208 if (it == mapOrphanTransactions.end())
209 it = mapOrphanTransactions.begin();
210 EraseOrphanTx(it->first);
222 //////////////////////////////////////////////////////////////////////////////
224 // CTransaction and CTxIndex
227 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
230 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
232 if (!ReadFromDisk(txindexRet.pos))
234 if (prevout.n >= vout.size())
242 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
245 return ReadFromDisk(txdb, prevout, txindex);
248 bool CTransaction::ReadFromDisk(COutPoint prevout)
252 return ReadFromDisk(txdb, prevout, txindex);
255 bool CTransaction::IsStandard() const
257 BOOST_FOREACH(const CTxIn& txin, vin)
259 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
260 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
261 // ~65-byte public keys, plus a few script ops.
262 if (txin.scriptSig.size() > 500)
264 if (!txin.scriptSig.IsPushOnly())
267 BOOST_FOREACH(const CTxOut& txout, vout)
268 if (!::IsStandard(txout.scriptPubKey))
274 // Check transaction inputs, and make sure any
275 // pay-to-script-hash transactions are evaluating IsStandard scripts
277 // Why bother? To avoid denial-of-service attacks; an attacker
278 // can submit a standard HASH... OP_EQUAL transaction,
279 // which will get accepted into blocks. The redemption
280 // script can be anything; an attacker could use a very
281 // expensive-to-check-upon-redemption script like:
282 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
284 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
287 return true; // Coinbases don't use vin normally
289 for (unsigned int i = 0; i < vin.size(); i++)
291 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
293 vector<vector<unsigned char> > vSolutions;
294 txnouttype whichType;
295 // get the scriptPubKey corresponding to this input:
296 const CScript& prevScript = prev.scriptPubKey;
297 if (!Solver(prevScript, whichType, vSolutions))
299 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
300 if (nArgsExpected < 0)
303 // Transactions with extra stuff in their scriptSigs are
304 // non-standard. Note that this EvalScript() call will
305 // be quick, because if there are any operations
306 // beside "push data" in the scriptSig the
307 // IsStandard() call returns false
308 vector<vector<unsigned char> > stack;
309 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
312 if (whichType == TX_SCRIPTHASH)
316 CScript subscript(stack.back().begin(), stack.back().end());
317 vector<vector<unsigned char> > vSolutions2;
318 txnouttype whichType2;
319 if (!Solver(subscript, whichType2, vSolutions2))
321 if (whichType2 == TX_SCRIPTHASH)
325 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
328 nArgsExpected += tmpExpected;
331 if (stack.size() != (unsigned int)nArgsExpected)
339 CTransaction::GetLegacySigOpCount() const
341 unsigned int nSigOps = 0;
342 BOOST_FOREACH(const CTxIn& txin, vin)
344 nSigOps += txin.scriptSig.GetSigOpCount(false);
346 BOOST_FOREACH(const CTxOut& txout, vout)
348 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
354 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
366 // Load the block this tx is in
368 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
370 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
375 // Update the tx's hashBlock
376 hashBlock = pblock->GetHash();
378 // Locate the transaction
379 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
380 if (pblock->vtx[nIndex] == *(CTransaction*)this)
382 if (nIndex == (int)pblock->vtx.size())
384 vMerkleBranch.clear();
386 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
390 // Fill in merkle branch
391 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
394 // Is the tx in a block that's in the main chain
395 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
396 if (mi == mapBlockIndex.end())
398 CBlockIndex* pindex = (*mi).second;
399 if (!pindex || !pindex->IsInMainChain())
402 return pindexBest->nHeight - pindex->nHeight + 1;
411 bool CTransaction::CheckTransaction() const
413 // Basic checks that don't depend on any context
415 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
417 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
419 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
420 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
422 // Check for negative or overflow output values
424 BOOST_FOREACH(const CTxOut& txout, vout)
426 if (txout.nValue < 0)
427 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
428 if (txout.nValue > MAX_MONEY)
429 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
430 nValueOut += txout.nValue;
431 if (!MoneyRange(nValueOut))
432 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
435 // Check for duplicate inputs
436 set<COutPoint> vInOutPoints;
437 BOOST_FOREACH(const CTxIn& txin, vin)
439 if (vInOutPoints.count(txin.prevout))
441 vInOutPoints.insert(txin.prevout);
446 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
447 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
451 BOOST_FOREACH(const CTxIn& txin, vin)
452 if (txin.prevout.IsNull())
453 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
459 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
460 bool* pfMissingInputs)
463 *pfMissingInputs = false;
465 if (!tx.CheckTransaction())
466 return error("CTxMemPool::accept() : CheckTransaction failed");
468 // Coinbase is only valid in a block, not as a loose transaction
470 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
472 // To help v0.1.5 clients who would see it as a negative number
473 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
474 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
476 // Rather not work on nonstandard transactions (unless -testnet)
477 if (!fTestNet && !tx.IsStandard())
478 return error("CTxMemPool::accept() : nonstandard transaction type");
480 // Do we already have it?
481 uint256 hash = tx.GetHash();
484 if (mapTx.count(hash))
488 if (txdb.ContainsTx(hash))
491 // Check for conflicts with in-memory transactions
492 CTransaction* ptxOld = NULL;
493 for (unsigned int i = 0; i < tx.vin.size(); i++)
495 COutPoint outpoint = tx.vin[i].prevout;
496 if (mapNextTx.count(outpoint))
498 // Disable replacement feature for now
501 // Allow replacing with a newer version of the same transaction
504 ptxOld = mapNextTx[outpoint].ptx;
505 if (ptxOld->IsFinal())
507 if (!tx.IsNewerThan(*ptxOld))
509 for (unsigned int i = 0; i < tx.vin.size(); i++)
511 COutPoint outpoint = tx.vin[i].prevout;
512 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
522 map<uint256, CTxIndex> mapUnused;
523 bool fInvalid = false;
524 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
527 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
529 *pfMissingInputs = true;
530 return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
533 // Check for non-standard pay-to-script-hash in inputs
534 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
535 return error("CTxMemPool::accept() : nonstandard transaction input");
537 // Note: if you modify this code to accept non-standard transactions, then
538 // you should add code here to check that the transaction does a
539 // reasonable number of ECDSA signature verifications.
541 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
542 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
544 // Don't accept it if it can't get into a block
545 if (nFees < tx.GetMinFee(1000, true, GMF_RELAY))
546 return error("CTxMemPool::accept() : not enough fees");
548 // Continuously rate-limit free transactions
549 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
550 // be annoying or make other's transactions take longer to confirm.
551 if (nFees < MIN_RELAY_TX_FEE)
553 static CCriticalSection cs;
554 static double dFreeCount;
555 static int64 nLastTime;
556 int64 nNow = GetTime();
560 // Use an exponentially decaying ~10-minute window:
561 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
563 // -limitfreerelay unit is thousand-bytes-per-minute
564 // At default rate it would take over a month to fill 1GB
565 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
566 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
568 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
573 // Check against previous transactions
574 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
575 if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
577 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
581 // Store transaction in memory
586 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
592 ///// are we sure this is ok when loading transactions or restoring block txes
593 // If updated, erase old tx from wallet
595 EraseFromWallets(ptxOld->GetHash());
597 printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str());
601 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
603 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
606 bool CTxMemPool::addUnchecked(CTransaction &tx)
608 printf("addUnchecked(): size %lu\n", mapTx.size());
609 // Add to memory pool without checking anything. Don't call this directly,
610 // call CTxMemPool::accept to properly check the transaction first.
613 uint256 hash = tx.GetHash();
615 for (unsigned int i = 0; i < tx.vin.size(); i++)
616 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
617 nTransactionsUpdated++;
623 bool CTxMemPool::remove(CTransaction &tx)
625 // Remove transaction from memory pool
628 uint256 hash = tx.GetHash();
629 if (mapTx.count(hash))
631 BOOST_FOREACH(const CTxIn& txin, tx.vin)
632 mapNextTx.erase(txin.prevout);
634 nTransactionsUpdated++;
645 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
647 if (hashBlock == 0 || nIndex == -1)
650 // Find the block it claims to be in
651 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
652 if (mi == mapBlockIndex.end())
654 CBlockIndex* pindex = (*mi).second;
655 if (!pindex || !pindex->IsInMainChain())
658 // Make sure the merkle branch connects to this block
659 if (!fMerkleVerified)
661 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
663 fMerkleVerified = true;
667 return pindexBest->nHeight - pindex->nHeight + 1;
671 int CMerkleTx::GetBlocksToMaturity() const
675 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
679 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
683 if (!IsInMainChain() && !ClientConnectInputs())
685 return CTransaction::AcceptToMemoryPool(txdb, false);
689 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
693 bool CMerkleTx::AcceptToMemoryPool()
696 return AcceptToMemoryPool(txdb);
701 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
706 // Add previous supporting transactions first
707 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
709 if (!tx.IsCoinBase())
711 uint256 hash = tx.GetHash();
712 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
713 tx.AcceptToMemoryPool(txdb, fCheckInputs);
716 return AcceptToMemoryPool(txdb, fCheckInputs);
721 bool CWalletTx::AcceptWalletTransaction()
724 return AcceptWalletTransaction(txdb);
727 int CTxIndex::GetDepthInMainChain() const
731 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
733 // Find the block in the index
734 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
735 if (mi == mapBlockIndex.end())
737 CBlockIndex* pindex = (*mi).second;
738 if (!pindex || !pindex->IsInMainChain())
740 return 1 + nBestHeight - pindex->nHeight;
752 //////////////////////////////////////////////////////////////////////////////
754 // CBlock and CBlockIndex
757 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
759 if (!fReadTransactions)
761 *this = pindex->GetBlockHeader();
764 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
766 if (GetHash() != pindex->GetBlockHash())
767 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
771 uint256 static GetOrphanRoot(const CBlock* pblock)
773 // Work back to the first block in the orphan chain
774 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
775 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
776 return pblock->GetHash();
779 int64 static GetBlockValue(int nHeight, int64 nFees)
781 int64 nSubsidy = 50 * COIN;
783 // Subsidy is cut in half every 4 years
784 nSubsidy >>= (nHeight / 210000);
786 return nSubsidy + nFees;
789 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
790 static const int64 nTargetSpacing = 10 * 60;
791 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
794 // minimum amount of work that could possibly be required nTime after
795 // minimum work required was nBase
797 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
799 // Testnet has min-difficulty blocks
800 // after nTargetSpacing*2 time between blocks:
801 if (fTestNet && nTime > nTargetSpacing*2)
802 return bnProofOfWorkLimit.GetCompact();
805 bnResult.SetCompact(nBase);
806 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
808 // Maximum 400% adjustment...
810 // ... in best-case exactly 4-times-normal target time
811 nTime -= nTargetTimespan*4;
813 if (bnResult > bnProofOfWorkLimit)
814 bnResult = bnProofOfWorkLimit;
815 return bnResult.GetCompact();
818 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
820 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
823 if (pindexLast == NULL)
824 return nProofOfWorkLimit;
826 // Only change once per interval
827 if ((pindexLast->nHeight+1) % nInterval != 0)
829 // Special rules for testnet after 15 Feb 2012:
830 if (fTestNet && pblock->nTime > 1329264000)
832 // If the new block's timestamp is more than 2* 10 minutes
833 // then allow mining of a min-difficulty block.
834 if (pblock->nTime - pindexLast->nTime > nTargetSpacing*2)
835 return nProofOfWorkLimit;
838 // Return the last non-special-min-difficulty-rules-block
839 const CBlockIndex* pindex = pindexLast;
840 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
841 pindex = pindex->pprev;
842 return pindex->nBits;
846 return pindexLast->nBits;
849 // Go back by what we want to be 14 days worth of blocks
850 const CBlockIndex* pindexFirst = pindexLast;
851 for (int i = 0; pindexFirst && i < nInterval-1; i++)
852 pindexFirst = pindexFirst->pprev;
855 // Limit adjustment step
856 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
857 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
858 if (nActualTimespan < nTargetTimespan/4)
859 nActualTimespan = nTargetTimespan/4;
860 if (nActualTimespan > nTargetTimespan*4)
861 nActualTimespan = nTargetTimespan*4;
865 bnNew.SetCompact(pindexLast->nBits);
866 bnNew *= nActualTimespan;
867 bnNew /= nTargetTimespan;
869 if (bnNew > bnProofOfWorkLimit)
870 bnNew = bnProofOfWorkLimit;
873 printf("GetNextWorkRequired RETARGET\n");
874 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
875 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
876 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
878 return bnNew.GetCompact();
881 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
884 bnTarget.SetCompact(nBits);
887 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
888 return error("CheckProofOfWork() : nBits below minimum work");
890 // Check proof of work matches claimed amount
891 if (hash > bnTarget.getuint256())
892 return error("CheckProofOfWork() : hash doesn't match nBits");
897 // Return maximum amount of blocks that other nodes claim to have
898 int GetNumBlocksOfPeers()
900 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
903 bool IsInitialBlockDownload()
905 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
907 static int64 nLastUpdate;
908 static CBlockIndex* pindexLastBest;
909 if (pindexBest != pindexLastBest)
911 pindexLastBest = pindexBest;
912 nLastUpdate = GetTime();
914 return (GetTime() - nLastUpdate < 10 &&
915 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
918 void static InvalidChainFound(CBlockIndex* pindexNew)
920 if (pindexNew->bnChainWork > bnBestInvalidWork)
922 bnBestInvalidWork = pindexNew->bnChainWork;
923 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
926 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());
927 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
928 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
929 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
932 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
934 nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
936 // Updating time can change work required on testnet:
938 nBits = GetNextWorkRequired(pindexPrev, this);
951 bool CTransaction::DisconnectInputs(CTxDB& txdb)
953 // Relinquish previous transactions' spent pointers
956 BOOST_FOREACH(const CTxIn& txin, vin)
958 COutPoint prevout = txin.prevout;
960 // Get prev txindex from disk
962 if (!txdb.ReadTxIndex(prevout.hash, txindex))
963 return error("DisconnectInputs() : ReadTxIndex failed");
965 if (prevout.n >= txindex.vSpent.size())
966 return error("DisconnectInputs() : prevout.n out of range");
968 // Mark outpoint as not spent
969 txindex.vSpent[prevout.n].SetNull();
972 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
973 return error("DisconnectInputs() : UpdateTxIndex failed");
977 // Remove transaction from index
978 // This can fail if a duplicate of this transaction was in a chain that got
979 // reorganized away. This is only possible if this transaction was completely
980 // spent, so erasing it would be a no-op anway.
981 txdb.EraseTxIndex(*this);
987 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
988 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
990 // FetchInputs can return false either because we just haven't seen some inputs
991 // (in which case the transaction should be stored as an orphan)
992 // or because the transaction is malformed (in which case the transaction should
993 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
997 return true; // Coinbase transactions have no inputs to fetch.
999 for (unsigned int i = 0; i < vin.size(); i++)
1001 COutPoint prevout = vin[i].prevout;
1002 if (inputsRet.count(prevout.hash))
1003 continue; // Got it already
1006 CTxIndex& txindex = inputsRet[prevout.hash].first;
1008 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1010 // Get txindex from current proposed changes
1011 txindex = mapTestPool.find(prevout.hash)->second;
1015 // Read txindex from txdb
1016 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1018 if (!fFound && (fBlock || fMiner))
1019 return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1022 CTransaction& txPrev = inputsRet[prevout.hash].second;
1023 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1025 // Get prev tx from single transactions in memory
1028 if (!mempool.exists(prevout.hash))
1029 return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1030 txPrev = mempool.lookup(prevout.hash);
1033 txindex.vSpent.resize(txPrev.vout.size());
1037 // Get prev tx from disk
1038 if (!txPrev.ReadFromDisk(txindex.pos))
1039 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1043 // Make sure all prevout.n's are valid:
1044 for (unsigned int i = 0; i < vin.size(); i++)
1046 const COutPoint prevout = vin[i].prevout;
1047 assert(inputsRet.count(prevout.hash) != 0);
1048 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1049 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1050 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1052 // Revisit this if/when transaction replacement is implemented and allows
1055 return DoS(100, error("FetchInputs() : %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()));
1062 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1064 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1065 if (mi == inputs.end())
1066 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1068 const CTransaction& txPrev = (mi->second).second;
1069 if (input.prevout.n >= txPrev.vout.size())
1070 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1072 return txPrev.vout[input.prevout.n];
1075 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1081 for (unsigned int i = 0; i < vin.size(); i++)
1083 nResult += GetOutputFor(vin[i], inputs).nValue;
1089 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1094 unsigned int nSigOps = 0;
1095 for (unsigned int i = 0; i < vin.size(); i++)
1097 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1098 if (prevout.scriptPubKey.IsPayToScriptHash())
1099 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1104 bool CTransaction::ConnectInputs(MapPrevTx inputs,
1105 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1106 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1108 // Take over previous transactions' spent pointers
1109 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1110 // fMiner is true when called from the internal bitcoin miner
1111 // ... both are false when called from CTransaction::AcceptToMemoryPool
1116 for (unsigned int i = 0; i < vin.size(); i++)
1118 COutPoint prevout = vin[i].prevout;
1119 assert(inputs.count(prevout.hash) > 0);
1120 CTxIndex& txindex = inputs[prevout.hash].first;
1121 CTransaction& txPrev = inputs[prevout.hash].second;
1123 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1124 return DoS(100, 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()));
1126 // If prev is coinbase, check that it's matured
1127 if (txPrev.IsCoinBase())
1128 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1129 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1130 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1132 // Check for conflicts (double-spend)
1133 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1134 // for an attacker to attempt to split the network.
1135 if (!txindex.vSpent[prevout.n].IsNull())
1136 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());
1138 // Check for negative or overflow input values
1139 nValueIn += txPrev.vout[prevout.n].nValue;
1140 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1141 return DoS(100, error("ConnectInputs() : txin values out of range"));
1143 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1144 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1145 // still computed and checked, and any change will be caught at the next checkpoint.
1146 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1149 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1151 // only during transition phase for P2SH: do not invoke anti-DoS code for
1152 // potentially old clients relaying bad P2SH transactions
1153 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1154 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1156 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1160 // Mark outpoints as spent
1161 txindex.vSpent[prevout.n] = posThisTx;
1164 if (fBlock || fMiner)
1166 mapTestPool[prevout.hash] = txindex;
1170 if (nValueIn < GetValueOut())
1171 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1173 // Tally transaction fees
1174 int64 nTxFee = nValueIn - GetValueOut();
1176 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1178 if (!MoneyRange(nFees))
1179 return DoS(100, error("ConnectInputs() : nFees out of range"));
1186 bool CTransaction::ClientConnectInputs()
1191 // Take over previous transactions' spent pointers
1195 for (unsigned int i = 0; i < vin.size(); i++)
1197 // Get prev tx from single transactions in memory
1198 COutPoint prevout = vin[i].prevout;
1199 if (!mempool.exists(prevout.hash))
1201 CTransaction& txPrev = mempool.lookup(prevout.hash);
1203 if (prevout.n >= txPrev.vout.size())
1207 if (!VerifySignature(txPrev, *this, i, true, 0))
1208 return error("ConnectInputs() : VerifySignature failed");
1210 ///// this is redundant with the mempool.mapNextTx stuff,
1211 ///// not sure which I want to get rid of
1212 ///// this has to go away now that posNext is gone
1213 // // Check for conflicts
1214 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1215 // return error("ConnectInputs() : prev tx already used");
1217 // // Flag outpoints as used
1218 // txPrev.vout[prevout.n].posNext = posThisTx;
1220 nValueIn += txPrev.vout[prevout.n].nValue;
1222 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1223 return error("ClientConnectInputs() : txin values out of range");
1225 if (GetValueOut() > nValueIn)
1235 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1237 // Disconnect in reverse order
1238 for (int i = vtx.size()-1; i >= 0; i--)
1239 if (!vtx[i].DisconnectInputs(txdb))
1242 // Update block index on disk without changing it in memory.
1243 // The memory index structure will be changed after the db commits.
1246 CDiskBlockIndex blockindexPrev(pindex->pprev);
1247 blockindexPrev.hashNext = 0;
1248 if (!txdb.WriteBlockIndex(blockindexPrev))
1249 return error("DisconnectBlock() : WriteBlockIndex failed");
1255 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1257 // Check it again in case a previous version let a bad block in
1261 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1262 // unless those are already completely spent.
1263 // If such overwrites are allowed, coinbases and transactions depending upon those
1264 // can be duplicated to remove the ability to spend the first instance -- even after
1265 // being sent to another address.
1266 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1267 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1268 // already refuses previously-known transaction id's entirely.
1269 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1270 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1271 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1273 BOOST_FOREACH(CTransaction& tx, vtx)
1275 CTxIndex txindexOld;
1276 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1278 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1285 // BIP16 didn't become active until Apr 1 2012 (Feb 15 on testnet)
1286 int64 nBIP16SwitchTime = fTestNet ? 1329264000 : 1333238400;
1287 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1289 //// issue here: it doesn't know the version
1290 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size());
1292 map<uint256, CTxIndex> mapQueuedChanges;
1294 unsigned int nSigOps = 0;
1295 BOOST_FOREACH(CTransaction& tx, vtx)
1297 nSigOps += tx.GetLegacySigOpCount();
1298 if (nSigOps > MAX_BLOCK_SIGOPS)
1299 return DoS(100, error("ConnectBlock() : too many sigops"));
1301 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1302 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1304 MapPrevTx mapInputs;
1305 if (!tx.IsCoinBase())
1308 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1311 if (fStrictPayToScriptHash)
1313 // Add in sigops done by pay-to-script-hash inputs;
1314 // this is to prevent a "rogue miner" from creating
1315 // an incredibly-expensive-to-validate block.
1316 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1317 if (nSigOps > MAX_BLOCK_SIGOPS)
1318 return DoS(100, error("ConnectBlock() : too many sigops"));
1321 nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
1323 if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1327 mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
1330 // Write queued txindex changes
1331 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1333 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1334 return error("ConnectBlock() : UpdateTxIndex failed");
1337 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1340 // Update block index on disk without changing it in memory.
1341 // The memory index structure will be changed after the db commits.
1344 CDiskBlockIndex blockindexPrev(pindex->pprev);
1345 blockindexPrev.hashNext = pindex->GetBlockHash();
1346 if (!txdb.WriteBlockIndex(blockindexPrev))
1347 return error("ConnectBlock() : WriteBlockIndex failed");
1350 // Watch for transactions paying to me
1351 BOOST_FOREACH(CTransaction& tx, vtx)
1352 SyncWithWallets(tx, this, true);
1357 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1359 printf("REORGANIZE\n");
1362 CBlockIndex* pfork = pindexBest;
1363 CBlockIndex* plonger = pindexNew;
1364 while (pfork != plonger)
1366 while (plonger->nHeight > pfork->nHeight)
1367 if (!(plonger = plonger->pprev))
1368 return error("Reorganize() : plonger->pprev is null");
1369 if (pfork == plonger)
1371 if (!(pfork = pfork->pprev))
1372 return error("Reorganize() : pfork->pprev is null");
1375 // List of what to disconnect
1376 vector<CBlockIndex*> vDisconnect;
1377 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1378 vDisconnect.push_back(pindex);
1380 // List of what to connect
1381 vector<CBlockIndex*> vConnect;
1382 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1383 vConnect.push_back(pindex);
1384 reverse(vConnect.begin(), vConnect.end());
1386 printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
1387 printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
1389 // Disconnect shorter branch
1390 vector<CTransaction> vResurrect;
1391 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1394 if (!block.ReadFromDisk(pindex))
1395 return error("Reorganize() : ReadFromDisk for disconnect failed");
1396 if (!block.DisconnectBlock(txdb, pindex))
1397 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1399 // Queue memory transactions to resurrect
1400 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1401 if (!tx.IsCoinBase())
1402 vResurrect.push_back(tx);
1405 // Connect longer branch
1406 vector<CTransaction> vDelete;
1407 for (unsigned int i = 0; i < vConnect.size(); i++)
1409 CBlockIndex* pindex = vConnect[i];
1411 if (!block.ReadFromDisk(pindex))
1412 return error("Reorganize() : ReadFromDisk for connect failed");
1413 if (!block.ConnectBlock(txdb, pindex))
1417 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1420 // Queue memory transactions to delete
1421 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1422 vDelete.push_back(tx);
1424 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1425 return error("Reorganize() : WriteHashBestChain failed");
1427 // Make sure it's successfully written to disk before changing memory structure
1428 if (!txdb.TxnCommit())
1429 return error("Reorganize() : TxnCommit failed");
1431 // Disconnect shorter branch
1432 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1434 pindex->pprev->pnext = NULL;
1436 // Connect longer branch
1437 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1439 pindex->pprev->pnext = pindex;
1441 // Resurrect memory transactions that were in the disconnected branch
1442 BOOST_FOREACH(CTransaction& tx, vResurrect)
1443 tx.AcceptToMemoryPool(txdb, false);
1445 // Delete redundant memory transactions that are in the connected branch
1446 BOOST_FOREACH(CTransaction& tx, vDelete)
1449 printf("REORGANIZE: done\n");
1456 runCommand(std::string strCommand)
1458 int nErr = ::system(strCommand.c_str());
1460 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1463 // Called from inside SetBestChain: attaches a block to the new best chain being built
1464 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1466 uint256 hash = GetHash();
1468 // Adding to current best branch
1469 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1472 InvalidChainFound(pindexNew);
1475 if (!txdb.TxnCommit())
1476 return error("SetBestChain() : TxnCommit failed");
1478 // Add to current best branch
1479 pindexNew->pprev->pnext = pindexNew;
1481 // Delete redundant memory transactions
1482 BOOST_FOREACH(CTransaction& tx, vtx)
1488 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1490 uint256 hash = GetHash();
1493 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1495 txdb.WriteHashBestChain(hash);
1496 if (!txdb.TxnCommit())
1497 return error("SetBestChain() : TxnCommit failed");
1498 pindexGenesisBlock = pindexNew;
1500 else if (hashPrevBlock == hashBestChain)
1502 if (!SetBestChainInner(txdb, pindexNew))
1503 return error("SetBestChain() : SetBestChainInner failed");
1507 // the first block in the new chain that will cause it to become the new best chain
1508 CBlockIndex *pindexIntermediate = pindexNew;
1510 // list of blocks that need to be connected afterwards
1511 std::vector<CBlockIndex*> vpindexSecondary;
1513 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1514 // Try to limit how much needs to be done inside
1515 while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork)
1517 vpindexSecondary.push_back(pindexIntermediate);
1518 pindexIntermediate = pindexIntermediate->pprev;
1521 if (!vpindexSecondary.empty())
1522 printf("Postponing %i reconnects\n", vpindexSecondary.size());
1524 // Switch to new best branch
1525 if (!Reorganize(txdb, pindexIntermediate))
1528 InvalidChainFound(pindexNew);
1529 return error("SetBestChain() : Reorganize failed");
1532 // Connect futher blocks
1533 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1536 if (!block.ReadFromDisk(pindex))
1538 printf("SetBestChain() : ReadFromDisk failed\n");
1542 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1543 if (!block.SetBestChainInner(txdb, pindex))
1548 // Update best block in wallet (so we can detect restored wallets)
1549 bool fIsInitialDownload = IsInitialBlockDownload();
1550 if (!fIsInitialDownload)
1552 const CBlockLocator locator(pindexNew);
1553 ::SetBestChain(locator);
1557 hashBestChain = hash;
1558 pindexBest = pindexNew;
1559 nBestHeight = pindexBest->nHeight;
1560 bnBestChainWork = pindexNew->bnChainWork;
1561 nTimeBestReceived = GetTime();
1562 nTransactionsUpdated++;
1563 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1565 std::string strCmd = GetArg("-blocknotify", "");
1567 if (!fIsInitialDownload && !strCmd.empty())
1569 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1570 boost::thread t(runCommand, strCmd); // thread runs free
1577 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1579 // Check for duplicate
1580 uint256 hash = GetHash();
1581 if (mapBlockIndex.count(hash))
1582 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1584 // Construct new block index object
1585 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1587 return error("AddToBlockIndex() : new CBlockIndex failed");
1588 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1589 pindexNew->phashBlock = &((*mi).first);
1590 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1591 if (miPrev != mapBlockIndex.end())
1593 pindexNew->pprev = (*miPrev).second;
1594 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1596 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1600 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1601 if (!txdb.TxnCommit())
1605 if (pindexNew->bnChainWork > bnBestChainWork)
1606 if (!SetBestChain(txdb, pindexNew))
1611 if (pindexNew == pindexBest)
1613 // Notify UI to display prev block's coinbase if it was ours
1614 static uint256 hashPrevBestCoinBase;
1615 UpdatedTransaction(hashPrevBestCoinBase);
1616 hashPrevBestCoinBase = vtx[0].GetHash();
1626 bool CBlock::CheckBlock() const
1628 // These are checks that are independent of context
1629 // that can be verified before saving an orphan block.
1632 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
1633 return DoS(100, error("CheckBlock() : size limits failed"));
1635 // Check proof of work matches claimed amount
1636 if (!CheckProofOfWork(GetHash(), nBits))
1637 return DoS(50, error("CheckBlock() : proof of work failed"));
1640 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1641 return error("CheckBlock() : block timestamp too far in the future");
1643 // First transaction must be coinbase, the rest must not be
1644 if (vtx.empty() || !vtx[0].IsCoinBase())
1645 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1646 for (unsigned int i = 1; i < vtx.size(); i++)
1647 if (vtx[i].IsCoinBase())
1648 return DoS(100, error("CheckBlock() : more than one coinbase"));
1650 // Check transactions
1651 BOOST_FOREACH(const CTransaction& tx, vtx)
1652 if (!tx.CheckTransaction())
1653 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1655 // Check for duplicate txids. This is caught by ConnectInputs(),
1656 // but catching it earlier avoids a potential DoS attack:
1657 set<uint256> uniqueTx;
1658 BOOST_FOREACH(const CTransaction& tx, vtx)
1660 uniqueTx.insert(tx.GetHash());
1662 if (uniqueTx.size() != vtx.size())
1663 return DoS(100, error("CheckBlock() : duplicate transaction"));
1665 unsigned int nSigOps = 0;
1666 BOOST_FOREACH(const CTransaction& tx, vtx)
1668 nSigOps += tx.GetLegacySigOpCount();
1670 if (nSigOps > MAX_BLOCK_SIGOPS)
1671 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1674 if (hashMerkleRoot != BuildMerkleTree())
1675 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1680 bool CBlock::AcceptBlock()
1682 // Check for duplicate
1683 uint256 hash = GetHash();
1684 if (mapBlockIndex.count(hash))
1685 return error("AcceptBlock() : block already in mapBlockIndex");
1687 // Get prev block index
1688 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1689 if (mi == mapBlockIndex.end())
1690 return DoS(10, error("AcceptBlock() : prev block not found"));
1691 CBlockIndex* pindexPrev = (*mi).second;
1692 int nHeight = pindexPrev->nHeight+1;
1694 // Check proof of work
1695 if (nBits != GetNextWorkRequired(pindexPrev, this))
1696 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1698 // Check timestamp against prev
1699 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1700 return error("AcceptBlock() : block's timestamp is too early");
1702 // Check that all transactions are finalized
1703 BOOST_FOREACH(const CTransaction& tx, vtx)
1704 if (!tx.IsFinal(nHeight, GetBlockTime()))
1705 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1707 // Check that the block chain matches the known block chain up to a checkpoint
1708 if (!Checkpoints::CheckBlock(nHeight, hash))
1709 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1711 // Write block to history file
1712 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
1713 return error("AcceptBlock() : out of disk space");
1714 unsigned int nFile = -1;
1715 unsigned int nBlockPos = 0;
1716 if (!WriteToDisk(nFile, nBlockPos))
1717 return error("AcceptBlock() : WriteToDisk failed");
1718 if (!AddToBlockIndex(nFile, nBlockPos))
1719 return error("AcceptBlock() : AddToBlockIndex failed");
1721 // Relay inventory, but don't relay old inventory during initial block download
1722 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1723 if (hashBestChain == hash)
1726 BOOST_FOREACH(CNode* pnode, vNodes)
1727 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1728 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1734 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1736 // Check for duplicate
1737 uint256 hash = pblock->GetHash();
1738 if (mapBlockIndex.count(hash))
1739 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1740 if (mapOrphanBlocks.count(hash))
1741 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1743 // Preliminary checks
1744 if (!pblock->CheckBlock())
1745 return error("ProcessBlock() : CheckBlock FAILED");
1747 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1748 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1750 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1751 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1755 pfrom->Misbehaving(100);
1756 return error("ProcessBlock() : block with timestamp before last checkpoint");
1759 bnNewBlock.SetCompact(pblock->nBits);
1761 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1762 if (bnNewBlock > bnRequired)
1765 pfrom->Misbehaving(100);
1766 return error("ProcessBlock() : block with too little proof-of-work");
1771 // If don't already have its previous block, shunt it off to holding area until we get it
1772 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1774 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1775 CBlock* pblock2 = new CBlock(*pblock);
1776 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1777 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1779 // Ask this guy to fill in what we're missing
1781 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1786 if (!pblock->AcceptBlock())
1787 return error("ProcessBlock() : AcceptBlock FAILED");
1789 // Recursively process any orphan blocks that depended on this one
1790 vector<uint256> vWorkQueue;
1791 vWorkQueue.push_back(hash);
1792 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1794 uint256 hashPrev = vWorkQueue[i];
1795 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1796 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1799 CBlock* pblockOrphan = (*mi).second;
1800 if (pblockOrphan->AcceptBlock())
1801 vWorkQueue.push_back(pblockOrphan->GetHash());
1802 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1803 delete pblockOrphan;
1805 mapOrphanBlocksByPrev.erase(hashPrev);
1808 printf("ProcessBlock: ACCEPTED\n");
1819 bool CheckDiskSpace(uint64 nAdditionalBytes)
1821 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1823 // Check for 15MB because database could create another 10MB log file at any time
1824 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1827 string strMessage = _("Warning: Disk space is low ");
1828 strMiscWarning = strMessage;
1829 printf("*** %s\n", strMessage.c_str());
1830 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION | wxMODAL);
1837 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1841 FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
1844 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1846 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1855 static unsigned int nCurrentBlockFile = 1;
1857 FILE* AppendBlockFile(unsigned int& nFileRet)
1862 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1865 if (fseek(file, 0, SEEK_END) != 0)
1867 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1868 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1870 nFileRet = nCurrentBlockFile;
1874 nCurrentBlockFile++;
1878 bool LoadBlockIndex(bool fAllowNew)
1882 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1883 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1884 pchMessageStart[0] = 0xfa;
1885 pchMessageStart[1] = 0xbf;
1886 pchMessageStart[2] = 0xb5;
1887 pchMessageStart[3] = 0xda;
1894 if (!txdb.LoadBlockIndex())
1899 // Init with genesis block
1901 if (mapBlockIndex.empty())
1907 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1908 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1909 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1910 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1911 // vMerkleTree: 4a5e1e
1914 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1916 txNew.vin.resize(1);
1917 txNew.vout.resize(1);
1918 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1919 txNew.vout[0].nValue = 50 * COIN;
1920 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1922 block.vtx.push_back(txNew);
1923 block.hashPrevBlock = 0;
1924 block.hashMerkleRoot = block.BuildMerkleTree();
1926 block.nTime = 1231006505;
1927 block.nBits = 0x1d00ffff;
1928 block.nNonce = 2083236893;
1932 block.nTime = 1296688602;
1933 block.nBits = 0x1d07fff8;
1934 block.nNonce = 384568319;
1938 printf("%s\n", block.GetHash().ToString().c_str());
1939 printf("%s\n", hashGenesisBlock.ToString().c_str());
1940 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1941 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1943 assert(block.GetHash() == hashGenesisBlock);
1945 // Start new block file
1947 unsigned int nBlockPos;
1948 if (!block.WriteToDisk(nFile, nBlockPos))
1949 return error("LoadBlockIndex() : writing genesis block to disk failed");
1950 if (!block.AddToBlockIndex(nFile, nBlockPos))
1951 return error("LoadBlockIndex() : genesis block not accepted");
1959 void PrintBlockTree()
1961 // precompute tree structure
1962 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1963 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1965 CBlockIndex* pindex = (*mi).second;
1966 mapNext[pindex->pprev].push_back(pindex);
1968 //while (rand() % 3 == 0)
1969 // mapNext[pindex->pprev].push_back(pindex);
1972 vector<pair<int, CBlockIndex*> > vStack;
1973 vStack.push_back(make_pair(0, pindexGenesisBlock));
1976 while (!vStack.empty())
1978 int nCol = vStack.back().first;
1979 CBlockIndex* pindex = vStack.back().second;
1982 // print split or gap
1983 if (nCol > nPrevCol)
1985 for (int i = 0; i < nCol-1; i++)
1989 else if (nCol < nPrevCol)
1991 for (int i = 0; i < nCol; i++)
1998 for (int i = 0; i < nCol; i++)
2003 block.ReadFromDisk(pindex);
2004 printf("%d (%u,%u) %s %s tx %d",
2008 block.GetHash().ToString().substr(0,20).c_str(),
2009 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2012 PrintWallets(block);
2014 // put the main timechain first
2015 vector<CBlockIndex*>& vNext = mapNext[pindex];
2016 for (unsigned int i = 0; i < vNext.size(); i++)
2018 if (vNext[i]->pnext)
2020 swap(vNext[0], vNext[i]);
2026 for (unsigned int i = 0; i < vNext.size(); i++)
2027 vStack.push_back(make_pair(nCol+i, vNext[i]));
2040 //////////////////////////////////////////////////////////////////////////////
2045 map<uint256, CAlert> mapAlerts;
2046 CCriticalSection cs_mapAlerts;
2048 string GetWarnings(string strFor)
2051 string strStatusBar;
2053 if (GetBoolArg("-testsafemode"))
2056 // Misc warnings like out of disk space and clock is wrong
2057 if (strMiscWarning != "")
2060 strStatusBar = strMiscWarning;
2063 // Longer invalid proof-of-work chain
2064 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2067 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2073 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2075 const CAlert& alert = item.second;
2076 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2078 nPriority = alert.nPriority;
2079 strStatusBar = alert.strStatusBar;
2084 if (strFor == "statusbar")
2085 return strStatusBar;
2086 else if (strFor == "rpc")
2088 assert(!"GetWarnings() : invalid parameter");
2092 bool CAlert::ProcessAlert()
2094 if (!CheckSignature())
2101 // Cancel previous alerts
2102 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2104 const CAlert& alert = (*mi).second;
2107 printf("cancelling alert %d\n", alert.nID);
2108 mapAlerts.erase(mi++);
2110 else if (!alert.IsInEffect())
2112 printf("expiring alert %d\n", alert.nID);
2113 mapAlerts.erase(mi++);
2119 // Check if this alert has been cancelled
2120 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2122 const CAlert& alert = item.second;
2123 if (alert.Cancels(*this))
2125 printf("alert already cancelled by %d\n", alert.nID);
2131 mapAlerts.insert(make_pair(GetHash(), *this));
2134 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2146 //////////////////////////////////////////////////////////////////////////////
2152 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2158 bool txInMap = false;
2161 txInMap = (mempool.exists(inv.hash));
2164 mapOrphanTransactions.count(inv.hash) ||
2165 txdb.ContainsTx(inv.hash);
2169 return mapBlockIndex.count(inv.hash) ||
2170 mapOrphanBlocks.count(inv.hash);
2172 // Don't know what it is, just say we already got one
2179 // The message start string is designed to be unlikely to occur in normal data.
2180 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2181 // a large 4-byte int at any alignment.
2182 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2185 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2187 static map<CService, vector<unsigned char> > mapReuseKey;
2188 RandAddSeedPerfmon();
2190 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2191 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2193 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2195 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2203 if (strCommand == "version")
2205 // Each connection can only send one version message
2206 if (pfrom->nVersion != 0)
2208 pfrom->Misbehaving(1);
2216 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2217 if (pfrom->nVersion < MIN_PROTO_VERSION)
2219 // Since February 20, 2012, the protocol is initiated at version 209,
2220 // and earlier versions are no longer supported
2221 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2222 pfrom->fDisconnect = true;
2226 if (pfrom->nVersion == 10300)
2227 pfrom->nVersion = 300;
2229 vRecv >> addrFrom >> nNonce;
2231 vRecv >> pfrom->strSubVer;
2233 vRecv >> pfrom->nStartingHeight;
2235 // Disconnect if we connected to ourself
2236 if (nNonce == nLocalHostNonce && nNonce > 1)
2238 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2239 pfrom->fDisconnect = true;
2243 // Be shy and don't send version until we hear
2244 if (pfrom->fInbound)
2245 pfrom->PushVersion();
2247 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2249 AddTimeData(pfrom->addr, nTime);
2252 pfrom->PushMessage("verack");
2253 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2255 if (!pfrom->fInbound)
2257 // Advertise our address
2258 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() &&
2259 !IsInitialBlockDownload())
2261 CAddress addr(addrLocalHost);
2262 addr.nTime = GetAdjustedTime();
2263 pfrom->PushAddress(addr);
2266 // Get recent addresses
2267 if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2269 pfrom->PushMessage("getaddr");
2270 pfrom->fGetAddr = true;
2272 addrman.Good(pfrom->addr);
2274 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2276 addrman.Add(addrFrom, addrFrom);
2277 addrman.Good(addrFrom);
2281 // Ask the first connected node for block updates
2282 static int nAskedForBlocks = 0;
2283 if (!pfrom->fClient &&
2284 (pfrom->nVersion < NOBLKS_VERSION_START ||
2285 pfrom->nVersion >= NOBLKS_VERSION_END) &&
2286 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2289 pfrom->PushGetBlocks(pindexBest, uint256(0));
2295 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2296 item.second.RelayTo(pfrom);
2299 pfrom->fSuccessfullyConnected = true;
2301 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2303 cPeerBlockCounts.input(pfrom->nStartingHeight);
2307 else if (pfrom->nVersion == 0)
2309 // Must have a version message before anything else
2310 pfrom->Misbehaving(1);
2315 else if (strCommand == "verack")
2317 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2321 else if (strCommand == "addr")
2323 vector<CAddress> vAddr;
2326 // Don't want addr from older versions unless seeding
2327 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2329 if (vAddr.size() > 1000)
2331 pfrom->Misbehaving(20);
2332 return error("message addr size() = %d", vAddr.size());
2335 // Store the new addresses
2336 int64 nNow = GetAdjustedTime();
2337 int64 nSince = nNow - 10 * 60;
2338 BOOST_FOREACH(CAddress& addr, vAddr)
2342 // ignore IPv6 for now, since it isn't implemented anyway
2345 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2346 addr.nTime = nNow - 5 * 24 * 60 * 60;
2347 pfrom->AddAddressKnown(addr);
2348 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2350 // Relay to a limited number of other nodes
2353 // Use deterministic randomness to send to the same nodes for 24 hours
2354 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2355 static uint256 hashSalt;
2357 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2358 int64 hashAddr = addr.GetHash();
2359 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2360 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2361 multimap<uint256, CNode*> mapMix;
2362 BOOST_FOREACH(CNode* pnode, vNodes)
2364 if (pnode->nVersion < CADDR_TIME_VERSION)
2366 unsigned int nPointer;
2367 memcpy(&nPointer, &pnode, sizeof(nPointer));
2368 uint256 hashKey = hashRand ^ nPointer;
2369 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2370 mapMix.insert(make_pair(hashKey, pnode));
2372 int nRelayNodes = 2;
2373 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2374 ((*mi).second)->PushAddress(addr);
2378 addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60);
2379 if (vAddr.size() < 1000)
2380 pfrom->fGetAddr = false;
2384 else if (strCommand == "inv")
2388 if (vInv.size() > 50000)
2390 pfrom->Misbehaving(20);
2391 return error("message inv size() = %d", vInv.size());
2395 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
2397 const CInv &inv = vInv[nInv];
2401 pfrom->AddInventoryKnown(inv);
2403 bool fAlreadyHave = AlreadyHave(txdb, inv);
2405 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2407 // Always request the last block in an inv bundle (even if we already have it), as it is the
2408 // trigger for the other side to send further invs. If we are stuck on a (very long) side chain,
2409 // this is necessary to connect earlier received orphan blocks to the chain again.
2410 if (!fAlreadyHave || (inv.type == MSG_BLOCK && nInv==vInv.size()-1))
2412 if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2413 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2415 // Track requests for our stuff
2416 Inventory(inv.hash);
2421 else if (strCommand == "getdata")
2425 if (vInv.size() > 50000)
2427 pfrom->Misbehaving(20);
2428 return error("message getdata size() = %d", vInv.size());
2431 BOOST_FOREACH(const CInv& inv, vInv)
2435 printf("received getdata for: %s\n", inv.ToString().c_str());
2437 if (inv.type == MSG_BLOCK)
2439 // Send block from disk
2440 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2441 if (mi != mapBlockIndex.end())
2444 block.ReadFromDisk((*mi).second);
2445 pfrom->PushMessage("block", block);
2447 // Trigger them to send a getblocks request for the next batch of inventory
2448 if (inv.hash == pfrom->hashContinue)
2450 // Bypass PushInventory, this must send even if redundant,
2451 // and we want it right after the last block so they don't
2452 // wait for other stuff first.
2454 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2455 pfrom->PushMessage("inv", vInv);
2456 pfrom->hashContinue = 0;
2460 else if (inv.IsKnownType())
2462 // Send stream from relay memory
2465 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2466 if (mi != mapRelay.end())
2467 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2471 // Track requests for our stuff
2472 Inventory(inv.hash);
2477 else if (strCommand == "getblocks")
2479 CBlockLocator locator;
2481 vRecv >> locator >> hashStop;
2483 // Find the last block the caller has in the main chain
2484 CBlockIndex* pindex = locator.GetBlockIndex();
2486 // Send the rest of the chain
2488 pindex = pindex->pnext;
2489 int nLimit = 500 + locator.GetDistanceBack();
2490 unsigned int nBytes = 0;
2491 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2492 for (; pindex; pindex = pindex->pnext)
2494 if (pindex->GetBlockHash() == hashStop)
2496 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2499 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2501 block.ReadFromDisk(pindex, true);
2502 nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
2503 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2505 // When this block is requested, we'll send an inv that'll make them
2506 // getblocks the next batch of inventory.
2507 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2508 pfrom->hashContinue = pindex->GetBlockHash();
2515 else if (strCommand == "getheaders")
2517 CBlockLocator locator;
2519 vRecv >> locator >> hashStop;
2521 CBlockIndex* pindex = NULL;
2522 if (locator.IsNull())
2524 // If locator is null, return the hashStop block
2525 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2526 if (mi == mapBlockIndex.end())
2528 pindex = (*mi).second;
2532 // Find the last block the caller has in the main chain
2533 pindex = locator.GetBlockIndex();
2535 pindex = pindex->pnext;
2538 vector<CBlock> vHeaders;
2540 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
2541 for (; pindex; pindex = pindex->pnext)
2543 vHeaders.push_back(pindex->GetBlockHeader());
2544 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2547 pfrom->PushMessage("headers", vHeaders);
2551 else if (strCommand == "tx")
2553 vector<uint256> vWorkQueue;
2554 CDataStream vMsg(vRecv);
2559 CInv inv(MSG_TX, tx.GetHash());
2560 pfrom->AddInventoryKnown(inv);
2562 bool fMissingInputs = false;
2563 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
2565 SyncWithWallets(tx, NULL, true);
2566 RelayMessage(inv, vMsg);
2567 mapAlreadyAskedFor.erase(inv);
2568 vWorkQueue.push_back(inv.hash);
2570 // Recursively process any orphan transactions that depended on this one
2571 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2573 uint256 hashPrev = vWorkQueue[i];
2574 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2575 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2578 const CDataStream& vMsg = *((*mi).second);
2580 CDataStream(vMsg) >> tx;
2581 CInv inv(MSG_TX, tx.GetHash());
2583 if (tx.AcceptToMemoryPool(txdb, true))
2585 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2586 SyncWithWallets(tx, NULL, true);
2587 RelayMessage(inv, vMsg);
2588 mapAlreadyAskedFor.erase(inv);
2589 vWorkQueue.push_back(inv.hash);
2594 BOOST_FOREACH(uint256 hash, vWorkQueue)
2595 EraseOrphanTx(hash);
2597 else if (fMissingInputs)
2599 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2602 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2603 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
2605 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
2607 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2611 else if (strCommand == "block")
2616 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2619 CInv inv(MSG_BLOCK, block.GetHash());
2620 pfrom->AddInventoryKnown(inv);
2622 if (ProcessBlock(pfrom, &block))
2623 mapAlreadyAskedFor.erase(inv);
2624 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2628 else if (strCommand == "getaddr")
2630 pfrom->vAddrToSend.clear();
2631 vector<CAddress> vAddr = addrman.GetAddr();
2632 BOOST_FOREACH(const CAddress &addr, vAddr)
2633 pfrom->PushAddress(addr);
2637 else if (strCommand == "checkorder")
2642 if (!GetBoolArg("-allowreceivebyip"))
2644 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2651 /// we have a chance to check the order here
2653 // Keep giving the same key to the same ip until they use it
2654 if (!mapReuseKey.count(pfrom->addr))
2655 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
2657 // Send back approval of order and pubkey to use
2658 CScript scriptPubKey;
2659 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
2660 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2664 else if (strCommand == "reply")
2669 CRequestTracker tracker;
2671 LOCK(pfrom->cs_mapRequests);
2672 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2673 if (mi != pfrom->mapRequests.end())
2675 tracker = (*mi).second;
2676 pfrom->mapRequests.erase(mi);
2679 if (!tracker.IsNull())
2680 tracker.fn(tracker.param1, vRecv);
2684 else if (strCommand == "ping")
2686 if (pfrom->nVersion > BIP0031_VERSION)
2690 // Echo the message back with the nonce. This allows for two useful features:
2692 // 1) A remote node can quickly check if the connection is operational
2693 // 2) Remote nodes can measure the latency of the network thread. If this node
2694 // is overloaded it won't respond to pings quickly and the remote node can
2695 // avoid sending us more work, like chain download requests.
2697 // The nonce stops the remote getting confused between different pings: without
2698 // it, if the remote node sends a ping once per second and this node takes 5
2699 // seconds to respond to each, the 5th ping the remote sends would appear to
2700 // return very quickly.
2701 pfrom->PushMessage("pong", nonce);
2706 else if (strCommand == "alert")
2711 if (alert.ProcessAlert())
2714 pfrom->setKnown.insert(alert.GetHash());
2717 BOOST_FOREACH(CNode* pnode, vNodes)
2718 alert.RelayTo(pnode);
2726 // Ignore unknown commands for extensibility
2730 // Update the last seen time for this node's address
2731 if (pfrom->fNetworkNode)
2732 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2733 AddressCurrentlyConnected(pfrom->addr);
2739 bool ProcessMessages(CNode* pfrom)
2741 CDataStream& vRecv = pfrom->vRecv;
2745 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2749 // (4) message start
2758 // Scan for message start
2759 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2760 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2761 if (vRecv.end() - pstart < nHeaderSize)
2763 if ((int)vRecv.size() > nHeaderSize)
2765 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2766 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2770 if (pstart - vRecv.begin() > 0)
2771 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2772 vRecv.erase(vRecv.begin(), pstart);
2775 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2780 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2783 string strCommand = hdr.GetCommand();
2786 unsigned int nMessageSize = hdr.nMessageSize;
2787 if (nMessageSize > MAX_SIZE)
2789 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2792 if (nMessageSize > vRecv.size())
2794 // Rewind and wait for rest of message
2795 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2800 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2801 unsigned int nChecksum = 0;
2802 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2803 if (nChecksum != hdr.nChecksum)
2805 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2806 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2810 // Copy message to its own buffer
2811 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2812 vRecv.ignore(nMessageSize);
2820 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2825 catch (std::ios_base::failure& e)
2827 if (strstr(e.what(), "end of data"))
2829 // Allow exceptions from underlength message on vRecv
2830 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());
2832 else if (strstr(e.what(), "size too large"))
2834 // Allow exceptions from overlong size
2835 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2839 PrintExceptionContinue(&e, "ProcessMessage()");
2842 catch (std::exception& e) {
2843 PrintExceptionContinue(&e, "ProcessMessage()");
2845 PrintExceptionContinue(NULL, "ProcessMessage()");
2849 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2857 bool SendMessages(CNode* pto, bool fSendTrickle)
2859 TRY_LOCK(cs_main, lockMain);
2861 // Don't send anything until we get their version message
2862 if (pto->nVersion == 0)
2865 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
2867 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
2868 if (pto->nVersion > BIP0031_VERSION)
2869 pto->PushMessage("ping", 0);
2871 pto->PushMessage("ping");
2874 // Resend wallet transactions that haven't gotten in a block yet
2875 ResendWalletTransactions();
2877 // Address refresh broadcast
2878 static int64 nLastRebroadcast;
2879 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
2883 BOOST_FOREACH(CNode* pnode, vNodes)
2885 // Periodically clear setAddrKnown to allow refresh broadcasts
2886 if (nLastRebroadcast)
2887 pnode->setAddrKnown.clear();
2889 // Rebroadcast our address
2890 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable())
2892 CAddress addr(addrLocalHost);
2893 addr.nTime = GetAdjustedTime();
2894 pnode->PushAddress(addr);
2898 nLastRebroadcast = GetTime();
2906 vector<CAddress> vAddr;
2907 vAddr.reserve(pto->vAddrToSend.size());
2908 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2910 // returns true if wasn't already contained in the set
2911 if (pto->setAddrKnown.insert(addr).second)
2913 vAddr.push_back(addr);
2914 // receiver rejects addr messages larger than 1000
2915 if (vAddr.size() >= 1000)
2917 pto->PushMessage("addr", vAddr);
2922 pto->vAddrToSend.clear();
2924 pto->PushMessage("addr", vAddr);
2929 // Message: inventory
2932 vector<CInv> vInvWait;
2934 LOCK(pto->cs_inventory);
2935 vInv.reserve(pto->vInventoryToSend.size());
2936 vInvWait.reserve(pto->vInventoryToSend.size());
2937 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2939 if (pto->setInventoryKnown.count(inv))
2942 // trickle out tx inv to protect privacy
2943 if (inv.type == MSG_TX && !fSendTrickle)
2945 // 1/4 of tx invs blast to all immediately
2946 static uint256 hashSalt;
2948 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2949 uint256 hashRand = inv.hash ^ hashSalt;
2950 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2951 bool fTrickleWait = ((hashRand & 3) != 0);
2953 // always trickle our own transactions
2957 if (GetTransaction(inv.hash, wtx))
2959 fTrickleWait = true;
2964 vInvWait.push_back(inv);
2969 // returns true if wasn't already contained in the set
2970 if (pto->setInventoryKnown.insert(inv).second)
2972 vInv.push_back(inv);
2973 if (vInv.size() >= 1000)
2975 pto->PushMessage("inv", vInv);
2980 pto->vInventoryToSend = vInvWait;
2983 pto->PushMessage("inv", vInv);
2989 vector<CInv> vGetData;
2990 int64 nNow = GetTime() * 1000000;
2992 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2994 const CInv& inv = (*pto->mapAskFor.begin()).second;
2995 if (!AlreadyHave(txdb, inv))
2997 printf("sending getdata: %s\n", inv.ToString().c_str());
2998 vGetData.push_back(inv);
2999 if (vGetData.size() >= 1000)
3001 pto->PushMessage("getdata", vGetData);
3005 mapAlreadyAskedFor[inv] = nNow;
3006 pto->mapAskFor.erase(pto->mapAskFor.begin());
3008 if (!vGetData.empty())
3009 pto->PushMessage("getdata", vGetData);
3028 //////////////////////////////////////////////////////////////////////////////
3033 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3035 unsigned char* pdata = (unsigned char*)pbuffer;
3036 unsigned int blocks = 1 + ((len + 8) / 64);
3037 unsigned char* pend = pdata + 64 * blocks;
3038 memset(pdata + len, 0, 64 * blocks - len);
3040 unsigned int bits = len * 8;
3041 pend[-1] = (bits >> 0) & 0xff;
3042 pend[-2] = (bits >> 8) & 0xff;
3043 pend[-3] = (bits >> 16) & 0xff;
3044 pend[-4] = (bits >> 24) & 0xff;
3048 static const unsigned int pSHA256InitState[8] =
3049 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3051 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3054 unsigned char data[64];
3058 for (int i = 0; i < 16; i++)
3059 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3061 for (int i = 0; i < 8; i++)
3062 ctx.h[i] = ((uint32_t*)pinit)[i];
3064 SHA256_Update(&ctx, data, sizeof(data));
3065 for (int i = 0; i < 8; i++)
3066 ((uint32_t*)pstate)[i] = ctx.h[i];
3070 // ScanHash scans nonces looking for a hash with at least some zero bits.
3071 // It operates on big endian data. Caller does the byte reversing.
3072 // All input buffers are 16-byte aligned. nNonce is usually preserved
3073 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3074 // the block is rebuilt and nNonce starts over at zero.
3076 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3078 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3082 // Hash pdata using pmidstate as the starting state into
3083 // preformatted buffer phash1, then hash phash1 into phash
3085 SHA256Transform(phash1, pdata, pmidstate);
3086 SHA256Transform(phash, phash1, pSHA256InitState);
3088 // Return the nonce if the hash has at least some zero bits,
3089 // caller will check if it has enough to reach the target
3090 if (((unsigned short*)phash)[14] == 0)
3093 // If nothing found after trying for a while, return -1
3094 if ((nNonce & 0xffff) == 0)
3096 nHashesDone = 0xffff+1;
3097 return (unsigned int) -1;
3102 // Some explaining would be appreciated
3107 set<uint256> setDependsOn;
3110 COrphan(CTransaction* ptxIn)
3118 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3119 BOOST_FOREACH(uint256 hash, setDependsOn)
3120 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3125 uint64 nLastBlockTx = 0;
3126 uint64 nLastBlockSize = 0;
3128 CBlock* CreateNewBlock(CReserveKey& reservekey)
3130 CBlockIndex* pindexPrev = pindexBest;
3133 auto_ptr<CBlock> pblock(new CBlock());
3137 // Create coinbase tx
3139 txNew.vin.resize(1);
3140 txNew.vin[0].prevout.SetNull();
3141 txNew.vout.resize(1);
3142 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3144 // Add our coinbase tx as first transaction
3145 pblock->vtx.push_back(txNew);
3147 // Collect memory pool transactions into the block
3150 LOCK2(cs_main, mempool.cs);
3153 // Priority order to process transactions
3154 list<COrphan> vOrphan; // list memory doesn't move
3155 map<uint256, vector<COrphan*> > mapDependers;
3156 multimap<double, CTransaction*> mapPriority;
3157 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3159 CTransaction& tx = (*mi).second;
3160 if (tx.IsCoinBase() || !tx.IsFinal())
3163 COrphan* porphan = NULL;
3164 double dPriority = 0;
3165 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3167 // Read prev transaction
3168 CTransaction txPrev;
3170 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3172 // Has to wait for dependencies
3175 // Use list for automatic deletion
3176 vOrphan.push_back(COrphan(&tx));
3177 porphan = &vOrphan.back();
3179 mapDependers[txin.prevout.hash].push_back(porphan);
3180 porphan->setDependsOn.insert(txin.prevout.hash);
3183 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3185 // Read block header
3186 int nConf = txindex.GetDepthInMainChain();
3188 dPriority += (double)nValueIn * nConf;
3190 if (fDebug && GetBoolArg("-printpriority"))
3191 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3194 // Priority is sum(valuein * age) / txsize
3195 dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3198 porphan->dPriority = dPriority;
3200 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3202 if (fDebug && GetBoolArg("-printpriority"))
3204 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3211 // Collect transactions into block
3212 map<uint256, CTxIndex> mapTestPool;
3213 uint64 nBlockSize = 1000;
3214 uint64 nBlockTx = 0;
3215 int nBlockSigOps = 100;
3216 while (!mapPriority.empty())
3218 // Take highest priority transaction off priority queue
3219 double dPriority = -(*mapPriority.begin()).first;
3220 CTransaction& tx = *(*mapPriority.begin()).second;
3221 mapPriority.erase(mapPriority.begin());
3224 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3225 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3228 // Legacy limits on sigOps:
3229 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
3230 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3233 // Transaction fee required depends on block size
3234 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3235 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
3237 // Connecting shouldn't fail due to dependency on other memory pool transactions
3238 // because we're already processing them in order of dependency
3239 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3240 MapPrevTx mapInputs;
3242 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3245 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3246 if (nTxFees < nMinFee)
3249 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3250 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3253 if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3255 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3256 swap(mapTestPool, mapTestPoolTmp);
3259 pblock->vtx.push_back(tx);
3260 nBlockSize += nTxSize;
3262 nBlockSigOps += nTxSigOps;
3265 // Add transactions that depend on this one to the priority queue
3266 uint256 hash = tx.GetHash();
3267 if (mapDependers.count(hash))
3269 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3271 if (!porphan->setDependsOn.empty())
3273 porphan->setDependsOn.erase(hash);
3274 if (porphan->setDependsOn.empty())
3275 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3281 nLastBlockTx = nBlockTx;
3282 nLastBlockSize = nBlockSize;
3283 printf("CreateNewBlock(): total size %lu\n", nBlockSize);
3286 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3289 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3290 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3291 pblock->UpdateTime(pindexPrev);
3292 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
3295 return pblock.release();
3299 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3301 // Update nExtraNonce
3302 static uint256 hashPrevBlock;
3303 if (hashPrevBlock != pblock->hashPrevBlock)
3306 hashPrevBlock = pblock->hashPrevBlock;
3309 pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
3310 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3312 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3316 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3319 // Prebuild hash buffers
3326 uint256 hashPrevBlock;
3327 uint256 hashMerkleRoot;
3330 unsigned int nNonce;
3333 unsigned char pchPadding0[64];
3335 unsigned char pchPadding1[64];
3338 memset(&tmp, 0, sizeof(tmp));
3340 tmp.block.nVersion = pblock->nVersion;
3341 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3342 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3343 tmp.block.nTime = pblock->nTime;
3344 tmp.block.nBits = pblock->nBits;
3345 tmp.block.nNonce = pblock->nNonce;
3347 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3348 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3350 // Byte swap all the input buffer
3351 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3352 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3354 // Precalc the first half of the first hash, which stays constant
3355 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3357 memcpy(pdata, &tmp.block, 128);
3358 memcpy(phash1, &tmp.hash1, 64);
3362 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3364 uint256 hash = pblock->GetHash();
3365 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3367 if (hash > hashTarget)
3371 printf("BitcoinMiner:\n");
3372 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3374 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3375 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3380 if (pblock->hashPrevBlock != hashBestChain)
3381 return error("BitcoinMiner : generated block is stale");
3383 // Remove key from key pool
3384 reservekey.KeepKey();
3386 // Track how many getdata requests this block gets
3388 LOCK(wallet.cs_wallet);
3389 wallet.mapRequestCount[pblock->GetHash()] = 0;
3392 // Process this block the same as if we had received it from another node
3393 if (!ProcessBlock(NULL, pblock))
3394 return error("BitcoinMiner : ProcessBlock, block not accepted");
3400 void static ThreadBitcoinMiner(void* parg);
3402 static bool fGenerateBitcoins = false;
3403 static bool fLimitProcessors = false;
3404 static int nLimitProcessors = -1;
3406 void static BitcoinMiner(CWallet *pwallet)
3408 printf("BitcoinMiner started\n");
3409 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3411 // Each thread has its own key and counter
3412 CReserveKey reservekey(pwallet);
3413 unsigned int nExtraNonce = 0;
3415 while (fGenerateBitcoins)
3419 while (vNodes.empty() || IsInitialBlockDownload())
3424 if (!fGenerateBitcoins)
3432 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3433 CBlockIndex* pindexPrev = pindexBest;
3435 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3438 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3440 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3444 // Prebuild hash buffers
3446 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3447 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3448 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3450 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3452 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3453 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
3454 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3460 int64 nStart = GetTime();
3461 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3463 uint256& hash = *alignup<16>(hashbuf);
3466 unsigned int nHashesDone = 0;
3467 unsigned int nNonceFound;
3470 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3471 (char*)&hash, nHashesDone);
3473 // Check if something found
3474 if (nNonceFound != (unsigned int) -1)
3476 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
3477 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3479 if (hash <= hashTarget)
3482 pblock->nNonce = ByteReverse(nNonceFound);
3483 assert(hash == pblock->GetHash());
3485 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3486 CheckWork(pblock.get(), *pwalletMain, reservekey);
3487 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3493 static int64 nHashCounter;
3494 if (nHPSTimerStart == 0)
3496 nHPSTimerStart = GetTimeMillis();
3500 nHashCounter += nHashesDone;
3501 if (GetTimeMillis() - nHPSTimerStart > 4000)
3503 static CCriticalSection cs;
3506 if (GetTimeMillis() - nHPSTimerStart > 4000)
3508 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3509 nHPSTimerStart = GetTimeMillis();
3511 static int64 nLogTime;
3512 if (GetTime() - nLogTime > 30 * 60)
3514 nLogTime = GetTime();
3515 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3516 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
3522 // Check for stop or if block needs to be rebuilt
3525 if (!fGenerateBitcoins)
3527 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
3531 if (nBlockNonce >= 0xffff0000)
3533 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3535 if (pindexPrev != pindexBest)
3538 // Update nTime every few seconds
3539 pblock->UpdateTime(pindexPrev);
3540 nBlockTime = ByteReverse(pblock->nTime);
3543 // Changing pblock->nTime can change work required on testnet:
3544 nBlockBits = ByteReverse(pblock->nBits);
3545 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3551 void static ThreadBitcoinMiner(void* parg)
3553 CWallet* pwallet = (CWallet*)parg;
3556 vnThreadsRunning[THREAD_MINER]++;
3557 BitcoinMiner(pwallet);
3558 vnThreadsRunning[THREAD_MINER]--;
3560 catch (std::exception& e) {
3561 vnThreadsRunning[THREAD_MINER]--;
3562 PrintException(&e, "ThreadBitcoinMiner()");
3564 vnThreadsRunning[THREAD_MINER]--;
3565 PrintException(NULL, "ThreadBitcoinMiner()");
3568 if (vnThreadsRunning[THREAD_MINER] == 0)
3570 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
3574 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3576 fGenerateBitcoins = fGenerate;
3577 nLimitProcessors = GetArg("-genproclimit", -1);
3578 if (nLimitProcessors == 0)
3579 fGenerateBitcoins = false;
3580 fLimitProcessors = (nLimitProcessors != -1);
3584 int nProcessors = boost::thread::hardware_concurrency();
3585 printf("%d processors\n", nProcessors);
3586 if (nProcessors < 1)
3588 if (fLimitProcessors && nProcessors > nLimitProcessors)
3589 nProcessors = nLimitProcessors;
3590 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
3591 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3592 for (int i = 0; i < nAddThreads; i++)
3594 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3595 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");