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 map<uint256, map<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 bool AddOrphanTx(const CDataStream& vMsg)
166 CDataStream(vMsg) >> tx;
167 uint256 hash = tx.GetHash();
168 if (mapOrphanTransactions.count(hash))
171 CDataStream* pvMsg = new CDataStream(vMsg);
173 // Ignore big transactions, to avoid a
174 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
175 // large transaction with a missing parent then we assume
176 // it will rebroadcast it later, after the parent transaction(s)
177 // have been mined or received.
178 // 10,000 orphans, each of which is at most 5,000 bytes big is
179 // at most 500 megabytes of orphans:
180 if (pvMsg->size() > 5000)
183 printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
187 mapOrphanTransactions[hash] = pvMsg;
188 BOOST_FOREACH(const CTxIn& txin, tx.vin)
189 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
191 printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
192 mapOrphanTransactions.size());
196 void static EraseOrphanTx(uint256 hash)
198 if (!mapOrphanTransactions.count(hash))
200 const CDataStream* pvMsg = mapOrphanTransactions[hash];
202 CDataStream(*pvMsg) >> tx;
203 BOOST_FOREACH(const CTxIn& txin, tx.vin)
205 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
206 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
207 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
210 mapOrphanTransactions.erase(hash);
213 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
215 unsigned int nEvicted = 0;
216 while (mapOrphanTransactions.size() > nMaxOrphans)
218 // Evict a random orphan:
219 std::vector<unsigned char> randbytes(32);
220 RAND_bytes(&randbytes[0], 32);
221 uint256 randomhash(randbytes);
222 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
223 if (it == mapOrphanTransactions.end())
224 it = mapOrphanTransactions.begin();
225 EraseOrphanTx(it->first);
237 //////////////////////////////////////////////////////////////////////////////
239 // CTransaction and CTxIndex
242 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
245 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
247 if (!ReadFromDisk(txindexRet.pos))
249 if (prevout.n >= vout.size())
257 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
260 return ReadFromDisk(txdb, prevout, txindex);
263 bool CTransaction::ReadFromDisk(COutPoint prevout)
267 return ReadFromDisk(txdb, prevout, txindex);
270 bool CTransaction::IsStandard() const
272 BOOST_FOREACH(const CTxIn& txin, vin)
274 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
275 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
276 // ~65-byte public keys, plus a few script ops.
277 if (txin.scriptSig.size() > 500)
279 if (!txin.scriptSig.IsPushOnly())
282 BOOST_FOREACH(const CTxOut& txout, vout)
283 if (!::IsStandard(txout.scriptPubKey))
289 // Check transaction inputs, and make sure any
290 // pay-to-script-hash transactions are evaluating IsStandard scripts
292 // Why bother? To avoid denial-of-service attacks; an attacker
293 // can submit a standard HASH... OP_EQUAL transaction,
294 // which will get accepted into blocks. The redemption
295 // script can be anything; an attacker could use a very
296 // expensive-to-check-upon-redemption script like:
297 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
299 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
302 return true; // Coinbases don't use vin normally
304 for (unsigned int i = 0; i < vin.size(); i++)
306 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
308 vector<vector<unsigned char> > vSolutions;
309 txnouttype whichType;
310 // get the scriptPubKey corresponding to this input:
311 const CScript& prevScript = prev.scriptPubKey;
312 if (!Solver(prevScript, whichType, vSolutions))
314 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
315 if (nArgsExpected < 0)
318 // Transactions with extra stuff in their scriptSigs are
319 // non-standard. Note that this EvalScript() call will
320 // be quick, because if there are any operations
321 // beside "push data" in the scriptSig the
322 // IsStandard() call returns false
323 vector<vector<unsigned char> > stack;
324 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
327 if (whichType == TX_SCRIPTHASH)
331 CScript subscript(stack.back().begin(), stack.back().end());
332 vector<vector<unsigned char> > vSolutions2;
333 txnouttype whichType2;
334 if (!Solver(subscript, whichType2, vSolutions2))
336 if (whichType2 == TX_SCRIPTHASH)
340 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
343 nArgsExpected += tmpExpected;
346 if (stack.size() != (unsigned int)nArgsExpected)
354 CTransaction::GetLegacySigOpCount() const
356 unsigned int nSigOps = 0;
357 BOOST_FOREACH(const CTxIn& txin, vin)
359 nSigOps += txin.scriptSig.GetSigOpCount(false);
361 BOOST_FOREACH(const CTxOut& txout, vout)
363 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
369 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
381 // Load the block this tx is in
383 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
385 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
390 // Update the tx's hashBlock
391 hashBlock = pblock->GetHash();
393 // Locate the transaction
394 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
395 if (pblock->vtx[nIndex] == *(CTransaction*)this)
397 if (nIndex == (int)pblock->vtx.size())
399 vMerkleBranch.clear();
401 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
405 // Fill in merkle branch
406 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
409 // Is the tx in a block that's in the main chain
410 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
411 if (mi == mapBlockIndex.end())
413 CBlockIndex* pindex = (*mi).second;
414 if (!pindex || !pindex->IsInMainChain())
417 return pindexBest->nHeight - pindex->nHeight + 1;
426 bool CTransaction::CheckTransaction() const
428 // Basic checks that don't depend on any context
430 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
432 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
434 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
435 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
437 // Check for negative or overflow output values
439 BOOST_FOREACH(const CTxOut& txout, vout)
441 if (txout.nValue < 0)
442 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
443 if (txout.nValue > MAX_MONEY)
444 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
445 nValueOut += txout.nValue;
446 if (!MoneyRange(nValueOut))
447 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
450 // Check for duplicate inputs
451 set<COutPoint> vInOutPoints;
452 BOOST_FOREACH(const CTxIn& txin, vin)
454 if (vInOutPoints.count(txin.prevout))
456 vInOutPoints.insert(txin.prevout);
461 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
462 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
466 BOOST_FOREACH(const CTxIn& txin, vin)
467 if (txin.prevout.IsNull())
468 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
474 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
475 bool* pfMissingInputs)
478 *pfMissingInputs = false;
480 if (!tx.CheckTransaction())
481 return error("CTxMemPool::accept() : CheckTransaction failed");
483 // Coinbase is only valid in a block, not as a loose transaction
485 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
487 // To help v0.1.5 clients who would see it as a negative number
488 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
489 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
491 // Rather not work on nonstandard transactions (unless -testnet)
492 if (!fTestNet && !tx.IsStandard())
493 return error("CTxMemPool::accept() : nonstandard transaction type");
495 // Do we already have it?
496 uint256 hash = tx.GetHash();
499 if (mapTx.count(hash))
503 if (txdb.ContainsTx(hash))
506 // Check for conflicts with in-memory transactions
507 CTransaction* ptxOld = NULL;
508 for (unsigned int i = 0; i < tx.vin.size(); i++)
510 COutPoint outpoint = tx.vin[i].prevout;
511 if (mapNextTx.count(outpoint))
513 // Disable replacement feature for now
516 // Allow replacing with a newer version of the same transaction
519 ptxOld = mapNextTx[outpoint].ptx;
520 if (ptxOld->IsFinal())
522 if (!tx.IsNewerThan(*ptxOld))
524 for (unsigned int i = 0; i < tx.vin.size(); i++)
526 COutPoint outpoint = tx.vin[i].prevout;
527 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
537 map<uint256, CTxIndex> mapUnused;
538 bool fInvalid = false;
539 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
542 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
544 *pfMissingInputs = true;
545 return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
548 // Check for non-standard pay-to-script-hash in inputs
549 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
550 return error("CTxMemPool::accept() : nonstandard transaction input");
552 // Note: if you modify this code to accept non-standard transactions, then
553 // you should add code here to check that the transaction does a
554 // reasonable number of ECDSA signature verifications.
556 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
557 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
559 // Don't accept it if it can't get into a block
560 if (nFees < tx.GetMinFee(1000, true, GMF_RELAY))
561 return error("CTxMemPool::accept() : not enough fees");
563 // Continuously rate-limit free transactions
564 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
565 // be annoying or make other's transactions take longer to confirm.
566 if (nFees < MIN_RELAY_TX_FEE)
568 static CCriticalSection cs;
569 static double dFreeCount;
570 static int64 nLastTime;
571 int64 nNow = GetTime();
575 // Use an exponentially decaying ~10-minute window:
576 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
578 // -limitfreerelay unit is thousand-bytes-per-minute
579 // At default rate it would take over a month to fill 1GB
580 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
581 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
583 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
588 // Check against previous transactions
589 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
590 if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
592 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
596 // Store transaction in memory
601 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
607 ///// are we sure this is ok when loading transactions or restoring block txes
608 // If updated, erase old tx from wallet
610 EraseFromWallets(ptxOld->GetHash());
612 printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str());
616 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
618 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
621 bool CTxMemPool::addUnchecked(CTransaction &tx)
623 printf("addUnchecked(): size %lu\n", mapTx.size());
624 // Add to memory pool without checking anything. Don't call this directly,
625 // call CTxMemPool::accept to properly check the transaction first.
628 uint256 hash = tx.GetHash();
630 for (unsigned int i = 0; i < tx.vin.size(); i++)
631 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
632 nTransactionsUpdated++;
638 bool CTxMemPool::remove(CTransaction &tx)
640 // Remove transaction from memory pool
643 uint256 hash = tx.GetHash();
644 if (mapTx.count(hash))
646 BOOST_FOREACH(const CTxIn& txin, tx.vin)
647 mapNextTx.erase(txin.prevout);
649 nTransactionsUpdated++;
660 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
662 if (hashBlock == 0 || nIndex == -1)
665 // Find the block it claims to be in
666 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
667 if (mi == mapBlockIndex.end())
669 CBlockIndex* pindex = (*mi).second;
670 if (!pindex || !pindex->IsInMainChain())
673 // Make sure the merkle branch connects to this block
674 if (!fMerkleVerified)
676 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
678 fMerkleVerified = true;
682 return pindexBest->nHeight - pindex->nHeight + 1;
686 int CMerkleTx::GetBlocksToMaturity() const
690 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
694 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
698 if (!IsInMainChain() && !ClientConnectInputs())
700 return CTransaction::AcceptToMemoryPool(txdb, false);
704 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
708 bool CMerkleTx::AcceptToMemoryPool()
711 return AcceptToMemoryPool(txdb);
716 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
721 // Add previous supporting transactions first
722 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
724 if (!tx.IsCoinBase())
726 uint256 hash = tx.GetHash();
727 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
728 tx.AcceptToMemoryPool(txdb, fCheckInputs);
731 return AcceptToMemoryPool(txdb, fCheckInputs);
736 bool CWalletTx::AcceptWalletTransaction()
739 return AcceptWalletTransaction(txdb);
742 int CTxIndex::GetDepthInMainChain() const
746 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
748 // Find the block in the index
749 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
750 if (mi == mapBlockIndex.end())
752 CBlockIndex* pindex = (*mi).second;
753 if (!pindex || !pindex->IsInMainChain())
755 return 1 + nBestHeight - pindex->nHeight;
767 //////////////////////////////////////////////////////////////////////////////
769 // CBlock and CBlockIndex
772 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
774 if (!fReadTransactions)
776 *this = pindex->GetBlockHeader();
779 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
781 if (GetHash() != pindex->GetBlockHash())
782 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
786 uint256 static GetOrphanRoot(const CBlock* pblock)
788 // Work back to the first block in the orphan chain
789 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
790 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
791 return pblock->GetHash();
794 int64 static GetBlockValue(int nHeight, int64 nFees)
796 int64 nSubsidy = 50 * COIN;
798 // Subsidy is cut in half every 4 years
799 nSubsidy >>= (nHeight / 210000);
801 return nSubsidy + nFees;
804 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
805 static const int64 nTargetSpacing = 10 * 60;
806 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
809 // minimum amount of work that could possibly be required nTime after
810 // minimum work required was nBase
812 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
814 // Testnet has min-difficulty blocks
815 // after nTargetSpacing*2 time between blocks:
816 if (fTestNet && nTime > nTargetSpacing*2)
817 return bnProofOfWorkLimit.GetCompact();
820 bnResult.SetCompact(nBase);
821 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
823 // Maximum 400% adjustment...
825 // ... in best-case exactly 4-times-normal target time
826 nTime -= nTargetTimespan*4;
828 if (bnResult > bnProofOfWorkLimit)
829 bnResult = bnProofOfWorkLimit;
830 return bnResult.GetCompact();
833 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
835 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
838 if (pindexLast == NULL)
839 return nProofOfWorkLimit;
841 // Only change once per interval
842 if ((pindexLast->nHeight+1) % nInterval != 0)
844 // Special rules for testnet after 15 Feb 2012:
845 if (fTestNet && pblock->nTime > 1329264000)
847 // If the new block's timestamp is more than 2* 10 minutes
848 // then allow mining of a min-difficulty block.
849 if (pblock->nTime - pindexLast->nTime > nTargetSpacing*2)
850 return nProofOfWorkLimit;
853 // Return the last non-special-min-difficulty-rules-block
854 const CBlockIndex* pindex = pindexLast;
855 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
856 pindex = pindex->pprev;
857 return pindex->nBits;
861 return pindexLast->nBits;
864 // Go back by what we want to be 14 days worth of blocks
865 const CBlockIndex* pindexFirst = pindexLast;
866 for (int i = 0; pindexFirst && i < nInterval-1; i++)
867 pindexFirst = pindexFirst->pprev;
870 // Limit adjustment step
871 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
872 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
873 if (nActualTimespan < nTargetTimespan/4)
874 nActualTimespan = nTargetTimespan/4;
875 if (nActualTimespan > nTargetTimespan*4)
876 nActualTimespan = nTargetTimespan*4;
880 bnNew.SetCompact(pindexLast->nBits);
881 bnNew *= nActualTimespan;
882 bnNew /= nTargetTimespan;
884 if (bnNew > bnProofOfWorkLimit)
885 bnNew = bnProofOfWorkLimit;
888 printf("GetNextWorkRequired RETARGET\n");
889 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
890 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
891 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
893 return bnNew.GetCompact();
896 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
899 bnTarget.SetCompact(nBits);
902 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
903 return error("CheckProofOfWork() : nBits below minimum work");
905 // Check proof of work matches claimed amount
906 if (hash > bnTarget.getuint256())
907 return error("CheckProofOfWork() : hash doesn't match nBits");
912 // Return maximum amount of blocks that other nodes claim to have
913 int GetNumBlocksOfPeers()
915 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
918 bool IsInitialBlockDownload()
920 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
922 static int64 nLastUpdate;
923 static CBlockIndex* pindexLastBest;
924 if (pindexBest != pindexLastBest)
926 pindexLastBest = pindexBest;
927 nLastUpdate = GetTime();
929 return (GetTime() - nLastUpdate < 10 &&
930 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
933 void static InvalidChainFound(CBlockIndex* pindexNew)
935 if (pindexNew->bnChainWork > bnBestInvalidWork)
937 bnBestInvalidWork = pindexNew->bnChainWork;
938 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
941 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());
942 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
943 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
944 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
947 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
949 nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
951 // Updating time can change work required on testnet:
953 nBits = GetNextWorkRequired(pindexPrev, this);
966 bool CTransaction::DisconnectInputs(CTxDB& txdb)
968 // Relinquish previous transactions' spent pointers
971 BOOST_FOREACH(const CTxIn& txin, vin)
973 COutPoint prevout = txin.prevout;
975 // Get prev txindex from disk
977 if (!txdb.ReadTxIndex(prevout.hash, txindex))
978 return error("DisconnectInputs() : ReadTxIndex failed");
980 if (prevout.n >= txindex.vSpent.size())
981 return error("DisconnectInputs() : prevout.n out of range");
983 // Mark outpoint as not spent
984 txindex.vSpent[prevout.n].SetNull();
987 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
988 return error("DisconnectInputs() : UpdateTxIndex failed");
992 // Remove transaction from index
993 // This can fail if a duplicate of this transaction was in a chain that got
994 // reorganized away. This is only possible if this transaction was completely
995 // spent, so erasing it would be a no-op anway.
996 txdb.EraseTxIndex(*this);
1002 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1003 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1005 // FetchInputs can return false either because we just haven't seen some inputs
1006 // (in which case the transaction should be stored as an orphan)
1007 // or because the transaction is malformed (in which case the transaction should
1008 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1012 return true; // Coinbase transactions have no inputs to fetch.
1014 for (unsigned int i = 0; i < vin.size(); i++)
1016 COutPoint prevout = vin[i].prevout;
1017 if (inputsRet.count(prevout.hash))
1018 continue; // Got it already
1021 CTxIndex& txindex = inputsRet[prevout.hash].first;
1023 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1025 // Get txindex from current proposed changes
1026 txindex = mapTestPool.find(prevout.hash)->second;
1030 // Read txindex from txdb
1031 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1033 if (!fFound && (fBlock || fMiner))
1034 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());
1037 CTransaction& txPrev = inputsRet[prevout.hash].second;
1038 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1040 // Get prev tx from single transactions in memory
1043 if (!mempool.exists(prevout.hash))
1044 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());
1045 txPrev = mempool.lookup(prevout.hash);
1048 txindex.vSpent.resize(txPrev.vout.size());
1052 // Get prev tx from disk
1053 if (!txPrev.ReadFromDisk(txindex.pos))
1054 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1058 // Make sure all prevout.n's are valid:
1059 for (unsigned int i = 0; i < vin.size(); i++)
1061 const COutPoint prevout = vin[i].prevout;
1062 assert(inputsRet.count(prevout.hash) != 0);
1063 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1064 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1065 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1067 // Revisit this if/when transaction replacement is implemented and allows
1070 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()));
1077 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1079 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1080 if (mi == inputs.end())
1081 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1083 const CTransaction& txPrev = (mi->second).second;
1084 if (input.prevout.n >= txPrev.vout.size())
1085 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1087 return txPrev.vout[input.prevout.n];
1090 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1096 for (unsigned int i = 0; i < vin.size(); i++)
1098 nResult += GetOutputFor(vin[i], inputs).nValue;
1104 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1109 unsigned int nSigOps = 0;
1110 for (unsigned int i = 0; i < vin.size(); i++)
1112 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1113 if (prevout.scriptPubKey.IsPayToScriptHash())
1114 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1119 bool CTransaction::ConnectInputs(MapPrevTx inputs,
1120 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1121 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1123 // Take over previous transactions' spent pointers
1124 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1125 // fMiner is true when called from the internal bitcoin miner
1126 // ... both are false when called from CTransaction::AcceptToMemoryPool
1131 for (unsigned int i = 0; i < vin.size(); i++)
1133 COutPoint prevout = vin[i].prevout;
1134 assert(inputs.count(prevout.hash) > 0);
1135 CTxIndex& txindex = inputs[prevout.hash].first;
1136 CTransaction& txPrev = inputs[prevout.hash].second;
1138 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1139 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()));
1141 // If prev is coinbase, check that it's matured
1142 if (txPrev.IsCoinBase())
1143 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1144 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1145 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1147 // Check for conflicts (double-spend)
1148 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1149 // for an attacker to attempt to split the network.
1150 if (!txindex.vSpent[prevout.n].IsNull())
1151 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());
1153 // Check for negative or overflow input values
1154 nValueIn += txPrev.vout[prevout.n].nValue;
1155 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1156 return DoS(100, error("ConnectInputs() : txin values out of range"));
1158 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1159 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1160 // still computed and checked, and any change will be caught at the next checkpoint.
1161 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1164 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1166 // only during transition phase for P2SH: do not invoke anti-DoS code for
1167 // potentially old clients relaying bad P2SH transactions
1168 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1169 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1171 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1175 // Mark outpoints as spent
1176 txindex.vSpent[prevout.n] = posThisTx;
1179 if (fBlock || fMiner)
1181 mapTestPool[prevout.hash] = txindex;
1185 if (nValueIn < GetValueOut())
1186 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1188 // Tally transaction fees
1189 int64 nTxFee = nValueIn - GetValueOut();
1191 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1193 if (!MoneyRange(nFees))
1194 return DoS(100, error("ConnectInputs() : nFees out of range"));
1201 bool CTransaction::ClientConnectInputs()
1206 // Take over previous transactions' spent pointers
1210 for (unsigned int i = 0; i < vin.size(); i++)
1212 // Get prev tx from single transactions in memory
1213 COutPoint prevout = vin[i].prevout;
1214 if (!mempool.exists(prevout.hash))
1216 CTransaction& txPrev = mempool.lookup(prevout.hash);
1218 if (prevout.n >= txPrev.vout.size())
1222 if (!VerifySignature(txPrev, *this, i, true, 0))
1223 return error("ConnectInputs() : VerifySignature failed");
1225 ///// this is redundant with the mempool.mapNextTx stuff,
1226 ///// not sure which I want to get rid of
1227 ///// this has to go away now that posNext is gone
1228 // // Check for conflicts
1229 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1230 // return error("ConnectInputs() : prev tx already used");
1232 // // Flag outpoints as used
1233 // txPrev.vout[prevout.n].posNext = posThisTx;
1235 nValueIn += txPrev.vout[prevout.n].nValue;
1237 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1238 return error("ClientConnectInputs() : txin values out of range");
1240 if (GetValueOut() > nValueIn)
1250 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1252 // Disconnect in reverse order
1253 for (int i = vtx.size()-1; i >= 0; i--)
1254 if (!vtx[i].DisconnectInputs(txdb))
1257 // Update block index on disk without changing it in memory.
1258 // The memory index structure will be changed after the db commits.
1261 CDiskBlockIndex blockindexPrev(pindex->pprev);
1262 blockindexPrev.hashNext = 0;
1263 if (!txdb.WriteBlockIndex(blockindexPrev))
1264 return error("DisconnectBlock() : WriteBlockIndex failed");
1270 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1272 // Check it again in case a previous version let a bad block in
1276 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1277 // unless those are already completely spent.
1278 // If such overwrites are allowed, coinbases and transactions depending upon those
1279 // can be duplicated to remove the ability to spend the first instance -- even after
1280 // being sent to another address.
1281 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1282 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1283 // already refuses previously-known transaction id's entirely.
1284 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1285 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1286 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1288 BOOST_FOREACH(CTransaction& tx, vtx)
1290 CTxIndex txindexOld;
1291 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1293 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1300 // BIP16 didn't become active until Apr 1 2012 (Feb 15 on testnet)
1301 int64 nBIP16SwitchTime = fTestNet ? 1329264000 : 1333238400;
1302 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1304 //// issue here: it doesn't know the version
1305 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size());
1307 map<uint256, CTxIndex> mapQueuedChanges;
1309 unsigned int nSigOps = 0;
1310 BOOST_FOREACH(CTransaction& tx, vtx)
1312 nSigOps += tx.GetLegacySigOpCount();
1313 if (nSigOps > MAX_BLOCK_SIGOPS)
1314 return DoS(100, error("ConnectBlock() : too many sigops"));
1316 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1317 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1319 MapPrevTx mapInputs;
1320 if (!tx.IsCoinBase())
1323 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1326 if (fStrictPayToScriptHash)
1328 // Add in sigops done by pay-to-script-hash inputs;
1329 // this is to prevent a "rogue miner" from creating
1330 // an incredibly-expensive-to-validate block.
1331 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1332 if (nSigOps > MAX_BLOCK_SIGOPS)
1333 return DoS(100, error("ConnectBlock() : too many sigops"));
1336 nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
1338 if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1342 mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
1345 // Write queued txindex changes
1346 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1348 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1349 return error("ConnectBlock() : UpdateTxIndex failed");
1352 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1355 // Update block index on disk without changing it in memory.
1356 // The memory index structure will be changed after the db commits.
1359 CDiskBlockIndex blockindexPrev(pindex->pprev);
1360 blockindexPrev.hashNext = pindex->GetBlockHash();
1361 if (!txdb.WriteBlockIndex(blockindexPrev))
1362 return error("ConnectBlock() : WriteBlockIndex failed");
1365 // Watch for transactions paying to me
1366 BOOST_FOREACH(CTransaction& tx, vtx)
1367 SyncWithWallets(tx, this, true);
1372 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1374 printf("REORGANIZE\n");
1377 CBlockIndex* pfork = pindexBest;
1378 CBlockIndex* plonger = pindexNew;
1379 while (pfork != plonger)
1381 while (plonger->nHeight > pfork->nHeight)
1382 if (!(plonger = plonger->pprev))
1383 return error("Reorganize() : plonger->pprev is null");
1384 if (pfork == plonger)
1386 if (!(pfork = pfork->pprev))
1387 return error("Reorganize() : pfork->pprev is null");
1390 // List of what to disconnect
1391 vector<CBlockIndex*> vDisconnect;
1392 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1393 vDisconnect.push_back(pindex);
1395 // List of what to connect
1396 vector<CBlockIndex*> vConnect;
1397 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1398 vConnect.push_back(pindex);
1399 reverse(vConnect.begin(), vConnect.end());
1401 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());
1402 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());
1404 // Disconnect shorter branch
1405 vector<CTransaction> vResurrect;
1406 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1409 if (!block.ReadFromDisk(pindex))
1410 return error("Reorganize() : ReadFromDisk for disconnect failed");
1411 if (!block.DisconnectBlock(txdb, pindex))
1412 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1414 // Queue memory transactions to resurrect
1415 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1416 if (!tx.IsCoinBase())
1417 vResurrect.push_back(tx);
1420 // Connect longer branch
1421 vector<CTransaction> vDelete;
1422 for (unsigned int i = 0; i < vConnect.size(); i++)
1424 CBlockIndex* pindex = vConnect[i];
1426 if (!block.ReadFromDisk(pindex))
1427 return error("Reorganize() : ReadFromDisk for connect failed");
1428 if (!block.ConnectBlock(txdb, pindex))
1432 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1435 // Queue memory transactions to delete
1436 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1437 vDelete.push_back(tx);
1439 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1440 return error("Reorganize() : WriteHashBestChain failed");
1442 // Make sure it's successfully written to disk before changing memory structure
1443 if (!txdb.TxnCommit())
1444 return error("Reorganize() : TxnCommit failed");
1446 // Disconnect shorter branch
1447 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1449 pindex->pprev->pnext = NULL;
1451 // Connect longer branch
1452 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1454 pindex->pprev->pnext = pindex;
1456 // Resurrect memory transactions that were in the disconnected branch
1457 BOOST_FOREACH(CTransaction& tx, vResurrect)
1458 tx.AcceptToMemoryPool(txdb, false);
1460 // Delete redundant memory transactions that are in the connected branch
1461 BOOST_FOREACH(CTransaction& tx, vDelete)
1464 printf("REORGANIZE: done\n");
1471 runCommand(std::string strCommand)
1473 int nErr = ::system(strCommand.c_str());
1475 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1478 // Called from inside SetBestChain: attaches a block to the new best chain being built
1479 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1481 uint256 hash = GetHash();
1483 // Adding to current best branch
1484 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1487 InvalidChainFound(pindexNew);
1490 if (!txdb.TxnCommit())
1491 return error("SetBestChain() : TxnCommit failed");
1493 // Add to current best branch
1494 pindexNew->pprev->pnext = pindexNew;
1496 // Delete redundant memory transactions
1497 BOOST_FOREACH(CTransaction& tx, vtx)
1503 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1505 uint256 hash = GetHash();
1508 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1510 txdb.WriteHashBestChain(hash);
1511 if (!txdb.TxnCommit())
1512 return error("SetBestChain() : TxnCommit failed");
1513 pindexGenesisBlock = pindexNew;
1515 else if (hashPrevBlock == hashBestChain)
1517 if (!SetBestChainInner(txdb, pindexNew))
1518 return error("SetBestChain() : SetBestChainInner failed");
1522 // the first block in the new chain that will cause it to become the new best chain
1523 CBlockIndex *pindexIntermediate = pindexNew;
1525 // list of blocks that need to be connected afterwards
1526 std::vector<CBlockIndex*> vpindexSecondary;
1528 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1529 // Try to limit how much needs to be done inside
1530 while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork)
1532 vpindexSecondary.push_back(pindexIntermediate);
1533 pindexIntermediate = pindexIntermediate->pprev;
1536 if (!vpindexSecondary.empty())
1537 printf("Postponing %i reconnects\n", vpindexSecondary.size());
1539 // Switch to new best branch
1540 if (!Reorganize(txdb, pindexIntermediate))
1543 InvalidChainFound(pindexNew);
1544 return error("SetBestChain() : Reorganize failed");
1547 // Connect futher blocks
1548 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1551 if (!block.ReadFromDisk(pindex))
1553 printf("SetBestChain() : ReadFromDisk failed\n");
1557 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1558 if (!block.SetBestChainInner(txdb, pindex))
1563 // Update best block in wallet (so we can detect restored wallets)
1564 bool fIsInitialDownload = IsInitialBlockDownload();
1565 if (!fIsInitialDownload)
1567 const CBlockLocator locator(pindexNew);
1568 ::SetBestChain(locator);
1572 hashBestChain = hash;
1573 pindexBest = pindexNew;
1574 nBestHeight = pindexBest->nHeight;
1575 bnBestChainWork = pindexNew->bnChainWork;
1576 nTimeBestReceived = GetTime();
1577 nTransactionsUpdated++;
1578 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1580 std::string strCmd = GetArg("-blocknotify", "");
1582 if (!fIsInitialDownload && !strCmd.empty())
1584 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1585 boost::thread t(runCommand, strCmd); // thread runs free
1592 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1594 // Check for duplicate
1595 uint256 hash = GetHash();
1596 if (mapBlockIndex.count(hash))
1597 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1599 // Construct new block index object
1600 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1602 return error("AddToBlockIndex() : new CBlockIndex failed");
1603 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1604 pindexNew->phashBlock = &((*mi).first);
1605 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1606 if (miPrev != mapBlockIndex.end())
1608 pindexNew->pprev = (*miPrev).second;
1609 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1611 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1615 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1616 if (!txdb.TxnCommit())
1620 if (pindexNew->bnChainWork > bnBestChainWork)
1621 if (!SetBestChain(txdb, pindexNew))
1626 if (pindexNew == pindexBest)
1628 // Notify UI to display prev block's coinbase if it was ours
1629 static uint256 hashPrevBestCoinBase;
1630 UpdatedTransaction(hashPrevBestCoinBase);
1631 hashPrevBestCoinBase = vtx[0].GetHash();
1641 bool CBlock::CheckBlock() const
1643 // These are checks that are independent of context
1644 // that can be verified before saving an orphan block.
1647 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
1648 return DoS(100, error("CheckBlock() : size limits failed"));
1650 // Check proof of work matches claimed amount
1651 if (!CheckProofOfWork(GetHash(), nBits))
1652 return DoS(50, error("CheckBlock() : proof of work failed"));
1655 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1656 return error("CheckBlock() : block timestamp too far in the future");
1658 // First transaction must be coinbase, the rest must not be
1659 if (vtx.empty() || !vtx[0].IsCoinBase())
1660 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1661 for (unsigned int i = 1; i < vtx.size(); i++)
1662 if (vtx[i].IsCoinBase())
1663 return DoS(100, error("CheckBlock() : more than one coinbase"));
1665 // Check transactions
1666 BOOST_FOREACH(const CTransaction& tx, vtx)
1667 if (!tx.CheckTransaction())
1668 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1670 // Check for duplicate txids. This is caught by ConnectInputs(),
1671 // but catching it earlier avoids a potential DoS attack:
1672 set<uint256> uniqueTx;
1673 BOOST_FOREACH(const CTransaction& tx, vtx)
1675 uniqueTx.insert(tx.GetHash());
1677 if (uniqueTx.size() != vtx.size())
1678 return DoS(100, error("CheckBlock() : duplicate transaction"));
1680 unsigned int nSigOps = 0;
1681 BOOST_FOREACH(const CTransaction& tx, vtx)
1683 nSigOps += tx.GetLegacySigOpCount();
1685 if (nSigOps > MAX_BLOCK_SIGOPS)
1686 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1689 if (hashMerkleRoot != BuildMerkleTree())
1690 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1695 bool CBlock::AcceptBlock()
1697 // Check for duplicate
1698 uint256 hash = GetHash();
1699 if (mapBlockIndex.count(hash))
1700 return error("AcceptBlock() : block already in mapBlockIndex");
1702 // Get prev block index
1703 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1704 if (mi == mapBlockIndex.end())
1705 return DoS(10, error("AcceptBlock() : prev block not found"));
1706 CBlockIndex* pindexPrev = (*mi).second;
1707 int nHeight = pindexPrev->nHeight+1;
1709 // Check proof of work
1710 if (nBits != GetNextWorkRequired(pindexPrev, this))
1711 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1713 // Check timestamp against prev
1714 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1715 return error("AcceptBlock() : block's timestamp is too early");
1717 // Check that all transactions are finalized
1718 BOOST_FOREACH(const CTransaction& tx, vtx)
1719 if (!tx.IsFinal(nHeight, GetBlockTime()))
1720 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1722 // Check that the block chain matches the known block chain up to a checkpoint
1723 if (!Checkpoints::CheckBlock(nHeight, hash))
1724 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1726 // Write block to history file
1727 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
1728 return error("AcceptBlock() : out of disk space");
1729 unsigned int nFile = -1;
1730 unsigned int nBlockPos = 0;
1731 if (!WriteToDisk(nFile, nBlockPos))
1732 return error("AcceptBlock() : WriteToDisk failed");
1733 if (!AddToBlockIndex(nFile, nBlockPos))
1734 return error("AcceptBlock() : AddToBlockIndex failed");
1736 // Relay inventory, but don't relay old inventory during initial block download
1737 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1738 if (hashBestChain == hash)
1741 BOOST_FOREACH(CNode* pnode, vNodes)
1742 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1743 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1749 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1751 // Check for duplicate
1752 uint256 hash = pblock->GetHash();
1753 if (mapBlockIndex.count(hash))
1754 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1755 if (mapOrphanBlocks.count(hash))
1756 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1758 // Preliminary checks
1759 if (!pblock->CheckBlock())
1760 return error("ProcessBlock() : CheckBlock FAILED");
1762 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1763 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1765 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1766 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1770 pfrom->Misbehaving(100);
1771 return error("ProcessBlock() : block with timestamp before last checkpoint");
1774 bnNewBlock.SetCompact(pblock->nBits);
1776 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1777 if (bnNewBlock > bnRequired)
1780 pfrom->Misbehaving(100);
1781 return error("ProcessBlock() : block with too little proof-of-work");
1786 // If don't already have its previous block, shunt it off to holding area until we get it
1787 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1789 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1790 CBlock* pblock2 = new CBlock(*pblock);
1791 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1792 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1794 // Ask this guy to fill in what we're missing
1796 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1801 if (!pblock->AcceptBlock())
1802 return error("ProcessBlock() : AcceptBlock FAILED");
1804 // Recursively process any orphan blocks that depended on this one
1805 vector<uint256> vWorkQueue;
1806 vWorkQueue.push_back(hash);
1807 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1809 uint256 hashPrev = vWorkQueue[i];
1810 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1811 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1814 CBlock* pblockOrphan = (*mi).second;
1815 if (pblockOrphan->AcceptBlock())
1816 vWorkQueue.push_back(pblockOrphan->GetHash());
1817 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1818 delete pblockOrphan;
1820 mapOrphanBlocksByPrev.erase(hashPrev);
1823 printf("ProcessBlock: ACCEPTED\n");
1834 bool CheckDiskSpace(uint64 nAdditionalBytes)
1836 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1838 // Check for 15MB because database could create another 10MB log file at any time
1839 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1842 string strMessage = _("Warning: Disk space is low ");
1843 strMiscWarning = strMessage;
1844 printf("*** %s\n", strMessage.c_str());
1845 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION | wxMODAL);
1852 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1856 FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
1859 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1861 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1870 static unsigned int nCurrentBlockFile = 1;
1872 FILE* AppendBlockFile(unsigned int& nFileRet)
1877 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1880 if (fseek(file, 0, SEEK_END) != 0)
1882 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1883 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1885 nFileRet = nCurrentBlockFile;
1889 nCurrentBlockFile++;
1893 bool LoadBlockIndex(bool fAllowNew)
1897 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1898 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1899 pchMessageStart[0] = 0xfa;
1900 pchMessageStart[1] = 0xbf;
1901 pchMessageStart[2] = 0xb5;
1902 pchMessageStart[3] = 0xda;
1909 if (!txdb.LoadBlockIndex())
1914 // Init with genesis block
1916 if (mapBlockIndex.empty())
1922 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1923 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1924 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1925 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1926 // vMerkleTree: 4a5e1e
1929 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1931 txNew.vin.resize(1);
1932 txNew.vout.resize(1);
1933 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1934 txNew.vout[0].nValue = 50 * COIN;
1935 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1937 block.vtx.push_back(txNew);
1938 block.hashPrevBlock = 0;
1939 block.hashMerkleRoot = block.BuildMerkleTree();
1941 block.nTime = 1231006505;
1942 block.nBits = 0x1d00ffff;
1943 block.nNonce = 2083236893;
1947 block.nTime = 1296688602;
1948 block.nBits = 0x1d07fff8;
1949 block.nNonce = 384568319;
1953 printf("%s\n", block.GetHash().ToString().c_str());
1954 printf("%s\n", hashGenesisBlock.ToString().c_str());
1955 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1956 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1958 assert(block.GetHash() == hashGenesisBlock);
1960 // Start new block file
1962 unsigned int nBlockPos;
1963 if (!block.WriteToDisk(nFile, nBlockPos))
1964 return error("LoadBlockIndex() : writing genesis block to disk failed");
1965 if (!block.AddToBlockIndex(nFile, nBlockPos))
1966 return error("LoadBlockIndex() : genesis block not accepted");
1974 void PrintBlockTree()
1976 // precompute tree structure
1977 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1978 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1980 CBlockIndex* pindex = (*mi).second;
1981 mapNext[pindex->pprev].push_back(pindex);
1983 //while (rand() % 3 == 0)
1984 // mapNext[pindex->pprev].push_back(pindex);
1987 vector<pair<int, CBlockIndex*> > vStack;
1988 vStack.push_back(make_pair(0, pindexGenesisBlock));
1991 while (!vStack.empty())
1993 int nCol = vStack.back().first;
1994 CBlockIndex* pindex = vStack.back().second;
1997 // print split or gap
1998 if (nCol > nPrevCol)
2000 for (int i = 0; i < nCol-1; i++)
2004 else if (nCol < nPrevCol)
2006 for (int i = 0; i < nCol; i++)
2013 for (int i = 0; i < nCol; i++)
2018 block.ReadFromDisk(pindex);
2019 printf("%d (%u,%u) %s %s tx %d",
2023 block.GetHash().ToString().substr(0,20).c_str(),
2024 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2027 PrintWallets(block);
2029 // put the main timechain first
2030 vector<CBlockIndex*>& vNext = mapNext[pindex];
2031 for (unsigned int i = 0; i < vNext.size(); i++)
2033 if (vNext[i]->pnext)
2035 swap(vNext[0], vNext[i]);
2041 for (unsigned int i = 0; i < vNext.size(); i++)
2042 vStack.push_back(make_pair(nCol+i, vNext[i]));
2055 //////////////////////////////////////////////////////////////////////////////
2060 map<uint256, CAlert> mapAlerts;
2061 CCriticalSection cs_mapAlerts;
2063 string GetWarnings(string strFor)
2066 string strStatusBar;
2068 if (GetBoolArg("-testsafemode"))
2071 // Misc warnings like out of disk space and clock is wrong
2072 if (strMiscWarning != "")
2075 strStatusBar = strMiscWarning;
2078 // Longer invalid proof-of-work chain
2079 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2082 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2088 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2090 const CAlert& alert = item.second;
2091 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2093 nPriority = alert.nPriority;
2094 strStatusBar = alert.strStatusBar;
2099 if (strFor == "statusbar")
2100 return strStatusBar;
2101 else if (strFor == "rpc")
2103 assert(!"GetWarnings() : invalid parameter");
2107 bool CAlert::ProcessAlert()
2109 if (!CheckSignature())
2116 // Cancel previous alerts
2117 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2119 const CAlert& alert = (*mi).second;
2122 printf("cancelling alert %d\n", alert.nID);
2123 mapAlerts.erase(mi++);
2125 else if (!alert.IsInEffect())
2127 printf("expiring alert %d\n", alert.nID);
2128 mapAlerts.erase(mi++);
2134 // Check if this alert has been cancelled
2135 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2137 const CAlert& alert = item.second;
2138 if (alert.Cancels(*this))
2140 printf("alert already cancelled by %d\n", alert.nID);
2146 mapAlerts.insert(make_pair(GetHash(), *this));
2149 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2161 //////////////////////////////////////////////////////////////////////////////
2167 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2173 bool txInMap = false;
2176 txInMap = (mempool.exists(inv.hash));
2179 mapOrphanTransactions.count(inv.hash) ||
2180 txdb.ContainsTx(inv.hash);
2184 return mapBlockIndex.count(inv.hash) ||
2185 mapOrphanBlocks.count(inv.hash);
2187 // Don't know what it is, just say we already got one
2194 // The message start string is designed to be unlikely to occur in normal data.
2195 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2196 // a large 4-byte int at any alignment.
2197 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2200 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2202 static map<CService, vector<unsigned char> > mapReuseKey;
2203 RandAddSeedPerfmon();
2205 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2206 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2208 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2210 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2218 if (strCommand == "version")
2220 // Each connection can only send one version message
2221 if (pfrom->nVersion != 0)
2223 pfrom->Misbehaving(1);
2231 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2232 if (pfrom->nVersion < MIN_PROTO_VERSION)
2234 // Since February 20, 2012, the protocol is initiated at version 209,
2235 // and earlier versions are no longer supported
2236 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2237 pfrom->fDisconnect = true;
2241 if (pfrom->nVersion == 10300)
2242 pfrom->nVersion = 300;
2244 vRecv >> addrFrom >> nNonce;
2246 vRecv >> pfrom->strSubVer;
2248 vRecv >> pfrom->nStartingHeight;
2250 // Disconnect if we connected to ourself
2251 if (nNonce == nLocalHostNonce && nNonce > 1)
2253 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2254 pfrom->fDisconnect = true;
2258 // Be shy and don't send version until we hear
2259 if (pfrom->fInbound)
2260 pfrom->PushVersion();
2262 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2264 AddTimeData(pfrom->addr, nTime);
2267 pfrom->PushMessage("verack");
2268 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2270 if (!pfrom->fInbound)
2272 // Advertise our address
2273 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() &&
2274 !IsInitialBlockDownload())
2276 CAddress addr(addrLocalHost);
2277 addr.nTime = GetAdjustedTime();
2278 pfrom->PushAddress(addr);
2281 // Get recent addresses
2282 if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2284 pfrom->PushMessage("getaddr");
2285 pfrom->fGetAddr = true;
2287 addrman.Good(pfrom->addr);
2289 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2291 addrman.Add(addrFrom, addrFrom);
2292 addrman.Good(addrFrom);
2296 // Ask the first connected node for block updates
2297 static int nAskedForBlocks = 0;
2298 if (!pfrom->fClient &&
2299 (pfrom->nVersion < NOBLKS_VERSION_START ||
2300 pfrom->nVersion >= NOBLKS_VERSION_END) &&
2301 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2304 pfrom->PushGetBlocks(pindexBest, uint256(0));
2310 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2311 item.second.RelayTo(pfrom);
2314 pfrom->fSuccessfullyConnected = true;
2316 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2318 cPeerBlockCounts.input(pfrom->nStartingHeight);
2322 else if (pfrom->nVersion == 0)
2324 // Must have a version message before anything else
2325 pfrom->Misbehaving(1);
2330 else if (strCommand == "verack")
2332 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2336 else if (strCommand == "addr")
2338 vector<CAddress> vAddr;
2341 // Don't want addr from older versions unless seeding
2342 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2344 if (vAddr.size() > 1000)
2346 pfrom->Misbehaving(20);
2347 return error("message addr size() = %d", vAddr.size());
2350 // Store the new addresses
2351 int64 nNow = GetAdjustedTime();
2352 int64 nSince = nNow - 10 * 60;
2353 BOOST_FOREACH(CAddress& addr, vAddr)
2357 // ignore IPv6 for now, since it isn't implemented anyway
2360 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2361 addr.nTime = nNow - 5 * 24 * 60 * 60;
2362 pfrom->AddAddressKnown(addr);
2363 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2365 // Relay to a limited number of other nodes
2368 // Use deterministic randomness to send to the same nodes for 24 hours
2369 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2370 static uint256 hashSalt;
2372 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2373 int64 hashAddr = addr.GetHash();
2374 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2375 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2376 multimap<uint256, CNode*> mapMix;
2377 BOOST_FOREACH(CNode* pnode, vNodes)
2379 if (pnode->nVersion < CADDR_TIME_VERSION)
2381 unsigned int nPointer;
2382 memcpy(&nPointer, &pnode, sizeof(nPointer));
2383 uint256 hashKey = hashRand ^ nPointer;
2384 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2385 mapMix.insert(make_pair(hashKey, pnode));
2387 int nRelayNodes = 2;
2388 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2389 ((*mi).second)->PushAddress(addr);
2393 addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60);
2394 if (vAddr.size() < 1000)
2395 pfrom->fGetAddr = false;
2399 else if (strCommand == "inv")
2403 if (vInv.size() > 50000)
2405 pfrom->Misbehaving(20);
2406 return error("message inv size() = %d", vInv.size());
2410 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
2412 const CInv &inv = vInv[nInv];
2416 pfrom->AddInventoryKnown(inv);
2418 bool fAlreadyHave = AlreadyHave(txdb, inv);
2420 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2422 // Always request the last block in an inv bundle (even if we already have it), as it is the
2423 // trigger for the other side to send further invs. If we are stuck on a (very long) side chain,
2424 // this is necessary to connect earlier received orphan blocks to the chain again.
2425 if (!fAlreadyHave || (inv.type == MSG_BLOCK && nInv==vInv.size()-1))
2427 if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2428 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2430 // Track requests for our stuff
2431 Inventory(inv.hash);
2436 else if (strCommand == "getdata")
2440 if (vInv.size() > 50000)
2442 pfrom->Misbehaving(20);
2443 return error("message getdata size() = %d", vInv.size());
2446 BOOST_FOREACH(const CInv& inv, vInv)
2450 printf("received getdata for: %s\n", inv.ToString().c_str());
2452 if (inv.type == MSG_BLOCK)
2454 // Send block from disk
2455 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2456 if (mi != mapBlockIndex.end())
2459 block.ReadFromDisk((*mi).second);
2460 pfrom->PushMessage("block", block);
2462 // Trigger them to send a getblocks request for the next batch of inventory
2463 if (inv.hash == pfrom->hashContinue)
2465 // Bypass PushInventory, this must send even if redundant,
2466 // and we want it right after the last block so they don't
2467 // wait for other stuff first.
2469 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2470 pfrom->PushMessage("inv", vInv);
2471 pfrom->hashContinue = 0;
2475 else if (inv.IsKnownType())
2477 // Send stream from relay memory
2480 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2481 if (mi != mapRelay.end())
2482 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2486 // Track requests for our stuff
2487 Inventory(inv.hash);
2492 else if (strCommand == "getblocks")
2494 CBlockLocator locator;
2496 vRecv >> locator >> hashStop;
2498 // Find the last block the caller has in the main chain
2499 CBlockIndex* pindex = locator.GetBlockIndex();
2501 // Send the rest of the chain
2503 pindex = pindex->pnext;
2504 int nLimit = 500 + locator.GetDistanceBack();
2505 unsigned int nBytes = 0;
2506 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2507 for (; pindex; pindex = pindex->pnext)
2509 if (pindex->GetBlockHash() == hashStop)
2511 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2514 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2516 block.ReadFromDisk(pindex, true);
2517 nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
2518 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2520 // When this block is requested, we'll send an inv that'll make them
2521 // getblocks the next batch of inventory.
2522 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2523 pfrom->hashContinue = pindex->GetBlockHash();
2530 else if (strCommand == "getheaders")
2532 CBlockLocator locator;
2534 vRecv >> locator >> hashStop;
2536 CBlockIndex* pindex = NULL;
2537 if (locator.IsNull())
2539 // If locator is null, return the hashStop block
2540 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2541 if (mi == mapBlockIndex.end())
2543 pindex = (*mi).second;
2547 // Find the last block the caller has in the main chain
2548 pindex = locator.GetBlockIndex();
2550 pindex = pindex->pnext;
2553 vector<CBlock> vHeaders;
2555 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
2556 for (; pindex; pindex = pindex->pnext)
2558 vHeaders.push_back(pindex->GetBlockHeader());
2559 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2562 pfrom->PushMessage("headers", vHeaders);
2566 else if (strCommand == "tx")
2568 vector<uint256> vWorkQueue;
2569 vector<uint256> vEraseQueue;
2570 CDataStream vMsg(vRecv);
2575 CInv inv(MSG_TX, tx.GetHash());
2576 pfrom->AddInventoryKnown(inv);
2578 bool fMissingInputs = false;
2579 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
2581 SyncWithWallets(tx, NULL, true);
2582 RelayMessage(inv, vMsg);
2583 mapAlreadyAskedFor.erase(inv);
2584 vWorkQueue.push_back(inv.hash);
2585 vEraseQueue.push_back(inv.hash);
2587 // Recursively process any orphan transactions that depended on this one
2588 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2590 uint256 hashPrev = vWorkQueue[i];
2591 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
2592 mi != mapOrphanTransactionsByPrev[hashPrev].end();
2595 const CDataStream& vMsg = *((*mi).second);
2597 CDataStream(vMsg) >> tx;
2598 CInv inv(MSG_TX, tx.GetHash());
2599 bool fMissingInputs2 = false;
2601 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
2603 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2604 SyncWithWallets(tx, NULL, true);
2605 RelayMessage(inv, vMsg);
2606 mapAlreadyAskedFor.erase(inv);
2607 vWorkQueue.push_back(inv.hash);
2608 vEraseQueue.push_back(inv.hash);
2610 else if (!fMissingInputs2)
2613 vEraseQueue.push_back(inv.hash);
2614 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2619 BOOST_FOREACH(uint256 hash, vEraseQueue)
2620 EraseOrphanTx(hash);
2622 else if (fMissingInputs)
2626 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2627 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
2629 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
2631 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2635 else if (strCommand == "block")
2640 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2643 CInv inv(MSG_BLOCK, block.GetHash());
2644 pfrom->AddInventoryKnown(inv);
2646 if (ProcessBlock(pfrom, &block))
2647 mapAlreadyAskedFor.erase(inv);
2648 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2652 else if (strCommand == "getaddr")
2654 pfrom->vAddrToSend.clear();
2655 vector<CAddress> vAddr = addrman.GetAddr();
2656 BOOST_FOREACH(const CAddress &addr, vAddr)
2657 pfrom->PushAddress(addr);
2661 else if (strCommand == "checkorder")
2666 if (!GetBoolArg("-allowreceivebyip"))
2668 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2675 /// we have a chance to check the order here
2677 // Keep giving the same key to the same ip until they use it
2678 if (!mapReuseKey.count(pfrom->addr))
2679 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
2681 // Send back approval of order and pubkey to use
2682 CScript scriptPubKey;
2683 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
2684 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2688 else if (strCommand == "reply")
2693 CRequestTracker tracker;
2695 LOCK(pfrom->cs_mapRequests);
2696 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2697 if (mi != pfrom->mapRequests.end())
2699 tracker = (*mi).second;
2700 pfrom->mapRequests.erase(mi);
2703 if (!tracker.IsNull())
2704 tracker.fn(tracker.param1, vRecv);
2708 else if (strCommand == "ping")
2710 if (pfrom->nVersion > BIP0031_VERSION)
2714 // Echo the message back with the nonce. This allows for two useful features:
2716 // 1) A remote node can quickly check if the connection is operational
2717 // 2) Remote nodes can measure the latency of the network thread. If this node
2718 // is overloaded it won't respond to pings quickly and the remote node can
2719 // avoid sending us more work, like chain download requests.
2721 // The nonce stops the remote getting confused between different pings: without
2722 // it, if the remote node sends a ping once per second and this node takes 5
2723 // seconds to respond to each, the 5th ping the remote sends would appear to
2724 // return very quickly.
2725 pfrom->PushMessage("pong", nonce);
2730 else if (strCommand == "alert")
2735 if (alert.ProcessAlert())
2738 pfrom->setKnown.insert(alert.GetHash());
2741 BOOST_FOREACH(CNode* pnode, vNodes)
2742 alert.RelayTo(pnode);
2750 // Ignore unknown commands for extensibility
2754 // Update the last seen time for this node's address
2755 if (pfrom->fNetworkNode)
2756 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2757 AddressCurrentlyConnected(pfrom->addr);
2763 bool ProcessMessages(CNode* pfrom)
2765 CDataStream& vRecv = pfrom->vRecv;
2769 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2773 // (4) message start
2782 // Scan for message start
2783 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2784 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2785 if (vRecv.end() - pstart < nHeaderSize)
2787 if ((int)vRecv.size() > nHeaderSize)
2789 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2790 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2794 if (pstart - vRecv.begin() > 0)
2795 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2796 vRecv.erase(vRecv.begin(), pstart);
2799 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2804 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2807 string strCommand = hdr.GetCommand();
2810 unsigned int nMessageSize = hdr.nMessageSize;
2811 if (nMessageSize > MAX_SIZE)
2813 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2816 if (nMessageSize > vRecv.size())
2818 // Rewind and wait for rest of message
2819 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2824 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2825 unsigned int nChecksum = 0;
2826 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2827 if (nChecksum != hdr.nChecksum)
2829 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2830 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2834 // Copy message to its own buffer
2835 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2836 vRecv.ignore(nMessageSize);
2844 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2849 catch (std::ios_base::failure& e)
2851 if (strstr(e.what(), "end of data"))
2853 // Allow exceptions from underlength message on vRecv
2854 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());
2856 else if (strstr(e.what(), "size too large"))
2858 // Allow exceptions from overlong size
2859 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2863 PrintExceptionContinue(&e, "ProcessMessage()");
2866 catch (std::exception& e) {
2867 PrintExceptionContinue(&e, "ProcessMessage()");
2869 PrintExceptionContinue(NULL, "ProcessMessage()");
2873 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2881 bool SendMessages(CNode* pto, bool fSendTrickle)
2883 TRY_LOCK(cs_main, lockMain);
2885 // Don't send anything until we get their version message
2886 if (pto->nVersion == 0)
2889 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
2891 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
2892 if (pto->nVersion > BIP0031_VERSION)
2893 pto->PushMessage("ping", 0);
2895 pto->PushMessage("ping");
2898 // Resend wallet transactions that haven't gotten in a block yet
2899 ResendWalletTransactions();
2901 // Address refresh broadcast
2902 static int64 nLastRebroadcast;
2903 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
2907 BOOST_FOREACH(CNode* pnode, vNodes)
2909 // Periodically clear setAddrKnown to allow refresh broadcasts
2910 if (nLastRebroadcast)
2911 pnode->setAddrKnown.clear();
2913 // Rebroadcast our address
2914 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable())
2916 CAddress addr(addrLocalHost);
2917 addr.nTime = GetAdjustedTime();
2918 pnode->PushAddress(addr);
2922 nLastRebroadcast = GetTime();
2930 vector<CAddress> vAddr;
2931 vAddr.reserve(pto->vAddrToSend.size());
2932 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2934 // returns true if wasn't already contained in the set
2935 if (pto->setAddrKnown.insert(addr).second)
2937 vAddr.push_back(addr);
2938 // receiver rejects addr messages larger than 1000
2939 if (vAddr.size() >= 1000)
2941 pto->PushMessage("addr", vAddr);
2946 pto->vAddrToSend.clear();
2948 pto->PushMessage("addr", vAddr);
2953 // Message: inventory
2956 vector<CInv> vInvWait;
2958 LOCK(pto->cs_inventory);
2959 vInv.reserve(pto->vInventoryToSend.size());
2960 vInvWait.reserve(pto->vInventoryToSend.size());
2961 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2963 if (pto->setInventoryKnown.count(inv))
2966 // trickle out tx inv to protect privacy
2967 if (inv.type == MSG_TX && !fSendTrickle)
2969 // 1/4 of tx invs blast to all immediately
2970 static uint256 hashSalt;
2972 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2973 uint256 hashRand = inv.hash ^ hashSalt;
2974 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2975 bool fTrickleWait = ((hashRand & 3) != 0);
2977 // always trickle our own transactions
2981 if (GetTransaction(inv.hash, wtx))
2983 fTrickleWait = true;
2988 vInvWait.push_back(inv);
2993 // returns true if wasn't already contained in the set
2994 if (pto->setInventoryKnown.insert(inv).second)
2996 vInv.push_back(inv);
2997 if (vInv.size() >= 1000)
2999 pto->PushMessage("inv", vInv);
3004 pto->vInventoryToSend = vInvWait;
3007 pto->PushMessage("inv", vInv);
3013 vector<CInv> vGetData;
3014 int64 nNow = GetTime() * 1000000;
3016 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3018 const CInv& inv = (*pto->mapAskFor.begin()).second;
3019 if (!AlreadyHave(txdb, inv))
3021 printf("sending getdata: %s\n", inv.ToString().c_str());
3022 vGetData.push_back(inv);
3023 if (vGetData.size() >= 1000)
3025 pto->PushMessage("getdata", vGetData);
3029 mapAlreadyAskedFor[inv] = nNow;
3030 pto->mapAskFor.erase(pto->mapAskFor.begin());
3032 if (!vGetData.empty())
3033 pto->PushMessage("getdata", vGetData);
3052 //////////////////////////////////////////////////////////////////////////////
3057 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3059 unsigned char* pdata = (unsigned char*)pbuffer;
3060 unsigned int blocks = 1 + ((len + 8) / 64);
3061 unsigned char* pend = pdata + 64 * blocks;
3062 memset(pdata + len, 0, 64 * blocks - len);
3064 unsigned int bits = len * 8;
3065 pend[-1] = (bits >> 0) & 0xff;
3066 pend[-2] = (bits >> 8) & 0xff;
3067 pend[-3] = (bits >> 16) & 0xff;
3068 pend[-4] = (bits >> 24) & 0xff;
3072 static const unsigned int pSHA256InitState[8] =
3073 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3075 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3078 unsigned char data[64];
3082 for (int i = 0; i < 16; i++)
3083 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3085 for (int i = 0; i < 8; i++)
3086 ctx.h[i] = ((uint32_t*)pinit)[i];
3088 SHA256_Update(&ctx, data, sizeof(data));
3089 for (int i = 0; i < 8; i++)
3090 ((uint32_t*)pstate)[i] = ctx.h[i];
3094 // ScanHash scans nonces looking for a hash with at least some zero bits.
3095 // It operates on big endian data. Caller does the byte reversing.
3096 // All input buffers are 16-byte aligned. nNonce is usually preserved
3097 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3098 // the block is rebuilt and nNonce starts over at zero.
3100 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3102 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3106 // Hash pdata using pmidstate as the starting state into
3107 // preformatted buffer phash1, then hash phash1 into phash
3109 SHA256Transform(phash1, pdata, pmidstate);
3110 SHA256Transform(phash, phash1, pSHA256InitState);
3112 // Return the nonce if the hash has at least some zero bits,
3113 // caller will check if it has enough to reach the target
3114 if (((unsigned short*)phash)[14] == 0)
3117 // If nothing found after trying for a while, return -1
3118 if ((nNonce & 0xffff) == 0)
3120 nHashesDone = 0xffff+1;
3121 return (unsigned int) -1;
3126 // Some explaining would be appreciated
3131 set<uint256> setDependsOn;
3134 COrphan(CTransaction* ptxIn)
3142 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3143 BOOST_FOREACH(uint256 hash, setDependsOn)
3144 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3149 uint64 nLastBlockTx = 0;
3150 uint64 nLastBlockSize = 0;
3152 CBlock* CreateNewBlock(CReserveKey& reservekey)
3154 CBlockIndex* pindexPrev = pindexBest;
3157 auto_ptr<CBlock> pblock(new CBlock());
3161 // Create coinbase tx
3163 txNew.vin.resize(1);
3164 txNew.vin[0].prevout.SetNull();
3165 txNew.vout.resize(1);
3166 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3168 // Add our coinbase tx as first transaction
3169 pblock->vtx.push_back(txNew);
3171 // Collect memory pool transactions into the block
3174 LOCK2(cs_main, mempool.cs);
3177 // Priority order to process transactions
3178 list<COrphan> vOrphan; // list memory doesn't move
3179 map<uint256, vector<COrphan*> > mapDependers;
3180 multimap<double, CTransaction*> mapPriority;
3181 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3183 CTransaction& tx = (*mi).second;
3184 if (tx.IsCoinBase() || !tx.IsFinal())
3187 COrphan* porphan = NULL;
3188 double dPriority = 0;
3189 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3191 // Read prev transaction
3192 CTransaction txPrev;
3194 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3196 // Has to wait for dependencies
3199 // Use list for automatic deletion
3200 vOrphan.push_back(COrphan(&tx));
3201 porphan = &vOrphan.back();
3203 mapDependers[txin.prevout.hash].push_back(porphan);
3204 porphan->setDependsOn.insert(txin.prevout.hash);
3207 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3209 // Read block header
3210 int nConf = txindex.GetDepthInMainChain();
3212 dPriority += (double)nValueIn * nConf;
3214 if (fDebug && GetBoolArg("-printpriority"))
3215 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3218 // Priority is sum(valuein * age) / txsize
3219 dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3222 porphan->dPriority = dPriority;
3224 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3226 if (fDebug && GetBoolArg("-printpriority"))
3228 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3235 // Collect transactions into block
3236 map<uint256, CTxIndex> mapTestPool;
3237 uint64 nBlockSize = 1000;
3238 uint64 nBlockTx = 0;
3239 int nBlockSigOps = 100;
3240 while (!mapPriority.empty())
3242 // Take highest priority transaction off priority queue
3243 double dPriority = -(*mapPriority.begin()).first;
3244 CTransaction& tx = *(*mapPriority.begin()).second;
3245 mapPriority.erase(mapPriority.begin());
3248 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3249 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3252 // Legacy limits on sigOps:
3253 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
3254 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3257 // Transaction fee required depends on block size
3258 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3259 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
3261 // Connecting shouldn't fail due to dependency on other memory pool transactions
3262 // because we're already processing them in order of dependency
3263 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3264 MapPrevTx mapInputs;
3266 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3269 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3270 if (nTxFees < nMinFee)
3273 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3274 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3277 if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3279 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3280 swap(mapTestPool, mapTestPoolTmp);
3283 pblock->vtx.push_back(tx);
3284 nBlockSize += nTxSize;
3286 nBlockSigOps += nTxSigOps;
3289 // Add transactions that depend on this one to the priority queue
3290 uint256 hash = tx.GetHash();
3291 if (mapDependers.count(hash))
3293 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3295 if (!porphan->setDependsOn.empty())
3297 porphan->setDependsOn.erase(hash);
3298 if (porphan->setDependsOn.empty())
3299 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3305 nLastBlockTx = nBlockTx;
3306 nLastBlockSize = nBlockSize;
3307 printf("CreateNewBlock(): total size %lu\n", nBlockSize);
3310 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3313 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3314 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3315 pblock->UpdateTime(pindexPrev);
3316 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
3319 return pblock.release();
3323 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3325 // Update nExtraNonce
3326 static uint256 hashPrevBlock;
3327 if (hashPrevBlock != pblock->hashPrevBlock)
3330 hashPrevBlock = pblock->hashPrevBlock;
3333 pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
3334 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3336 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3340 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3343 // Prebuild hash buffers
3350 uint256 hashPrevBlock;
3351 uint256 hashMerkleRoot;
3354 unsigned int nNonce;
3357 unsigned char pchPadding0[64];
3359 unsigned char pchPadding1[64];
3362 memset(&tmp, 0, sizeof(tmp));
3364 tmp.block.nVersion = pblock->nVersion;
3365 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3366 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3367 tmp.block.nTime = pblock->nTime;
3368 tmp.block.nBits = pblock->nBits;
3369 tmp.block.nNonce = pblock->nNonce;
3371 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3372 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3374 // Byte swap all the input buffer
3375 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3376 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3378 // Precalc the first half of the first hash, which stays constant
3379 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3381 memcpy(pdata, &tmp.block, 128);
3382 memcpy(phash1, &tmp.hash1, 64);
3386 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3388 uint256 hash = pblock->GetHash();
3389 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3391 if (hash > hashTarget)
3395 printf("BitcoinMiner:\n");
3396 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3398 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3399 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3404 if (pblock->hashPrevBlock != hashBestChain)
3405 return error("BitcoinMiner : generated block is stale");
3407 // Remove key from key pool
3408 reservekey.KeepKey();
3410 // Track how many getdata requests this block gets
3412 LOCK(wallet.cs_wallet);
3413 wallet.mapRequestCount[pblock->GetHash()] = 0;
3416 // Process this block the same as if we had received it from another node
3417 if (!ProcessBlock(NULL, pblock))
3418 return error("BitcoinMiner : ProcessBlock, block not accepted");
3424 void static ThreadBitcoinMiner(void* parg);
3426 static bool fGenerateBitcoins = false;
3427 static bool fLimitProcessors = false;
3428 static int nLimitProcessors = -1;
3430 void static BitcoinMiner(CWallet *pwallet)
3432 printf("BitcoinMiner started\n");
3433 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3435 // Each thread has its own key and counter
3436 CReserveKey reservekey(pwallet);
3437 unsigned int nExtraNonce = 0;
3439 while (fGenerateBitcoins)
3443 while (vNodes.empty() || IsInitialBlockDownload())
3448 if (!fGenerateBitcoins)
3456 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3457 CBlockIndex* pindexPrev = pindexBest;
3459 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3462 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3464 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3468 // Prebuild hash buffers
3470 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3471 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3472 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3474 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3476 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3477 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
3478 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3484 int64 nStart = GetTime();
3485 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3487 uint256& hash = *alignup<16>(hashbuf);
3490 unsigned int nHashesDone = 0;
3491 unsigned int nNonceFound;
3494 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3495 (char*)&hash, nHashesDone);
3497 // Check if something found
3498 if (nNonceFound != (unsigned int) -1)
3500 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
3501 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3503 if (hash <= hashTarget)
3506 pblock->nNonce = ByteReverse(nNonceFound);
3507 assert(hash == pblock->GetHash());
3509 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3510 CheckWork(pblock.get(), *pwalletMain, reservekey);
3511 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3517 static int64 nHashCounter;
3518 if (nHPSTimerStart == 0)
3520 nHPSTimerStart = GetTimeMillis();
3524 nHashCounter += nHashesDone;
3525 if (GetTimeMillis() - nHPSTimerStart > 4000)
3527 static CCriticalSection cs;
3530 if (GetTimeMillis() - nHPSTimerStart > 4000)
3532 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3533 nHPSTimerStart = GetTimeMillis();
3535 static int64 nLogTime;
3536 if (GetTime() - nLogTime > 30 * 60)
3538 nLogTime = GetTime();
3539 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3540 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
3546 // Check for stop or if block needs to be rebuilt
3549 if (!fGenerateBitcoins)
3551 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
3555 if (nBlockNonce >= 0xffff0000)
3557 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3559 if (pindexPrev != pindexBest)
3562 // Update nTime every few seconds
3563 pblock->UpdateTime(pindexPrev);
3564 nBlockTime = ByteReverse(pblock->nTime);
3567 // Changing pblock->nTime can change work required on testnet:
3568 nBlockBits = ByteReverse(pblock->nBits);
3569 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3575 void static ThreadBitcoinMiner(void* parg)
3577 CWallet* pwallet = (CWallet*)parg;
3580 vnThreadsRunning[THREAD_MINER]++;
3581 BitcoinMiner(pwallet);
3582 vnThreadsRunning[THREAD_MINER]--;
3584 catch (std::exception& e) {
3585 vnThreadsRunning[THREAD_MINER]--;
3586 PrintException(&e, "ThreadBitcoinMiner()");
3588 vnThreadsRunning[THREAD_MINER]--;
3589 PrintException(NULL, "ThreadBitcoinMiner()");
3592 if (vnThreadsRunning[THREAD_MINER] == 0)
3594 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
3598 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3600 fGenerateBitcoins = fGenerate;
3601 nLimitProcessors = GetArg("-genproclimit", -1);
3602 if (nLimitProcessors == 0)
3603 fGenerateBitcoins = false;
3604 fLimitProcessors = (nLimitProcessors != -1);
3608 int nProcessors = boost::thread::hardware_concurrency();
3609 printf("%d processors\n", nProcessors);
3610 if (nProcessors < 1)
3612 if (fLimitProcessors && nProcessors > nLimitProcessors)
3613 nProcessors = nLimitProcessors;
3614 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
3615 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3616 for (int i = 0; i < nAddThreads; i++)
3618 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3619 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");