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 COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
12 #include "ui_interface.h"
13 #include "checkqueue.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
19 using namespace boost;
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
31 unsigned int nTransactionsUpdated = 0;
33 map<uint256, CBlockIndex*> mapBlockIndex;
34 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
35 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
36 CBlockIndex* pindexGenesisBlock = NULL;
38 CBigNum bnBestChainWork = 0;
39 CBigNum bnBestInvalidWork = 0;
40 uint256 hashBestChain = 0;
41 CBlockIndex* pindexBest = NULL;
42 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
43 int64 nTimeBestReceived = 0;
44 int nScriptCheckThreads = 0;
45 bool fImporting = false;
46 bool fReindex = false;
47 bool fBenchmark = false;
48 bool fTxIndex = false;
49 unsigned int nCoinCacheSize = 5000;
51 CMedianFilter<int> cPeerBlockCounts(8, 0); // Amount of blocks that other nodes claim to have
53 map<uint256, CBlock*> mapOrphanBlocks;
54 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
56 map<uint256, CDataStream*> mapOrphanTransactions;
57 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
59 // Constant stuff for coinbase transactions we create:
60 CScript COINBASE_FLAGS;
62 const string strMessageMagic = "Bitcoin Signed Message:\n";
68 int64 nTransactionFee = 0;
72 //////////////////////////////////////////////////////////////////////////////
74 // dispatching functions
77 // These functions dispatch to one or all registered wallets
80 void RegisterWallet(CWallet* pwalletIn)
83 LOCK(cs_setpwalletRegistered);
84 setpwalletRegistered.insert(pwalletIn);
88 void UnregisterWallet(CWallet* pwalletIn)
91 LOCK(cs_setpwalletRegistered);
92 setpwalletRegistered.erase(pwalletIn);
96 // get the wallet transaction with the given hash (if it exists)
97 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
99 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
100 if (pwallet->GetTransaction(hashTx,wtx))
105 // erases transaction with the given hash from all wallets
106 void static EraseFromWallets(uint256 hash)
108 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
109 pwallet->EraseFromWallet(hash);
112 // make sure all wallets know about the given transaction, in the given block
113 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate)
115 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
116 pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
119 // notify wallets about a new best chain
120 void static SetBestChain(const CBlockLocator& loc)
122 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
123 pwallet->SetBestChain(loc);
126 // notify wallets about an updated transaction
127 void static UpdatedTransaction(const uint256& hashTx)
129 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
130 pwallet->UpdatedTransaction(hashTx);
134 void static PrintWallets(const CBlock& block)
136 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
137 pwallet->PrintWallet(block);
140 // notify wallets about an incoming inventory (for request counts)
141 void static Inventory(const uint256& hash)
143 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
144 pwallet->Inventory(hash);
147 // ask wallets to resend their transactions
148 void static ResendWalletTransactions()
150 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
151 pwallet->ResendWalletTransactions();
160 //////////////////////////////////////////////////////////////////////////////
162 // CCoinsView implementations
165 bool CCoinsView::GetCoins(uint256 txid, CCoins &coins) { return false; }
166 bool CCoinsView::SetCoins(uint256 txid, const CCoins &coins) { return false; }
167 bool CCoinsView::HaveCoins(uint256 txid) { return false; }
168 CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
169 bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
170 bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
171 bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
174 CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
175 bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); }
176 bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
177 bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); }
178 CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
179 bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
180 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
181 bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
182 bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); }
184 CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
186 bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) {
187 if (cacheCoins.count(txid)) {
188 coins = cacheCoins[txid];
191 if (base->GetCoins(txid, coins)) {
192 cacheCoins[txid] = coins;
198 std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(uint256 txid) {
199 std::map<uint256,CCoins>::iterator it = cacheCoins.find(txid);
200 if (it != cacheCoins.end())
203 if (!base->GetCoins(txid,tmp))
205 std::pair<std::map<uint256,CCoins>::iterator,bool> ret = cacheCoins.insert(std::make_pair(txid, tmp));
209 CCoins &CCoinsViewCache::GetCoins(uint256 txid) {
210 std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
211 assert(it != cacheCoins.end());
215 bool CCoinsViewCache::SetCoins(uint256 txid, const CCoins &coins) {
216 cacheCoins[txid] = coins;
220 bool CCoinsViewCache::HaveCoins(uint256 txid) {
221 return FetchCoins(txid) != cacheCoins.end();
224 CBlockIndex *CCoinsViewCache::GetBestBlock() {
225 if (pindexTip == NULL)
226 pindexTip = base->GetBestBlock();
230 bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
235 bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
236 for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
237 cacheCoins[it->first] = it->second;
242 bool CCoinsViewCache::Flush() {
243 bool fOk = base->BatchWrite(cacheCoins, pindexTip);
249 unsigned int CCoinsViewCache::GetCacheSize() {
250 return cacheCoins.size();
253 /** CCoinsView that brings transactions from a memorypool into view.
254 It does not check for spendings by memory pool transactions. */
255 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
257 bool CCoinsViewMemPool::GetCoins(uint256 txid, CCoins &coins) {
258 if (base->GetCoins(txid, coins))
260 if (mempool.exists(txid)) {
261 const CTransaction &tx = mempool.lookup(txid);
262 coins = CCoins(tx, MEMPOOL_HEIGHT);
268 bool CCoinsViewMemPool::HaveCoins(uint256 txid) {
269 return mempool.exists(txid) || base->HaveCoins(txid);
272 CCoinsViewCache *pcoinsTip = NULL;
273 CBlockTreeDB *pblocktree = NULL;
275 //////////////////////////////////////////////////////////////////////////////
277 // mapOrphanTransactions
280 bool AddOrphanTx(const CDataStream& vMsg)
283 CDataStream(vMsg) >> tx;
284 uint256 hash = tx.GetHash();
285 if (mapOrphanTransactions.count(hash))
288 CDataStream* pvMsg = new CDataStream(vMsg);
290 // Ignore big transactions, to avoid a
291 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
292 // large transaction with a missing parent then we assume
293 // it will rebroadcast it later, after the parent transaction(s)
294 // have been mined or received.
295 // 10,000 orphans, each of which is at most 5,000 bytes big is
296 // at most 500 megabytes of orphans:
297 if (pvMsg->size() > 5000)
299 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
304 mapOrphanTransactions[hash] = pvMsg;
305 BOOST_FOREACH(const CTxIn& txin, tx.vin)
306 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
308 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
309 mapOrphanTransactions.size());
313 void static EraseOrphanTx(uint256 hash)
315 if (!mapOrphanTransactions.count(hash))
317 const CDataStream* pvMsg = mapOrphanTransactions[hash];
319 CDataStream(*pvMsg) >> tx;
320 BOOST_FOREACH(const CTxIn& txin, tx.vin)
322 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
323 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
324 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
327 mapOrphanTransactions.erase(hash);
330 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
332 unsigned int nEvicted = 0;
333 while (mapOrphanTransactions.size() > nMaxOrphans)
335 // Evict a random orphan:
336 uint256 randomhash = GetRandHash();
337 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
338 if (it == mapOrphanTransactions.end())
339 it = mapOrphanTransactions.begin();
340 EraseOrphanTx(it->first);
352 //////////////////////////////////////////////////////////////////////////////
357 bool CTransaction::IsStandard() const
359 if (nVersion > CTransaction::CURRENT_VERSION)
365 // Extremely large transactions with lots of inputs can cost the network
366 // almost as much to process as they cost the sender in fees, because
367 // computing signature hashes is O(ninputs*txsize). Limiting transactions
368 // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
369 unsigned int sz = this->GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
370 if (sz >= MAX_STANDARD_TX_SIZE)
373 BOOST_FOREACH(const CTxIn& txin, vin)
375 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
376 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
377 // ~65-byte public keys, plus a few script ops.
378 if (txin.scriptSig.size() > 500)
380 if (!txin.scriptSig.IsPushOnly())
383 BOOST_FOREACH(const CTxOut& txout, vout) {
384 if (!::IsStandard(txout.scriptPubKey))
386 if (txout.nValue == 0)
393 // Check transaction inputs, and make sure any
394 // pay-to-script-hash transactions are evaluating IsStandard scripts
396 // Why bother? To avoid denial-of-service attacks; an attacker
397 // can submit a standard HASH... OP_EQUAL transaction,
398 // which will get accepted into blocks. The redemption
399 // script can be anything; an attacker could use a very
400 // expensive-to-check-upon-redemption script like:
401 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
403 bool CTransaction::AreInputsStandard(CCoinsViewCache& mapInputs) const
406 return true; // Coinbases don't use vin normally
408 for (unsigned int i = 0; i < vin.size(); i++)
410 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
412 vector<vector<unsigned char> > vSolutions;
413 txnouttype whichType;
414 // get the scriptPubKey corresponding to this input:
415 const CScript& prevScript = prev.scriptPubKey;
416 if (!Solver(prevScript, whichType, vSolutions))
418 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
419 if (nArgsExpected < 0)
422 // Transactions with extra stuff in their scriptSigs are
423 // non-standard. Note that this EvalScript() call will
424 // be quick, because if there are any operations
425 // beside "push data" in the scriptSig the
426 // IsStandard() call returns false
427 vector<vector<unsigned char> > stack;
428 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
431 if (whichType == TX_SCRIPTHASH)
435 CScript subscript(stack.back().begin(), stack.back().end());
436 vector<vector<unsigned char> > vSolutions2;
437 txnouttype whichType2;
438 if (!Solver(subscript, whichType2, vSolutions2))
440 if (whichType2 == TX_SCRIPTHASH)
444 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
447 nArgsExpected += tmpExpected;
450 if (stack.size() != (unsigned int)nArgsExpected)
458 CTransaction::GetLegacySigOpCount() const
460 unsigned int nSigOps = 0;
461 BOOST_FOREACH(const CTxIn& txin, vin)
463 nSigOps += txin.scriptSig.GetSigOpCount(false);
465 BOOST_FOREACH(const CTxOut& txout, vout)
467 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
473 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
477 if (pblock == NULL) {
479 if (pcoinsTip->GetCoins(GetHash(), coins)) {
480 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
482 if (!blockTmp.ReadFromDisk(pindex))
490 // Update the tx's hashBlock
491 hashBlock = pblock->GetHash();
493 // Locate the transaction
494 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
495 if (pblock->vtx[nIndex] == *(CTransaction*)this)
497 if (nIndex == (int)pblock->vtx.size())
499 vMerkleBranch.clear();
501 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
505 // Fill in merkle branch
506 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
509 // Is the tx in a block that's in the main chain
510 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
511 if (mi == mapBlockIndex.end())
513 CBlockIndex* pindex = (*mi).second;
514 if (!pindex || !pindex->IsInMainChain())
517 return pindexBest->nHeight - pindex->nHeight + 1;
526 bool CTransaction::CheckTransaction(CValidationState &state) const
528 // Basic checks that don't depend on any context
530 return state.DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
532 return state.DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
534 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
535 return state.DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
537 // Check for negative or overflow output values
539 BOOST_FOREACH(const CTxOut& txout, vout)
541 if (txout.nValue < 0)
542 return state.DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
543 if (txout.nValue > MAX_MONEY)
544 return state.DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
545 nValueOut += txout.nValue;
546 if (!MoneyRange(nValueOut))
547 return state.DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
550 // Check for duplicate inputs
551 set<COutPoint> vInOutPoints;
552 BOOST_FOREACH(const CTxIn& txin, vin)
554 if (vInOutPoints.count(txin.prevout))
555 return state.DoS(100, error("CTransaction::CheckTransaction() : duplicate inputs"));
556 vInOutPoints.insert(txin.prevout);
561 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
562 return state.DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
566 BOOST_FOREACH(const CTxIn& txin, vin)
567 if (txin.prevout.IsNull())
568 return state.DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
574 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
575 enum GetMinFee_mode mode) const
577 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
578 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
580 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
581 unsigned int nNewBlockSize = nBlockSize + nBytes;
582 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
588 // Transactions under 10K are free
589 // (about 4500 BTC if made of 50 BTC inputs)
595 // Free transaction area
596 if (nNewBlockSize < 27000)
601 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
602 if (nMinFee < nBaseFee)
604 BOOST_FOREACH(const CTxOut& txout, vout)
605 if (txout.nValue < CENT)
609 // Raise the price as the block approaches full
610 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
612 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
614 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
617 if (!MoneyRange(nMinFee))
622 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
626 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
628 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
629 while (it != mapNextTx.end() && it->first.hash == hashTx) {
630 coins.Spend(it->first.n); // and remove those outputs from coins
635 bool CTxMemPool::accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree,
636 bool* pfMissingInputs)
639 *pfMissingInputs = false;
641 if (!tx.CheckTransaction(state))
642 return error("CTxMemPool::accept() : CheckTransaction failed");
644 // Coinbase is only valid in a block, not as a loose transaction
646 return state.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
648 // To help v0.1.5 clients who would see it as a negative number
649 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
650 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
652 // Rather not work on nonstandard transactions (unless -testnet)
653 if (!fTestNet && !tx.IsStandard())
654 return error("CTxMemPool::accept() : nonstandard transaction type");
656 // is it already in the memory pool?
657 uint256 hash = tx.GetHash();
660 if (mapTx.count(hash))
664 // Check for conflicts with in-memory transactions
665 CTransaction* ptxOld = NULL;
666 for (unsigned int i = 0; i < tx.vin.size(); i++)
668 COutPoint outpoint = tx.vin[i].prevout;
669 if (mapNextTx.count(outpoint))
671 // Disable replacement feature for now
674 // Allow replacing with a newer version of the same transaction
677 ptxOld = mapNextTx[outpoint].ptx;
678 if (ptxOld->IsFinal())
680 if (!tx.IsNewerThan(*ptxOld))
682 for (unsigned int i = 0; i < tx.vin.size(); i++)
684 COutPoint outpoint = tx.vin[i].prevout;
685 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
695 CCoinsViewCache view(dummy);
699 CCoinsViewMemPool viewMemPool(*pcoinsTip, *this);
700 view.SetBackend(viewMemPool);
702 // do we already have it?
703 if (view.HaveCoins(hash))
706 // do all inputs exist?
707 // Note that this does not check for the presence of actual outputs (see the next check for that),
708 // only helps filling in pfMissingInputs (to determine missing vs spent).
709 BOOST_FOREACH(const CTxIn txin, tx.vin) {
710 if (!view.HaveCoins(txin.prevout.hash)) {
712 *pfMissingInputs = true;
717 // are the actual inputs available?
718 if (!tx.HaveInputs(view))
719 return state.Invalid(error("CTxMemPool::accept() : inputs already spent"));
721 // Bring the best block into scope
724 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
725 view.SetBackend(dummy);
728 // Check for non-standard pay-to-script-hash in inputs
729 if (!tx.AreInputsStandard(view) && !fTestNet)
730 return error("CTxMemPool::accept() : nonstandard transaction input");
732 // Note: if you modify this code to accept non-standard transactions, then
733 // you should add code here to check that the transaction does a
734 // reasonable number of ECDSA signature verifications.
736 int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
737 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
739 // Don't accept it if it can't get into a block
740 int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
741 if (fLimitFree && nFees < txMinFee)
742 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
743 hash.ToString().c_str(),
746 // Continuously rate-limit free transactions
747 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
748 // be annoying or make others' transactions take longer to confirm.
749 if (fLimitFree && nFees < MIN_RELAY_TX_FEE)
751 static double dFreeCount;
752 static int64 nLastTime;
753 int64 nNow = GetTime();
757 // Use an exponentially decaying ~10-minute window:
758 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
760 // -limitfreerelay unit is thousand-bytes-per-minute
761 // At default rate it would take over a month to fill 1GB
762 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
763 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
765 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
769 // Check against previous transactions
770 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
771 if (!tx.CheckInputs(state, view, true, SCRIPT_VERIFY_P2SH))
773 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
777 // Store transaction in memory
782 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
785 addUnchecked(hash, tx);
788 ///// are we sure this is ok when loading transactions or restoring block txes
789 // If updated, erase old tx from wallet
791 EraseFromWallets(ptxOld->GetHash());
792 SyncWithWallets(hash, tx, NULL, true);
794 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
795 hash.ToString().substr(0,10).c_str(),
800 bool CTransaction::AcceptToMemoryPool(CValidationState &state, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs)
803 return mempool.accept(state, *this, fCheckInputs, fLimitFree, pfMissingInputs);
804 } catch(std::runtime_error &e) {
805 return state.Abort(_("System error: ") + e.what());
809 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
811 // Add to memory pool without checking anything. Don't call this directly,
812 // call CTxMemPool::accept to properly check the transaction first.
815 for (unsigned int i = 0; i < tx.vin.size(); i++)
816 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
817 nTransactionsUpdated++;
823 bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive)
825 // Remove transaction from memory pool
828 uint256 hash = tx.GetHash();
829 if (mapTx.count(hash))
832 for (unsigned int i = 0; i < tx.vout.size(); i++) {
833 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
834 if (it != mapNextTx.end())
835 remove(*it->second.ptx, true);
838 BOOST_FOREACH(const CTxIn& txin, tx.vin)
839 mapNextTx.erase(txin.prevout);
841 nTransactionsUpdated++;
847 bool CTxMemPool::removeConflicts(const CTransaction &tx)
849 // Remove transactions which depend on inputs of tx, recursively
851 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
852 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
853 if (it != mapNextTx.end()) {
854 const CTransaction &txConflict = *it->second.ptx;
855 if (txConflict != tx)
856 remove(txConflict, true);
862 void CTxMemPool::clear()
867 ++nTransactionsUpdated;
870 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
875 vtxid.reserve(mapTx.size());
876 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
877 vtxid.push_back((*mi).first);
883 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
885 if (hashBlock == 0 || nIndex == -1)
888 // Find the block it claims to be in
889 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
890 if (mi == mapBlockIndex.end())
892 CBlockIndex* pindex = (*mi).second;
893 if (!pindex || !pindex->IsInMainChain())
896 // Make sure the merkle branch connects to this block
897 if (!fMerkleVerified)
899 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
901 fMerkleVerified = true;
905 return pindexBest->nHeight - pindex->nHeight + 1;
909 int CMerkleTx::GetBlocksToMaturity() const
913 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
917 bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs, bool fLimitFree)
919 CValidationState state;
920 return CTransaction::AcceptToMemoryPool(state, fCheckInputs, fLimitFree);
925 bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
929 // Add previous supporting transactions first
930 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
932 if (!tx.IsCoinBase())
934 uint256 hash = tx.GetHash();
935 if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
936 tx.AcceptToMemoryPool(fCheckInputs, false);
939 return AcceptToMemoryPool(fCheckInputs, false);
945 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
946 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
948 CBlockIndex *pindexSlow = NULL;
953 if (mempool.exists(hash))
955 txOut = mempool.lookup(hash);
962 if (pblocktree->ReadTxIndex(hash, postx)) {
963 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
967 fseek(file, postx.nTxOffset, SEEK_CUR);
969 } catch (std::exception &e) {
970 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
972 hashBlock = header.GetHash();
973 if (txOut.GetHash() != hash)
974 return error("%s() : txid mismatch", __PRETTY_FUNCTION__);
979 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
982 CCoinsViewCache &view = *pcoinsTip;
984 if (view.GetCoins(hash, coins))
985 nHeight = coins.nHeight;
988 pindexSlow = FindBlockByHeight(nHeight);
994 if (block.ReadFromDisk(pindexSlow)) {
995 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
996 if (tx.GetHash() == hash) {
998 hashBlock = pindexSlow->GetBlockHash();
1013 //////////////////////////////////////////////////////////////////////////////
1015 // CBlock and CBlockIndex
1018 static CBlockIndex* pblockindexFBBHLast;
1019 CBlockIndex* FindBlockByHeight(int nHeight)
1021 CBlockIndex *pblockindex;
1022 if (nHeight < nBestHeight / 2)
1023 pblockindex = pindexGenesisBlock;
1025 pblockindex = pindexBest;
1026 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
1027 pblockindex = pblockindexFBBHLast;
1028 while (pblockindex->nHeight > nHeight)
1029 pblockindex = pblockindex->pprev;
1030 while (pblockindex->nHeight < nHeight)
1031 pblockindex = pblockindex->pnext;
1032 pblockindexFBBHLast = pblockindex;
1036 bool CBlock::ReadFromDisk(const CBlockIndex* pindex)
1038 if (!ReadFromDisk(pindex->GetBlockPos()))
1040 if (GetHash() != pindex->GetBlockHash())
1041 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1045 uint256 static GetOrphanRoot(const CBlockHeader* pblock)
1047 // Work back to the first block in the orphan chain
1048 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1049 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1050 return pblock->GetHash();
1053 int64 static GetBlockValue(int nHeight, int64 nFees)
1055 int64 nSubsidy = 50 * COIN;
1057 // Subsidy is cut in half every 210000 blocks, which will occur approximately every 4 years
1058 nSubsidy >>= (nHeight / 210000);
1060 return nSubsidy + nFees;
1063 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1064 static const int64 nTargetSpacing = 10 * 60;
1065 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
1068 // minimum amount of work that could possibly be required nTime after
1069 // minimum work required was nBase
1071 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1073 // Testnet has min-difficulty blocks
1074 // after nTargetSpacing*2 time between blocks:
1075 if (fTestNet && nTime > nTargetSpacing*2)
1076 return bnProofOfWorkLimit.GetCompact();
1079 bnResult.SetCompact(nBase);
1080 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
1082 // Maximum 400% adjustment...
1084 // ... in best-case exactly 4-times-normal target time
1085 nTime -= nTargetTimespan*4;
1087 if (bnResult > bnProofOfWorkLimit)
1088 bnResult = bnProofOfWorkLimit;
1089 return bnResult.GetCompact();
1092 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
1094 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
1097 if (pindexLast == NULL)
1098 return nProofOfWorkLimit;
1100 // Only change once per interval
1101 if ((pindexLast->nHeight+1) % nInterval != 0)
1103 // Special difficulty rule for testnet:
1106 // If the new block's timestamp is more than 2* 10 minutes
1107 // then allow mining of a min-difficulty block.
1108 if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
1109 return nProofOfWorkLimit;
1112 // Return the last non-special-min-difficulty-rules-block
1113 const CBlockIndex* pindex = pindexLast;
1114 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
1115 pindex = pindex->pprev;
1116 return pindex->nBits;
1120 return pindexLast->nBits;
1123 // Go back by what we want to be 14 days worth of blocks
1124 const CBlockIndex* pindexFirst = pindexLast;
1125 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1126 pindexFirst = pindexFirst->pprev;
1127 assert(pindexFirst);
1129 // Limit adjustment step
1130 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1131 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1132 if (nActualTimespan < nTargetTimespan/4)
1133 nActualTimespan = nTargetTimespan/4;
1134 if (nActualTimespan > nTargetTimespan*4)
1135 nActualTimespan = nTargetTimespan*4;
1139 bnNew.SetCompact(pindexLast->nBits);
1140 bnNew *= nActualTimespan;
1141 bnNew /= nTargetTimespan;
1143 if (bnNew > bnProofOfWorkLimit)
1144 bnNew = bnProofOfWorkLimit;
1147 printf("GetNextWorkRequired RETARGET\n");
1148 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1149 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1150 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1152 return bnNew.GetCompact();
1155 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1158 bnTarget.SetCompact(nBits);
1161 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1162 return error("CheckProofOfWork() : nBits below minimum work");
1164 // Check proof of work matches claimed amount
1165 if (hash > bnTarget.getuint256())
1166 return error("CheckProofOfWork() : hash doesn't match nBits");
1171 // Return maximum amount of blocks that other nodes claim to have
1172 int GetNumBlocksOfPeers()
1174 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1177 bool IsInitialBlockDownload()
1179 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate() || fReindex || fImporting)
1181 static int64 nLastUpdate;
1182 static CBlockIndex* pindexLastBest;
1183 if (pindexBest != pindexLastBest)
1185 pindexLastBest = pindexBest;
1186 nLastUpdate = GetTime();
1188 return (GetTime() - nLastUpdate < 10 &&
1189 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1192 void static InvalidChainFound(CBlockIndex* pindexNew)
1194 if (pindexNew->bnChainWork > bnBestInvalidWork)
1196 bnBestInvalidWork = pindexNew->bnChainWork;
1197 pblocktree->WriteBestInvalidWork(bnBestInvalidWork);
1198 uiInterface.NotifyBlocksChanged();
1200 printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n",
1201 BlockHashStr(pindexNew->GetBlockHash()).c_str(), pindexNew->nHeight,
1202 pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1203 pindexNew->GetBlockTime()).c_str());
1204 printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n",
1205 BlockHashStr(hashBestChain).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
1206 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1207 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1208 printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1211 void static InvalidBlockFound(CBlockIndex *pindex) {
1212 pindex->nStatus |= BLOCK_FAILED_VALID;
1213 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
1214 setBlockIndexValid.erase(pindex);
1215 InvalidChainFound(pindex);
1216 if (pindex->pnext) {
1217 CValidationState stateDummy;
1218 ConnectBestBlock(stateDummy); // reorganise away from the failed block
1222 bool ConnectBestBlock(CValidationState &state) {
1224 CBlockIndex *pindexNewBest;
1227 std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
1228 if (it == setBlockIndexValid.rend())
1230 pindexNewBest = *it;
1233 if (pindexNewBest == pindexBest || (pindexBest && pindexNewBest->bnChainWork == pindexBest->bnChainWork))
1234 return true; // nothing to do
1237 CBlockIndex *pindexTest = pindexNewBest;
1238 std::vector<CBlockIndex*> vAttach;
1240 if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
1241 // mark descendants failed
1242 CBlockIndex *pindexFailed = pindexNewBest;
1243 while (pindexTest != pindexFailed) {
1244 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
1245 setBlockIndexValid.erase(pindexFailed);
1246 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
1247 pindexFailed = pindexFailed->pprev;
1249 InvalidChainFound(pindexNewBest);
1253 if (pindexBest == NULL || pindexTest->bnChainWork > pindexBest->bnChainWork)
1254 vAttach.push_back(pindexTest);
1256 if (pindexTest->pprev == NULL || pindexTest->pnext != NULL) {
1257 reverse(vAttach.begin(), vAttach.end());
1258 BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) {
1259 if (fRequestShutdown)
1262 if (!SetBestChain(state, pindexSwitch))
1264 } catch(std::runtime_error &e) {
1265 return state.Abort(_("System error: ") + e.what());
1270 pindexTest = pindexTest->pprev;
1275 void CBlockHeader::UpdateTime(const CBlockIndex* pindexPrev)
1277 nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1279 // Updating time can change work required on testnet:
1281 nBits = GetNextWorkRequired(pindexPrev, this);
1294 const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view)
1296 const CCoins &coins = view.GetCoins(input.prevout.hash);
1297 assert(coins.IsAvailable(input.prevout.n));
1298 return coins.vout[input.prevout.n];
1301 int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const
1307 for (unsigned int i = 0; i < vin.size(); i++)
1308 nResult += GetOutputFor(vin[i], inputs).nValue;
1313 unsigned int CTransaction::GetP2SHSigOpCount(CCoinsViewCache& inputs) const
1318 unsigned int nSigOps = 0;
1319 for (unsigned int i = 0; i < vin.size(); i++)
1321 const CTxOut &prevout = GetOutputFor(vin[i], inputs);
1322 if (prevout.scriptPubKey.IsPayToScriptHash())
1323 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1328 bool CTransaction::UpdateCoins(CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash) const
1330 // mark inputs spent
1331 if (!IsCoinBase()) {
1332 BOOST_FOREACH(const CTxIn &txin, vin) {
1333 CCoins &coins = inputs.GetCoins(txin.prevout.hash);
1335 assert(coins.Spend(txin.prevout, undo));
1336 txundo.vprevout.push_back(undo);
1341 assert(inputs.SetCoins(txhash, CCoins(*this, nHeight)));
1346 bool CTransaction::HaveInputs(CCoinsViewCache &inputs) const
1348 if (!IsCoinBase()) {
1349 // first check whether information about the prevout hash is available
1350 for (unsigned int i = 0; i < vin.size(); i++) {
1351 const COutPoint &prevout = vin[i].prevout;
1352 if (!inputs.HaveCoins(prevout.hash))
1356 // then check whether the actual outputs are available
1357 for (unsigned int i = 0; i < vin.size(); i++) {
1358 const COutPoint &prevout = vin[i].prevout;
1359 const CCoins &coins = inputs.GetCoins(prevout.hash);
1360 if (!coins.IsAvailable(prevout.n))
1367 bool CScriptCheck::operator()() const {
1368 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1369 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1370 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1374 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1376 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1379 bool CTransaction::CheckInputs(CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks) const
1384 pvChecks->reserve(vin.size());
1386 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1387 // for an attacker to attempt to split the network.
1388 if (!HaveInputs(inputs))
1389 return state.Invalid(error("CheckInputs() : %s inputs unavailable", GetHash().ToString().substr(0,10).c_str()));
1391 // While checking, GetBestBlock() refers to the parent block.
1392 // This is also true for mempool checks.
1393 int nSpendHeight = inputs.GetBestBlock()->nHeight + 1;
1396 for (unsigned int i = 0; i < vin.size(); i++)
1398 const COutPoint &prevout = vin[i].prevout;
1399 const CCoins &coins = inputs.GetCoins(prevout.hash);
1401 // If prev is coinbase, check that it's matured
1402 if (coins.IsCoinBase()) {
1403 if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
1404 return state.Invalid(error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight));
1407 // Check for negative or overflow input values
1408 nValueIn += coins.vout[prevout.n].nValue;
1409 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1410 return state.DoS(100, error("CheckInputs() : txin values out of range"));
1414 if (nValueIn < GetValueOut())
1415 return state.DoS(100, error("CheckInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1417 // Tally transaction fees
1418 int64 nTxFee = nValueIn - GetValueOut();
1420 return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1422 if (!MoneyRange(nFees))
1423 return state.DoS(100, error("CheckInputs() : nFees out of range"));
1425 // The first loop above does all the inexpensive checks.
1426 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1427 // Helps prevent CPU exhaustion attacks.
1429 // Skip ECDSA signature verification when connecting blocks
1430 // before the last block chain checkpoint. This is safe because block merkle hashes are
1431 // still computed and checked, and any change will be caught at the next checkpoint.
1432 if (fScriptChecks) {
1433 for (unsigned int i = 0; i < vin.size(); i++) {
1434 const COutPoint &prevout = vin[i].prevout;
1435 const CCoins &coins = inputs.GetCoins(prevout.hash);
1438 CScriptCheck check(coins, *this, i, flags, 0);
1440 pvChecks->push_back(CScriptCheck());
1441 check.swap(pvChecks->back());
1442 } else if (!check())
1443 return state.DoS(100,false);
1454 bool CBlock::DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
1456 assert(pindex == view.GetBestBlock());
1463 CBlockUndo blockUndo;
1464 CDiskBlockPos pos = pindex->GetUndoPos();
1466 return error("DisconnectBlock() : no undo data available");
1467 if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
1468 return error("DisconnectBlock() : failure reading undo data");
1470 if (blockUndo.vtxundo.size() + 1 != vtx.size())
1471 return error("DisconnectBlock() : block and undo data inconsistent");
1473 // undo transactions in reverse order
1474 for (int i = vtx.size() - 1; i >= 0; i--) {
1475 const CTransaction &tx = vtx[i];
1476 uint256 hash = tx.GetHash();
1478 // check that all outputs are available
1479 if (!view.HaveCoins(hash)) {
1480 fClean = fClean && error("DisconnectBlock() : outputs still spent? database corrupted");
1481 view.SetCoins(hash, CCoins());
1483 CCoins &outs = view.GetCoins(hash);
1485 CCoins outsBlock = CCoins(tx, pindex->nHeight);
1486 if (outs != outsBlock)
1487 fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
1493 if (i > 0) { // not coinbases
1494 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1495 if (txundo.vprevout.size() != tx.vin.size())
1496 return error("DisconnectBlock() : transaction and undo data inconsistent");
1497 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1498 const COutPoint &out = tx.vin[j].prevout;
1499 const CTxInUndo &undo = txundo.vprevout[j];
1501 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1502 if (undo.nHeight != 0) {
1503 // undo data contains height: this is the last output of the prevout tx being spent
1504 if (!coins.IsPruned())
1505 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
1507 coins.fCoinBase = undo.fCoinBase;
1508 coins.nHeight = undo.nHeight;
1509 coins.nVersion = undo.nVersion;
1511 if (coins.IsPruned())
1512 fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
1514 if (coins.IsAvailable(out.n))
1515 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
1516 if (coins.vout.size() < out.n+1)
1517 coins.vout.resize(out.n+1);
1518 coins.vout[out.n] = undo.txout;
1519 if (!view.SetCoins(out.hash, coins))
1520 return error("DisconnectBlock() : cannot restore coin inputs");
1525 // move best block pointer to prevout block
1526 view.SetBestBlock(pindex->pprev);
1536 void static FlushBlockFile()
1538 LOCK(cs_LastBlockFile);
1540 CDiskBlockPos posOld(nLastBlockFile, 0);
1542 FILE *fileOld = OpenBlockFile(posOld);
1544 FileCommit(fileOld);
1548 fileOld = OpenUndoFile(posOld);
1550 FileCommit(fileOld);
1555 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1557 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1559 void ThreadScriptCheck(void*) {
1560 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1561 RenameThread("bitcoin-scriptch");
1562 scriptcheckqueue.Thread();
1563 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1566 void ThreadScriptCheckQuit() {
1567 scriptcheckqueue.Quit();
1570 bool CBlock::ConnectBlock(CValidationState &state, CBlockIndex* pindex, CCoinsViewCache &view, bool fJustCheck)
1572 // Check it again in case a previous version let a bad block in
1573 if (!CheckBlock(state, !fJustCheck, !fJustCheck))
1576 // verify that the view's current state corresponds to the previous block
1577 assert(pindex->pprev == view.GetBestBlock());
1579 // Special case for the genesis block, skipping connection of its transactions
1580 // (its coinbase is unspendable)
1581 if (GetHash() == hashGenesisBlock) {
1582 view.SetBestBlock(pindex);
1583 pindexGenesisBlock = pindex;
1587 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1589 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1590 // unless those are already completely spent.
1591 // If such overwrites are allowed, coinbases and transactions depending upon those
1592 // can be duplicated to remove the ability to spend the first instance -- even after
1593 // being sent to another address.
1594 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1595 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1596 // already refuses previously-known transaction ids entirely.
1597 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1598 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1599 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1600 // initial block download.
1601 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1602 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1603 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1604 if (fEnforceBIP30) {
1605 for (unsigned int i=0; i<vtx.size(); i++) {
1606 uint256 hash = GetTxHash(i);
1607 if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
1608 return error("ConnectBlock() : tried to overwrite transaction");
1612 // BIP16 didn't become active until Apr 1 2012
1613 int64 nBIP16SwitchTime = 1333238400;
1614 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1616 unsigned int flags = SCRIPT_VERIFY_NOCACHE |
1617 (fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE);
1619 CBlockUndo blockundo;
1621 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1623 int64 nStart = GetTimeMicros();
1626 unsigned int nSigOps = 0;
1627 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(vtx.size()));
1628 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1629 vPos.reserve(vtx.size());
1630 for (unsigned int i=0; i<vtx.size(); i++)
1633 const CTransaction &tx = vtx[i];
1635 nInputs += tx.vin.size();
1636 nSigOps += tx.GetLegacySigOpCount();
1637 if (nSigOps > MAX_BLOCK_SIGOPS)
1638 return state.DoS(100, error("ConnectBlock() : too many sigops"));
1640 if (!tx.IsCoinBase())
1642 if (!tx.HaveInputs(view))
1643 return state.DoS(100, error("ConnectBlock() : inputs missing/spent"));
1645 if (fStrictPayToScriptHash)
1647 // Add in sigops done by pay-to-script-hash inputs;
1648 // this is to prevent a "rogue miner" from creating
1649 // an incredibly-expensive-to-validate block.
1650 nSigOps += tx.GetP2SHSigOpCount(view);
1651 if (nSigOps > MAX_BLOCK_SIGOPS)
1652 return state.DoS(100, error("ConnectBlock() : too many sigops"));
1655 nFees += tx.GetValueIn(view)-tx.GetValueOut();
1657 std::vector<CScriptCheck> vChecks;
1658 if (!tx.CheckInputs(state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
1660 control.Add(vChecks);
1664 if (!tx.UpdateCoins(state, view, txundo, pindex->nHeight, GetTxHash(i)))
1665 return error("ConnectBlock() : UpdateInputs failed");
1666 if (!tx.IsCoinBase())
1667 blockundo.vtxundo.push_back(txundo);
1669 vPos.push_back(std::make_pair(GetTxHash(i), pos));
1670 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1672 int64 nTime = GetTimeMicros() - nStart;
1674 printf("- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (unsigned)vtx.size(), 0.001 * nTime, 0.001 * nTime / vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
1676 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1677 return state.DoS(100, error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)));
1679 if (!control.Wait())
1680 return state.DoS(100, false);
1681 int64 nTime2 = GetTimeMicros() - nStart;
1683 printf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
1688 // Write undo information to disk
1689 if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
1691 if (pindex->GetUndoPos().IsNull()) {
1693 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1694 return error("ConnectBlock() : FindUndoPos failed");
1695 if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
1696 return state.Abort(_("Failed to write undo data"));
1698 // update nUndoPos in block index
1699 pindex->nUndoPos = pos.nPos;
1700 pindex->nStatus |= BLOCK_HAVE_UNDO;
1703 pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
1705 CDiskBlockIndex blockindex(pindex);
1706 if (!pblocktree->WriteBlockIndex(blockindex))
1707 return state.Abort(_("Failed to write block index"));
1711 if (!pblocktree->WriteTxIndex(vPos))
1712 return state.Abort(_("Failed to write transaction index"));
1714 // add this block to the view's block chain
1715 assert(view.SetBestBlock(pindex));
1717 // Watch for transactions paying to me
1718 for (unsigned int i=0; i<vtx.size(); i++)
1719 SyncWithWallets(GetTxHash(i), vtx[i], this, true);
1724 bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
1726 // All modifications to the coin state will be done in this cache.
1727 // Only when all have succeeded, we push it to pcoinsTip.
1728 CCoinsViewCache view(*pcoinsTip, true);
1730 // Find the fork (typically, there is none)
1731 CBlockIndex* pfork = view.GetBestBlock();
1732 CBlockIndex* plonger = pindexNew;
1733 while (pfork && pfork != plonger)
1735 while (plonger->nHeight > pfork->nHeight) {
1736 plonger = plonger->pprev;
1737 assert(plonger != NULL);
1739 if (pfork == plonger)
1741 pfork = pfork->pprev;
1742 assert(pfork != NULL);
1745 // List of what to disconnect (typically nothing)
1746 vector<CBlockIndex*> vDisconnect;
1747 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1748 vDisconnect.push_back(pindex);
1750 // List of what to connect (typically only pindexNew)
1751 vector<CBlockIndex*> vConnect;
1752 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1753 vConnect.push_back(pindex);
1754 reverse(vConnect.begin(), vConnect.end());
1756 if (vDisconnect.size() > 0) {
1757 printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), BlockHashStr(pfork->GetBlockHash()).c_str(), BlockHashStr(pindexBest->GetBlockHash()).c_str());
1758 printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), BlockHashStr(pfork->GetBlockHash()).c_str(), BlockHashStr(pindexNew->GetBlockHash()).c_str());
1761 // Disconnect shorter branch
1762 vector<CTransaction> vResurrect;
1763 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
1765 if (!block.ReadFromDisk(pindex))
1766 return state.Abort(_("Failed to read block"));
1767 int64 nStart = GetTimeMicros();
1768 if (!block.DisconnectBlock(state, pindex, view))
1769 return error("SetBestBlock() : DisconnectBlock %s failed", BlockHashStr(pindex->GetBlockHash()).c_str());
1771 printf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1773 // Queue memory transactions to resurrect.
1774 // We only do this for blocks after the last checkpoint (reorganisation before that
1775 // point should only happen with -reindex/-loadblock, or a misbehaving peer.
1776 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1777 if (!tx.IsCoinBase() && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
1778 vResurrect.push_back(tx);
1781 // Connect longer branch
1782 vector<CTransaction> vDelete;
1783 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
1785 if (!block.ReadFromDisk(pindex))
1786 return state.Abort(_("Failed to read block"));
1787 int64 nStart = GetTimeMicros();
1788 if (!block.ConnectBlock(state, pindex, view)) {
1789 if (state.IsInvalid()) {
1790 InvalidChainFound(pindexNew);
1791 InvalidBlockFound(pindex);
1793 return error("SetBestBlock() : ConnectBlock %s failed", BlockHashStr(pindex->GetBlockHash()).c_str());
1796 printf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1798 // Queue memory transactions to delete
1799 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1800 vDelete.push_back(tx);
1803 // Flush changes to global coin state
1804 int64 nStart = GetTimeMicros();
1805 int nModified = view.GetCacheSize();
1806 assert(view.Flush());
1807 int64 nTime = GetTimeMicros() - nStart;
1809 printf("- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified);
1811 // Make sure it's successfully written to disk before changing memory structure
1812 bool fIsInitialDownload = IsInitialBlockDownload();
1813 if (!fIsInitialDownload || pcoinsTip->GetCacheSize() > nCoinCacheSize) {
1814 // Typical CCoins structures on disk are around 100 bytes in size.
1815 // Pushing a new one to the database can cause it to be written
1816 // twice (once in the log, and once in the tables). This is already
1817 // an overestimation, as most will delete an existing entry or
1818 // overwrite one. Still, use a conservative safety factor of 2.
1819 if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
1820 return state.Error();
1823 if (!pcoinsTip->Flush())
1824 return state.Abort(_("Failed to write to coin database"));
1827 // At this point, all changes have been done to the database.
1828 // Proceed by updating the memory structures.
1830 // Disconnect shorter branch
1831 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1833 pindex->pprev->pnext = NULL;
1835 // Connect longer branch
1836 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1838 pindex->pprev->pnext = pindex;
1840 // Resurrect memory transactions that were in the disconnected branch
1841 BOOST_FOREACH(CTransaction& tx, vResurrect) {
1842 // ignore validation errors in resurrected transactions
1843 CValidationState stateDummy;
1844 tx.AcceptToMemoryPool(stateDummy, true, false);
1847 // Delete redundant memory transactions that are in the connected branch
1848 BOOST_FOREACH(CTransaction& tx, vDelete) {
1850 mempool.removeConflicts(tx);
1853 // Update best block in wallet (so we can detect restored wallets)
1854 if (!fIsInitialDownload)
1856 const CBlockLocator locator(pindexNew);
1857 ::SetBestChain(locator);
1861 hashBestChain = pindexNew->GetBlockHash();
1862 pindexBest = pindexNew;
1863 pblockindexFBBHLast = NULL;
1864 nBestHeight = pindexBest->nHeight;
1865 bnBestChainWork = pindexNew->bnChainWork;
1866 nTimeBestReceived = GetTime();
1867 nTransactionsUpdated++;
1868 printf("SetBestChain: new best=%s height=%d work=%s tx=%lu date=%s\n",
1869 BlockHashStr(hashBestChain).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), (unsigned long)pindexNew->nChainTx,
1870 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1872 // Check the version of the last 100 blocks to see if we need to upgrade:
1873 if (!fIsInitialDownload)
1876 const CBlockIndex* pindex = pindexBest;
1877 for (int i = 0; i < 100 && pindex != NULL; i++)
1879 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1881 pindex = pindex->pprev;
1884 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1885 if (nUpgraded > 100/2)
1886 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1887 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1890 std::string strCmd = GetArg("-blocknotify", "");
1892 if (!fIsInitialDownload && !strCmd.empty())
1894 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1895 boost::thread t(runCommand, strCmd); // thread runs free
1902 bool CBlock::AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos)
1904 // Check for duplicate
1905 uint256 hash = GetHash();
1906 if (mapBlockIndex.count(hash))
1907 return state.Invalid(error("AddToBlockIndex() : %s already exists", BlockHashStr(hash).c_str()));
1909 // Construct new block index object
1910 CBlockIndex* pindexNew = new CBlockIndex(*this);
1912 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1913 pindexNew->phashBlock = &((*mi).first);
1914 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1915 if (miPrev != mapBlockIndex.end())
1917 pindexNew->pprev = (*miPrev).second;
1918 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1920 pindexNew->nTx = vtx.size();
1921 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1922 pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
1923 pindexNew->nFile = pos.nFile;
1924 pindexNew->nDataPos = pos.nPos;
1925 pindexNew->nUndoPos = 0;
1926 pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
1927 setBlockIndexValid.insert(pindexNew);
1929 if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew)))
1930 return state.Abort(_("Failed to write block index"));
1933 if (!ConnectBestBlock(state))
1936 if (pindexNew == pindexBest)
1938 // Notify UI to display prev block's coinbase if it was ours
1939 static uint256 hashPrevBestCoinBase;
1940 UpdatedTransaction(hashPrevBestCoinBase);
1941 hashPrevBestCoinBase = GetTxHash(0);
1944 if (!pblocktree->Flush())
1945 return state.Abort(_("Failed to sync block index"));
1947 uiInterface.NotifyBlocksChanged();
1952 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown = false)
1954 bool fUpdatedLast = false;
1956 LOCK(cs_LastBlockFile);
1959 if (nLastBlockFile != pos.nFile) {
1960 nLastBlockFile = pos.nFile;
1961 infoLastBlockFile.SetNull();
1962 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile);
1963 fUpdatedLast = true;
1966 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
1967 printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
1970 infoLastBlockFile.SetNull();
1971 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
1972 fUpdatedLast = true;
1974 pos.nFile = nLastBlockFile;
1975 pos.nPos = infoLastBlockFile.nSize;
1978 infoLastBlockFile.nSize += nAddSize;
1979 infoLastBlockFile.AddBlock(nHeight, nTime);
1982 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
1983 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
1984 if (nNewChunks > nOldChunks) {
1985 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
1986 FILE *file = OpenBlockFile(pos);
1988 printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
1989 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
1994 return state.Error();
1998 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
1999 return state.Abort(_("Failed to write file info"));
2001 pblocktree->WriteLastBlockFile(nLastBlockFile);
2006 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2010 LOCK(cs_LastBlockFile);
2012 unsigned int nNewSize;
2013 if (nFile == nLastBlockFile) {
2014 pos.nPos = infoLastBlockFile.nUndoSize;
2015 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2016 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2017 return state.Abort(_("Failed to write block info"));
2019 CBlockFileInfo info;
2020 if (!pblocktree->ReadBlockFileInfo(nFile, info))
2021 return state.Abort(_("Failed to read block info"));
2022 pos.nPos = info.nUndoSize;
2023 nNewSize = (info.nUndoSize += nAddSize);
2024 if (!pblocktree->WriteBlockFileInfo(nFile, info))
2025 return state.Abort(_("Failed to write block info"));
2028 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2029 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2030 if (nNewChunks > nOldChunks) {
2031 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2032 FILE *file = OpenUndoFile(pos);
2034 printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2035 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2040 return state.Error();
2047 bool CBlock::CheckBlock(CValidationState &state, bool fCheckPOW, bool fCheckMerkleRoot) const
2049 // These are checks that are independent of context
2050 // that can be verified before saving an orphan block.
2053 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2054 return state.DoS(100, error("CheckBlock() : size limits failed"));
2056 // Check proof of work matches claimed amount
2057 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2058 return state.DoS(50, error("CheckBlock() : proof of work failed"));
2061 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2062 return state.Invalid(error("CheckBlock() : block timestamp too far in the future"));
2064 // First transaction must be coinbase, the rest must not be
2065 if (vtx.empty() || !vtx[0].IsCoinBase())
2066 return state.DoS(100, error("CheckBlock() : first tx is not coinbase"));
2067 for (unsigned int i = 1; i < vtx.size(); i++)
2068 if (vtx[i].IsCoinBase())
2069 return state.DoS(100, error("CheckBlock() : more than one coinbase"));
2071 // Check transactions
2072 BOOST_FOREACH(const CTransaction& tx, vtx)
2073 if (!tx.CheckTransaction(state))
2074 return error("CheckBlock() : CheckTransaction failed");
2076 // Build the merkle tree already. We need it anyway later, and it makes the
2077 // block cache the transaction hashes, which means they don't need to be
2078 // recalculated many times during this block's validation.
2081 // Check for duplicate txids. This is caught by ConnectInputs(),
2082 // but catching it earlier avoids a potential DoS attack:
2083 set<uint256> uniqueTx;
2084 for (unsigned int i=0; i<vtx.size(); i++) {
2085 uniqueTx.insert(GetTxHash(i));
2087 if (uniqueTx.size() != vtx.size())
2088 return state.DoS(100, error("CheckBlock() : duplicate transaction"));
2090 unsigned int nSigOps = 0;
2091 BOOST_FOREACH(const CTransaction& tx, vtx)
2093 nSigOps += tx.GetLegacySigOpCount();
2095 if (nSigOps > MAX_BLOCK_SIGOPS)
2096 return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2098 // Check merkle root
2099 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2100 return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2105 bool CBlock::AcceptBlock(CValidationState &state, CDiskBlockPos *dbp)
2107 // Check for duplicate
2108 uint256 hash = GetHash();
2109 if (mapBlockIndex.count(hash))
2110 return state.Invalid(error("AcceptBlock() : block already in mapBlockIndex"));
2112 // Get prev block index
2113 CBlockIndex* pindexPrev = NULL;
2115 if (hash != hashGenesisBlock) {
2116 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2117 if (mi == mapBlockIndex.end())
2118 return state.DoS(10, error("AcceptBlock() : prev block not found"));
2119 pindexPrev = (*mi).second;
2120 nHeight = pindexPrev->nHeight+1;
2122 // Check proof of work
2123 if (nBits != GetNextWorkRequired(pindexPrev, this))
2124 return state.DoS(100, error("AcceptBlock() : incorrect proof of work"));
2126 // Check timestamp against prev
2127 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
2128 return state.Invalid(error("AcceptBlock() : block's timestamp is too early"));
2130 // Check that all transactions are finalized
2131 BOOST_FOREACH(const CTransaction& tx, vtx)
2132 if (!tx.IsFinal(nHeight, GetBlockTime()))
2133 return state.DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2135 // Check that the block chain matches the known block chain up to a checkpoint
2136 if (!Checkpoints::CheckBlock(nHeight, hash))
2137 return state.DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
2139 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2142 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
2143 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
2145 return state.Invalid(error("AcceptBlock() : rejected nVersion=1 block"));
2148 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2151 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2152 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
2153 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
2155 CScript expect = CScript() << nHeight;
2156 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2157 return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2162 // Write block to history file
2164 unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
2165 CDiskBlockPos blockPos;
2168 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, nTime, dbp != NULL))
2169 return error("AcceptBlock() : FindBlockPos failed");
2171 if (!WriteToDisk(blockPos))
2172 return state.Abort(_("Failed to write block"));
2173 if (!AddToBlockIndex(state, blockPos))
2174 return error("AcceptBlock() : AddToBlockIndex failed");
2175 } catch(std::runtime_error &e) {
2176 return state.Abort(_("System error: ") + e.what());
2179 // Relay inventory, but don't relay old inventory during initial block download
2180 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2181 if (hashBestChain == hash)
2184 BOOST_FOREACH(CNode* pnode, vNodes)
2185 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2186 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2192 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2194 unsigned int nFound = 0;
2195 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2197 if (pstart->nVersion >= minVersion)
2199 pstart = pstart->pprev;
2201 return (nFound >= nRequired);
2204 bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2206 // Check for duplicate
2207 uint256 hash = pblock->GetHash();
2208 if (mapBlockIndex.count(hash))
2209 return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, BlockHashStr(hash).c_str()));
2210 if (mapOrphanBlocks.count(hash))
2211 return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", BlockHashStr(hash).c_str()));
2213 // Preliminary checks
2214 if (!pblock->CheckBlock(state))
2215 return error("ProcessBlock() : CheckBlock FAILED");
2217 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
2218 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
2220 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2221 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2224 return state.DoS(100, error("ProcessBlock() : block with timestamp before last checkpoint"));
2227 bnNewBlock.SetCompact(pblock->nBits);
2229 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
2230 if (bnNewBlock > bnRequired)
2232 return state.DoS(100, error("ProcessBlock() : block with too little proof-of-work"));
2237 // If we don't already have its previous block, shunt it off to holding area until we get it
2238 if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
2240 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", BlockHashStr(pblock->hashPrevBlock).c_str());
2242 // Accept orphans as long as there is a node to request its parents from
2244 CBlock* pblock2 = new CBlock(*pblock);
2245 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2246 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2248 // Ask this guy to fill in what we're missing
2249 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2255 if (!pblock->AcceptBlock(state, dbp))
2256 return error("ProcessBlock() : AcceptBlock FAILED");
2258 // Recursively process any orphan blocks that depended on this one
2259 vector<uint256> vWorkQueue;
2260 vWorkQueue.push_back(hash);
2261 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2263 uint256 hashPrev = vWorkQueue[i];
2264 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2265 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2268 CBlock* pblockOrphan = (*mi).second;
2269 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan resolution (that is, feeding people an invalid block based on LegitBlockX in order to get anyone relaying LegitBlockX banned)
2270 CValidationState stateDummy;
2271 if (pblockOrphan->AcceptBlock(stateDummy))
2272 vWorkQueue.push_back(pblockOrphan->GetHash());
2273 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2274 delete pblockOrphan;
2276 mapOrphanBlocksByPrev.erase(hashPrev);
2279 printf("ProcessBlock: ACCEPTED\n");
2290 CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
2292 header = block.GetBlockHeader();
2294 vector<bool> vMatch;
2295 vector<uint256> vHashes;
2297 vMatch.reserve(block.vtx.size());
2298 vHashes.reserve(block.vtx.size());
2300 for (unsigned int i = 0; i < block.vtx.size(); i++)
2302 uint256 hash = block.vtx[i].GetHash();
2303 if (filter.IsRelevantAndUpdate(block.vtx[i], hash))
2305 vMatch.push_back(true);
2306 vMatchedTxn.push_back(make_pair(i, hash));
2309 vMatch.push_back(false);
2310 vHashes.push_back(hash);
2313 txn = CPartialMerkleTree(vHashes, vMatch);
2323 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
2325 // hash at height 0 is the txids themself
2328 // calculate left hash
2329 uint256 left = CalcHash(height-1, pos*2, vTxid), right;
2330 // calculate right hash if not beyong the end of the array - copy left hash otherwise1
2331 if (pos*2+1 < CalcTreeWidth(height-1))
2332 right = CalcHash(height-1, pos*2+1, vTxid);
2335 // combine subhashes
2336 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2340 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
2341 // determine whether this node is the parent of at least one matched txid
2342 bool fParentOfMatch = false;
2343 for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
2344 fParentOfMatch |= vMatch[p];
2345 // store as flag bit
2346 vBits.push_back(fParentOfMatch);
2347 if (height==0 || !fParentOfMatch) {
2348 // if at height 0, or nothing interesting below, store hash and stop
2349 vHash.push_back(CalcHash(height, pos, vTxid));
2351 // otherwise, don't store any hash, but descend into the subtrees
2352 TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
2353 if (pos*2+1 < CalcTreeWidth(height-1))
2354 TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
2358 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
2359 if (nBitsUsed >= vBits.size()) {
2360 // overflowed the bits array - failure
2364 bool fParentOfMatch = vBits[nBitsUsed++];
2365 if (height==0 || !fParentOfMatch) {
2366 // if at height 0, or nothing interesting below, use stored hash and do not descend
2367 if (nHashUsed >= vHash.size()) {
2368 // overflowed the hash array - failure
2372 const uint256 &hash = vHash[nHashUsed++];
2373 if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
2374 vMatch.push_back(hash);
2377 // otherwise, descend into the subtrees to extract matched txids and hashes
2378 uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
2379 if (pos*2+1 < CalcTreeWidth(height-1))
2380 right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
2383 // and combine them before returning
2384 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2388 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
2393 // calculate height of tree
2395 while (CalcTreeWidth(nHeight) > 1)
2398 // traverse the partial tree
2399 TraverseAndBuild(nHeight, 0, vTxid, vMatch);
2402 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
2404 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
2406 // An empty set will not work
2407 if (nTransactions == 0)
2409 // check for excessively high numbers of transactions
2410 if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
2412 // there can never be more hashes provided than one for every txid
2413 if (vHash.size() > nTransactions)
2415 // there must be at least one bit per node in the partial tree, and at least one node per hash
2416 if (vBits.size() < vHash.size())
2418 // calculate height of tree
2420 while (CalcTreeWidth(nHeight) > 1)
2422 // traverse the partial tree
2423 unsigned int nBitsUsed = 0, nHashUsed = 0;
2424 uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
2425 // verify that no problems occured during the tree traversal
2428 // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
2429 if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
2431 // verify that all hashes were consumed
2432 if (nHashUsed != vHash.size())
2434 return hashMerkleRoot;
2443 bool AbortNode(const std::string &strMessage) {
2444 fRequestShutdown = true;
2445 strMiscWarning = strMessage;
2446 printf("*** %s\n", strMessage.c_str());
2447 uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR | CClientUIInterface::MODAL);
2452 bool CheckDiskSpace(uint64 nAdditionalBytes)
2454 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2456 // Check for nMinDiskSpace bytes (currently 50MB)
2457 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2458 return AbortNode(_("Error: Disk space is low!"));
2463 CCriticalSection cs_LastBlockFile;
2464 CBlockFileInfo infoLastBlockFile;
2465 int nLastBlockFile = 0;
2467 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2471 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2472 boost::filesystem::create_directories(path.parent_path());
2473 FILE* file = fopen(path.string().c_str(), "rb+");
2474 if (!file && !fReadOnly)
2475 file = fopen(path.string().c_str(), "wb+");
2477 printf("Unable to open file %s\n", path.string().c_str());
2481 if (fseek(file, pos.nPos, SEEK_SET)) {
2482 printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2490 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2491 return OpenDiskFile(pos, "blk", fReadOnly);
2494 FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2495 return OpenDiskFile(pos, "rev", fReadOnly);
2498 CBlockIndex * InsertBlockIndex(uint256 hash)
2504 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2505 if (mi != mapBlockIndex.end())
2506 return (*mi).second;
2509 CBlockIndex* pindexNew = new CBlockIndex();
2511 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
2512 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2513 pindexNew->phashBlock = &((*mi).first);
2518 bool static LoadBlockIndexDB()
2520 if (!pblocktree->LoadBlockIndexGuts())
2523 if (fRequestShutdown)
2526 // Calculate bnChainWork
2527 vector<pair<int, CBlockIndex*> > vSortedByHeight;
2528 vSortedByHeight.reserve(mapBlockIndex.size());
2529 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2531 CBlockIndex* pindex = item.second;
2532 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2534 sort(vSortedByHeight.begin(), vSortedByHeight.end());
2535 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2537 CBlockIndex* pindex = item.second;
2538 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
2539 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2540 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
2541 setBlockIndexValid.insert(pindex);
2544 // Load block file info
2545 pblocktree->ReadLastBlockFile(nLastBlockFile);
2546 printf("LoadBlockIndex(): last block file = %i\n", nLastBlockFile);
2547 if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2548 printf("LoadBlockIndex(): last block file: %s\n", infoLastBlockFile.ToString().c_str());
2550 // Load bnBestInvalidWork, OK if it doesn't exist
2551 pblocktree->ReadBestInvalidWork(bnBestInvalidWork);
2553 // Check whether we need to continue reindexing
2554 bool fReindexing = false;
2555 pblocktree->ReadReindexing(fReindexing);
2556 fReindex |= fReindexing;
2558 // Check whether we have a transaction index
2559 pblocktree->ReadFlag("txindex", fTxIndex);
2560 printf("LoadBlockIndex(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
2562 // Load hashBestChain pointer to end of best chain
2563 pindexBest = pcoinsTip->GetBestBlock();
2564 if (pindexBest == NULL)
2566 hashBestChain = pindexBest->GetBlockHash();
2567 nBestHeight = pindexBest->nHeight;
2568 bnBestChainWork = pindexBest->bnChainWork;
2570 // set 'next' pointers in best chain
2571 CBlockIndex *pindex = pindexBest;
2572 while(pindex != NULL && pindex->pprev != NULL) {
2573 CBlockIndex *pindexPrev = pindex->pprev;
2574 pindexPrev->pnext = pindex;
2575 pindex = pindexPrev;
2577 printf("LoadBlockIndex(): hashBestChain=%s height=%d date=%s\n",
2578 BlockHashStr(hashBestChain).c_str(), nBestHeight,
2579 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2585 if (pindexBest == NULL || pindexBest->pprev == NULL)
2588 // Verify blocks in the best chain
2589 int nCheckLevel = GetArg("-checklevel", 3);
2590 int nCheckDepth = GetArg( "-checkblocks", 288);
2591 if (nCheckDepth == 0)
2592 nCheckDepth = 1000000000; // suffices until the year 19000
2593 if (nCheckDepth > nBestHeight)
2594 nCheckDepth = nBestHeight;
2595 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2596 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2597 CCoinsViewCache coins(*pcoinsTip, true);
2598 CBlockIndex* pindexState = pindexBest;
2599 CBlockIndex* pindexFailure = NULL;
2600 int nGoodTransactions = 0;
2601 CValidationState state;
2602 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
2604 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
2607 // check level 0: read from disk
2608 if (!block.ReadFromDisk(pindex))
2609 return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2610 // check level 1: verify block validity
2611 if (nCheckLevel >= 1 && !block.CheckBlock(state))
2612 return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2613 // check level 2: verify undo validity
2614 if (nCheckLevel >= 2 && pindex) {
2616 CDiskBlockPos pos = pindex->GetUndoPos();
2617 if (!pos.IsNull()) {
2618 if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
2619 return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2622 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
2623 if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
2625 if (!block.DisconnectBlock(state, pindex, coins, &fClean))
2626 return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2627 pindexState = pindex->pprev;
2629 nGoodTransactions = 0;
2630 pindexFailure = pindex;
2632 nGoodTransactions += block.vtx.size();
2636 return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", pindexBest->nHeight - pindexFailure->nHeight + 1, nGoodTransactions);
2638 // check level 4: try reconnecting blocks
2639 if (nCheckLevel >= 4) {
2640 CBlockIndex *pindex = pindexState;
2641 while (pindex != pindexBest && !fRequestShutdown) {
2642 pindex = pindex->pnext;
2644 if (!block.ReadFromDisk(pindex))
2645 return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2646 if (!block.ConnectBlock(state, pindex, coins))
2647 return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2651 printf("No coin database inconsistencies in last %i blocks (%i transactions)\n", pindexBest->nHeight - pindexState->nHeight, nGoodTransactions);
2656 bool LoadBlockIndex()
2660 pchMessageStart[0] = 0x0b;
2661 pchMessageStart[1] = 0x11;
2662 pchMessageStart[2] = 0x09;
2663 pchMessageStart[3] = 0x07;
2664 hashGenesisBlock = uint256("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943");
2668 // Load block index from databases
2670 if (!fReindex && !LoadBlockIndexDB())
2677 bool InitBlockIndex() {
2678 // Check whether we're already initialized
2679 if (pindexGenesisBlock != NULL)
2682 // Use the provided setting for -txindex in the new database
2683 fTxIndex = GetBoolArg("-txindex", false);
2684 pblocktree->WriteFlag("txindex", fTxIndex);
2685 printf("Initializing databases...\n");
2687 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
2690 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
2691 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2692 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
2693 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
2694 // vMerkleTree: 4a5e1e
2697 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
2699 txNew.vin.resize(1);
2700 txNew.vout.resize(1);
2701 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2702 txNew.vout[0].nValue = 50 * COIN;
2703 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
2705 block.vtx.push_back(txNew);
2706 block.hashPrevBlock = 0;
2707 block.hashMerkleRoot = block.BuildMerkleTree();
2709 block.nTime = 1231006505;
2710 block.nBits = 0x1d00ffff;
2711 block.nNonce = 2083236893;
2715 block.nTime = 1296688602;
2716 block.nNonce = 414098458;
2720 uint256 hash = block.GetHash();
2721 printf("%s\n", hash.ToString().c_str());
2722 printf("%s\n", hashGenesisBlock.ToString().c_str());
2723 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
2724 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
2726 assert(hash == hashGenesisBlock);
2728 // Start new block file
2730 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2731 CDiskBlockPos blockPos;
2732 CValidationState state;
2733 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.nTime))
2734 return error("AcceptBlock() : FindBlockPos failed");
2735 if (!block.WriteToDisk(blockPos))
2736 return error("LoadBlockIndex() : writing genesis block to disk failed");
2737 if (!block.AddToBlockIndex(state, blockPos))
2738 return error("LoadBlockIndex() : genesis block not accepted");
2739 } catch(std::runtime_error &e) {
2740 return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
2749 void PrintBlockTree()
2751 // pre-compute tree structure
2752 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2753 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2755 CBlockIndex* pindex = (*mi).second;
2756 mapNext[pindex->pprev].push_back(pindex);
2758 //while (rand() % 3 == 0)
2759 // mapNext[pindex->pprev].push_back(pindex);
2762 vector<pair<int, CBlockIndex*> > vStack;
2763 vStack.push_back(make_pair(0, pindexGenesisBlock));
2766 while (!vStack.empty())
2768 int nCol = vStack.back().first;
2769 CBlockIndex* pindex = vStack.back().second;
2772 // print split or gap
2773 if (nCol > nPrevCol)
2775 for (int i = 0; i < nCol-1; i++)
2779 else if (nCol < nPrevCol)
2781 for (int i = 0; i < nCol; i++)
2788 for (int i = 0; i < nCol; i++)
2793 block.ReadFromDisk(pindex);
2794 printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
2796 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2797 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
2800 PrintWallets(block);
2802 // put the main time-chain first
2803 vector<CBlockIndex*>& vNext = mapNext[pindex];
2804 for (unsigned int i = 0; i < vNext.size(); i++)
2806 if (vNext[i]->pnext)
2808 swap(vNext[0], vNext[i]);
2814 for (unsigned int i = 0; i < vNext.size(); i++)
2815 vStack.push_back(make_pair(nCol+i, vNext[i]));
2819 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
2821 int64 nStart = GetTimeMillis();
2825 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
2826 uint64 nStartByte = 0;
2828 // (try to) skip already indexed part
2829 CBlockFileInfo info;
2830 if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) {
2831 nStartByte = info.nSize;
2832 blkdat.Seek(info.nSize);
2835 uint64 nRewind = blkdat.GetPos();
2836 while (blkdat.good() && !blkdat.eof() && !fRequestShutdown) {
2837 blkdat.SetPos(nRewind);
2838 nRewind++; // start one byte further next time, in case of failure
2839 blkdat.SetLimit(); // remove former limit
2840 unsigned int nSize = 0;
2843 unsigned char buf[4];
2844 blkdat.FindByte(pchMessageStart[0]);
2845 nRewind = blkdat.GetPos()+1;
2846 blkdat >> FLATDATA(buf);
2847 if (memcmp(buf, pchMessageStart, 4))
2851 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
2853 } catch (std::exception &e) {
2854 // no valid block header found; don't complain
2859 uint64 nBlockPos = blkdat.GetPos();
2860 blkdat.SetLimit(nBlockPos + nSize);
2863 nRewind = blkdat.GetPos();
2866 if (nBlockPos >= nStartByte) {
2869 dbp->nPos = nBlockPos;
2870 CValidationState state;
2871 if (ProcessBlock(state, NULL, &block, dbp))
2873 if (state.IsError())
2876 } catch (std::exception &e) {
2877 printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__);
2881 } catch(std::runtime_error &e) {
2882 AbortNode(_("Error: system error: ") + e.what());
2885 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2898 //////////////////////////////////////////////////////////////////////////////
2903 extern map<uint256, CAlert> mapAlerts;
2904 extern CCriticalSection cs_mapAlerts;
2906 string GetWarnings(string strFor)
2909 string strStatusBar;
2912 if (GetBoolArg("-testsafemode"))
2915 if (!CLIENT_VERSION_IS_RELEASE)
2916 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
2918 // Misc warnings like out of disk space and clock is wrong
2919 if (strMiscWarning != "")
2922 strStatusBar = strMiscWarning;
2925 // Longer invalid proof-of-work chain
2926 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2929 strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");
2935 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2937 const CAlert& alert = item.second;
2938 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2940 nPriority = alert.nPriority;
2941 strStatusBar = alert.strStatusBar;
2946 if (strFor == "statusbar")
2947 return strStatusBar;
2948 else if (strFor == "rpc")
2950 assert(!"GetWarnings() : invalid parameter");
2961 //////////////////////////////////////////////////////////////////////////////
2967 bool static AlreadyHave(const CInv& inv)
2973 bool txInMap = false;
2976 txInMap = mempool.exists(inv.hash);
2978 return txInMap || mapOrphanTransactions.count(inv.hash) ||
2979 pcoinsTip->HaveCoins(inv.hash);
2982 return mapBlockIndex.count(inv.hash) ||
2983 mapOrphanBlocks.count(inv.hash);
2985 // Don't know what it is, just say we already got one
2992 // The message start string is designed to be unlikely to occur in normal data.
2993 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
2994 // a large 4-byte int at any alignment.
2995 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2998 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3000 RandAddSeedPerfmon();
3002 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3003 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3005 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3013 if (strCommand == "version")
3015 // Each connection can only send one version message
3016 if (pfrom->nVersion != 0)
3018 pfrom->Misbehaving(1);
3026 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3027 if (pfrom->nVersion < MIN_PROTO_VERSION)
3029 // Since February 20, 2012, the protocol is initiated at version 209,
3030 // and earlier versions are no longer supported
3031 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3032 pfrom->fDisconnect = true;
3036 if (pfrom->nVersion == 10300)
3037 pfrom->nVersion = 300;
3039 vRecv >> addrFrom >> nNonce;
3041 vRecv >> pfrom->strSubVer;
3043 vRecv >> pfrom->nStartingHeight;
3045 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3047 pfrom->fRelayTxes = true;
3049 if (pfrom->fInbound && addrMe.IsRoutable())
3051 pfrom->addrLocal = addrMe;
3055 // Disconnect if we connected to ourself
3056 if (nNonce == nLocalHostNonce && nNonce > 1)
3058 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3059 pfrom->fDisconnect = true;
3063 // Be shy and don't send version until we hear
3064 if (pfrom->fInbound)
3065 pfrom->PushVersion();
3067 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3069 AddTimeData(pfrom->addr, nTime);
3072 pfrom->PushMessage("verack");
3073 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3075 if (!pfrom->fInbound)
3077 // Advertise our address
3078 if (!fNoListen && !IsInitialBlockDownload())
3080 CAddress addr = GetLocalAddress(&pfrom->addr);
3081 if (addr.IsRoutable())
3082 pfrom->PushAddress(addr);
3085 // Get recent addresses
3086 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3088 pfrom->PushMessage("getaddr");
3089 pfrom->fGetAddr = true;
3091 addrman.Good(pfrom->addr);
3093 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3095 addrman.Add(addrFrom, addrFrom);
3096 addrman.Good(addrFrom);
3100 // Ask the first connected node for block updates
3101 static int nAskedForBlocks = 0;
3102 if (!pfrom->fClient && !pfrom->fOneShot && !fImporting && !fReindex &&
3103 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3104 (pfrom->nVersion < NOBLKS_VERSION_START ||
3105 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3106 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3109 pfrom->PushGetBlocks(pindexBest, uint256(0));
3115 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3116 item.second.RelayTo(pfrom);
3119 pfrom->fSuccessfullyConnected = true;
3121 printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
3123 cPeerBlockCounts.input(pfrom->nStartingHeight);
3127 else if (pfrom->nVersion == 0)
3129 // Must have a version message before anything else
3130 pfrom->Misbehaving(1);
3135 else if (strCommand == "verack")
3137 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3141 else if (strCommand == "addr")
3143 vector<CAddress> vAddr;
3146 // Don't want addr from older versions unless seeding
3147 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3149 if (vAddr.size() > 1000)
3151 pfrom->Misbehaving(20);
3152 return error("message addr size() = %"PRIszu"", vAddr.size());
3155 // Store the new addresses
3156 vector<CAddress> vAddrOk;
3157 int64 nNow = GetAdjustedTime();
3158 int64 nSince = nNow - 10 * 60;
3159 BOOST_FOREACH(CAddress& addr, vAddr)
3163 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3164 addr.nTime = nNow - 5 * 24 * 60 * 60;
3165 pfrom->AddAddressKnown(addr);
3166 bool fReachable = IsReachable(addr);
3167 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3169 // Relay to a limited number of other nodes
3172 // Use deterministic randomness to send to the same nodes for 24 hours
3173 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3174 static uint256 hashSalt;
3176 hashSalt = GetRandHash();
3177 uint64 hashAddr = addr.GetHash();
3178 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3179 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3180 multimap<uint256, CNode*> mapMix;
3181 BOOST_FOREACH(CNode* pnode, vNodes)
3183 if (pnode->nVersion < CADDR_TIME_VERSION)
3185 unsigned int nPointer;
3186 memcpy(&nPointer, &pnode, sizeof(nPointer));
3187 uint256 hashKey = hashRand ^ nPointer;
3188 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3189 mapMix.insert(make_pair(hashKey, pnode));
3191 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3192 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3193 ((*mi).second)->PushAddress(addr);
3196 // Do not store addresses outside our network
3198 vAddrOk.push_back(addr);
3200 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3201 if (vAddr.size() < 1000)
3202 pfrom->fGetAddr = false;
3203 if (pfrom->fOneShot)
3204 pfrom->fDisconnect = true;
3208 else if (strCommand == "inv")
3212 if (vInv.size() > MAX_INV_SZ)
3214 pfrom->Misbehaving(20);
3215 return error("message inv size() = %"PRIszu"", vInv.size());
3218 // find last block in inv vector
3219 unsigned int nLastBlock = (unsigned int)(-1);
3220 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3221 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3222 nLastBlock = vInv.size() - 1 - nInv;
3226 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3228 const CInv &inv = vInv[nInv];
3232 pfrom->AddInventoryKnown(inv);
3234 bool fAlreadyHave = AlreadyHave(inv);
3236 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3238 if (!fAlreadyHave) {
3239 if (!fImporting && !fReindex)
3241 } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3242 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3243 } else if (nInv == nLastBlock) {
3244 // In case we are on a very long side-chain, it is possible that we already have
3245 // the last block in an inv bundle sent in response to getblocks. Try to detect
3246 // this situation and push another getblocks to continue.
3247 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3249 printf("force request: %s\n", inv.ToString().c_str());
3252 // Track requests for our stuff
3253 Inventory(inv.hash);
3258 else if (strCommand == "getdata")
3262 if (vInv.size() > MAX_INV_SZ)
3264 pfrom->Misbehaving(20);
3265 return error("message getdata size() = %"PRIszu"", vInv.size());
3268 if (fDebugNet || (vInv.size() != 1))
3269 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3271 vector<CInv> vNotFound;
3272 BOOST_FOREACH(const CInv& inv, vInv)
3276 if (fDebugNet || (vInv.size() == 1))
3277 printf("received getdata for: %s\n", inv.ToString().c_str());
3279 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3281 // Send block from disk
3282 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3283 if (mi != mapBlockIndex.end())
3286 block.ReadFromDisk((*mi).second);
3287 if (inv.type == MSG_BLOCK)
3288 pfrom->PushMessage("block", block);
3289 else // MSG_FILTERED_BLOCK)
3291 LOCK(pfrom->cs_filter);
3294 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3295 pfrom->PushMessage("merkleblock", merkleBlock);
3296 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3297 // This avoids hurting performance by pointlessly requiring a round-trip
3298 // Note that there is currently no way for a node to request any single transactions we didnt send here -
3299 // they must either disconnect and retry or request the full block.
3300 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3301 // however we MUST always provide at least what the remote peer needs
3302 typedef std::pair<unsigned int, uint256> PairType;
3303 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3304 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3305 pfrom->PushMessage("tx", block.vtx[pair.first]);
3311 // Trigger them to send a getblocks request for the next batch of inventory
3312 if (inv.hash == pfrom->hashContinue)
3314 // Bypass PushInventory, this must send even if redundant,
3315 // and we want it right after the last block so they don't
3316 // wait for other stuff first.
3318 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
3319 pfrom->PushMessage("inv", vInv);
3320 pfrom->hashContinue = 0;
3324 else if (inv.IsKnownType())
3326 // Send stream from relay memory
3327 bool pushed = false;
3330 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3331 if (mi != mapRelay.end()) {
3332 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3336 if (!pushed && inv.type == MSG_TX) {
3338 if (mempool.exists(inv.hash)) {
3339 CTransaction tx = mempool.lookup(inv.hash);
3340 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3343 pfrom->PushMessage("tx", ss);
3348 vNotFound.push_back(inv);
3352 // Track requests for our stuff.
3353 Inventory(inv.hash);
3355 if (!vNotFound.empty()) {
3356 // Let the peer know that we didn't find what it asked for, so it doesn't
3357 // have to wait around forever. Currently only SPV clients actually care
3358 // about this message: it's needed when they are recursively walking the
3359 // dependencies of relevant unconfirmed transactions. SPV clients want to
3360 // do that because they want to know about (and store and rebroadcast and
3361 // risk analyze) the dependencies of transactions relevant to them, without
3362 // having to download the entire memory pool.
3363 pfrom->PushMessage("notfound", vNotFound);
3369 else if (strCommand == "getblocks")
3371 CBlockLocator locator;
3373 vRecv >> locator >> hashStop;
3375 // Find the last block the caller has in the main chain
3376 CBlockIndex* pindex = locator.GetBlockIndex();
3378 // Send the rest of the chain
3380 pindex = pindex->pnext;
3382 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), BlockHashStr(hashStop).c_str(), nLimit);
3383 for (; pindex; pindex = pindex->pnext)
3385 if (pindex->GetBlockHash() == hashStop)
3387 printf(" getblocks stopping at %d %s\n", pindex->nHeight, BlockHashStr(pindex->GetBlockHash()).c_str());
3390 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3393 // When this block is requested, we'll send an inv that'll make them
3394 // getblocks the next batch of inventory.
3395 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, BlockHashStr(pindex->GetBlockHash()).c_str());
3396 pfrom->hashContinue = pindex->GetBlockHash();
3403 else if (strCommand == "getheaders")
3405 CBlockLocator locator;
3407 vRecv >> locator >> hashStop;
3409 CBlockIndex* pindex = NULL;
3410 if (locator.IsNull())
3412 // If locator is null, return the hashStop block
3413 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3414 if (mi == mapBlockIndex.end())
3416 pindex = (*mi).second;
3420 // Find the last block the caller has in the main chain
3421 pindex = locator.GetBlockIndex();
3423 pindex = pindex->pnext;
3426 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3427 vector<CBlock> vHeaders;
3429 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), BlockHashStr(hashStop).c_str());
3430 for (; pindex; pindex = pindex->pnext)
3432 vHeaders.push_back(pindex->GetBlockHeader());
3433 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3436 pfrom->PushMessage("headers", vHeaders);
3440 else if (strCommand == "tx")
3442 vector<uint256> vWorkQueue;
3443 vector<uint256> vEraseQueue;
3444 CDataStream vMsg(vRecv);
3448 CInv inv(MSG_TX, tx.GetHash());
3449 pfrom->AddInventoryKnown(inv);
3451 bool fMissingInputs = false;
3452 CValidationState state;
3453 if (tx.AcceptToMemoryPool(state, true, true, &fMissingInputs))
3455 RelayTransaction(tx, inv.hash, vMsg);
3456 mapAlreadyAskedFor.erase(inv);
3457 vWorkQueue.push_back(inv.hash);
3458 vEraseQueue.push_back(inv.hash);
3460 // Recursively process any orphan transactions that depended on this one
3461 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3463 uint256 hashPrev = vWorkQueue[i];
3464 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3465 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3468 const CDataStream& vMsg = *((*mi).second);
3470 CDataStream(vMsg) >> tx;
3471 CInv inv(MSG_TX, tx.GetHash());
3472 bool fMissingInputs2 = false;
3473 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get anyone relaying LegitTxX banned)
3474 CValidationState stateDummy;
3476 if (tx.AcceptToMemoryPool(stateDummy, true, true, &fMissingInputs2))
3478 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3479 RelayTransaction(tx, inv.hash, vMsg);
3480 mapAlreadyAskedFor.erase(inv);
3481 vWorkQueue.push_back(inv.hash);
3482 vEraseQueue.push_back(inv.hash);
3484 else if (!fMissingInputs2)
3486 // invalid or too-little-fee orphan
3487 vEraseQueue.push_back(inv.hash);
3488 printf(" removed orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3493 BOOST_FOREACH(uint256 hash, vEraseQueue)
3494 EraseOrphanTx(hash);
3496 else if (fMissingInputs)
3500 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3501 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3503 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3506 if (state.IsInvalid(nDoS))
3507 pfrom->Misbehaving(nDoS);
3511 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
3516 printf("received block %s\n", BlockHashStr(block.GetHash()).c_str());
3519 CInv inv(MSG_BLOCK, block.GetHash());
3520 pfrom->AddInventoryKnown(inv);
3522 CValidationState state;
3523 if (ProcessBlock(state, pfrom, &block))
3524 mapAlreadyAskedFor.erase(inv);
3526 if (state.IsInvalid(nDoS))
3527 pfrom->Misbehaving(nDoS);
3531 else if (strCommand == "getaddr")
3533 pfrom->vAddrToSend.clear();
3534 vector<CAddress> vAddr = addrman.GetAddr();
3535 BOOST_FOREACH(const CAddress &addr, vAddr)
3536 pfrom->PushAddress(addr);
3540 else if (strCommand == "mempool")
3542 std::vector<uint256> vtxid;
3543 LOCK2(mempool.cs, pfrom->cs_filter);
3544 mempool.queryHashes(vtxid);
3546 BOOST_FOREACH(uint256& hash, vtxid) {
3547 CInv inv(MSG_TX, hash);
3548 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(mempool.lookup(hash), hash)) ||
3550 vInv.push_back(inv);
3551 if (vInv.size() == MAX_INV_SZ)
3554 if (vInv.size() > 0)
3555 pfrom->PushMessage("inv", vInv);
3559 else if (strCommand == "ping")
3561 if (pfrom->nVersion > BIP0031_VERSION)
3565 // Echo the message back with the nonce. This allows for two useful features:
3567 // 1) A remote node can quickly check if the connection is operational
3568 // 2) Remote nodes can measure the latency of the network thread. If this node
3569 // is overloaded it won't respond to pings quickly and the remote node can
3570 // avoid sending us more work, like chain download requests.
3572 // The nonce stops the remote getting confused between different pings: without
3573 // it, if the remote node sends a ping once per second and this node takes 5
3574 // seconds to respond to each, the 5th ping the remote sends would appear to
3575 // return very quickly.
3576 pfrom->PushMessage("pong", nonce);
3581 else if (strCommand == "alert")
3586 uint256 alertHash = alert.GetHash();
3587 if (pfrom->setKnown.count(alertHash) == 0)
3589 if (alert.ProcessAlert())
3592 pfrom->setKnown.insert(alertHash);
3595 BOOST_FOREACH(CNode* pnode, vNodes)
3596 alert.RelayTo(pnode);
3600 // Small DoS penalty so peers that send us lots of
3601 // duplicate/expired/invalid-signature/whatever alerts
3602 // eventually get banned.
3603 // This isn't a Misbehaving(100) (immediate ban) because the
3604 // peer might be an older or different implementation with
3605 // a different signature key, etc.
3606 pfrom->Misbehaving(10);
3612 else if (strCommand == "filterload")
3614 CBloomFilter filter;
3617 if (!filter.IsWithinSizeConstraints())
3618 // There is no excuse for sending a too-large filter
3619 pfrom->Misbehaving(100);
3622 LOCK(pfrom->cs_filter);
3623 delete pfrom->pfilter;
3624 pfrom->pfilter = new CBloomFilter(filter);
3626 pfrom->fRelayTxes = true;
3630 else if (strCommand == "filteradd")
3632 vector<unsigned char> vData;
3635 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
3636 // and thus, the maximum size any matched object can have) in a filteradd message
3637 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
3639 pfrom->Misbehaving(100);
3641 LOCK(pfrom->cs_filter);
3643 pfrom->pfilter->insert(vData);
3645 pfrom->Misbehaving(100);
3650 else if (strCommand == "filterclear")
3652 LOCK(pfrom->cs_filter);
3653 delete pfrom->pfilter;
3654 pfrom->pfilter = NULL;
3655 pfrom->fRelayTxes = true;
3661 // Ignore unknown commands for extensibility
3665 // Update the last seen time for this node's address
3666 if (pfrom->fNetworkNode)
3667 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3668 AddressCurrentlyConnected(pfrom->addr);
3674 bool ProcessMessages(CNode* pfrom)
3676 CDataStream& vRecv = pfrom->vRecv;
3680 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3684 // (4) message start
3693 // Don't bother if send buffer is too full to respond anyway
3694 if (pfrom->vSend.size() >= SendBufferSize())
3697 // Scan for message start
3698 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3699 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3700 if (vRecv.end() - pstart < nHeaderSize)
3702 if ((int)vRecv.size() > nHeaderSize)
3704 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3705 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3709 if (pstart - vRecv.begin() > 0)
3710 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3711 vRecv.erase(vRecv.begin(), pstart);
3714 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3719 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3722 string strCommand = hdr.GetCommand();
3725 unsigned int nMessageSize = hdr.nMessageSize;
3726 if (nMessageSize > MAX_SIZE)
3728 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3731 if (nMessageSize > vRecv.size())
3733 // Rewind and wait for rest of message
3734 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3739 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3740 unsigned int nChecksum = 0;
3741 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3742 if (nChecksum != hdr.nChecksum)
3744 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3745 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3749 // Copy message to its own buffer
3750 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3751 vRecv.ignore(nMessageSize);
3759 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3764 catch (std::ios_base::failure& e)
3766 if (strstr(e.what(), "end of data"))
3768 // Allow exceptions from under-length message on vRecv
3769 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
3771 else if (strstr(e.what(), "size too large"))
3773 // Allow exceptions from over-long size
3774 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3778 PrintExceptionContinue(&e, "ProcessMessages()");
3781 catch (std::exception& e) {
3782 PrintExceptionContinue(&e, "ProcessMessages()");
3784 PrintExceptionContinue(NULL, "ProcessMessages()");
3788 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3796 bool SendMessages(CNode* pto, bool fSendTrickle)
3798 TRY_LOCK(cs_main, lockMain);
3800 // Don't send anything until we get their version message
3801 if (pto->nVersion == 0)
3804 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3806 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3808 if (pto->nVersion > BIP0031_VERSION)
3809 pto->PushMessage("ping", nonce);
3811 pto->PushMessage("ping");
3814 // Resend wallet transactions that haven't gotten in a block yet
3815 // Except during reindex, importing and IBD, when old wallet
3816 // transactions become unconfirmed and spams other nodes.
3817 if (!fReindex && !fImporting && !IsInitialBlockDownload())
3819 ResendWalletTransactions();
3822 // Address refresh broadcast
3823 static int64 nLastRebroadcast;
3824 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3828 BOOST_FOREACH(CNode* pnode, vNodes)
3830 // Periodically clear setAddrKnown to allow refresh broadcasts
3831 if (nLastRebroadcast)
3832 pnode->setAddrKnown.clear();
3834 // Rebroadcast our address
3837 CAddress addr = GetLocalAddress(&pnode->addr);
3838 if (addr.IsRoutable())
3839 pnode->PushAddress(addr);
3843 nLastRebroadcast = GetTime();
3851 vector<CAddress> vAddr;
3852 vAddr.reserve(pto->vAddrToSend.size());
3853 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3855 // returns true if wasn't already contained in the set
3856 if (pto->setAddrKnown.insert(addr).second)
3858 vAddr.push_back(addr);
3859 // receiver rejects addr messages larger than 1000
3860 if (vAddr.size() >= 1000)
3862 pto->PushMessage("addr", vAddr);
3867 pto->vAddrToSend.clear();
3869 pto->PushMessage("addr", vAddr);
3874 // Message: inventory
3877 vector<CInv> vInvWait;
3879 LOCK(pto->cs_inventory);
3880 vInv.reserve(pto->vInventoryToSend.size());
3881 vInvWait.reserve(pto->vInventoryToSend.size());
3882 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3884 if (pto->setInventoryKnown.count(inv))
3887 // trickle out tx inv to protect privacy
3888 if (inv.type == MSG_TX && !fSendTrickle)
3890 // 1/4 of tx invs blast to all immediately
3891 static uint256 hashSalt;
3893 hashSalt = GetRandHash();
3894 uint256 hashRand = inv.hash ^ hashSalt;
3895 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3896 bool fTrickleWait = ((hashRand & 3) != 0);
3898 // always trickle our own transactions
3902 if (GetTransaction(inv.hash, wtx))
3904 fTrickleWait = true;
3909 vInvWait.push_back(inv);
3914 // returns true if wasn't already contained in the set
3915 if (pto->setInventoryKnown.insert(inv).second)
3917 vInv.push_back(inv);
3918 if (vInv.size() >= 1000)
3920 pto->PushMessage("inv", vInv);
3925 pto->vInventoryToSend = vInvWait;
3928 pto->PushMessage("inv", vInv);
3934 vector<CInv> vGetData;
3935 int64 nNow = GetTime() * 1000000;
3936 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3938 const CInv& inv = (*pto->mapAskFor.begin()).second;
3939 if (!AlreadyHave(inv))
3942 printf("sending getdata: %s\n", inv.ToString().c_str());
3943 vGetData.push_back(inv);
3944 if (vGetData.size() >= 1000)
3946 pto->PushMessage("getdata", vGetData);
3949 mapAlreadyAskedFor[inv] = nNow;
3951 pto->mapAskFor.erase(pto->mapAskFor.begin());
3953 if (!vGetData.empty())
3954 pto->PushMessage("getdata", vGetData);
3973 //////////////////////////////////////////////////////////////////////////////
3978 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3980 unsigned char* pdata = (unsigned char*)pbuffer;
3981 unsigned int blocks = 1 + ((len + 8) / 64);
3982 unsigned char* pend = pdata + 64 * blocks;
3983 memset(pdata + len, 0, 64 * blocks - len);
3985 unsigned int bits = len * 8;
3986 pend[-1] = (bits >> 0) & 0xff;
3987 pend[-2] = (bits >> 8) & 0xff;
3988 pend[-3] = (bits >> 16) & 0xff;
3989 pend[-4] = (bits >> 24) & 0xff;
3993 static const unsigned int pSHA256InitState[8] =
3994 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3996 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3999 unsigned char data[64];
4003 for (int i = 0; i < 16; i++)
4004 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
4006 for (int i = 0; i < 8; i++)
4007 ctx.h[i] = ((uint32_t*)pinit)[i];
4009 SHA256_Update(&ctx, data, sizeof(data));
4010 for (int i = 0; i < 8; i++)
4011 ((uint32_t*)pstate)[i] = ctx.h[i];
4015 // ScanHash scans nonces looking for a hash with at least some zero bits.
4016 // It operates on big endian data. Caller does the byte reversing.
4017 // All input buffers are 16-byte aligned. nNonce is usually preserved
4018 // between calls, but periodically or if nNonce is 0xffff0000 or above,
4019 // the block is rebuilt and nNonce starts over at zero.
4021 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
4023 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
4027 // Hash pdata using pmidstate as the starting state into
4028 // pre-formatted buffer phash1, then hash phash1 into phash
4030 SHA256Transform(phash1, pdata, pmidstate);
4031 SHA256Transform(phash, phash1, pSHA256InitState);
4033 // Return the nonce if the hash has at least some zero bits,
4034 // caller will check if it has enough to reach the target
4035 if (((unsigned short*)phash)[14] == 0)
4038 // If nothing found after trying for a while, return -1
4039 if ((nNonce & 0xffff) == 0)
4041 nHashesDone = 0xffff+1;
4042 return (unsigned int) -1;
4047 // Some explaining would be appreciated
4052 set<uint256> setDependsOn;
4056 COrphan(CTransaction* ptxIn)
4059 dPriority = dFeePerKb = 0;
4064 printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
4065 ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
4066 BOOST_FOREACH(uint256 hash, setDependsOn)
4067 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
4072 uint64 nLastBlockTx = 0;
4073 uint64 nLastBlockSize = 0;
4075 // We want to sort transactions by priority and fee, so:
4076 typedef boost::tuple<double, double, CTransaction*> TxPriority;
4077 class TxPriorityCompare
4081 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
4082 bool operator()(const TxPriority& a, const TxPriority& b)
4086 if (a.get<1>() == b.get<1>())
4087 return a.get<0>() < b.get<0>();
4088 return a.get<1>() < b.get<1>();
4092 if (a.get<0>() == b.get<0>())
4093 return a.get<1>() < b.get<1>();
4094 return a.get<0>() < b.get<0>();
4099 CBlockTemplate* CreateNewBlock(CReserveKey& reservekey)
4102 auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
4103 if(!pblocktemplate.get())
4105 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
4107 // Create coinbase tx
4109 txNew.vin.resize(1);
4110 txNew.vin[0].prevout.SetNull();
4111 txNew.vout.resize(1);
4112 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
4114 // Add our coinbase tx as first transaction
4115 pblock->vtx.push_back(txNew);
4116 pblocktemplate->vTxFees.push_back(-1); // updated at end
4117 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
4119 // Largest block you're willing to create:
4120 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
4121 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
4122 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
4124 // How much of the block should be dedicated to high-priority transactions,
4125 // included regardless of the fees they pay
4126 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
4127 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
4129 // Minimum block size you want to create; block will be filled with free transactions
4130 // until there are no more or the block reaches this size:
4131 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
4132 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
4134 // Fee-per-kilobyte amount considered the same as "free"
4135 // Be careful setting this: if you set it to zero then
4136 // a transaction spammer can cheaply fill blocks using
4137 // 1-satoshi-fee transactions. It should be set above the real
4138 // cost to you of processing a transaction.
4139 int64 nMinTxFee = MIN_TX_FEE;
4140 if (mapArgs.count("-mintxfee"))
4141 ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
4143 // Collect memory pool transactions into the block
4146 LOCK2(cs_main, mempool.cs);
4147 CBlockIndex* pindexPrev = pindexBest;
4148 CCoinsViewCache view(*pcoinsTip, true);
4150 // Priority order to process transactions
4151 list<COrphan> vOrphan; // list memory doesn't move
4152 map<uint256, vector<COrphan*> > mapDependers;
4153 bool fPrintPriority = GetBoolArg("-printpriority");
4155 // This vector will be sorted into a priority queue:
4156 vector<TxPriority> vecPriority;
4157 vecPriority.reserve(mempool.mapTx.size());
4158 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
4160 CTransaction& tx = (*mi).second;
4161 if (tx.IsCoinBase() || !tx.IsFinal())
4164 COrphan* porphan = NULL;
4165 double dPriority = 0;
4167 bool fMissingInputs = false;
4168 BOOST_FOREACH(const CTxIn& txin, tx.vin)
4170 // Read prev transaction
4172 if (!view.GetCoins(txin.prevout.hash, coins))
4174 // This should never happen; all transactions in the memory
4175 // pool should connect to either transactions in the chain
4176 // or other transactions in the memory pool.
4177 if (!mempool.mapTx.count(txin.prevout.hash))
4179 printf("ERROR: mempool transaction missing input\n");
4180 if (fDebug) assert("mempool transaction missing input" == 0);
4181 fMissingInputs = true;
4187 // Has to wait for dependencies
4190 // Use list for automatic deletion
4191 vOrphan.push_back(COrphan(&tx));
4192 porphan = &vOrphan.back();
4194 mapDependers[txin.prevout.hash].push_back(porphan);
4195 porphan->setDependsOn.insert(txin.prevout.hash);
4196 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
4200 int64 nValueIn = coins.vout[txin.prevout.n].nValue;
4201 nTotalIn += nValueIn;
4203 int nConf = pindexPrev->nHeight - coins.nHeight + 1;
4205 dPriority += (double)nValueIn * nConf;
4207 if (fMissingInputs) continue;
4209 // Priority is sum(valuein * age) / txsize
4210 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4211 dPriority /= nTxSize;
4213 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
4214 // client code rounds up the size to the nearest 1K. That's good, because it gives an
4215 // incentive to create smaller transactions.
4216 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
4220 porphan->dPriority = dPriority;
4221 porphan->dFeePerKb = dFeePerKb;
4224 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
4227 // Collect transactions into block
4228 uint64 nBlockSize = 1000;
4229 uint64 nBlockTx = 0;
4230 int nBlockSigOps = 100;
4231 bool fSortedByFee = (nBlockPrioritySize <= 0);
4233 TxPriorityCompare comparer(fSortedByFee);
4234 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4236 while (!vecPriority.empty())
4238 // Take highest priority transaction off the priority queue:
4239 double dPriority = vecPriority.front().get<0>();
4240 double dFeePerKb = vecPriority.front().get<1>();
4241 CTransaction& tx = *(vecPriority.front().get<2>());
4243 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
4244 vecPriority.pop_back();
4246 // second layer cached modifications just for this transaction
4247 CCoinsViewCache viewTemp(view, true);
4250 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4251 if (nBlockSize + nTxSize >= nBlockMaxSize)
4254 // Legacy limits on sigOps:
4255 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
4256 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4259 // Skip free transactions if we're past the minimum block size:
4260 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
4263 // Prioritize by fee once past the priority size or we run out of high-priority
4265 if (!fSortedByFee &&
4266 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
4268 fSortedByFee = true;
4269 comparer = TxPriorityCompare(fSortedByFee);
4270 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4273 if (!tx.HaveInputs(viewTemp))
4276 int64 nTxFees = tx.GetValueIn(viewTemp)-tx.GetValueOut();
4278 nTxSigOps += tx.GetP2SHSigOpCount(viewTemp);
4279 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4282 CValidationState state;
4283 if (!tx.CheckInputs(state, viewTemp, true, SCRIPT_VERIFY_P2SH))
4287 uint256 hash = tx.GetHash();
4288 if (!tx.UpdateCoins(state, viewTemp, txundo, pindexPrev->nHeight+1, hash))
4291 // push changes from the second layer cache to the first one
4295 pblock->vtx.push_back(tx);
4296 pblocktemplate->vTxFees.push_back(nTxFees);
4297 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
4298 nBlockSize += nTxSize;
4300 nBlockSigOps += nTxSigOps;
4305 printf("priority %.1f feeperkb %.1f txid %s\n",
4306 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
4309 // Add transactions that depend on this one to the priority queue
4310 if (mapDependers.count(hash))
4312 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
4314 if (!porphan->setDependsOn.empty())
4316 porphan->setDependsOn.erase(hash);
4317 if (porphan->setDependsOn.empty())
4319 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
4320 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
4327 nLastBlockTx = nBlockTx;
4328 nLastBlockSize = nBlockSize;
4329 printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
4331 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
4332 pblocktemplate->vTxFees[0] = -nFees;
4335 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
4336 pblock->UpdateTime(pindexPrev);
4337 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
4339 pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
4340 pblocktemplate->vTxSigOps[0] = pblock->vtx[0].GetLegacySigOpCount();
4342 CBlockIndex indexDummy(*pblock);
4343 indexDummy.pprev = pindexPrev;
4344 indexDummy.nHeight = pindexPrev->nHeight + 1;
4345 CCoinsViewCache viewNew(*pcoinsTip, true);
4346 CValidationState state;
4347 if (!pblock->ConnectBlock(state, &indexDummy, viewNew, true))
4348 throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
4351 return pblocktemplate.release();
4355 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
4357 // Update nExtraNonce
4358 static uint256 hashPrevBlock;
4359 if (hashPrevBlock != pblock->hashPrevBlock)
4362 hashPrevBlock = pblock->hashPrevBlock;
4365 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4366 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4367 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
4369 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
4373 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
4376 // Pre-build hash buffers
4383 uint256 hashPrevBlock;
4384 uint256 hashMerkleRoot;
4387 unsigned int nNonce;
4390 unsigned char pchPadding0[64];
4392 unsigned char pchPadding1[64];
4395 memset(&tmp, 0, sizeof(tmp));
4397 tmp.block.nVersion = pblock->nVersion;
4398 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
4399 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
4400 tmp.block.nTime = pblock->nTime;
4401 tmp.block.nBits = pblock->nBits;
4402 tmp.block.nNonce = pblock->nNonce;
4404 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
4405 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
4407 // Byte swap all the input buffer
4408 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
4409 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
4411 // Precalc the first half of the first hash, which stays constant
4412 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
4414 memcpy(pdata, &tmp.block, 128);
4415 memcpy(phash1, &tmp.hash1, 64);
4419 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
4421 uint256 hash = pblock->GetHash();
4422 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4424 if (hash > hashTarget)
4428 printf("BitcoinMiner:\n");
4429 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
4431 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
4436 if (pblock->hashPrevBlock != hashBestChain)
4437 return error("BitcoinMiner : generated block is stale");
4439 // Remove key from key pool
4440 reservekey.KeepKey();
4442 // Track how many getdata requests this block gets
4444 LOCK(wallet.cs_wallet);
4445 wallet.mapRequestCount[pblock->GetHash()] = 0;
4448 // Process this block the same as if we had received it from another node
4449 CValidationState state;
4450 if (!ProcessBlock(state, NULL, pblock))
4451 return error("BitcoinMiner : ProcessBlock, block not accepted");
4457 void static ThreadBitcoinMiner(void* parg);
4459 static bool fGenerateBitcoins = false;
4460 static bool fLimitProcessors = false;
4461 static int nLimitProcessors = -1;
4463 void static BitcoinMiner(CWallet *pwallet)
4465 printf("BitcoinMiner started\n");
4466 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4468 // Make this thread recognisable as the mining thread
4469 RenameThread("bitcoin-miner");
4471 // Each thread has its own key and counter
4472 CReserveKey reservekey(pwallet);
4473 unsigned int nExtraNonce = 0;
4475 while (fGenerateBitcoins)
4479 while (vNodes.empty() || IsInitialBlockDownload())
4484 if (!fGenerateBitcoins)
4492 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
4493 CBlockIndex* pindexPrev = pindexBest;
4495 auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(reservekey));
4496 if (!pblocktemplate.get())
4498 CBlock *pblock = &pblocktemplate->block;
4499 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
4501 printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
4502 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
4506 // Pre-build hash buffers
4508 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
4509 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
4510 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
4512 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
4514 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
4515 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
4516 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
4522 int64 nStart = GetTime();
4523 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4525 uint256& hash = *alignup<16>(hashbuf);
4528 unsigned int nHashesDone = 0;
4529 unsigned int nNonceFound;
4532 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
4533 (char*)&hash, nHashesDone);
4535 // Check if something found
4536 if (nNonceFound != (unsigned int) -1)
4538 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
4539 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
4541 if (hash <= hashTarget)
4544 pblock->nNonce = ByteReverse(nNonceFound);
4545 assert(hash == pblock->GetHash());
4547 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4548 CheckWork(pblock, *pwalletMain, reservekey);
4549 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4555 static int64 nHashCounter;
4556 if (nHPSTimerStart == 0)
4558 nHPSTimerStart = GetTimeMillis();
4562 nHashCounter += nHashesDone;
4563 if (GetTimeMillis() - nHPSTimerStart > 4000)
4565 static CCriticalSection cs;
4568 if (GetTimeMillis() - nHPSTimerStart > 4000)
4570 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
4571 nHPSTimerStart = GetTimeMillis();
4573 static int64 nLogTime;
4574 if (GetTime() - nLogTime > 30 * 60)
4576 nLogTime = GetTime();
4577 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
4583 // Check for stop or if block needs to be rebuilt
4586 if (!fGenerateBitcoins)
4588 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4592 if (nBlockNonce >= 0xffff0000)
4594 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4596 if (pindexPrev != pindexBest)
4599 // Update nTime every few seconds
4600 pblock->UpdateTime(pindexPrev);
4601 nBlockTime = ByteReverse(pblock->nTime);
4604 // Changing pblock->nTime can change work required on testnet:
4605 nBlockBits = ByteReverse(pblock->nBits);
4606 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4612 void static ThreadBitcoinMiner(void* parg)
4614 CWallet* pwallet = (CWallet*)parg;
4617 vnThreadsRunning[THREAD_MINER]++;
4618 BitcoinMiner(pwallet);
4619 vnThreadsRunning[THREAD_MINER]--;
4621 catch (std::exception& e) {
4622 vnThreadsRunning[THREAD_MINER]--;
4623 PrintException(&e, "ThreadBitcoinMiner()");
4625 vnThreadsRunning[THREAD_MINER]--;
4626 PrintException(NULL, "ThreadBitcoinMiner()");
4629 if (vnThreadsRunning[THREAD_MINER] == 0)
4631 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4635 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4637 fGenerateBitcoins = fGenerate;
4638 nLimitProcessors = GetArg("-genproclimit", -1);
4639 if (nLimitProcessors == 0)
4640 fGenerateBitcoins = false;
4641 fLimitProcessors = (nLimitProcessors != -1);
4645 int nProcessors = boost::thread::hardware_concurrency();
4646 printf("%d processors\n", nProcessors);
4647 if (nProcessors < 1)
4649 if (fLimitProcessors && nProcessors > nLimitProcessors)
4650 nProcessors = nLimitProcessors;
4651 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4652 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4653 for (int i = 0; i < nAddThreads; i++)
4655 if (!NewThread(ThreadBitcoinMiner, pwallet))
4656 printf("Error: NewThread(ThreadBitcoinMiner) failed\n");
4662 // Amount compression:
4663 // * If the amount is 0, output 0
4664 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
4665 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
4666 // * call the result n
4667 // * output 1 + 10*(9*n + d - 1) + e
4668 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
4669 // (this is decodable, as d is in [1-9] and e is in [0-9])
4671 uint64 CTxOutCompressor::CompressAmount(uint64 n)
4676 while (((n % 10) == 0) && e < 9) {
4682 assert(d >= 1 && d <= 9);
4684 return 1 + (n*9 + d - 1)*10 + e;
4686 return 1 + (n - 1)*10 + 9;
4690 uint64 CTxOutCompressor::DecompressAmount(uint64 x)
4692 // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
4696 // x = 10*(9*n + d - 1) + e
4702 int d = (x % 9) + 1;