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 BOOST_FOREACH(const CTxIn& txin, vin)
367 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
368 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
369 // ~65-byte public keys, plus a few script ops.
370 if (txin.scriptSig.size() > 500)
372 if (!txin.scriptSig.IsPushOnly())
375 BOOST_FOREACH(const CTxOut& txout, vout) {
376 if (!::IsStandard(txout.scriptPubKey))
378 if (txout.nValue == 0)
385 // Check transaction inputs, and make sure any
386 // pay-to-script-hash transactions are evaluating IsStandard scripts
388 // Why bother? To avoid denial-of-service attacks; an attacker
389 // can submit a standard HASH... OP_EQUAL transaction,
390 // which will get accepted into blocks. The redemption
391 // script can be anything; an attacker could use a very
392 // expensive-to-check-upon-redemption script like:
393 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
395 bool CTransaction::AreInputsStandard(CCoinsViewCache& mapInputs) const
398 return true; // Coinbases don't use vin normally
400 for (unsigned int i = 0; i < vin.size(); i++)
402 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
404 vector<vector<unsigned char> > vSolutions;
405 txnouttype whichType;
406 // get the scriptPubKey corresponding to this input:
407 const CScript& prevScript = prev.scriptPubKey;
408 if (!Solver(prevScript, whichType, vSolutions))
410 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
411 if (nArgsExpected < 0)
414 // Transactions with extra stuff in their scriptSigs are
415 // non-standard. Note that this EvalScript() call will
416 // be quick, because if there are any operations
417 // beside "push data" in the scriptSig the
418 // IsStandard() call returns false
419 vector<vector<unsigned char> > stack;
420 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
423 if (whichType == TX_SCRIPTHASH)
427 CScript subscript(stack.back().begin(), stack.back().end());
428 vector<vector<unsigned char> > vSolutions2;
429 txnouttype whichType2;
430 if (!Solver(subscript, whichType2, vSolutions2))
432 if (whichType2 == TX_SCRIPTHASH)
436 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
439 nArgsExpected += tmpExpected;
442 if (stack.size() != (unsigned int)nArgsExpected)
450 CTransaction::GetLegacySigOpCount() const
452 unsigned int nSigOps = 0;
453 BOOST_FOREACH(const CTxIn& txin, vin)
455 nSigOps += txin.scriptSig.GetSigOpCount(false);
457 BOOST_FOREACH(const CTxOut& txout, vout)
459 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
465 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
469 if (pblock == NULL) {
471 if (pcoinsTip->GetCoins(GetHash(), coins)) {
472 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
474 if (!blockTmp.ReadFromDisk(pindex))
482 // Update the tx's hashBlock
483 hashBlock = pblock->GetHash();
485 // Locate the transaction
486 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
487 if (pblock->vtx[nIndex] == *(CTransaction*)this)
489 if (nIndex == (int)pblock->vtx.size())
491 vMerkleBranch.clear();
493 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
497 // Fill in merkle branch
498 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
501 // Is the tx in a block that's in the main chain
502 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
503 if (mi == mapBlockIndex.end())
505 CBlockIndex* pindex = (*mi).second;
506 if (!pindex || !pindex->IsInMainChain())
509 return pindexBest->nHeight - pindex->nHeight + 1;
518 bool CTransaction::CheckTransaction() const
520 // Basic checks that don't depend on any context
522 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
524 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
526 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
527 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
529 // Check for negative or overflow output values
531 BOOST_FOREACH(const CTxOut& txout, vout)
533 if (txout.nValue < 0)
534 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
535 if (txout.nValue > MAX_MONEY)
536 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
537 nValueOut += txout.nValue;
538 if (!MoneyRange(nValueOut))
539 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
542 // Check for duplicate inputs
543 set<COutPoint> vInOutPoints;
544 BOOST_FOREACH(const CTxIn& txin, vin)
546 if (vInOutPoints.count(txin.prevout))
548 vInOutPoints.insert(txin.prevout);
553 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
554 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
558 BOOST_FOREACH(const CTxIn& txin, vin)
559 if (txin.prevout.IsNull())
560 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
566 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
567 enum GetMinFee_mode mode) const
569 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
570 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
572 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
573 unsigned int nNewBlockSize = nBlockSize + nBytes;
574 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
580 // Transactions under 10K are free
581 // (about 4500 BTC if made of 50 BTC inputs)
587 // Free transaction area
588 if (nNewBlockSize < 27000)
593 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
594 if (nMinFee < nBaseFee)
596 BOOST_FOREACH(const CTxOut& txout, vout)
597 if (txout.nValue < CENT)
601 // Raise the price as the block approaches full
602 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
604 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
606 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
609 if (!MoneyRange(nMinFee))
614 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
618 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
620 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
621 while (it != mapNextTx.end() && it->first.hash == hashTx) {
622 coins.Spend(it->first.n); // and remove those outputs from coins
627 bool CTxMemPool::accept(CTransaction &tx, bool fCheckInputs, bool fLimitFree,
628 bool* pfMissingInputs)
631 *pfMissingInputs = false;
633 if (!tx.CheckTransaction())
634 return error("CTxMemPool::accept() : CheckTransaction failed");
636 // Coinbase is only valid in a block, not as a loose transaction
638 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
640 // To help v0.1.5 clients who would see it as a negative number
641 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
642 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
644 // Rather not work on nonstandard transactions (unless -testnet)
645 if (!fTestNet && !tx.IsStandard())
646 return error("CTxMemPool::accept() : nonstandard transaction type");
648 // is it already in the memory pool?
649 uint256 hash = tx.GetHash();
652 if (mapTx.count(hash))
656 // Check for conflicts with in-memory transactions
657 CTransaction* ptxOld = NULL;
658 for (unsigned int i = 0; i < tx.vin.size(); i++)
660 COutPoint outpoint = tx.vin[i].prevout;
661 if (mapNextTx.count(outpoint))
663 // Disable replacement feature for now
666 // Allow replacing with a newer version of the same transaction
669 ptxOld = mapNextTx[outpoint].ptx;
670 if (ptxOld->IsFinal())
672 if (!tx.IsNewerThan(*ptxOld))
674 for (unsigned int i = 0; i < tx.vin.size(); i++)
676 COutPoint outpoint = tx.vin[i].prevout;
677 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
687 CCoinsViewCache view(dummy);
691 CCoinsViewMemPool viewMemPool(*pcoinsTip, *this);
692 view.SetBackend(viewMemPool);
694 // do we already have it?
695 if (view.HaveCoins(hash))
698 // do all inputs exist?
699 // Note that this does not check for the presence of actual outputs (see the next check for that),
700 // only helps filling in pfMissingInputs (to determine missing vs spent).
701 BOOST_FOREACH(const CTxIn txin, tx.vin) {
702 if (!view.HaveCoins(txin.prevout.hash)) {
704 *pfMissingInputs = true;
709 // are the actual inputs available?
710 if (!tx.HaveInputs(view))
711 return error("CTxMemPool::accept() : inputs already spent");
713 // Bring the best block into scope
716 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
717 view.SetBackend(dummy);
720 // Check for non-standard pay-to-script-hash in inputs
721 if (!tx.AreInputsStandard(view) && !fTestNet)
722 return error("CTxMemPool::accept() : nonstandard transaction input");
724 // Note: if you modify this code to accept non-standard transactions, then
725 // you should add code here to check that the transaction does a
726 // reasonable number of ECDSA signature verifications.
728 int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
729 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
731 // Don't accept it if it can't get into a block
732 int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
733 if (fLimitFree && nFees < txMinFee)
734 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
735 hash.ToString().c_str(),
738 // Continuously rate-limit free transactions
739 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
740 // be annoying or make others' transactions take longer to confirm.
741 if (fLimitFree && nFees < MIN_RELAY_TX_FEE)
743 static double dFreeCount;
744 static int64 nLastTime;
745 int64 nNow = GetTime();
749 // Use an exponentially decaying ~10-minute window:
750 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
752 // -limitfreerelay unit is thousand-bytes-per-minute
753 // At default rate it would take over a month to fill 1GB
754 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
755 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
757 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
761 // Check against previous transactions
762 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
763 if (!tx.CheckInputs(view, true, SCRIPT_VERIFY_P2SH))
765 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
769 // Store transaction in memory
774 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
777 addUnchecked(hash, tx);
780 ///// are we sure this is ok when loading transactions or restoring block txes
781 // If updated, erase old tx from wallet
783 EraseFromWallets(ptxOld->GetHash());
784 SyncWithWallets(hash, tx, NULL, true);
786 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
787 hash.ToString().substr(0,10).c_str(),
792 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs)
794 return mempool.accept(*this, fCheckInputs, fLimitFree, pfMissingInputs);
797 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
799 // Add to memory pool without checking anything. Don't call this directly,
800 // call CTxMemPool::accept to properly check the transaction first.
803 for (unsigned int i = 0; i < tx.vin.size(); i++)
804 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
805 nTransactionsUpdated++;
811 bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive)
813 // Remove transaction from memory pool
816 uint256 hash = tx.GetHash();
817 if (mapTx.count(hash))
820 for (unsigned int i = 0; i < tx.vout.size(); i++) {
821 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
822 if (it != mapNextTx.end())
823 remove(*it->second.ptx, true);
826 BOOST_FOREACH(const CTxIn& txin, tx.vin)
827 mapNextTx.erase(txin.prevout);
829 nTransactionsUpdated++;
835 bool CTxMemPool::removeConflicts(const CTransaction &tx)
837 // Remove transactions which depend on inputs of tx, recursively
839 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
840 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
841 if (it != mapNextTx.end()) {
842 const CTransaction &txConflict = *it->second.ptx;
843 if (txConflict != tx)
844 remove(txConflict, true);
850 void CTxMemPool::clear()
855 ++nTransactionsUpdated;
858 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
863 vtxid.reserve(mapTx.size());
864 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
865 vtxid.push_back((*mi).first);
871 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
873 if (hashBlock == 0 || nIndex == -1)
876 // Find the block it claims to be in
877 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
878 if (mi == mapBlockIndex.end())
880 CBlockIndex* pindex = (*mi).second;
881 if (!pindex || !pindex->IsInMainChain())
884 // Make sure the merkle branch connects to this block
885 if (!fMerkleVerified)
887 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
889 fMerkleVerified = true;
893 return pindexBest->nHeight - pindex->nHeight + 1;
897 int CMerkleTx::GetBlocksToMaturity() const
901 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
905 bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs, bool fLimitFree)
907 return CTransaction::AcceptToMemoryPool(fCheckInputs, fLimitFree);
912 bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
916 // Add previous supporting transactions first
917 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
919 if (!tx.IsCoinBase())
921 uint256 hash = tx.GetHash();
922 if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
923 tx.AcceptToMemoryPool(fCheckInputs, false);
926 return AcceptToMemoryPool(fCheckInputs, false);
932 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
933 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
935 CBlockIndex *pindexSlow = NULL;
940 if (mempool.exists(hash))
942 txOut = mempool.lookup(hash);
949 if (pblocktree->ReadTxIndex(hash, postx)) {
950 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
954 fseek(file, postx.nTxOffset, SEEK_CUR);
956 } catch (std::exception &e) {
957 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
959 hashBlock = header.GetHash();
960 if (txOut.GetHash() != hash)
961 return error("%s() : txid mismatch", __PRETTY_FUNCTION__);
966 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
969 CCoinsViewCache &view = *pcoinsTip;
971 if (view.GetCoins(hash, coins))
972 nHeight = coins.nHeight;
975 pindexSlow = FindBlockByHeight(nHeight);
981 if (block.ReadFromDisk(pindexSlow)) {
982 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
983 if (tx.GetHash() == hash) {
985 hashBlock = pindexSlow->GetBlockHash();
1000 //////////////////////////////////////////////////////////////////////////////
1002 // CBlock and CBlockIndex
1005 static CBlockIndex* pblockindexFBBHLast;
1006 CBlockIndex* FindBlockByHeight(int nHeight)
1008 CBlockIndex *pblockindex;
1009 if (nHeight < nBestHeight / 2)
1010 pblockindex = pindexGenesisBlock;
1012 pblockindex = pindexBest;
1013 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
1014 pblockindex = pblockindexFBBHLast;
1015 while (pblockindex->nHeight > nHeight)
1016 pblockindex = pblockindex->pprev;
1017 while (pblockindex->nHeight < nHeight)
1018 pblockindex = pblockindex->pnext;
1019 pblockindexFBBHLast = pblockindex;
1023 bool CBlock::ReadFromDisk(const CBlockIndex* pindex)
1025 if (!ReadFromDisk(pindex->GetBlockPos()))
1027 if (GetHash() != pindex->GetBlockHash())
1028 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1032 uint256 static GetOrphanRoot(const CBlockHeader* pblock)
1034 // Work back to the first block in the orphan chain
1035 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1036 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1037 return pblock->GetHash();
1040 int64 static GetBlockValue(int nHeight, int64 nFees)
1042 int64 nSubsidy = 50 * COIN;
1044 // Subsidy is cut in half every 210000 blocks, which will occur approximately every 4 years
1045 nSubsidy >>= (nHeight / 210000);
1047 return nSubsidy + nFees;
1050 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1051 static const int64 nTargetSpacing = 10 * 60;
1052 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
1055 // minimum amount of work that could possibly be required nTime after
1056 // minimum work required was nBase
1058 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1060 // Testnet has min-difficulty blocks
1061 // after nTargetSpacing*2 time between blocks:
1062 if (fTestNet && nTime > nTargetSpacing*2)
1063 return bnProofOfWorkLimit.GetCompact();
1066 bnResult.SetCompact(nBase);
1067 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
1069 // Maximum 400% adjustment...
1071 // ... in best-case exactly 4-times-normal target time
1072 nTime -= nTargetTimespan*4;
1074 if (bnResult > bnProofOfWorkLimit)
1075 bnResult = bnProofOfWorkLimit;
1076 return bnResult.GetCompact();
1079 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
1081 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
1084 if (pindexLast == NULL)
1085 return nProofOfWorkLimit;
1087 // Only change once per interval
1088 if ((pindexLast->nHeight+1) % nInterval != 0)
1090 // Special difficulty rule for testnet:
1093 // If the new block's timestamp is more than 2* 10 minutes
1094 // then allow mining of a min-difficulty block.
1095 if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
1096 return nProofOfWorkLimit;
1099 // Return the last non-special-min-difficulty-rules-block
1100 const CBlockIndex* pindex = pindexLast;
1101 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
1102 pindex = pindex->pprev;
1103 return pindex->nBits;
1107 return pindexLast->nBits;
1110 // Go back by what we want to be 14 days worth of blocks
1111 const CBlockIndex* pindexFirst = pindexLast;
1112 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1113 pindexFirst = pindexFirst->pprev;
1114 assert(pindexFirst);
1116 // Limit adjustment step
1117 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1118 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1119 if (nActualTimespan < nTargetTimespan/4)
1120 nActualTimespan = nTargetTimespan/4;
1121 if (nActualTimespan > nTargetTimespan*4)
1122 nActualTimespan = nTargetTimespan*4;
1126 bnNew.SetCompact(pindexLast->nBits);
1127 bnNew *= nActualTimespan;
1128 bnNew /= nTargetTimespan;
1130 if (bnNew > bnProofOfWorkLimit)
1131 bnNew = bnProofOfWorkLimit;
1134 printf("GetNextWorkRequired RETARGET\n");
1135 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1136 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1137 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1139 return bnNew.GetCompact();
1142 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1145 bnTarget.SetCompact(nBits);
1148 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1149 return error("CheckProofOfWork() : nBits below minimum work");
1151 // Check proof of work matches claimed amount
1152 if (hash > bnTarget.getuint256())
1153 return error("CheckProofOfWork() : hash doesn't match nBits");
1158 // Return maximum amount of blocks that other nodes claim to have
1159 int GetNumBlocksOfPeers()
1161 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1164 bool IsInitialBlockDownload()
1166 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate() || fReindex || fImporting)
1168 static int64 nLastUpdate;
1169 static CBlockIndex* pindexLastBest;
1170 if (pindexBest != pindexLastBest)
1172 pindexLastBest = pindexBest;
1173 nLastUpdate = GetTime();
1175 return (GetTime() - nLastUpdate < 10 &&
1176 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1179 void static InvalidChainFound(CBlockIndex* pindexNew)
1181 if (pindexNew->bnChainWork > bnBestInvalidWork)
1183 bnBestInvalidWork = pindexNew->bnChainWork;
1184 pblocktree->WriteBestInvalidWork(bnBestInvalidWork);
1185 uiInterface.NotifyBlocksChanged();
1187 printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n",
1188 BlockHashStr(pindexNew->GetBlockHash()).c_str(), pindexNew->nHeight,
1189 pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1190 pindexNew->GetBlockTime()).c_str());
1191 printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n",
1192 BlockHashStr(hashBestChain).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
1193 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1194 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1195 printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1198 void static InvalidBlockFound(CBlockIndex *pindex) {
1199 pindex->nStatus |= BLOCK_FAILED_VALID;
1200 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
1201 setBlockIndexValid.erase(pindex);
1202 InvalidChainFound(pindex);
1204 ConnectBestBlock(); // reorganise away from the failed block
1207 bool ConnectBestBlock() {
1209 CBlockIndex *pindexNewBest;
1212 std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
1213 if (it == setBlockIndexValid.rend())
1215 pindexNewBest = *it;
1218 if (pindexNewBest == pindexBest || (pindexBest && pindexNewBest->bnChainWork == pindexBest->bnChainWork))
1219 return true; // nothing to do
1222 CBlockIndex *pindexTest = pindexNewBest;
1223 std::vector<CBlockIndex*> vAttach;
1225 if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
1226 // mark descendants failed
1227 CBlockIndex *pindexFailed = pindexNewBest;
1228 while (pindexTest != pindexFailed) {
1229 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
1230 setBlockIndexValid.erase(pindexFailed);
1231 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
1232 pindexFailed = pindexFailed->pprev;
1234 InvalidChainFound(pindexNewBest);
1238 if (pindexBest == NULL || pindexTest->bnChainWork > pindexBest->bnChainWork)
1239 vAttach.push_back(pindexTest);
1241 if (pindexTest->pprev == NULL || pindexTest->pnext != NULL) {
1242 reverse(vAttach.begin(), vAttach.end());
1243 BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) {
1244 if (fRequestShutdown)
1246 if (!SetBestChain(pindexSwitch))
1251 pindexTest = pindexTest->pprev;
1256 void CBlockHeader::UpdateTime(const CBlockIndex* pindexPrev)
1258 nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1260 // Updating time can change work required on testnet:
1262 nBits = GetNextWorkRequired(pindexPrev, this);
1275 const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view)
1277 const CCoins &coins = view.GetCoins(input.prevout.hash);
1278 assert(coins.IsAvailable(input.prevout.n));
1279 return coins.vout[input.prevout.n];
1282 int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const
1288 for (unsigned int i = 0; i < vin.size(); i++)
1289 nResult += GetOutputFor(vin[i], inputs).nValue;
1294 unsigned int CTransaction::GetP2SHSigOpCount(CCoinsViewCache& inputs) const
1299 unsigned int nSigOps = 0;
1300 for (unsigned int i = 0; i < vin.size(); i++)
1302 const CTxOut &prevout = GetOutputFor(vin[i], inputs);
1303 if (prevout.scriptPubKey.IsPayToScriptHash())
1304 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1309 bool CTransaction::UpdateCoins(CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash) const
1311 // mark inputs spent
1312 if (!IsCoinBase()) {
1313 BOOST_FOREACH(const CTxIn &txin, vin) {
1314 CCoins &coins = inputs.GetCoins(txin.prevout.hash);
1316 if (!coins.Spend(txin.prevout, undo))
1317 return error("UpdateCoins() : cannot spend input");
1318 txundo.vprevout.push_back(undo);
1323 if (!inputs.SetCoins(txhash, CCoins(*this, nHeight)))
1324 return error("UpdateCoins() : cannot update output");
1329 bool CTransaction::HaveInputs(CCoinsViewCache &inputs) const
1331 if (!IsCoinBase()) {
1332 // first check whether information about the prevout hash is available
1333 for (unsigned int i = 0; i < vin.size(); i++) {
1334 const COutPoint &prevout = vin[i].prevout;
1335 if (!inputs.HaveCoins(prevout.hash))
1339 // then check whether the actual outputs are available
1340 for (unsigned int i = 0; i < vin.size(); i++) {
1341 const COutPoint &prevout = vin[i].prevout;
1342 const CCoins &coins = inputs.GetCoins(prevout.hash);
1343 if (!coins.IsAvailable(prevout.n))
1350 bool CScriptCheck::operator()() const {
1351 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1352 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1353 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1357 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1359 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1362 bool CTransaction::CheckInputs(CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks) const
1367 pvChecks->reserve(vin.size());
1369 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1370 // for an attacker to attempt to split the network.
1371 if (!HaveInputs(inputs))
1372 return error("CheckInputs() : %s inputs unavailable", GetHash().ToString().substr(0,10).c_str());
1374 // While checking, GetBestBlock() refers to the parent block.
1375 // This is also true for mempool checks.
1376 int nSpendHeight = inputs.GetBestBlock()->nHeight + 1;
1379 for (unsigned int i = 0; i < vin.size(); i++)
1381 const COutPoint &prevout = vin[i].prevout;
1382 const CCoins &coins = inputs.GetCoins(prevout.hash);
1384 // If prev is coinbase, check that it's matured
1385 if (coins.IsCoinBase()) {
1386 if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
1387 return error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight);
1390 // Check for negative or overflow input values
1391 nValueIn += coins.vout[prevout.n].nValue;
1392 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1393 return DoS(100, error("CheckInputs() : txin values out of range"));
1397 if (nValueIn < GetValueOut())
1398 return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1400 // Tally transaction fees
1401 int64 nTxFee = nValueIn - GetValueOut();
1403 return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1405 if (!MoneyRange(nFees))
1406 return DoS(100, error("CheckInputs() : nFees out of range"));
1408 // The first loop above does all the inexpensive checks.
1409 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1410 // Helps prevent CPU exhaustion attacks.
1412 // Skip ECDSA signature verification when connecting blocks
1413 // before the last block chain checkpoint. This is safe because block merkle hashes are
1414 // still computed and checked, and any change will be caught at the next checkpoint.
1415 if (fScriptChecks) {
1416 for (unsigned int i = 0; i < vin.size(); i++) {
1417 const COutPoint &prevout = vin[i].prevout;
1418 const CCoins &coins = inputs.GetCoins(prevout.hash);
1421 CScriptCheck check(coins, *this, i, flags, 0);
1423 pvChecks->push_back(CScriptCheck());
1424 check.swap(pvChecks->back());
1425 } else if (!check())
1426 return DoS(100,false);
1435 bool CTransaction::ClientCheckInputs() const
1440 // Take over previous transactions' spent pointers
1444 for (unsigned int i = 0; i < vin.size(); i++)
1446 // Get prev tx from single transactions in memory
1447 COutPoint prevout = vin[i].prevout;
1448 if (!mempool.exists(prevout.hash))
1450 CTransaction& txPrev = mempool.lookup(prevout.hash);
1452 if (prevout.n >= txPrev.vout.size())
1456 if (!VerifySignature(CCoins(txPrev, -1), *this, i, SCRIPT_VERIFY_P2SH, 0))
1457 return error("ConnectInputs() : VerifySignature failed");
1459 ///// this is redundant with the mempool.mapNextTx stuff,
1460 ///// not sure which I want to get rid of
1461 ///// this has to go away now that posNext is gone
1462 // // Check for conflicts
1463 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1464 // return error("ConnectInputs() : prev tx already used");
1466 // // Flag outpoints as used
1467 // txPrev.vout[prevout.n].posNext = posThisTx;
1469 nValueIn += txPrev.vout[prevout.n].nValue;
1471 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1472 return error("ClientConnectInputs() : txin values out of range");
1474 if (GetValueOut() > nValueIn)
1484 bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
1486 assert(pindex == view.GetBestBlock());
1493 CBlockUndo blockUndo;
1494 CDiskBlockPos pos = pindex->GetUndoPos();
1496 return error("DisconnectBlock() : no undo data available");
1497 if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
1498 return error("DisconnectBlock() : failure reading undo data");
1500 if (blockUndo.vtxundo.size() + 1 != vtx.size())
1501 return error("DisconnectBlock() : block and undo data inconsistent");
1503 // undo transactions in reverse order
1504 for (int i = vtx.size() - 1; i >= 0; i--) {
1505 const CTransaction &tx = vtx[i];
1506 uint256 hash = tx.GetHash();
1508 // check that all outputs are available
1509 if (!view.HaveCoins(hash)) {
1510 fClean = fClean && error("DisconnectBlock() : outputs still spent? database corrupted");
1511 view.SetCoins(hash, CCoins());
1513 CCoins &outs = view.GetCoins(hash);
1515 CCoins outsBlock = CCoins(tx, pindex->nHeight);
1516 if (outs != outsBlock)
1517 fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
1523 if (i > 0) { // not coinbases
1524 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1525 if (txundo.vprevout.size() != tx.vin.size())
1526 return error("DisconnectBlock() : transaction and undo data inconsistent");
1527 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1528 const COutPoint &out = tx.vin[j].prevout;
1529 const CTxInUndo &undo = txundo.vprevout[j];
1531 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1532 if (undo.nHeight != 0) {
1533 // undo data contains height: this is the last output of the prevout tx being spent
1534 if (!coins.IsPruned())
1535 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
1537 coins.fCoinBase = undo.fCoinBase;
1538 coins.nHeight = undo.nHeight;
1539 coins.nVersion = undo.nVersion;
1541 if (coins.IsPruned())
1542 fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
1544 if (coins.IsAvailable(out.n))
1545 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
1546 if (coins.vout.size() < out.n+1)
1547 coins.vout.resize(out.n+1);
1548 coins.vout[out.n] = undo.txout;
1549 if (!view.SetCoins(out.hash, coins))
1550 return error("DisconnectBlock() : cannot restore coin inputs");
1555 // move best block pointer to prevout block
1556 view.SetBestBlock(pindex->pprev);
1566 void static FlushBlockFile()
1568 LOCK(cs_LastBlockFile);
1570 CDiskBlockPos posOld(nLastBlockFile, 0);
1572 FILE *fileOld = OpenBlockFile(posOld);
1574 FileCommit(fileOld);
1578 fileOld = OpenUndoFile(posOld);
1580 FileCommit(fileOld);
1585 bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1587 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1589 void ThreadScriptCheck(void*) {
1590 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1591 RenameThread("bitcoin-scriptch");
1592 scriptcheckqueue.Thread();
1593 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1596 void ThreadScriptCheckQuit() {
1597 scriptcheckqueue.Quit();
1600 bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsViewCache &view, bool fJustCheck)
1602 // Check it again in case a previous version let a bad block in
1603 if (!CheckBlock(!fJustCheck, !fJustCheck))
1606 // verify that the view's current state corresponds to the previous block
1607 assert(pindex->pprev == view.GetBestBlock());
1609 // Special case for the genesis block, skipping connection of its transactions
1610 // (its coinbase is unspendable)
1611 if (GetHash() == hashGenesisBlock) {
1612 view.SetBestBlock(pindex);
1613 pindexGenesisBlock = pindex;
1617 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1619 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1620 // unless those are already completely spent.
1621 // If such overwrites are allowed, coinbases and transactions depending upon those
1622 // can be duplicated to remove the ability to spend the first instance -- even after
1623 // being sent to another address.
1624 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1625 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1626 // already refuses previously-known transaction ids entirely.
1627 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1628 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1629 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1630 // initial block download.
1631 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1632 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1633 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1634 if (fEnforceBIP30) {
1635 for (unsigned int i=0; i<vtx.size(); i++) {
1636 uint256 hash = GetTxHash(i);
1637 if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
1638 return error("ConnectBlock() : tried to overwrite transaction");
1642 // BIP16 didn't become active until Apr 1 2012
1643 int64 nBIP16SwitchTime = 1333238400;
1644 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1646 unsigned int flags = SCRIPT_VERIFY_NOCACHE |
1647 (fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE);
1649 CBlockUndo blockundo;
1651 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1653 int64 nStart = GetTimeMicros();
1656 unsigned int nSigOps = 0;
1657 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(vtx.size()));
1658 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1659 vPos.reserve(vtx.size());
1660 for (unsigned int i=0; i<vtx.size(); i++)
1663 const CTransaction &tx = vtx[i];
1665 nInputs += tx.vin.size();
1666 nSigOps += tx.GetLegacySigOpCount();
1667 if (nSigOps > MAX_BLOCK_SIGOPS)
1668 return DoS(100, error("ConnectBlock() : too many sigops"));
1670 if (!tx.IsCoinBase())
1672 if (!tx.HaveInputs(view))
1673 return DoS(100, error("ConnectBlock() : inputs missing/spent"));
1675 if (fStrictPayToScriptHash)
1677 // Add in sigops done by pay-to-script-hash inputs;
1678 // this is to prevent a "rogue miner" from creating
1679 // an incredibly-expensive-to-validate block.
1680 nSigOps += tx.GetP2SHSigOpCount(view);
1681 if (nSigOps > MAX_BLOCK_SIGOPS)
1682 return DoS(100, error("ConnectBlock() : too many sigops"));
1685 nFees += tx.GetValueIn(view)-tx.GetValueOut();
1687 std::vector<CScriptCheck> vChecks;
1688 if (!tx.CheckInputs(view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
1690 control.Add(vChecks);
1694 if (!tx.UpdateCoins(view, txundo, pindex->nHeight, GetTxHash(i)))
1695 return error("ConnectBlock() : UpdateInputs failed");
1696 if (!tx.IsCoinBase())
1697 blockundo.vtxundo.push_back(txundo);
1699 vPos.push_back(std::make_pair(GetTxHash(i), pos));
1700 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1702 int64 nTime = GetTimeMicros() - nStart;
1704 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));
1706 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1707 return error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees));
1709 if (!control.Wait())
1710 return DoS(100, false);
1711 int64 nTime2 = GetTimeMicros() - nStart;
1713 printf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
1718 // Write undo information to disk
1719 if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
1721 if (pindex->GetUndoPos().IsNull()) {
1723 if (!FindUndoPos(pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1724 return error("ConnectBlock() : FindUndoPos failed");
1725 if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
1726 return error("ConnectBlock() : CBlockUndo::WriteToDisk failed");
1728 // update nUndoPos in block index
1729 pindex->nUndoPos = pos.nPos;
1730 pindex->nStatus |= BLOCK_HAVE_UNDO;
1733 pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
1735 CDiskBlockIndex blockindex(pindex);
1736 if (!pblocktree->WriteBlockIndex(blockindex))
1737 return error("ConnectBlock() : WriteBlockIndex failed");
1741 pblocktree->WriteTxIndex(vPos);
1743 // add this block to the view's block chain
1744 if (!view.SetBestBlock(pindex))
1747 // Watch for transactions paying to me
1748 for (unsigned int i=0; i<vtx.size(); i++)
1749 SyncWithWallets(GetTxHash(i), vtx[i], this, true);
1754 bool SetBestChain(CBlockIndex* pindexNew)
1756 // All modifications to the coin state will be done in this cache.
1757 // Only when all have succeeded, we push it to pcoinsTip.
1758 CCoinsViewCache view(*pcoinsTip, true);
1760 // Find the fork (typically, there is none)
1761 CBlockIndex* pfork = view.GetBestBlock();
1762 CBlockIndex* plonger = pindexNew;
1763 while (pfork && pfork != plonger)
1765 while (plonger->nHeight > pfork->nHeight)
1766 if (!(plonger = plonger->pprev))
1767 return error("SetBestChain() : plonger->pprev is null");
1768 if (pfork == plonger)
1770 if (!(pfork = pfork->pprev))
1771 return error("SetBestChain() : pfork->pprev is null");
1774 // List of what to disconnect (typically nothing)
1775 vector<CBlockIndex*> vDisconnect;
1776 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1777 vDisconnect.push_back(pindex);
1779 // List of what to connect (typically only pindexNew)
1780 vector<CBlockIndex*> vConnect;
1781 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1782 vConnect.push_back(pindex);
1783 reverse(vConnect.begin(), vConnect.end());
1785 if (vDisconnect.size() > 0) {
1786 printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), BlockHashStr(pfork->GetBlockHash()).c_str(), BlockHashStr(pindexBest->GetBlockHash()).c_str());
1787 printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), BlockHashStr(pfork->GetBlockHash()).c_str(), BlockHashStr(pindexNew->GetBlockHash()).c_str());
1790 // Disconnect shorter branch
1791 vector<CTransaction> vResurrect;
1792 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
1794 if (!block.ReadFromDisk(pindex))
1795 return error("SetBestBlock() : ReadFromDisk for disconnect failed");
1796 int64 nStart = GetTimeMicros();
1797 if (!block.DisconnectBlock(pindex, view))
1798 return error("SetBestBlock() : DisconnectBlock %s failed", BlockHashStr(pindex->GetBlockHash()).c_str());
1800 printf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1802 // Queue memory transactions to resurrect.
1803 // We only do this for blocks after the last checkpoint (reorganisation before that
1804 // point should only happen with -reindex/-loadblock, or a misbehaving peer.
1805 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1806 if (!tx.IsCoinBase() && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
1807 vResurrect.push_back(tx);
1810 // Connect longer branch
1811 vector<CTransaction> vDelete;
1812 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
1814 if (!block.ReadFromDisk(pindex))
1815 return error("SetBestBlock() : ReadFromDisk for connect failed");
1816 int64 nStart = GetTimeMicros();
1817 if (!block.ConnectBlock(pindex, view)) {
1818 InvalidChainFound(pindexNew);
1819 InvalidBlockFound(pindex);
1820 return error("SetBestBlock() : ConnectBlock %s failed", BlockHashStr(pindex->GetBlockHash()).c_str());
1823 printf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1825 // Queue memory transactions to delete
1826 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1827 vDelete.push_back(tx);
1830 // Flush changes to global coin state
1831 int64 nStart = GetTimeMicros();
1832 int nModified = view.GetCacheSize();
1834 return error("SetBestBlock() : unable to modify coin state");
1835 int64 nTime = GetTimeMicros() - nStart;
1837 printf("- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified);
1839 // Make sure it's successfully written to disk before changing memory structure
1840 bool fIsInitialDownload = IsInitialBlockDownload();
1841 if (!fIsInitialDownload || pcoinsTip->GetCacheSize() > nCoinCacheSize) {
1844 if (!pcoinsTip->Flush())
1848 // At this point, all changes have been done to the database.
1849 // Proceed by updating the memory structures.
1851 // Disconnect shorter branch
1852 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1854 pindex->pprev->pnext = NULL;
1856 // Connect longer branch
1857 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1859 pindex->pprev->pnext = pindex;
1861 // Resurrect memory transactions that were in the disconnected branch
1862 BOOST_FOREACH(CTransaction& tx, vResurrect)
1863 tx.AcceptToMemoryPool(true, false);
1865 // Delete redundant memory transactions that are in the connected branch
1866 BOOST_FOREACH(CTransaction& tx, vDelete) {
1868 mempool.removeConflicts(tx);
1871 // Update best block in wallet (so we can detect restored wallets)
1872 if (!fIsInitialDownload)
1874 const CBlockLocator locator(pindexNew);
1875 ::SetBestChain(locator);
1879 hashBestChain = pindexNew->GetBlockHash();
1880 pindexBest = pindexNew;
1881 pblockindexFBBHLast = NULL;
1882 nBestHeight = pindexBest->nHeight;
1883 bnBestChainWork = pindexNew->bnChainWork;
1884 nTimeBestReceived = GetTime();
1885 nTransactionsUpdated++;
1886 printf("SetBestChain: new best=%s height=%d work=%s tx=%lu date=%s\n",
1887 BlockHashStr(hashBestChain).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), (unsigned long)pindexNew->nChainTx,
1888 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1890 // Check the version of the last 100 blocks to see if we need to upgrade:
1891 if (!fIsInitialDownload)
1894 const CBlockIndex* pindex = pindexBest;
1895 for (int i = 0; i < 100 && pindex != NULL; i++)
1897 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1899 pindex = pindex->pprev;
1902 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1903 if (nUpgraded > 100/2)
1904 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1905 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1908 std::string strCmd = GetArg("-blocknotify", "");
1910 if (!fIsInitialDownload && !strCmd.empty())
1912 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1913 boost::thread t(runCommand, strCmd); // thread runs free
1920 bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
1922 // Check for duplicate
1923 uint256 hash = GetHash();
1924 if (mapBlockIndex.count(hash))
1925 return error("AddToBlockIndex() : %s already exists", BlockHashStr(hash).c_str());
1927 // Construct new block index object
1928 CBlockIndex* pindexNew = new CBlockIndex(*this);
1930 return error("AddToBlockIndex() : new CBlockIndex failed");
1931 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1932 pindexNew->phashBlock = &((*mi).first);
1933 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1934 if (miPrev != mapBlockIndex.end())
1936 pindexNew->pprev = (*miPrev).second;
1937 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1939 pindexNew->nTx = vtx.size();
1940 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1941 pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
1942 pindexNew->nFile = pos.nFile;
1943 pindexNew->nDataPos = pos.nPos;
1944 pindexNew->nUndoPos = 0;
1945 pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
1946 setBlockIndexValid.insert(pindexNew);
1948 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew));
1951 if (!ConnectBestBlock())
1954 if (pindexNew == pindexBest)
1956 // Notify UI to display prev block's coinbase if it was ours
1957 static uint256 hashPrevBestCoinBase;
1958 UpdatedTransaction(hashPrevBestCoinBase);
1959 hashPrevBestCoinBase = GetTxHash(0);
1962 pblocktree->Flush();
1964 uiInterface.NotifyBlocksChanged();
1969 bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown = false)
1971 bool fUpdatedLast = false;
1973 LOCK(cs_LastBlockFile);
1976 if (nLastBlockFile != pos.nFile) {
1977 nLastBlockFile = pos.nFile;
1978 infoLastBlockFile.SetNull();
1979 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile);
1980 fUpdatedLast = true;
1983 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
1984 printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
1987 infoLastBlockFile.SetNull();
1988 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
1989 fUpdatedLast = true;
1991 pos.nFile = nLastBlockFile;
1992 pos.nPos = infoLastBlockFile.nSize;
1995 infoLastBlockFile.nSize += nAddSize;
1996 infoLastBlockFile.AddBlock(nHeight, nTime);
1999 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2000 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2001 if (nNewChunks > nOldChunks) {
2002 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2003 FILE *file = OpenBlockFile(pos);
2005 printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2006 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2011 return error("FindBlockPos() : out of disk space");
2015 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2016 return error("FindBlockPos() : cannot write updated block info");
2018 pblocktree->WriteLastBlockFile(nLastBlockFile);
2023 bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2027 LOCK(cs_LastBlockFile);
2029 unsigned int nNewSize;
2030 if (nFile == nLastBlockFile) {
2031 pos.nPos = infoLastBlockFile.nUndoSize;
2032 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2033 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2034 return error("FindUndoPos() : cannot write updated block info");
2036 CBlockFileInfo info;
2037 if (!pblocktree->ReadBlockFileInfo(nFile, info))
2038 return error("FindUndoPos() : cannot read block info");
2039 pos.nPos = info.nUndoSize;
2040 nNewSize = (info.nUndoSize += nAddSize);
2041 if (!pblocktree->WriteBlockFileInfo(nFile, info))
2042 return error("FindUndoPos() : cannot write updated block info");
2045 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2046 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2047 if (nNewChunks > nOldChunks) {
2048 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2049 FILE *file = OpenUndoFile(pos);
2051 printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2052 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2057 return error("FindUndoPos() : out of disk space");
2064 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
2066 // These are checks that are independent of context
2067 // that can be verified before saving an orphan block.
2070 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2071 return DoS(100, error("CheckBlock() : size limits failed"));
2073 // Check proof of work matches claimed amount
2074 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2075 return DoS(50, error("CheckBlock() : proof of work failed"));
2078 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2079 return error("CheckBlock() : block timestamp too far in the future");
2081 // First transaction must be coinbase, the rest must not be
2082 if (vtx.empty() || !vtx[0].IsCoinBase())
2083 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2084 for (unsigned int i = 1; i < vtx.size(); i++)
2085 if (vtx[i].IsCoinBase())
2086 return DoS(100, error("CheckBlock() : more than one coinbase"));
2088 // Check transactions
2089 BOOST_FOREACH(const CTransaction& tx, vtx)
2090 if (!tx.CheckTransaction())
2091 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2093 // Build the merkle tree already. We need it anyway later, and it makes the
2094 // block cache the transaction hashes, which means they don't need to be
2095 // recalculated many times during this block's validation.
2098 // Check for duplicate txids. This is caught by ConnectInputs(),
2099 // but catching it earlier avoids a potential DoS attack:
2100 set<uint256> uniqueTx;
2101 for (unsigned int i=0; i<vtx.size(); i++) {
2102 uniqueTx.insert(GetTxHash(i));
2104 if (uniqueTx.size() != vtx.size())
2105 return DoS(100, error("CheckBlock() : duplicate transaction"));
2107 unsigned int nSigOps = 0;
2108 BOOST_FOREACH(const CTransaction& tx, vtx)
2110 nSigOps += tx.GetLegacySigOpCount();
2112 if (nSigOps > MAX_BLOCK_SIGOPS)
2113 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2115 // Check merkle root
2116 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2117 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2122 bool CBlock::AcceptBlock(CDiskBlockPos *dbp)
2124 // Check for duplicate
2125 uint256 hash = GetHash();
2126 if (mapBlockIndex.count(hash))
2127 return error("AcceptBlock() : block already in mapBlockIndex");
2129 // Get prev block index
2130 CBlockIndex* pindexPrev = NULL;
2132 if (hash != hashGenesisBlock) {
2133 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2134 if (mi == mapBlockIndex.end())
2135 return DoS(10, error("AcceptBlock() : prev block not found"));
2136 pindexPrev = (*mi).second;
2137 nHeight = pindexPrev->nHeight+1;
2139 // Check proof of work
2140 if (nBits != GetNextWorkRequired(pindexPrev, this))
2141 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
2143 // Check timestamp against prev
2144 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
2145 return error("AcceptBlock() : block's timestamp is too early");
2147 // Check that all transactions are finalized
2148 BOOST_FOREACH(const CTransaction& tx, vtx)
2149 if (!tx.IsFinal(nHeight, GetBlockTime()))
2150 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2152 // Check that the block chain matches the known block chain up to a checkpoint
2153 if (!Checkpoints::CheckBlock(nHeight, hash))
2154 return DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
2156 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2159 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
2160 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
2162 return error("AcceptBlock() : rejected nVersion=1 block");
2165 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2168 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2169 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
2170 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
2172 CScript expect = CScript() << nHeight;
2173 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2174 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2179 // Write block to history file
2180 unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
2181 CDiskBlockPos blockPos;
2184 if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, nTime, dbp != NULL))
2185 return error("AcceptBlock() : FindBlockPos failed");
2187 if (!WriteToDisk(blockPos))
2188 return error("AcceptBlock() : WriteToDisk failed");
2189 if (!AddToBlockIndex(blockPos))
2190 return error("AcceptBlock() : AddToBlockIndex failed");
2192 // Relay inventory, but don't relay old inventory during initial block download
2193 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2194 if (hashBestChain == hash)
2197 BOOST_FOREACH(CNode* pnode, vNodes)
2198 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2199 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2205 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2207 unsigned int nFound = 0;
2208 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2210 if (pstart->nVersion >= minVersion)
2212 pstart = pstart->pprev;
2214 return (nFound >= nRequired);
2217 bool ProcessBlock(CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2219 // Check for duplicate
2220 uint256 hash = pblock->GetHash();
2221 if (mapBlockIndex.count(hash))
2222 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, BlockHashStr(hash).c_str());
2223 if (mapOrphanBlocks.count(hash))
2224 return error("ProcessBlock() : already have block (orphan) %s", BlockHashStr(hash).c_str());
2226 // Preliminary checks
2227 if (!pblock->CheckBlock())
2228 return error("ProcessBlock() : CheckBlock FAILED");
2230 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
2231 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
2233 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2234 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2238 pfrom->Misbehaving(100);
2239 return error("ProcessBlock() : block with timestamp before last checkpoint");
2242 bnNewBlock.SetCompact(pblock->nBits);
2244 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
2245 if (bnNewBlock > bnRequired)
2248 pfrom->Misbehaving(100);
2249 return error("ProcessBlock() : block with too little proof-of-work");
2254 // If we don't already have its previous block, shunt it off to holding area until we get it
2255 if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
2257 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", BlockHashStr(pblock->hashPrevBlock).c_str());
2259 // Accept orphans as long as there is a node to request its parents from
2261 CBlock* pblock2 = new CBlock(*pblock);
2262 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2263 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2265 // Ask this guy to fill in what we're missing
2266 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2272 if (!pblock->AcceptBlock(dbp))
2273 return error("ProcessBlock() : AcceptBlock FAILED");
2275 // Recursively process any orphan blocks that depended on this one
2276 vector<uint256> vWorkQueue;
2277 vWorkQueue.push_back(hash);
2278 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2280 uint256 hashPrev = vWorkQueue[i];
2281 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2282 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2285 CBlock* pblockOrphan = (*mi).second;
2286 if (pblockOrphan->AcceptBlock())
2287 vWorkQueue.push_back(pblockOrphan->GetHash());
2288 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2289 delete pblockOrphan;
2291 mapOrphanBlocksByPrev.erase(hashPrev);
2294 printf("ProcessBlock: ACCEPTED\n");
2305 CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
2307 header = block.GetBlockHeader();
2309 vector<bool> vMatch;
2310 vector<uint256> vHashes;
2312 vMatch.reserve(block.vtx.size());
2313 vHashes.reserve(block.vtx.size());
2315 for (unsigned int i = 0; i < block.vtx.size(); i++)
2317 uint256 hash = block.vtx[i].GetHash();
2318 if (filter.IsRelevantAndUpdate(block.vtx[i], hash))
2320 vMatch.push_back(true);
2321 vMatchedTxn.push_back(make_pair(i, hash));
2324 vMatch.push_back(false);
2325 vHashes.push_back(hash);
2328 txn = CPartialMerkleTree(vHashes, vMatch);
2338 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
2340 // hash at height 0 is the txids themself
2343 // calculate left hash
2344 uint256 left = CalcHash(height-1, pos*2, vTxid), right;
2345 // calculate right hash if not beyong the end of the array - copy left hash otherwise1
2346 if (pos*2+1 < CalcTreeWidth(height-1))
2347 right = CalcHash(height-1, pos*2+1, vTxid);
2350 // combine subhashes
2351 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2355 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
2356 // determine whether this node is the parent of at least one matched txid
2357 bool fParentOfMatch = false;
2358 for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
2359 fParentOfMatch |= vMatch[p];
2360 // store as flag bit
2361 vBits.push_back(fParentOfMatch);
2362 if (height==0 || !fParentOfMatch) {
2363 // if at height 0, or nothing interesting below, store hash and stop
2364 vHash.push_back(CalcHash(height, pos, vTxid));
2366 // otherwise, don't store any hash, but descend into the subtrees
2367 TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
2368 if (pos*2+1 < CalcTreeWidth(height-1))
2369 TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
2373 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
2374 if (nBitsUsed >= vBits.size()) {
2375 // overflowed the bits array - failure
2379 bool fParentOfMatch = vBits[nBitsUsed++];
2380 if (height==0 || !fParentOfMatch) {
2381 // if at height 0, or nothing interesting below, use stored hash and do not descend
2382 if (nHashUsed >= vHash.size()) {
2383 // overflowed the hash array - failure
2387 const uint256 &hash = vHash[nHashUsed++];
2388 if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
2389 vMatch.push_back(hash);
2392 // otherwise, descend into the subtrees to extract matched txids and hashes
2393 uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
2394 if (pos*2+1 < CalcTreeWidth(height-1))
2395 right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
2398 // and combine them before returning
2399 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2403 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
2408 // calculate height of tree
2410 while (CalcTreeWidth(nHeight) > 1)
2413 // traverse the partial tree
2414 TraverseAndBuild(nHeight, 0, vTxid, vMatch);
2417 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
2419 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
2421 // An empty set will not work
2422 if (nTransactions == 0)
2424 // check for excessively high numbers of transactions
2425 if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
2427 // there can never be more hashes provided than one for every txid
2428 if (vHash.size() > nTransactions)
2430 // there must be at least one bit per node in the partial tree, and at least one node per hash
2431 if (vBits.size() < vHash.size())
2433 // calculate height of tree
2435 while (CalcTreeWidth(nHeight) > 1)
2437 // traverse the partial tree
2438 unsigned int nBitsUsed = 0, nHashUsed = 0;
2439 uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
2440 // verify that no problems occured during the tree traversal
2443 // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
2444 if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
2446 // verify that all hashes were consumed
2447 if (nHashUsed != vHash.size())
2449 return hashMerkleRoot;
2459 bool CheckDiskSpace(uint64 nAdditionalBytes)
2461 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2463 // Check for nMinDiskSpace bytes (currently 50MB)
2464 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2467 string strMessage = _("Error: Disk space is low!");
2468 strMiscWarning = strMessage;
2469 printf("*** %s\n", strMessage.c_str());
2470 uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR);
2477 CCriticalSection cs_LastBlockFile;
2478 CBlockFileInfo infoLastBlockFile;
2479 int nLastBlockFile = 0;
2481 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2485 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2486 boost::filesystem::create_directories(path.parent_path());
2487 FILE* file = fopen(path.string().c_str(), "rb+");
2488 if (!file && !fReadOnly)
2489 file = fopen(path.string().c_str(), "wb+");
2491 printf("Unable to open file %s\n", path.string().c_str());
2495 if (fseek(file, pos.nPos, SEEK_SET)) {
2496 printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2504 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2505 return OpenDiskFile(pos, "blk", fReadOnly);
2508 FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2509 return OpenDiskFile(pos, "rev", fReadOnly);
2512 CBlockIndex * InsertBlockIndex(uint256 hash)
2518 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2519 if (mi != mapBlockIndex.end())
2520 return (*mi).second;
2523 CBlockIndex* pindexNew = new CBlockIndex();
2525 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
2526 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2527 pindexNew->phashBlock = &((*mi).first);
2532 bool static LoadBlockIndexDB()
2534 if (!pblocktree->LoadBlockIndexGuts())
2537 if (fRequestShutdown)
2540 // Calculate bnChainWork
2541 vector<pair<int, CBlockIndex*> > vSortedByHeight;
2542 vSortedByHeight.reserve(mapBlockIndex.size());
2543 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2545 CBlockIndex* pindex = item.second;
2546 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2548 sort(vSortedByHeight.begin(), vSortedByHeight.end());
2549 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2551 CBlockIndex* pindex = item.second;
2552 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
2553 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2554 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
2555 setBlockIndexValid.insert(pindex);
2558 // Load block file info
2559 pblocktree->ReadLastBlockFile(nLastBlockFile);
2560 printf("LoadBlockIndex(): last block file = %i\n", nLastBlockFile);
2561 if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2562 printf("LoadBlockIndex(): last block file: %s\n", infoLastBlockFile.ToString().c_str());
2564 // Load bnBestInvalidWork, OK if it doesn't exist
2565 pblocktree->ReadBestInvalidWork(bnBestInvalidWork);
2567 // Check whether we need to continue reindexing
2568 bool fReindexing = false;
2569 pblocktree->ReadReindexing(fReindexing);
2570 fReindex |= fReindexing;
2572 // Check whether we have a transaction index
2573 pblocktree->ReadFlag("txindex", fTxIndex);
2574 printf("LoadBlockIndex(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
2576 // Load hashBestChain pointer to end of best chain
2577 pindexBest = pcoinsTip->GetBestBlock();
2578 if (pindexBest == NULL)
2580 hashBestChain = pindexBest->GetBlockHash();
2581 nBestHeight = pindexBest->nHeight;
2582 bnBestChainWork = pindexBest->bnChainWork;
2584 // set 'next' pointers in best chain
2585 CBlockIndex *pindex = pindexBest;
2586 while(pindex != NULL && pindex->pprev != NULL) {
2587 CBlockIndex *pindexPrev = pindex->pprev;
2588 pindexPrev->pnext = pindex;
2589 pindex = pindexPrev;
2591 printf("LoadBlockIndex(): hashBestChain=%s height=%d date=%s\n",
2592 BlockHashStr(hashBestChain).c_str(), nBestHeight,
2593 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2599 if (pindexBest == NULL || pindexBest->pprev == NULL)
2602 // Verify blocks in the best chain
2603 int nCheckLevel = GetArg("-checklevel", 3);
2604 int nCheckDepth = GetArg( "-checkblocks", 288);
2605 if (nCheckDepth == 0)
2606 nCheckDepth = 1000000000; // suffices until the year 19000
2607 if (nCheckDepth > nBestHeight)
2608 nCheckDepth = nBestHeight;
2609 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2610 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2611 CCoinsViewCache coins(*pcoinsTip, true);
2612 CBlockIndex* pindexState = pindexBest;
2613 CBlockIndex* pindexFailure = NULL;
2614 int nGoodTransactions = 0;
2615 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
2617 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
2620 // check level 0: read from disk
2621 if (!block.ReadFromDisk(pindex))
2622 return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2623 // check level 1: verify block validity
2624 if (nCheckLevel >= 1 && !block.CheckBlock())
2625 return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2626 // check level 2: verify undo validity
2627 if (nCheckLevel >= 2 && pindex) {
2629 CDiskBlockPos pos = pindex->GetUndoPos();
2630 if (!pos.IsNull()) {
2631 if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
2632 return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2635 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
2636 if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
2638 if (!block.DisconnectBlock(pindex, coins, &fClean))
2639 return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2640 pindexState = pindex->pprev;
2642 nGoodTransactions = 0;
2643 pindexFailure = pindex;
2645 nGoodTransactions += block.vtx.size();
2649 return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", pindexBest->nHeight - pindexFailure->nHeight + 1, nGoodTransactions);
2651 // check level 4: try reconnecting blocks
2652 if (nCheckLevel >= 4) {
2653 CBlockIndex *pindex = pindexState;
2654 while (pindex != pindexBest && !fRequestShutdown) {
2655 pindex = pindex->pnext;
2657 if (!block.ReadFromDisk(pindex))
2658 return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2659 if (!block.ConnectBlock(pindex, coins))
2660 return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2664 printf("No coin database inconsistencies in last %i blocks (%i transactions)\n", pindexBest->nHeight - pindexState->nHeight, nGoodTransactions);
2669 bool LoadBlockIndex()
2673 pchMessageStart[0] = 0x0b;
2674 pchMessageStart[1] = 0x11;
2675 pchMessageStart[2] = 0x09;
2676 pchMessageStart[3] = 0x07;
2677 hashGenesisBlock = uint256("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943");
2681 // Load block index from databases
2683 if (!fReindex && !LoadBlockIndexDB())
2687 // Init with genesis block
2689 if (mapBlockIndex.empty())
2691 fTxIndex = GetBoolArg("-txindex", false);
2692 pblocktree->WriteFlag("txindex", fTxIndex);
2693 printf("Initializing databases...\n");
2699 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
2700 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2701 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
2702 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
2703 // vMerkleTree: 4a5e1e
2706 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
2708 txNew.vin.resize(1);
2709 txNew.vout.resize(1);
2710 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2711 txNew.vout[0].nValue = 50 * COIN;
2712 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
2714 block.vtx.push_back(txNew);
2715 block.hashPrevBlock = 0;
2716 block.hashMerkleRoot = block.BuildMerkleTree();
2718 block.nTime = 1231006505;
2719 block.nBits = 0x1d00ffff;
2720 block.nNonce = 2083236893;
2724 block.nTime = 1296688602;
2725 block.nNonce = 414098458;
2729 uint256 hash = block.GetHash();
2730 printf("%s\n", hash.ToString().c_str());
2731 printf("%s\n", hashGenesisBlock.ToString().c_str());
2732 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
2733 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
2735 assert(hash == hashGenesisBlock);
2737 // Start new block file
2738 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2739 CDiskBlockPos blockPos;
2740 if (!FindBlockPos(blockPos, nBlockSize+8, 0, block.nTime))
2741 return error("AcceptBlock() : FindBlockPos failed");
2742 if (!block.WriteToDisk(blockPos))
2743 return error("LoadBlockIndex() : writing genesis block to disk failed");
2744 if (!block.AddToBlockIndex(blockPos))
2745 return error("LoadBlockIndex() : genesis block not accepted");
2753 void PrintBlockTree()
2755 // pre-compute tree structure
2756 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2757 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2759 CBlockIndex* pindex = (*mi).second;
2760 mapNext[pindex->pprev].push_back(pindex);
2762 //while (rand() % 3 == 0)
2763 // mapNext[pindex->pprev].push_back(pindex);
2766 vector<pair<int, CBlockIndex*> > vStack;
2767 vStack.push_back(make_pair(0, pindexGenesisBlock));
2770 while (!vStack.empty())
2772 int nCol = vStack.back().first;
2773 CBlockIndex* pindex = vStack.back().second;
2776 // print split or gap
2777 if (nCol > nPrevCol)
2779 for (int i = 0; i < nCol-1; i++)
2783 else if (nCol < nPrevCol)
2785 for (int i = 0; i < nCol; i++)
2792 for (int i = 0; i < nCol; i++)
2797 block.ReadFromDisk(pindex);
2798 printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
2800 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2801 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
2804 PrintWallets(block);
2806 // put the main time-chain first
2807 vector<CBlockIndex*>& vNext = mapNext[pindex];
2808 for (unsigned int i = 0; i < vNext.size(); i++)
2810 if (vNext[i]->pnext)
2812 swap(vNext[0], vNext[i]);
2818 for (unsigned int i = 0; i < vNext.size(); i++)
2819 vStack.push_back(make_pair(nCol+i, vNext[i]));
2823 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
2825 int64 nStart = GetTimeMillis();
2829 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
2830 uint64 nStartByte = 0;
2832 // (try to) skip already indexed part
2833 CBlockFileInfo info;
2834 if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) {
2835 nStartByte = info.nSize;
2836 blkdat.Seek(info.nSize);
2839 uint64 nRewind = blkdat.GetPos();
2840 while (blkdat.good() && !blkdat.eof() && !fRequestShutdown) {
2841 blkdat.SetPos(nRewind);
2842 nRewind++; // start one byte further next time, in case of failure
2843 blkdat.SetLimit(); // remove former limit
2844 unsigned int nSize = 0;
2847 unsigned char buf[4];
2848 blkdat.FindByte(pchMessageStart[0]);
2849 nRewind = blkdat.GetPos()+1;
2850 blkdat >> FLATDATA(buf);
2851 if (memcmp(buf, pchMessageStart, 4))
2855 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
2857 } catch (std::exception &e) {
2858 // no valid block header found; don't complain
2863 uint64 nBlockPos = blkdat.GetPos();
2864 blkdat.SetLimit(nBlockPos + nSize);
2867 nRewind = blkdat.GetPos();
2870 if (nBlockPos >= nStartByte) {
2873 dbp->nPos = nBlockPos;
2874 if (ProcessBlock(NULL, &block, dbp))
2877 } catch (std::exception &e) {
2878 printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__);
2884 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2897 //////////////////////////////////////////////////////////////////////////////
2902 extern map<uint256, CAlert> mapAlerts;
2903 extern CCriticalSection cs_mapAlerts;
2905 string GetWarnings(string strFor)
2908 string strStatusBar;
2911 if (GetBoolArg("-testsafemode"))
2914 if (!CLIENT_VERSION_IS_RELEASE)
2915 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
2917 // Misc warnings like out of disk space and clock is wrong
2918 if (strMiscWarning != "")
2921 strStatusBar = strMiscWarning;
2924 // Longer invalid proof-of-work chain
2925 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2928 strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");
2934 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2936 const CAlert& alert = item.second;
2937 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2939 nPriority = alert.nPriority;
2940 strStatusBar = alert.strStatusBar;
2945 if (strFor == "statusbar")
2946 return strStatusBar;
2947 else if (strFor == "rpc")
2949 assert(!"GetWarnings() : invalid parameter");
2960 //////////////////////////////////////////////////////////////////////////////
2966 bool static AlreadyHave(const CInv& inv)
2972 bool txInMap = false;
2975 txInMap = mempool.exists(inv.hash);
2977 return txInMap || mapOrphanTransactions.count(inv.hash) ||
2978 pcoinsTip->HaveCoins(inv.hash);
2981 return mapBlockIndex.count(inv.hash) ||
2982 mapOrphanBlocks.count(inv.hash);
2984 // Don't know what it is, just say we already got one
2991 // The message start string is designed to be unlikely to occur in normal data.
2992 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
2993 // a large 4-byte int at any alignment.
2994 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2997 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2999 RandAddSeedPerfmon();
3001 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3002 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3004 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3012 if (strCommand == "version")
3014 // Each connection can only send one version message
3015 if (pfrom->nVersion != 0)
3017 pfrom->Misbehaving(1);
3025 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3026 if (pfrom->nVersion < MIN_PROTO_VERSION)
3028 // Since February 20, 2012, the protocol is initiated at version 209,
3029 // and earlier versions are no longer supported
3030 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3031 pfrom->fDisconnect = true;
3035 if (pfrom->nVersion == 10300)
3036 pfrom->nVersion = 300;
3038 vRecv >> addrFrom >> nNonce;
3040 vRecv >> pfrom->strSubVer;
3042 vRecv >> pfrom->nStartingHeight;
3044 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3046 pfrom->fRelayTxes = true;
3048 if (pfrom->fInbound && addrMe.IsRoutable())
3050 pfrom->addrLocal = addrMe;
3054 // Disconnect if we connected to ourself
3055 if (nNonce == nLocalHostNonce && nNonce > 1)
3057 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3058 pfrom->fDisconnect = true;
3062 // Be shy and don't send version until we hear
3063 if (pfrom->fInbound)
3064 pfrom->PushVersion();
3066 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3068 AddTimeData(pfrom->addr, nTime);
3071 pfrom->PushMessage("verack");
3072 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3074 if (!pfrom->fInbound)
3076 // Advertise our address
3077 if (!fNoListen && !IsInitialBlockDownload())
3079 CAddress addr = GetLocalAddress(&pfrom->addr);
3080 if (addr.IsRoutable())
3081 pfrom->PushAddress(addr);
3084 // Get recent addresses
3085 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3087 pfrom->PushMessage("getaddr");
3088 pfrom->fGetAddr = true;
3090 addrman.Good(pfrom->addr);
3092 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3094 addrman.Add(addrFrom, addrFrom);
3095 addrman.Good(addrFrom);
3099 // Ask the first connected node for block updates
3100 static int nAskedForBlocks = 0;
3101 if (!pfrom->fClient && !pfrom->fOneShot && !fImporting && !fReindex &&
3102 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3103 (pfrom->nVersion < NOBLKS_VERSION_START ||
3104 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3105 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3108 pfrom->PushGetBlocks(pindexBest, uint256(0));
3114 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3115 item.second.RelayTo(pfrom);
3118 pfrom->fSuccessfullyConnected = true;
3120 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());
3122 cPeerBlockCounts.input(pfrom->nStartingHeight);
3126 else if (pfrom->nVersion == 0)
3128 // Must have a version message before anything else
3129 pfrom->Misbehaving(1);
3134 else if (strCommand == "verack")
3136 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3140 else if (strCommand == "addr")
3142 vector<CAddress> vAddr;
3145 // Don't want addr from older versions unless seeding
3146 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3148 if (vAddr.size() > 1000)
3150 pfrom->Misbehaving(20);
3151 return error("message addr size() = %"PRIszu"", vAddr.size());
3154 // Store the new addresses
3155 vector<CAddress> vAddrOk;
3156 int64 nNow = GetAdjustedTime();
3157 int64 nSince = nNow - 10 * 60;
3158 BOOST_FOREACH(CAddress& addr, vAddr)
3162 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3163 addr.nTime = nNow - 5 * 24 * 60 * 60;
3164 pfrom->AddAddressKnown(addr);
3165 bool fReachable = IsReachable(addr);
3166 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3168 // Relay to a limited number of other nodes
3171 // Use deterministic randomness to send to the same nodes for 24 hours
3172 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3173 static uint256 hashSalt;
3175 hashSalt = GetRandHash();
3176 uint64 hashAddr = addr.GetHash();
3177 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3178 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3179 multimap<uint256, CNode*> mapMix;
3180 BOOST_FOREACH(CNode* pnode, vNodes)
3182 if (pnode->nVersion < CADDR_TIME_VERSION)
3184 unsigned int nPointer;
3185 memcpy(&nPointer, &pnode, sizeof(nPointer));
3186 uint256 hashKey = hashRand ^ nPointer;
3187 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3188 mapMix.insert(make_pair(hashKey, pnode));
3190 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3191 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3192 ((*mi).second)->PushAddress(addr);
3195 // Do not store addresses outside our network
3197 vAddrOk.push_back(addr);
3199 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3200 if (vAddr.size() < 1000)
3201 pfrom->fGetAddr = false;
3202 if (pfrom->fOneShot)
3203 pfrom->fDisconnect = true;
3207 else if (strCommand == "inv")
3211 if (vInv.size() > MAX_INV_SZ)
3213 pfrom->Misbehaving(20);
3214 return error("message inv size() = %"PRIszu"", vInv.size());
3217 // find last block in inv vector
3218 unsigned int nLastBlock = (unsigned int)(-1);
3219 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3220 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3221 nLastBlock = vInv.size() - 1 - nInv;
3225 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3227 const CInv &inv = vInv[nInv];
3231 pfrom->AddInventoryKnown(inv);
3233 bool fAlreadyHave = AlreadyHave(inv);
3235 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3237 if (!fAlreadyHave) {
3238 if (!fImporting && !fReindex)
3240 } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3241 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3242 } else if (nInv == nLastBlock) {
3243 // In case we are on a very long side-chain, it is possible that we already have
3244 // the last block in an inv bundle sent in response to getblocks. Try to detect
3245 // this situation and push another getblocks to continue.
3246 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3248 printf("force request: %s\n", inv.ToString().c_str());
3251 // Track requests for our stuff
3252 Inventory(inv.hash);
3257 else if (strCommand == "getdata")
3261 if (vInv.size() > MAX_INV_SZ)
3263 pfrom->Misbehaving(20);
3264 return error("message getdata size() = %"PRIszu"", vInv.size());
3267 if (fDebugNet || (vInv.size() != 1))
3268 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3270 vector<CInv> vNotFound;
3271 BOOST_FOREACH(const CInv& inv, vInv)
3275 if (fDebugNet || (vInv.size() == 1))
3276 printf("received getdata for: %s\n", inv.ToString().c_str());
3278 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3280 // Send block from disk
3281 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3282 if (mi != mapBlockIndex.end())
3285 block.ReadFromDisk((*mi).second);
3286 if (inv.type == MSG_BLOCK)
3287 pfrom->PushMessage("block", block);
3288 else // MSG_FILTERED_BLOCK)
3290 LOCK(pfrom->cs_filter);
3293 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3294 pfrom->PushMessage("merkleblock", merkleBlock);
3295 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3296 // This avoids hurting performance by pointlessly requiring a round-trip
3297 // Note that there is currently no way for a node to request any single transactions we didnt send here -
3298 // they must either disconnect and retry or request the full block.
3299 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3300 // however we MUST always provide at least what the remote peer needs
3301 typedef std::pair<unsigned int, uint256> PairType;
3302 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3303 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3304 pfrom->PushMessage("tx", block.vtx[pair.first]);
3310 // Trigger them to send a getblocks request for the next batch of inventory
3311 if (inv.hash == pfrom->hashContinue)
3313 // Bypass PushInventory, this must send even if redundant,
3314 // and we want it right after the last block so they don't
3315 // wait for other stuff first.
3317 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
3318 pfrom->PushMessage("inv", vInv);
3319 pfrom->hashContinue = 0;
3323 else if (inv.IsKnownType())
3325 // Send stream from relay memory
3326 bool pushed = false;
3329 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3330 if (mi != mapRelay.end()) {
3331 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3335 if (!pushed && inv.type == MSG_TX) {
3337 if (mempool.exists(inv.hash)) {
3338 CTransaction tx = mempool.lookup(inv.hash);
3339 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3342 pfrom->PushMessage("tx", ss);
3347 vNotFound.push_back(inv);
3351 // Track requests for our stuff.
3352 Inventory(inv.hash);
3354 if (!vNotFound.empty()) {
3355 // Let the peer know that we didn't find what it asked for, so it doesn't
3356 // have to wait around forever. Currently only SPV clients actually care
3357 // about this message: it's needed when they are recursively walking the
3358 // dependencies of relevant unconfirmed transactions. SPV clients want to
3359 // do that because they want to know about (and store and rebroadcast and
3360 // risk analyze) the dependencies of transactions relevant to them, without
3361 // having to download the entire memory pool.
3362 pfrom->PushMessage("notfound", vNotFound);
3368 else if (strCommand == "getblocks")
3370 CBlockLocator locator;
3372 vRecv >> locator >> hashStop;
3374 // Find the last block the caller has in the main chain
3375 CBlockIndex* pindex = locator.GetBlockIndex();
3377 // Send the rest of the chain
3379 pindex = pindex->pnext;
3381 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), BlockHashStr(hashStop).c_str(), nLimit);
3382 for (; pindex; pindex = pindex->pnext)
3384 if (pindex->GetBlockHash() == hashStop)
3386 printf(" getblocks stopping at %d %s\n", pindex->nHeight, BlockHashStr(pindex->GetBlockHash()).c_str());
3389 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3392 // When this block is requested, we'll send an inv that'll make them
3393 // getblocks the next batch of inventory.
3394 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, BlockHashStr(pindex->GetBlockHash()).c_str());
3395 pfrom->hashContinue = pindex->GetBlockHash();
3402 else if (strCommand == "getheaders")
3404 CBlockLocator locator;
3406 vRecv >> locator >> hashStop;
3408 CBlockIndex* pindex = NULL;
3409 if (locator.IsNull())
3411 // If locator is null, return the hashStop block
3412 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3413 if (mi == mapBlockIndex.end())
3415 pindex = (*mi).second;
3419 // Find the last block the caller has in the main chain
3420 pindex = locator.GetBlockIndex();
3422 pindex = pindex->pnext;
3425 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3426 vector<CBlock> vHeaders;
3428 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), BlockHashStr(hashStop).c_str());
3429 for (; pindex; pindex = pindex->pnext)
3431 vHeaders.push_back(pindex->GetBlockHeader());
3432 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3435 pfrom->PushMessage("headers", vHeaders);
3439 else if (strCommand == "tx")
3441 vector<uint256> vWorkQueue;
3442 vector<uint256> vEraseQueue;
3443 CDataStream vMsg(vRecv);
3447 CInv inv(MSG_TX, tx.GetHash());
3448 pfrom->AddInventoryKnown(inv);
3450 bool fMissingInputs = false;
3451 if (tx.AcceptToMemoryPool(true, true, &fMissingInputs))
3453 RelayTransaction(tx, inv.hash, vMsg);
3454 mapAlreadyAskedFor.erase(inv);
3455 vWorkQueue.push_back(inv.hash);
3456 vEraseQueue.push_back(inv.hash);
3458 // Recursively process any orphan transactions that depended on this one
3459 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3461 uint256 hashPrev = vWorkQueue[i];
3462 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3463 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3466 const CDataStream& vMsg = *((*mi).second);
3468 CDataStream(vMsg) >> tx;
3469 CInv inv(MSG_TX, tx.GetHash());
3470 bool fMissingInputs2 = false;
3472 if (tx.AcceptToMemoryPool(true, true, &fMissingInputs2))
3474 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3475 RelayTransaction(tx, inv.hash, vMsg);
3476 mapAlreadyAskedFor.erase(inv);
3477 vWorkQueue.push_back(inv.hash);
3478 vEraseQueue.push_back(inv.hash);
3480 else if (!fMissingInputs2)
3482 // invalid or too-little-fee orphan
3483 vEraseQueue.push_back(inv.hash);
3484 printf(" removed orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3489 BOOST_FOREACH(uint256 hash, vEraseQueue)
3490 EraseOrphanTx(hash);
3492 else if (fMissingInputs)
3496 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3497 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3499 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3501 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3505 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
3510 printf("received block %s\n", BlockHashStr(block.GetHash()).c_str());
3513 CInv inv(MSG_BLOCK, block.GetHash());
3514 pfrom->AddInventoryKnown(inv);
3516 if (ProcessBlock(pfrom, &block))
3517 mapAlreadyAskedFor.erase(inv);
3518 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3522 else if (strCommand == "getaddr")
3524 pfrom->vAddrToSend.clear();
3525 vector<CAddress> vAddr = addrman.GetAddr();
3526 BOOST_FOREACH(const CAddress &addr, vAddr)
3527 pfrom->PushAddress(addr);
3531 else if (strCommand == "mempool")
3533 std::vector<uint256> vtxid;
3534 LOCK2(mempool.cs, pfrom->cs_filter);
3535 mempool.queryHashes(vtxid);
3537 BOOST_FOREACH(uint256& hash, vtxid) {
3538 CInv inv(MSG_TX, hash);
3539 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(mempool.lookup(hash), hash)) ||
3541 vInv.push_back(inv);
3542 if (vInv.size() == MAX_INV_SZ)
3545 if (vInv.size() > 0)
3546 pfrom->PushMessage("inv", vInv);
3550 else if (strCommand == "ping")
3552 if (pfrom->nVersion > BIP0031_VERSION)
3556 // Echo the message back with the nonce. This allows for two useful features:
3558 // 1) A remote node can quickly check if the connection is operational
3559 // 2) Remote nodes can measure the latency of the network thread. If this node
3560 // is overloaded it won't respond to pings quickly and the remote node can
3561 // avoid sending us more work, like chain download requests.
3563 // The nonce stops the remote getting confused between different pings: without
3564 // it, if the remote node sends a ping once per second and this node takes 5
3565 // seconds to respond to each, the 5th ping the remote sends would appear to
3566 // return very quickly.
3567 pfrom->PushMessage("pong", nonce);
3572 else if (strCommand == "alert")
3577 uint256 alertHash = alert.GetHash();
3578 if (pfrom->setKnown.count(alertHash) == 0)
3580 if (alert.ProcessAlert())
3583 pfrom->setKnown.insert(alertHash);
3586 BOOST_FOREACH(CNode* pnode, vNodes)
3587 alert.RelayTo(pnode);
3591 // Small DoS penalty so peers that send us lots of
3592 // duplicate/expired/invalid-signature/whatever alerts
3593 // eventually get banned.
3594 // This isn't a Misbehaving(100) (immediate ban) because the
3595 // peer might be an older or different implementation with
3596 // a different signature key, etc.
3597 pfrom->Misbehaving(10);
3603 else if (strCommand == "filterload")
3605 CBloomFilter filter;
3608 if (!filter.IsWithinSizeConstraints())
3609 // There is no excuse for sending a too-large filter
3610 pfrom->Misbehaving(100);
3613 LOCK(pfrom->cs_filter);
3614 delete pfrom->pfilter;
3615 pfrom->pfilter = new CBloomFilter(filter);
3617 pfrom->fRelayTxes = true;
3621 else if (strCommand == "filteradd")
3623 vector<unsigned char> vData;
3626 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
3627 // and thus, the maximum size any matched object can have) in a filteradd message
3628 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
3630 pfrom->Misbehaving(100);
3632 LOCK(pfrom->cs_filter);
3634 pfrom->pfilter->insert(vData);
3636 pfrom->Misbehaving(100);
3641 else if (strCommand == "filterclear")
3643 LOCK(pfrom->cs_filter);
3644 delete pfrom->pfilter;
3645 pfrom->pfilter = NULL;
3646 pfrom->fRelayTxes = true;
3652 // Ignore unknown commands for extensibility
3656 // Update the last seen time for this node's address
3657 if (pfrom->fNetworkNode)
3658 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3659 AddressCurrentlyConnected(pfrom->addr);
3665 bool ProcessMessages(CNode* pfrom)
3667 CDataStream& vRecv = pfrom->vRecv;
3671 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3675 // (4) message start
3684 // Don't bother if send buffer is too full to respond anyway
3685 if (pfrom->vSend.size() >= SendBufferSize())
3688 // Scan for message start
3689 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3690 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3691 if (vRecv.end() - pstart < nHeaderSize)
3693 if ((int)vRecv.size() > nHeaderSize)
3695 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3696 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3700 if (pstart - vRecv.begin() > 0)
3701 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3702 vRecv.erase(vRecv.begin(), pstart);
3705 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3710 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3713 string strCommand = hdr.GetCommand();
3716 unsigned int nMessageSize = hdr.nMessageSize;
3717 if (nMessageSize > MAX_SIZE)
3719 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3722 if (nMessageSize > vRecv.size())
3724 // Rewind and wait for rest of message
3725 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3730 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3731 unsigned int nChecksum = 0;
3732 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3733 if (nChecksum != hdr.nChecksum)
3735 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3736 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3740 // Copy message to its own buffer
3741 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3742 vRecv.ignore(nMessageSize);
3750 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3755 catch (std::ios_base::failure& e)
3757 if (strstr(e.what(), "end of data"))
3759 // Allow exceptions from under-length message on vRecv
3760 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());
3762 else if (strstr(e.what(), "size too large"))
3764 // Allow exceptions from over-long size
3765 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3769 PrintExceptionContinue(&e, "ProcessMessages()");
3772 catch (std::exception& e) {
3773 PrintExceptionContinue(&e, "ProcessMessages()");
3775 PrintExceptionContinue(NULL, "ProcessMessages()");
3779 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3787 bool SendMessages(CNode* pto, bool fSendTrickle)
3789 TRY_LOCK(cs_main, lockMain);
3791 // Don't send anything until we get their version message
3792 if (pto->nVersion == 0)
3795 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3797 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3799 if (pto->nVersion > BIP0031_VERSION)
3800 pto->PushMessage("ping", nonce);
3802 pto->PushMessage("ping");
3805 // Resend wallet transactions that haven't gotten in a block yet
3806 ResendWalletTransactions();
3808 // Address refresh broadcast
3809 static int64 nLastRebroadcast;
3810 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3814 BOOST_FOREACH(CNode* pnode, vNodes)
3816 // Periodically clear setAddrKnown to allow refresh broadcasts
3817 if (nLastRebroadcast)
3818 pnode->setAddrKnown.clear();
3820 // Rebroadcast our address
3823 CAddress addr = GetLocalAddress(&pnode->addr);
3824 if (addr.IsRoutable())
3825 pnode->PushAddress(addr);
3829 nLastRebroadcast = GetTime();
3837 vector<CAddress> vAddr;
3838 vAddr.reserve(pto->vAddrToSend.size());
3839 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3841 // returns true if wasn't already contained in the set
3842 if (pto->setAddrKnown.insert(addr).second)
3844 vAddr.push_back(addr);
3845 // receiver rejects addr messages larger than 1000
3846 if (vAddr.size() >= 1000)
3848 pto->PushMessage("addr", vAddr);
3853 pto->vAddrToSend.clear();
3855 pto->PushMessage("addr", vAddr);
3860 // Message: inventory
3863 vector<CInv> vInvWait;
3865 LOCK(pto->cs_inventory);
3866 vInv.reserve(pto->vInventoryToSend.size());
3867 vInvWait.reserve(pto->vInventoryToSend.size());
3868 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3870 if (pto->setInventoryKnown.count(inv))
3873 // trickle out tx inv to protect privacy
3874 if (inv.type == MSG_TX && !fSendTrickle)
3876 // 1/4 of tx invs blast to all immediately
3877 static uint256 hashSalt;
3879 hashSalt = GetRandHash();
3880 uint256 hashRand = inv.hash ^ hashSalt;
3881 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3882 bool fTrickleWait = ((hashRand & 3) != 0);
3884 // always trickle our own transactions
3888 if (GetTransaction(inv.hash, wtx))
3890 fTrickleWait = true;
3895 vInvWait.push_back(inv);
3900 // returns true if wasn't already contained in the set
3901 if (pto->setInventoryKnown.insert(inv).second)
3903 vInv.push_back(inv);
3904 if (vInv.size() >= 1000)
3906 pto->PushMessage("inv", vInv);
3911 pto->vInventoryToSend = vInvWait;
3914 pto->PushMessage("inv", vInv);
3920 vector<CInv> vGetData;
3921 int64 nNow = GetTime() * 1000000;
3922 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3924 const CInv& inv = (*pto->mapAskFor.begin()).second;
3925 if (!AlreadyHave(inv))
3928 printf("sending getdata: %s\n", inv.ToString().c_str());
3929 vGetData.push_back(inv);
3930 if (vGetData.size() >= 1000)
3932 pto->PushMessage("getdata", vGetData);
3935 mapAlreadyAskedFor[inv] = nNow;
3937 pto->mapAskFor.erase(pto->mapAskFor.begin());
3939 if (!vGetData.empty())
3940 pto->PushMessage("getdata", vGetData);
3959 //////////////////////////////////////////////////////////////////////////////
3964 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3966 unsigned char* pdata = (unsigned char*)pbuffer;
3967 unsigned int blocks = 1 + ((len + 8) / 64);
3968 unsigned char* pend = pdata + 64 * blocks;
3969 memset(pdata + len, 0, 64 * blocks - len);
3971 unsigned int bits = len * 8;
3972 pend[-1] = (bits >> 0) & 0xff;
3973 pend[-2] = (bits >> 8) & 0xff;
3974 pend[-3] = (bits >> 16) & 0xff;
3975 pend[-4] = (bits >> 24) & 0xff;
3979 static const unsigned int pSHA256InitState[8] =
3980 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3982 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3985 unsigned char data[64];
3989 for (int i = 0; i < 16; i++)
3990 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3992 for (int i = 0; i < 8; i++)
3993 ctx.h[i] = ((uint32_t*)pinit)[i];
3995 SHA256_Update(&ctx, data, sizeof(data));
3996 for (int i = 0; i < 8; i++)
3997 ((uint32_t*)pstate)[i] = ctx.h[i];
4001 // ScanHash scans nonces looking for a hash with at least some zero bits.
4002 // It operates on big endian data. Caller does the byte reversing.
4003 // All input buffers are 16-byte aligned. nNonce is usually preserved
4004 // between calls, but periodically or if nNonce is 0xffff0000 or above,
4005 // the block is rebuilt and nNonce starts over at zero.
4007 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
4009 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
4013 // Hash pdata using pmidstate as the starting state into
4014 // pre-formatted buffer phash1, then hash phash1 into phash
4016 SHA256Transform(phash1, pdata, pmidstate);
4017 SHA256Transform(phash, phash1, pSHA256InitState);
4019 // Return the nonce if the hash has at least some zero bits,
4020 // caller will check if it has enough to reach the target
4021 if (((unsigned short*)phash)[14] == 0)
4024 // If nothing found after trying for a while, return -1
4025 if ((nNonce & 0xffff) == 0)
4027 nHashesDone = 0xffff+1;
4028 return (unsigned int) -1;
4033 // Some explaining would be appreciated
4038 set<uint256> setDependsOn;
4042 COrphan(CTransaction* ptxIn)
4045 dPriority = dFeePerKb = 0;
4050 printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
4051 ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
4052 BOOST_FOREACH(uint256 hash, setDependsOn)
4053 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
4058 uint64 nLastBlockTx = 0;
4059 uint64 nLastBlockSize = 0;
4061 // We want to sort transactions by priority and fee, so:
4062 typedef boost::tuple<double, double, CTransaction*> TxPriority;
4063 class TxPriorityCompare
4067 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
4068 bool operator()(const TxPriority& a, const TxPriority& b)
4072 if (a.get<1>() == b.get<1>())
4073 return a.get<0>() < b.get<0>();
4074 return a.get<1>() < b.get<1>();
4078 if (a.get<0>() == b.get<0>())
4079 return a.get<1>() < b.get<1>();
4080 return a.get<0>() < b.get<0>();
4085 CBlockTemplate* CreateNewBlock(CReserveKey& reservekey)
4088 auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
4089 if(!pblocktemplate.get())
4091 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
4093 // Create coinbase tx
4095 txNew.vin.resize(1);
4096 txNew.vin[0].prevout.SetNull();
4097 txNew.vout.resize(1);
4098 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
4100 // Add our coinbase tx as first transaction
4101 pblock->vtx.push_back(txNew);
4102 pblocktemplate->vTxFees.push_back(-1); // updated at end
4103 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
4105 // Largest block you're willing to create:
4106 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
4107 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
4108 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
4110 // How much of the block should be dedicated to high-priority transactions,
4111 // included regardless of the fees they pay
4112 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
4113 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
4115 // Minimum block size you want to create; block will be filled with free transactions
4116 // until there are no more or the block reaches this size:
4117 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
4118 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
4120 // Fee-per-kilobyte amount considered the same as "free"
4121 // Be careful setting this: if you set it to zero then
4122 // a transaction spammer can cheaply fill blocks using
4123 // 1-satoshi-fee transactions. It should be set above the real
4124 // cost to you of processing a transaction.
4125 int64 nMinTxFee = MIN_TX_FEE;
4126 if (mapArgs.count("-mintxfee"))
4127 ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
4129 // Collect memory pool transactions into the block
4132 LOCK2(cs_main, mempool.cs);
4133 CBlockIndex* pindexPrev = pindexBest;
4134 CCoinsViewCache view(*pcoinsTip, true);
4136 // Priority order to process transactions
4137 list<COrphan> vOrphan; // list memory doesn't move
4138 map<uint256, vector<COrphan*> > mapDependers;
4139 bool fPrintPriority = GetBoolArg("-printpriority");
4141 // This vector will be sorted into a priority queue:
4142 vector<TxPriority> vecPriority;
4143 vecPriority.reserve(mempool.mapTx.size());
4144 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
4146 CTransaction& tx = (*mi).second;
4147 if (tx.IsCoinBase() || !tx.IsFinal())
4150 COrphan* porphan = NULL;
4151 double dPriority = 0;
4153 bool fMissingInputs = false;
4154 BOOST_FOREACH(const CTxIn& txin, tx.vin)
4156 // Read prev transaction
4158 if (!view.GetCoins(txin.prevout.hash, coins))
4160 // This should never happen; all transactions in the memory
4161 // pool should connect to either transactions in the chain
4162 // or other transactions in the memory pool.
4163 if (!mempool.mapTx.count(txin.prevout.hash))
4165 printf("ERROR: mempool transaction missing input\n");
4166 if (fDebug) assert("mempool transaction missing input" == 0);
4167 fMissingInputs = true;
4173 // Has to wait for dependencies
4176 // Use list for automatic deletion
4177 vOrphan.push_back(COrphan(&tx));
4178 porphan = &vOrphan.back();
4180 mapDependers[txin.prevout.hash].push_back(porphan);
4181 porphan->setDependsOn.insert(txin.prevout.hash);
4182 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
4186 int64 nValueIn = coins.vout[txin.prevout.n].nValue;
4187 nTotalIn += nValueIn;
4189 int nConf = pindexPrev->nHeight - coins.nHeight + 1;
4191 dPriority += (double)nValueIn * nConf;
4193 if (fMissingInputs) continue;
4195 // Priority is sum(valuein * age) / txsize
4196 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4197 dPriority /= nTxSize;
4199 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
4200 // client code rounds up the size to the nearest 1K. That's good, because it gives an
4201 // incentive to create smaller transactions.
4202 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
4206 porphan->dPriority = dPriority;
4207 porphan->dFeePerKb = dFeePerKb;
4210 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
4213 // Collect transactions into block
4214 uint64 nBlockSize = 1000;
4215 uint64 nBlockTx = 0;
4216 int nBlockSigOps = 100;
4217 bool fSortedByFee = (nBlockPrioritySize <= 0);
4219 TxPriorityCompare comparer(fSortedByFee);
4220 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4222 while (!vecPriority.empty())
4224 // Take highest priority transaction off the priority queue:
4225 double dPriority = vecPriority.front().get<0>();
4226 double dFeePerKb = vecPriority.front().get<1>();
4227 CTransaction& tx = *(vecPriority.front().get<2>());
4229 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
4230 vecPriority.pop_back();
4232 // second layer cached modifications just for this transaction
4233 CCoinsViewCache viewTemp(view, true);
4236 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4237 if (nBlockSize + nTxSize >= nBlockMaxSize)
4240 // Legacy limits on sigOps:
4241 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
4242 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4245 // Skip free transactions if we're past the minimum block size:
4246 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
4249 // Prioritize by fee once past the priority size or we run out of high-priority
4251 if (!fSortedByFee &&
4252 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
4254 fSortedByFee = true;
4255 comparer = TxPriorityCompare(fSortedByFee);
4256 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4259 if (!tx.HaveInputs(viewTemp))
4262 int64 nTxFees = tx.GetValueIn(viewTemp)-tx.GetValueOut();
4264 nTxSigOps += tx.GetP2SHSigOpCount(viewTemp);
4265 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4268 if (!tx.CheckInputs(viewTemp, true, SCRIPT_VERIFY_P2SH))
4272 uint256 hash = tx.GetHash();
4273 if (!tx.UpdateCoins(viewTemp, txundo, pindexPrev->nHeight+1, hash))
4276 // push changes from the second layer cache to the first one
4280 pblock->vtx.push_back(tx);
4281 pblocktemplate->vTxFees.push_back(nTxFees);
4282 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
4283 nBlockSize += nTxSize;
4285 nBlockSigOps += nTxSigOps;
4290 printf("priority %.1f feeperkb %.1f txid %s\n",
4291 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
4294 // Add transactions that depend on this one to the priority queue
4295 if (mapDependers.count(hash))
4297 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
4299 if (!porphan->setDependsOn.empty())
4301 porphan->setDependsOn.erase(hash);
4302 if (porphan->setDependsOn.empty())
4304 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
4305 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
4312 nLastBlockTx = nBlockTx;
4313 nLastBlockSize = nBlockSize;
4314 printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
4316 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
4317 pblocktemplate->vTxFees[0] = -nFees;
4320 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
4321 pblock->UpdateTime(pindexPrev);
4322 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
4324 pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
4325 pblocktemplate->vTxSigOps[0] = pblock->vtx[0].GetLegacySigOpCount();
4327 CBlockIndex indexDummy(*pblock);
4328 indexDummy.pprev = pindexPrev;
4329 indexDummy.nHeight = pindexPrev->nHeight + 1;
4330 CCoinsViewCache viewNew(*pcoinsTip, true);
4331 if (!pblock->ConnectBlock(&indexDummy, viewNew, true))
4332 throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
4335 return pblocktemplate.release();
4339 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
4341 // Update nExtraNonce
4342 static uint256 hashPrevBlock;
4343 if (hashPrevBlock != pblock->hashPrevBlock)
4346 hashPrevBlock = pblock->hashPrevBlock;
4349 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4350 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4351 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
4353 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
4357 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
4360 // Pre-build hash buffers
4367 uint256 hashPrevBlock;
4368 uint256 hashMerkleRoot;
4371 unsigned int nNonce;
4374 unsigned char pchPadding0[64];
4376 unsigned char pchPadding1[64];
4379 memset(&tmp, 0, sizeof(tmp));
4381 tmp.block.nVersion = pblock->nVersion;
4382 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
4383 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
4384 tmp.block.nTime = pblock->nTime;
4385 tmp.block.nBits = pblock->nBits;
4386 tmp.block.nNonce = pblock->nNonce;
4388 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
4389 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
4391 // Byte swap all the input buffer
4392 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
4393 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
4395 // Precalc the first half of the first hash, which stays constant
4396 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
4398 memcpy(pdata, &tmp.block, 128);
4399 memcpy(phash1, &tmp.hash1, 64);
4403 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
4405 uint256 hash = pblock->GetHash();
4406 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4408 if (hash > hashTarget)
4412 printf("BitcoinMiner:\n");
4413 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
4415 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
4420 if (pblock->hashPrevBlock != hashBestChain)
4421 return error("BitcoinMiner : generated block is stale");
4423 // Remove key from key pool
4424 reservekey.KeepKey();
4426 // Track how many getdata requests this block gets
4428 LOCK(wallet.cs_wallet);
4429 wallet.mapRequestCount[pblock->GetHash()] = 0;
4432 // Process this block the same as if we had received it from another node
4433 if (!ProcessBlock(NULL, pblock))
4434 return error("BitcoinMiner : ProcessBlock, block not accepted");
4440 void static ThreadBitcoinMiner(void* parg);
4442 static bool fGenerateBitcoins = false;
4443 static bool fLimitProcessors = false;
4444 static int nLimitProcessors = -1;
4446 void static BitcoinMiner(CWallet *pwallet)
4448 printf("BitcoinMiner started\n");
4449 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4451 // Make this thread recognisable as the mining thread
4452 RenameThread("bitcoin-miner");
4454 // Each thread has its own key and counter
4455 CReserveKey reservekey(pwallet);
4456 unsigned int nExtraNonce = 0;
4458 while (fGenerateBitcoins)
4462 while (vNodes.empty() || IsInitialBlockDownload())
4467 if (!fGenerateBitcoins)
4475 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
4476 CBlockIndex* pindexPrev = pindexBest;
4478 auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(reservekey));
4479 if (!pblocktemplate.get())
4481 CBlock *pblock = &pblocktemplate->block;
4482 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
4484 printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
4485 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
4489 // Pre-build hash buffers
4491 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
4492 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
4493 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
4495 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
4497 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
4498 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
4499 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
4505 int64 nStart = GetTime();
4506 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4508 uint256& hash = *alignup<16>(hashbuf);
4511 unsigned int nHashesDone = 0;
4512 unsigned int nNonceFound;
4515 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
4516 (char*)&hash, nHashesDone);
4518 // Check if something found
4519 if (nNonceFound != (unsigned int) -1)
4521 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
4522 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
4524 if (hash <= hashTarget)
4527 pblock->nNonce = ByteReverse(nNonceFound);
4528 assert(hash == pblock->GetHash());
4530 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4531 CheckWork(pblock, *pwalletMain, reservekey);
4532 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4538 static int64 nHashCounter;
4539 if (nHPSTimerStart == 0)
4541 nHPSTimerStart = GetTimeMillis();
4545 nHashCounter += nHashesDone;
4546 if (GetTimeMillis() - nHPSTimerStart > 4000)
4548 static CCriticalSection cs;
4551 if (GetTimeMillis() - nHPSTimerStart > 4000)
4553 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
4554 nHPSTimerStart = GetTimeMillis();
4556 static int64 nLogTime;
4557 if (GetTime() - nLogTime > 30 * 60)
4559 nLogTime = GetTime();
4560 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
4566 // Check for stop or if block needs to be rebuilt
4569 if (!fGenerateBitcoins)
4571 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4575 if (nBlockNonce >= 0xffff0000)
4577 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4579 if (pindexPrev != pindexBest)
4582 // Update nTime every few seconds
4583 pblock->UpdateTime(pindexPrev);
4584 nBlockTime = ByteReverse(pblock->nTime);
4587 // Changing pblock->nTime can change work required on testnet:
4588 nBlockBits = ByteReverse(pblock->nBits);
4589 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4595 void static ThreadBitcoinMiner(void* parg)
4597 CWallet* pwallet = (CWallet*)parg;
4600 vnThreadsRunning[THREAD_MINER]++;
4601 BitcoinMiner(pwallet);
4602 vnThreadsRunning[THREAD_MINER]--;
4604 catch (std::exception& e) {
4605 vnThreadsRunning[THREAD_MINER]--;
4606 PrintException(&e, "ThreadBitcoinMiner()");
4608 vnThreadsRunning[THREAD_MINER]--;
4609 PrintException(NULL, "ThreadBitcoinMiner()");
4612 if (vnThreadsRunning[THREAD_MINER] == 0)
4614 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4618 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4620 fGenerateBitcoins = fGenerate;
4621 nLimitProcessors = GetArg("-genproclimit", -1);
4622 if (nLimitProcessors == 0)
4623 fGenerateBitcoins = false;
4624 fLimitProcessors = (nLimitProcessors != -1);
4628 int nProcessors = boost::thread::hardware_concurrency();
4629 printf("%d processors\n", nProcessors);
4630 if (nProcessors < 1)
4632 if (fLimitProcessors && nProcessors > nLimitProcessors)
4633 nProcessors = nLimitProcessors;
4634 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4635 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4636 for (int i = 0; i < nAddThreads; i++)
4638 if (!NewThread(ThreadBitcoinMiner, pwallet))
4639 printf("Error: NewThread(ThreadBitcoinMiner) failed\n");
4645 // Amount compression:
4646 // * If the amount is 0, output 0
4647 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
4648 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
4649 // * call the result n
4650 // * output 1 + 10*(9*n + d - 1) + e
4651 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
4652 // (this is decodable, as d is in [1-9] and e is in [0-9])
4654 uint64 CTxOutCompressor::CompressAmount(uint64 n)
4659 while (((n % 10) == 0) && e < 9) {
4665 assert(d >= 1 && d <= 9);
4667 return 1 + (n*9 + d - 1)*10 + e;
4669 return 1 + (n - 1)*10 + 9;
4673 uint64 CTxOutCompressor::DecompressAmount(uint64 x)
4675 // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
4679 // x = 10*(9*n + d - 1) + e
4685 int d = (x % 9) + 1;