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 unsigned int nCoinCacheSize = 5000;
50 CMedianFilter<int> cPeerBlockCounts(8, 0); // Amount of blocks that other nodes claim to have
52 map<uint256, CBlock*> mapOrphanBlocks;
53 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
55 map<uint256, CDataStream*> mapOrphanTransactions;
56 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
58 // Constant stuff for coinbase transactions we create:
59 CScript COINBASE_FLAGS;
61 const string strMessageMagic = "Bitcoin Signed Message:\n";
67 int64 nTransactionFee = 0;
71 //////////////////////////////////////////////////////////////////////////////
73 // dispatching functions
76 // These functions dispatch to one or all registered wallets
79 void RegisterWallet(CWallet* pwalletIn)
82 LOCK(cs_setpwalletRegistered);
83 setpwalletRegistered.insert(pwalletIn);
87 void UnregisterWallet(CWallet* pwalletIn)
90 LOCK(cs_setpwalletRegistered);
91 setpwalletRegistered.erase(pwalletIn);
95 // check whether the passed transaction is from us
96 bool static IsFromMe(CTransaction& tx)
98 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
99 if (pwallet->IsFromMe(tx))
104 // get the wallet transaction with the given hash (if it exists)
105 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
107 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
108 if (pwallet->GetTransaction(hashTx,wtx))
113 // erases transaction with the given hash from all wallets
114 void static EraseFromWallets(uint256 hash)
116 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
117 pwallet->EraseFromWallet(hash);
120 // make sure all wallets know about the given transaction, in the given block
121 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate)
123 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
124 pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
127 // notify wallets about a new best chain
128 void static SetBestChain(const CBlockLocator& loc)
130 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
131 pwallet->SetBestChain(loc);
134 // notify wallets about an updated transaction
135 void static UpdatedTransaction(const uint256& hashTx)
137 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
138 pwallet->UpdatedTransaction(hashTx);
142 void static PrintWallets(const CBlock& block)
144 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
145 pwallet->PrintWallet(block);
148 // notify wallets about an incoming inventory (for request counts)
149 void static Inventory(const uint256& hash)
151 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
152 pwallet->Inventory(hash);
155 // ask wallets to resend their transactions
156 void static ResendWalletTransactions()
158 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
159 pwallet->ResendWalletTransactions();
168 //////////////////////////////////////////////////////////////////////////////
170 // CCoinsView implementations
173 bool CCoinsView::GetCoins(uint256 txid, CCoins &coins) { return false; }
174 bool CCoinsView::SetCoins(uint256 txid, const CCoins &coins) { return false; }
175 bool CCoinsView::HaveCoins(uint256 txid) { return false; }
176 CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
177 bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
178 bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
179 bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
182 CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
183 bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); }
184 bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
185 bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); }
186 CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
187 bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
188 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
189 bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
190 bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); }
192 CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
194 bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) {
195 if (cacheCoins.count(txid)) {
196 coins = cacheCoins[txid];
199 if (base->GetCoins(txid, coins)) {
200 cacheCoins[txid] = coins;
206 std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(uint256 txid) {
207 std::map<uint256,CCoins>::iterator it = cacheCoins.find(txid);
208 if (it != cacheCoins.end())
211 if (!base->GetCoins(txid,tmp))
213 std::pair<std::map<uint256,CCoins>::iterator,bool> ret = cacheCoins.insert(std::make_pair(txid, tmp));
217 CCoins &CCoinsViewCache::GetCoins(uint256 txid) {
218 std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
219 assert(it != cacheCoins.end());
223 bool CCoinsViewCache::SetCoins(uint256 txid, const CCoins &coins) {
224 cacheCoins[txid] = coins;
228 bool CCoinsViewCache::HaveCoins(uint256 txid) {
229 return FetchCoins(txid) != cacheCoins.end();
232 CBlockIndex *CCoinsViewCache::GetBestBlock() {
233 if (pindexTip == NULL)
234 pindexTip = base->GetBestBlock();
238 bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
243 bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
244 for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
245 cacheCoins[it->first] = it->second;
250 bool CCoinsViewCache::Flush() {
251 bool fOk = base->BatchWrite(cacheCoins, pindexTip);
257 unsigned int CCoinsViewCache::GetCacheSize() {
258 return cacheCoins.size();
261 /** CCoinsView that brings transactions from a memorypool into view.
262 It does not check for spendings by memory pool transactions. */
263 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
265 bool CCoinsViewMemPool::GetCoins(uint256 txid, CCoins &coins) {
266 if (base->GetCoins(txid, coins))
268 if (mempool.exists(txid)) {
269 const CTransaction &tx = mempool.lookup(txid);
270 coins = CCoins(tx, MEMPOOL_HEIGHT);
276 bool CCoinsViewMemPool::HaveCoins(uint256 txid) {
277 return mempool.exists(txid) || base->HaveCoins(txid);
280 CCoinsViewCache *pcoinsTip = NULL;
281 CBlockTreeDB *pblocktree = NULL;
283 //////////////////////////////////////////////////////////////////////////////
285 // mapOrphanTransactions
288 bool AddOrphanTx(const CDataStream& vMsg)
291 CDataStream(vMsg) >> tx;
292 uint256 hash = tx.GetHash();
293 if (mapOrphanTransactions.count(hash))
296 CDataStream* pvMsg = new CDataStream(vMsg);
298 // Ignore big transactions, to avoid a
299 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
300 // large transaction with a missing parent then we assume
301 // it will rebroadcast it later, after the parent transaction(s)
302 // have been mined or received.
303 // 10,000 orphans, each of which is at most 5,000 bytes big is
304 // at most 500 megabytes of orphans:
305 if (pvMsg->size() > 5000)
307 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
312 mapOrphanTransactions[hash] = pvMsg;
313 BOOST_FOREACH(const CTxIn& txin, tx.vin)
314 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
316 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
317 mapOrphanTransactions.size());
321 void static EraseOrphanTx(uint256 hash)
323 if (!mapOrphanTransactions.count(hash))
325 const CDataStream* pvMsg = mapOrphanTransactions[hash];
327 CDataStream(*pvMsg) >> tx;
328 BOOST_FOREACH(const CTxIn& txin, tx.vin)
330 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
331 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
332 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
335 mapOrphanTransactions.erase(hash);
338 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
340 unsigned int nEvicted = 0;
341 while (mapOrphanTransactions.size() > nMaxOrphans)
343 // Evict a random orphan:
344 uint256 randomhash = GetRandHash();
345 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
346 if (it == mapOrphanTransactions.end())
347 it = mapOrphanTransactions.begin();
348 EraseOrphanTx(it->first);
360 //////////////////////////////////////////////////////////////////////////////
365 bool CTransaction::IsStandard() const
367 if (nVersion > CTransaction::CURRENT_VERSION)
370 BOOST_FOREACH(const CTxIn& txin, vin)
372 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
373 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
374 // ~65-byte public keys, plus a few script ops.
375 if (txin.scriptSig.size() > 500)
377 if (!txin.scriptSig.IsPushOnly())
380 BOOST_FOREACH(const CTxOut& txout, vout) {
381 if (!::IsStandard(txout.scriptPubKey))
383 if (txout.nValue == 0)
390 // Check transaction inputs, and make sure any
391 // pay-to-script-hash transactions are evaluating IsStandard scripts
393 // Why bother? To avoid denial-of-service attacks; an attacker
394 // can submit a standard HASH... OP_EQUAL transaction,
395 // which will get accepted into blocks. The redemption
396 // script can be anything; an attacker could use a very
397 // expensive-to-check-upon-redemption script like:
398 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
400 bool CTransaction::AreInputsStandard(CCoinsViewCache& mapInputs) const
403 return true; // Coinbases don't use vin normally
405 for (unsigned int i = 0; i < vin.size(); i++)
407 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
409 vector<vector<unsigned char> > vSolutions;
410 txnouttype whichType;
411 // get the scriptPubKey corresponding to this input:
412 const CScript& prevScript = prev.scriptPubKey;
413 if (!Solver(prevScript, whichType, vSolutions))
415 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
416 if (nArgsExpected < 0)
419 // Transactions with extra stuff in their scriptSigs are
420 // non-standard. Note that this EvalScript() call will
421 // be quick, because if there are any operations
422 // beside "push data" in the scriptSig the
423 // IsStandard() call returns false
424 vector<vector<unsigned char> > stack;
425 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
428 if (whichType == TX_SCRIPTHASH)
432 CScript subscript(stack.back().begin(), stack.back().end());
433 vector<vector<unsigned char> > vSolutions2;
434 txnouttype whichType2;
435 if (!Solver(subscript, whichType2, vSolutions2))
437 if (whichType2 == TX_SCRIPTHASH)
441 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
444 nArgsExpected += tmpExpected;
447 if (stack.size() != (unsigned int)nArgsExpected)
455 CTransaction::GetLegacySigOpCount() const
457 unsigned int nSigOps = 0;
458 BOOST_FOREACH(const CTxIn& txin, vin)
460 nSigOps += txin.scriptSig.GetSigOpCount(false);
462 BOOST_FOREACH(const CTxOut& txout, vout)
464 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
470 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
474 if (pblock == NULL) {
476 if (pcoinsTip->GetCoins(GetHash(), coins)) {
477 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
479 if (!blockTmp.ReadFromDisk(pindex))
487 // Update the tx's hashBlock
488 hashBlock = pblock->GetHash();
490 // Locate the transaction
491 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
492 if (pblock->vtx[nIndex] == *(CTransaction*)this)
494 if (nIndex == (int)pblock->vtx.size())
496 vMerkleBranch.clear();
498 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
502 // Fill in merkle branch
503 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
506 // Is the tx in a block that's in the main chain
507 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
508 if (mi == mapBlockIndex.end())
510 CBlockIndex* pindex = (*mi).second;
511 if (!pindex || !pindex->IsInMainChain())
514 return pindexBest->nHeight - pindex->nHeight + 1;
523 bool CTransaction::CheckTransaction() const
525 // Basic checks that don't depend on any context
527 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
529 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
531 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
532 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
534 // Check for negative or overflow output values
536 BOOST_FOREACH(const CTxOut& txout, vout)
538 if (txout.nValue < 0)
539 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
540 if (txout.nValue > MAX_MONEY)
541 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
542 nValueOut += txout.nValue;
543 if (!MoneyRange(nValueOut))
544 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
547 // Check for duplicate inputs
548 set<COutPoint> vInOutPoints;
549 BOOST_FOREACH(const CTxIn& txin, vin)
551 if (vInOutPoints.count(txin.prevout))
553 vInOutPoints.insert(txin.prevout);
558 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
559 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
563 BOOST_FOREACH(const CTxIn& txin, vin)
564 if (txin.prevout.IsNull())
565 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
571 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
572 enum GetMinFee_mode mode) const
574 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
575 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
577 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
578 unsigned int nNewBlockSize = nBlockSize + nBytes;
579 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
585 // Transactions under 10K are free
586 // (about 4500 BTC if made of 50 BTC inputs)
592 // Free transaction area
593 if (nNewBlockSize < 27000)
598 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
599 if (nMinFee < nBaseFee)
601 BOOST_FOREACH(const CTxOut& txout, vout)
602 if (txout.nValue < CENT)
606 // Raise the price as the block approaches full
607 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
609 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
611 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
614 if (!MoneyRange(nMinFee))
619 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
623 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
625 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
626 while (it != mapNextTx.end() && it->first.hash == hashTx) {
627 coins.Spend(it->first.n); // and remove those outputs from coins
632 bool CTxMemPool::accept(CTransaction &tx, bool fCheckInputs,
633 bool* pfMissingInputs)
636 *pfMissingInputs = false;
638 if (!tx.CheckTransaction())
639 return error("CTxMemPool::accept() : CheckTransaction failed");
641 // Coinbase is only valid in a block, not as a loose transaction
643 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
645 // To help v0.1.5 clients who would see it as a negative number
646 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
647 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
649 // Rather not work on nonstandard transactions (unless -testnet)
650 if (!fTestNet && !tx.IsStandard())
651 return error("CTxMemPool::accept() : nonstandard transaction type");
653 // is it already in the memory pool?
654 uint256 hash = tx.GetHash();
657 if (mapTx.count(hash))
661 // Check for conflicts with in-memory transactions
662 CTransaction* ptxOld = NULL;
663 for (unsigned int i = 0; i < tx.vin.size(); i++)
665 COutPoint outpoint = tx.vin[i].prevout;
666 if (mapNextTx.count(outpoint))
668 // Disable replacement feature for now
671 // Allow replacing with a newer version of the same transaction
674 ptxOld = mapNextTx[outpoint].ptx;
675 if (ptxOld->IsFinal())
677 if (!tx.IsNewerThan(*ptxOld))
679 for (unsigned int i = 0; i < tx.vin.size(); i++)
681 COutPoint outpoint = tx.vin[i].prevout;
682 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
692 CCoinsViewCache view(dummy);
696 CCoinsViewMemPool viewMemPool(*pcoinsTip, *this);
697 view.SetBackend(viewMemPool);
699 // do we already have it?
700 if (view.HaveCoins(hash))
703 // do all inputs exist?
704 // Note that this does not check for the presence of actual outputs (see the next check for that),
705 // only helps filling in pfMissingInputs (to determine missing vs spent).
706 BOOST_FOREACH(const CTxIn txin, tx.vin) {
707 if (!view.HaveCoins(txin.prevout.hash)) {
709 *pfMissingInputs = true;
714 // are the actual inputs available?
715 if (!tx.HaveInputs(view))
716 return error("CTxMemPool::accept() : inputs already spent");
718 // Bring the best block into scope
721 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
722 view.SetBackend(dummy);
725 // Check for non-standard pay-to-script-hash in inputs
726 if (!tx.AreInputsStandard(view) && !fTestNet)
727 return error("CTxMemPool::accept() : nonstandard transaction input");
729 // Note: if you modify this code to accept non-standard transactions, then
730 // you should add code here to check that the transaction does a
731 // reasonable number of ECDSA signature verifications.
733 int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
734 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
736 // Don't accept it if it can't get into a block
737 int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
738 if (nFees < txMinFee)
739 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
740 hash.ToString().c_str(),
743 // Continuously rate-limit free transactions
744 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
745 // be annoying or make others' transactions take longer to confirm.
746 if (nFees < MIN_RELAY_TX_FEE)
748 static CCriticalSection cs;
749 static double dFreeCount;
750 static int64 nLastTime;
751 int64 nNow = GetTime();
754 // Use an exponentially decaying ~10-minute window:
755 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
757 // -limitfreerelay unit is thousand-bytes-per-minute
758 // At default rate it would take over a month to fill 1GB
759 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
760 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
762 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
767 // Check against previous transactions
768 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
769 if (!tx.CheckInputs(view, true, SCRIPT_VERIFY_P2SH))
771 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
775 // Store transaction in memory
780 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
783 addUnchecked(hash, tx);
786 ///// are we sure this is ok when loading transactions or restoring block txes
787 // If updated, erase old tx from wallet
789 EraseFromWallets(ptxOld->GetHash());
791 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
792 hash.ToString().substr(0,10).c_str(),
797 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
799 return mempool.accept(*this, fCheckInputs, pfMissingInputs);
802 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
804 // Add to memory pool without checking anything. Don't call this directly,
805 // call CTxMemPool::accept to properly check the transaction first.
808 for (unsigned int i = 0; i < tx.vin.size(); i++)
809 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
810 nTransactionsUpdated++;
816 bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive)
818 // Remove transaction from memory pool
821 uint256 hash = tx.GetHash();
822 if (mapTx.count(hash))
825 for (unsigned int i = 0; i < tx.vout.size(); i++) {
826 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
827 if (it != mapNextTx.end())
828 remove(*it->second.ptx, true);
831 BOOST_FOREACH(const CTxIn& txin, tx.vin)
832 mapNextTx.erase(txin.prevout);
834 nTransactionsUpdated++;
840 bool CTxMemPool::removeConflicts(const CTransaction &tx)
842 // Remove transactions which depend on inputs of tx, recursively
844 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
845 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
846 if (it != mapNextTx.end()) {
847 const CTransaction &txConflict = *it->second.ptx;
848 if (txConflict != tx)
849 remove(txConflict, true);
855 void CTxMemPool::clear()
860 ++nTransactionsUpdated;
863 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
868 vtxid.reserve(mapTx.size());
869 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
870 vtxid.push_back((*mi).first);
876 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
878 if (hashBlock == 0 || nIndex == -1)
881 // Find the block it claims to be in
882 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
883 if (mi == mapBlockIndex.end())
885 CBlockIndex* pindex = (*mi).second;
886 if (!pindex || !pindex->IsInMainChain())
889 // Make sure the merkle branch connects to this block
890 if (!fMerkleVerified)
892 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
894 fMerkleVerified = true;
898 return pindexBest->nHeight - pindex->nHeight + 1;
902 int CMerkleTx::GetBlocksToMaturity() const
906 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
910 bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs)
912 return CTransaction::AcceptToMemoryPool(fCheckInputs);
917 bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
921 // Add previous supporting transactions first
922 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
924 if (!tx.IsCoinBase())
926 uint256 hash = tx.GetHash();
927 if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
928 tx.AcceptToMemoryPool(fCheckInputs);
931 return AcceptToMemoryPool(fCheckInputs);
937 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
938 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
940 CBlockIndex *pindexSlow = NULL;
945 if (mempool.exists(hash))
947 txOut = mempool.lookup(hash);
952 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
955 CCoinsViewCache &view = *pcoinsTip;
957 if (view.GetCoins(hash, coins))
958 nHeight = coins.nHeight;
961 pindexSlow = FindBlockByHeight(nHeight);
967 if (block.ReadFromDisk(pindexSlow)) {
968 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
969 if (tx.GetHash() == hash) {
971 hashBlock = pindexSlow->GetBlockHash();
986 //////////////////////////////////////////////////////////////////////////////
988 // CBlock and CBlockIndex
991 static CBlockIndex* pblockindexFBBHLast;
992 CBlockIndex* FindBlockByHeight(int nHeight)
994 CBlockIndex *pblockindex;
995 if (nHeight < nBestHeight / 2)
996 pblockindex = pindexGenesisBlock;
998 pblockindex = pindexBest;
999 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
1000 pblockindex = pblockindexFBBHLast;
1001 while (pblockindex->nHeight > nHeight)
1002 pblockindex = pblockindex->pprev;
1003 while (pblockindex->nHeight < nHeight)
1004 pblockindex = pblockindex->pnext;
1005 pblockindexFBBHLast = pblockindex;
1009 bool CBlock::ReadFromDisk(const CBlockIndex* pindex)
1011 if (!ReadFromDisk(pindex->GetBlockPos()))
1013 if (GetHash() != pindex->GetBlockHash())
1014 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1018 uint256 static GetOrphanRoot(const CBlockHeader* pblock)
1020 // Work back to the first block in the orphan chain
1021 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1022 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1023 return pblock->GetHash();
1026 int64 static GetBlockValue(int nHeight, int64 nFees)
1028 int64 nSubsidy = 50 * COIN;
1030 // Subsidy is cut in half every 210000 blocks, which will occur approximately every 4 years
1031 nSubsidy >>= (nHeight / 210000);
1033 return nSubsidy + nFees;
1036 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1037 static const int64 nTargetSpacing = 10 * 60;
1038 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
1041 // minimum amount of work that could possibly be required nTime after
1042 // minimum work required was nBase
1044 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1046 // Testnet has min-difficulty blocks
1047 // after nTargetSpacing*2 time between blocks:
1048 if (fTestNet && nTime > nTargetSpacing*2)
1049 return bnProofOfWorkLimit.GetCompact();
1052 bnResult.SetCompact(nBase);
1053 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
1055 // Maximum 400% adjustment...
1057 // ... in best-case exactly 4-times-normal target time
1058 nTime -= nTargetTimespan*4;
1060 if (bnResult > bnProofOfWorkLimit)
1061 bnResult = bnProofOfWorkLimit;
1062 return bnResult.GetCompact();
1065 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
1067 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
1070 if (pindexLast == NULL)
1071 return nProofOfWorkLimit;
1073 // Only change once per interval
1074 if ((pindexLast->nHeight+1) % nInterval != 0)
1076 // Special difficulty rule for testnet:
1079 // If the new block's timestamp is more than 2* 10 minutes
1080 // then allow mining of a min-difficulty block.
1081 if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
1082 return nProofOfWorkLimit;
1085 // Return the last non-special-min-difficulty-rules-block
1086 const CBlockIndex* pindex = pindexLast;
1087 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
1088 pindex = pindex->pprev;
1089 return pindex->nBits;
1093 return pindexLast->nBits;
1096 // Go back by what we want to be 14 days worth of blocks
1097 const CBlockIndex* pindexFirst = pindexLast;
1098 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1099 pindexFirst = pindexFirst->pprev;
1100 assert(pindexFirst);
1102 // Limit adjustment step
1103 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1104 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1105 if (nActualTimespan < nTargetTimespan/4)
1106 nActualTimespan = nTargetTimespan/4;
1107 if (nActualTimespan > nTargetTimespan*4)
1108 nActualTimespan = nTargetTimespan*4;
1112 bnNew.SetCompact(pindexLast->nBits);
1113 bnNew *= nActualTimespan;
1114 bnNew /= nTargetTimespan;
1116 if (bnNew > bnProofOfWorkLimit)
1117 bnNew = bnProofOfWorkLimit;
1120 printf("GetNextWorkRequired RETARGET\n");
1121 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1122 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1123 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1125 return bnNew.GetCompact();
1128 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1131 bnTarget.SetCompact(nBits);
1134 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1135 return error("CheckProofOfWork() : nBits below minimum work");
1137 // Check proof of work matches claimed amount
1138 if (hash > bnTarget.getuint256())
1139 return error("CheckProofOfWork() : hash doesn't match nBits");
1144 // Return maximum amount of blocks that other nodes claim to have
1145 int GetNumBlocksOfPeers()
1147 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1150 bool IsInitialBlockDownload()
1152 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate() || fReindex || fImporting)
1154 static int64 nLastUpdate;
1155 static CBlockIndex* pindexLastBest;
1156 if (pindexBest != pindexLastBest)
1158 pindexLastBest = pindexBest;
1159 nLastUpdate = GetTime();
1161 return (GetTime() - nLastUpdate < 10 &&
1162 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1165 void static InvalidChainFound(CBlockIndex* pindexNew)
1167 if (pindexNew->bnChainWork > bnBestInvalidWork)
1169 bnBestInvalidWork = pindexNew->bnChainWork;
1170 pblocktree->WriteBestInvalidWork(bnBestInvalidWork);
1171 uiInterface.NotifyBlocksChanged();
1173 printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n",
1174 BlockHashStr(pindexNew->GetBlockHash()).c_str(), pindexNew->nHeight,
1175 pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1176 pindexNew->GetBlockTime()).c_str());
1177 printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n",
1178 BlockHashStr(hashBestChain).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
1179 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1180 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1181 printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1184 void static InvalidBlockFound(CBlockIndex *pindex) {
1185 pindex->nStatus |= BLOCK_FAILED_VALID;
1186 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
1187 setBlockIndexValid.erase(pindex);
1188 InvalidChainFound(pindex);
1190 ConnectBestBlock(); // reorganise away from the failed block
1193 bool ConnectBestBlock() {
1195 CBlockIndex *pindexNewBest;
1198 std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
1199 if (it == setBlockIndexValid.rend())
1201 pindexNewBest = *it;
1204 if (pindexNewBest == pindexBest || (pindexBest && pindexNewBest->bnChainWork == pindexBest->bnChainWork))
1205 return true; // nothing to do
1208 CBlockIndex *pindexTest = pindexNewBest;
1209 std::vector<CBlockIndex*> vAttach;
1211 if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
1212 // mark descendants failed
1213 CBlockIndex *pindexFailed = pindexNewBest;
1214 while (pindexTest != pindexFailed) {
1215 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
1216 setBlockIndexValid.erase(pindexFailed);
1217 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
1218 pindexFailed = pindexFailed->pprev;
1220 InvalidChainFound(pindexNewBest);
1224 if (pindexBest == NULL || pindexTest->bnChainWork > pindexBest->bnChainWork)
1225 vAttach.push_back(pindexTest);
1227 if (pindexTest->pprev == NULL || pindexTest->pnext != NULL) {
1228 reverse(vAttach.begin(), vAttach.end());
1229 BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) {
1230 if (fRequestShutdown)
1232 if (!SetBestChain(pindexSwitch))
1237 pindexTest = pindexTest->pprev;
1242 void CBlockHeader::UpdateTime(const CBlockIndex* pindexPrev)
1244 nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1246 // Updating time can change work required on testnet:
1248 nBits = GetNextWorkRequired(pindexPrev, this);
1261 const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view)
1263 const CCoins &coins = view.GetCoins(input.prevout.hash);
1264 assert(coins.IsAvailable(input.prevout.n));
1265 return coins.vout[input.prevout.n];
1268 int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const
1274 for (unsigned int i = 0; i < vin.size(); i++)
1275 nResult += GetOutputFor(vin[i], inputs).nValue;
1280 unsigned int CTransaction::GetP2SHSigOpCount(CCoinsViewCache& inputs) const
1285 unsigned int nSigOps = 0;
1286 for (unsigned int i = 0; i < vin.size(); i++)
1288 const CTxOut &prevout = GetOutputFor(vin[i], inputs);
1289 if (prevout.scriptPubKey.IsPayToScriptHash())
1290 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1295 bool CTransaction::UpdateCoins(CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash) const
1297 // mark inputs spent
1298 if (!IsCoinBase()) {
1299 BOOST_FOREACH(const CTxIn &txin, vin) {
1300 CCoins &coins = inputs.GetCoins(txin.prevout.hash);
1302 if (!coins.Spend(txin.prevout, undo))
1303 return error("UpdateCoins() : cannot spend input");
1304 txundo.vprevout.push_back(undo);
1309 if (!inputs.SetCoins(txhash, CCoins(*this, nHeight)))
1310 return error("UpdateCoins() : cannot update output");
1315 bool CTransaction::HaveInputs(CCoinsViewCache &inputs) const
1317 if (!IsCoinBase()) {
1318 // first check whether information about the prevout hash is available
1319 for (unsigned int i = 0; i < vin.size(); i++) {
1320 const COutPoint &prevout = vin[i].prevout;
1321 if (!inputs.HaveCoins(prevout.hash))
1325 // then check whether the actual outputs are available
1326 for (unsigned int i = 0; i < vin.size(); i++) {
1327 const COutPoint &prevout = vin[i].prevout;
1328 const CCoins &coins = inputs.GetCoins(prevout.hash);
1329 if (!coins.IsAvailable(prevout.n))
1336 bool CScriptCheck::operator()() const {
1337 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1338 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1339 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1343 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1345 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1348 bool CTransaction::CheckInputs(CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks) const
1353 pvChecks->reserve(vin.size());
1355 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1356 // for an attacker to attempt to split the network.
1357 if (!HaveInputs(inputs))
1358 return error("CheckInputs() : %s inputs unavailable", GetHash().ToString().substr(0,10).c_str());
1360 // While checking, GetBestBlock() refers to the parent block.
1361 // This is also true for mempool checks.
1362 int nSpendHeight = inputs.GetBestBlock()->nHeight + 1;
1365 for (unsigned int i = 0; i < vin.size(); i++)
1367 const COutPoint &prevout = vin[i].prevout;
1368 const CCoins &coins = inputs.GetCoins(prevout.hash);
1370 // If prev is coinbase, check that it's matured
1371 if (coins.IsCoinBase()) {
1372 if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
1373 return error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight);
1376 // Check for negative or overflow input values
1377 nValueIn += coins.vout[prevout.n].nValue;
1378 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1379 return DoS(100, error("CheckInputs() : txin values out of range"));
1383 if (nValueIn < GetValueOut())
1384 return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1386 // Tally transaction fees
1387 int64 nTxFee = nValueIn - GetValueOut();
1389 return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1391 if (!MoneyRange(nFees))
1392 return DoS(100, error("CheckInputs() : nFees out of range"));
1394 // The first loop above does all the inexpensive checks.
1395 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1396 // Helps prevent CPU exhaustion attacks.
1398 // Skip ECDSA signature verification when connecting blocks
1399 // before the last block chain checkpoint. This is safe because block merkle hashes are
1400 // still computed and checked, and any change will be caught at the next checkpoint.
1401 if (fScriptChecks) {
1402 for (unsigned int i = 0; i < vin.size(); i++) {
1403 const COutPoint &prevout = vin[i].prevout;
1404 const CCoins &coins = inputs.GetCoins(prevout.hash);
1407 CScriptCheck check(coins, *this, i, flags, 0);
1409 pvChecks->push_back(CScriptCheck());
1410 check.swap(pvChecks->back());
1411 } else if (!check())
1412 return DoS(100,false);
1421 bool CTransaction::ClientCheckInputs() const
1426 // Take over previous transactions' spent pointers
1430 for (unsigned int i = 0; i < vin.size(); i++)
1432 // Get prev tx from single transactions in memory
1433 COutPoint prevout = vin[i].prevout;
1434 if (!mempool.exists(prevout.hash))
1436 CTransaction& txPrev = mempool.lookup(prevout.hash);
1438 if (prevout.n >= txPrev.vout.size())
1442 if (!VerifySignature(CCoins(txPrev, -1), *this, i, SCRIPT_VERIFY_P2SH, 0))
1443 return error("ConnectInputs() : VerifySignature failed");
1445 ///// this is redundant with the mempool.mapNextTx stuff,
1446 ///// not sure which I want to get rid of
1447 ///// this has to go away now that posNext is gone
1448 // // Check for conflicts
1449 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1450 // return error("ConnectInputs() : prev tx already used");
1452 // // Flag outpoints as used
1453 // txPrev.vout[prevout.n].posNext = posThisTx;
1455 nValueIn += txPrev.vout[prevout.n].nValue;
1457 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1458 return error("ClientConnectInputs() : txin values out of range");
1460 if (GetValueOut() > nValueIn)
1470 bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
1472 assert(pindex == view.GetBestBlock());
1479 CBlockUndo blockUndo;
1480 CDiskBlockPos pos = pindex->GetUndoPos();
1482 return error("DisconnectBlock() : no undo data available");
1483 if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
1484 return error("DisconnectBlock() : failure reading undo data");
1486 if (blockUndo.vtxundo.size() + 1 != vtx.size())
1487 return error("DisconnectBlock() : block and undo data inconsistent");
1489 // undo transactions in reverse order
1490 for (int i = vtx.size() - 1; i >= 0; i--) {
1491 const CTransaction &tx = vtx[i];
1492 uint256 hash = tx.GetHash();
1494 // check that all outputs are available
1495 if (!view.HaveCoins(hash)) {
1496 fClean = fClean && error("DisconnectBlock() : outputs still spent? database corrupted");
1497 view.SetCoins(hash, CCoins());
1499 CCoins &outs = view.GetCoins(hash);
1501 CCoins outsBlock = CCoins(tx, pindex->nHeight);
1502 if (outs != outsBlock)
1503 fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
1509 if (i > 0) { // not coinbases
1510 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1511 if (txundo.vprevout.size() != tx.vin.size())
1512 return error("DisconnectBlock() : transaction and undo data inconsistent");
1513 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1514 const COutPoint &out = tx.vin[j].prevout;
1515 const CTxInUndo &undo = txundo.vprevout[j];
1517 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1518 if (undo.nHeight != 0) {
1519 // undo data contains height: this is the last output of the prevout tx being spent
1520 if (!coins.IsPruned())
1521 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
1523 coins.fCoinBase = undo.fCoinBase;
1524 coins.nHeight = undo.nHeight;
1525 coins.nVersion = undo.nVersion;
1527 if (coins.IsPruned())
1528 fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
1530 if (coins.IsAvailable(out.n))
1531 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
1532 if (coins.vout.size() < out.n+1)
1533 coins.vout.resize(out.n+1);
1534 coins.vout[out.n] = undo.txout;
1535 if (!view.SetCoins(out.hash, coins))
1536 return error("DisconnectBlock() : cannot restore coin inputs");
1541 // move best block pointer to prevout block
1542 view.SetBestBlock(pindex->pprev);
1552 void static FlushBlockFile()
1554 LOCK(cs_LastBlockFile);
1556 CDiskBlockPos posOld(nLastBlockFile, 0);
1558 FILE *fileOld = OpenBlockFile(posOld);
1560 FileCommit(fileOld);
1564 fileOld = OpenUndoFile(posOld);
1566 FileCommit(fileOld);
1571 bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1573 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1575 void ThreadScriptCheck(void*) {
1576 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1577 RenameThread("bitcoin-scriptch");
1578 scriptcheckqueue.Thread();
1579 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1582 void ThreadScriptCheckQuit() {
1583 scriptcheckqueue.Quit();
1586 bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsViewCache &view, bool fJustCheck)
1588 // Check it again in case a previous version let a bad block in
1589 if (!CheckBlock(!fJustCheck, !fJustCheck))
1592 // verify that the view's current state corresponds to the previous block
1593 assert(pindex->pprev == view.GetBestBlock());
1595 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1597 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1598 // unless those are already completely spent.
1599 // If such overwrites are allowed, coinbases and transactions depending upon those
1600 // can be duplicated to remove the ability to spend the first instance -- even after
1601 // being sent to another address.
1602 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1603 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1604 // already refuses previously-known transaction ids entirely.
1605 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1606 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1607 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1608 // initial block download.
1609 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1610 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1611 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1612 if (fEnforceBIP30) {
1613 for (unsigned int i=0; i<vtx.size(); i++) {
1614 uint256 hash = GetTxHash(i);
1615 if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
1616 return error("ConnectBlock() : tried to overwrite transaction");
1620 // BIP16 didn't become active until Apr 1 2012
1621 int64 nBIP16SwitchTime = 1333238400;
1622 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1624 unsigned int flags = SCRIPT_VERIFY_NOCACHE |
1625 (fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE);
1627 CBlockUndo blockundo;
1629 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1631 int64 nStart = GetTimeMicros();
1634 unsigned int nSigOps = 0;
1635 for (unsigned int i=0; i<vtx.size(); i++)
1638 const CTransaction &tx = vtx[i];
1640 nInputs += tx.vin.size();
1641 nSigOps += tx.GetLegacySigOpCount();
1642 if (nSigOps > MAX_BLOCK_SIGOPS)
1643 return DoS(100, error("ConnectBlock() : too many sigops"));
1645 if (!tx.IsCoinBase())
1647 if (!tx.HaveInputs(view))
1648 return DoS(100, error("ConnectBlock() : inputs missing/spent"));
1650 if (fStrictPayToScriptHash)
1652 // Add in sigops done by pay-to-script-hash inputs;
1653 // this is to prevent a "rogue miner" from creating
1654 // an incredibly-expensive-to-validate block.
1655 nSigOps += tx.GetP2SHSigOpCount(view);
1656 if (nSigOps > MAX_BLOCK_SIGOPS)
1657 return DoS(100, error("ConnectBlock() : too many sigops"));
1660 nFees += tx.GetValueIn(view)-tx.GetValueOut();
1662 std::vector<CScriptCheck> vChecks;
1663 if (!tx.CheckInputs(view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
1665 control.Add(vChecks);
1669 if (!tx.UpdateCoins(view, txundo, pindex->nHeight, GetTxHash(i)))
1670 return error("ConnectBlock() : UpdateInputs failed");
1671 if (!tx.IsCoinBase())
1672 blockundo.vtxundo.push_back(txundo);
1675 int64 nTime = GetTimeMicros() - nStart;
1677 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));
1679 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1680 return error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees));
1682 if (!control.Wait())
1683 return DoS(100, false);
1684 int64 nTime2 = GetTimeMicros() - nStart;
1686 printf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
1691 // Write undo information to disk
1692 if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
1694 if (pindex->GetUndoPos().IsNull()) {
1696 if (!FindUndoPos(pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1697 return error("ConnectBlock() : FindUndoPos failed");
1698 if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
1699 return error("ConnectBlock() : CBlockUndo::WriteToDisk failed");
1701 // update nUndoPos in block index
1702 pindex->nUndoPos = pos.nPos;
1703 pindex->nStatus |= BLOCK_HAVE_UNDO;
1706 pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
1708 CDiskBlockIndex blockindex(pindex);
1709 if (!pblocktree->WriteBlockIndex(blockindex))
1710 return error("ConnectBlock() : WriteBlockIndex failed");
1713 // add this block to the view's block chain
1714 if (!view.SetBestBlock(pindex))
1717 // Watch for transactions paying to me
1718 for (unsigned int i=0; i<vtx.size(); i++)
1719 SyncWithWallets(GetTxHash(i), vtx[i], this, true);
1724 bool SetBestChain(CBlockIndex* pindexNew)
1726 // All modifications to the coin state will be done in this cache.
1727 // Only when all have succeeded, we push it to pcoinsTip.
1728 CCoinsViewCache view(*pcoinsTip, true);
1730 // special case for attaching the genesis block
1731 // note that no ConnectBlock is called, so its coinbase output is non-spendable
1732 if (pindexGenesisBlock == NULL && pindexNew->GetBlockHash() == hashGenesisBlock)
1734 view.SetBestBlock(pindexNew);
1737 pindexGenesisBlock = pindexNew;
1738 pindexBest = pindexNew;
1739 hashBestChain = pindexNew->GetBlockHash();
1740 nBestHeight = pindexBest->nHeight;
1741 bnBestChainWork = pindexNew->bnChainWork;
1745 // Find the fork (typically, there is none)
1746 CBlockIndex* pfork = view.GetBestBlock();
1747 CBlockIndex* plonger = pindexNew;
1748 while (pfork && pfork != plonger)
1750 while (plonger->nHeight > pfork->nHeight)
1751 if (!(plonger = plonger->pprev))
1752 return error("SetBestChain() : plonger->pprev is null");
1753 if (pfork == plonger)
1755 if (!(pfork = pfork->pprev))
1756 return error("SetBestChain() : pfork->pprev is null");
1759 // List of what to disconnect (typically nothing)
1760 vector<CBlockIndex*> vDisconnect;
1761 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1762 vDisconnect.push_back(pindex);
1764 // List of what to connect (typically only pindexNew)
1765 vector<CBlockIndex*> vConnect;
1766 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1767 vConnect.push_back(pindex);
1768 reverse(vConnect.begin(), vConnect.end());
1770 if (vDisconnect.size() > 0) {
1771 printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), BlockHashStr(pfork->GetBlockHash()).c_str(), BlockHashStr(pindexBest->GetBlockHash()).c_str());
1772 printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), BlockHashStr(pfork->GetBlockHash()).c_str(), BlockHashStr(pindexNew->GetBlockHash()).c_str());
1775 // Disconnect shorter branch
1776 vector<CTransaction> vResurrect;
1777 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
1779 if (!block.ReadFromDisk(pindex))
1780 return error("SetBestBlock() : ReadFromDisk for disconnect failed");
1781 int64 nStart = GetTimeMicros();
1782 if (!block.DisconnectBlock(pindex, view))
1783 return error("SetBestBlock() : DisconnectBlock %s failed", BlockHashStr(pindex->GetBlockHash()).c_str());
1785 printf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1787 // Queue memory transactions to resurrect.
1788 // We only do this for blocks after the last checkpoint (reorganisation before that
1789 // point should only happen with -reindex/-loadblock, or a misbehaving peer.
1790 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1791 if (!tx.IsCoinBase() && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
1792 vResurrect.push_back(tx);
1795 // Connect longer branch
1796 vector<CTransaction> vDelete;
1797 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
1799 if (!block.ReadFromDisk(pindex))
1800 return error("SetBestBlock() : ReadFromDisk for connect failed");
1801 int64 nStart = GetTimeMicros();
1802 if (!block.ConnectBlock(pindex, view)) {
1803 InvalidChainFound(pindexNew);
1804 InvalidBlockFound(pindex);
1805 return error("SetBestBlock() : ConnectBlock %s failed", BlockHashStr(pindex->GetBlockHash()).c_str());
1808 printf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1810 // Queue memory transactions to delete
1811 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1812 vDelete.push_back(tx);
1815 // Flush changes to global coin state
1816 int64 nStart = GetTimeMicros();
1817 int nModified = view.GetCacheSize();
1819 return error("SetBestBlock() : unable to modify coin state");
1820 int64 nTime = GetTimeMicros() - nStart;
1822 printf("- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified);
1824 // Make sure it's successfully written to disk before changing memory structure
1825 bool fIsInitialDownload = IsInitialBlockDownload();
1826 if (!fIsInitialDownload || pcoinsTip->GetCacheSize() > nCoinCacheSize) {
1829 if (!pcoinsTip->Flush())
1833 // At this point, all changes have been done to the database.
1834 // Proceed by updating the memory structures.
1836 // Disconnect shorter branch
1837 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1839 pindex->pprev->pnext = NULL;
1841 // Connect longer branch
1842 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1844 pindex->pprev->pnext = pindex;
1846 // Resurrect memory transactions that were in the disconnected branch
1847 BOOST_FOREACH(CTransaction& tx, vResurrect)
1848 tx.AcceptToMemoryPool();
1850 // Delete redundant memory transactions that are in the connected branch
1851 BOOST_FOREACH(CTransaction& tx, vDelete) {
1853 mempool.removeConflicts(tx);
1856 // Update best block in wallet (so we can detect restored wallets)
1857 if (!fIsInitialDownload)
1859 const CBlockLocator locator(pindexNew);
1860 ::SetBestChain(locator);
1864 hashBestChain = pindexNew->GetBlockHash();
1865 pindexBest = pindexNew;
1866 pblockindexFBBHLast = NULL;
1867 nBestHeight = pindexBest->nHeight;
1868 bnBestChainWork = pindexNew->bnChainWork;
1869 nTimeBestReceived = GetTime();
1870 nTransactionsUpdated++;
1871 printf("SetBestChain: new best=%s height=%d work=%s tx=%lu date=%s\n",
1872 BlockHashStr(hashBestChain).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), (unsigned long)pindexNew->nChainTx,
1873 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1875 // Check the version of the last 100 blocks to see if we need to upgrade:
1876 if (!fIsInitialDownload)
1879 const CBlockIndex* pindex = pindexBest;
1880 for (int i = 0; i < 100 && pindex != NULL; i++)
1882 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1884 pindex = pindex->pprev;
1887 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1888 if (nUpgraded > 100/2)
1889 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1890 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1893 std::string strCmd = GetArg("-blocknotify", "");
1895 if (!fIsInitialDownload && !strCmd.empty())
1897 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1898 boost::thread t(runCommand, strCmd); // thread runs free
1905 bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
1907 // Check for duplicate
1908 uint256 hash = GetHash();
1909 if (mapBlockIndex.count(hash))
1910 return error("AddToBlockIndex() : %s already exists", BlockHashStr(hash).c_str());
1912 // Construct new block index object
1913 CBlockIndex* pindexNew = new CBlockIndex(*this);
1915 return error("AddToBlockIndex() : new CBlockIndex failed");
1916 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1917 pindexNew->phashBlock = &((*mi).first);
1918 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1919 if (miPrev != mapBlockIndex.end())
1921 pindexNew->pprev = (*miPrev).second;
1922 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1924 pindexNew->nTx = vtx.size();
1925 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1926 pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
1927 pindexNew->nFile = pos.nFile;
1928 pindexNew->nDataPos = pos.nPos;
1929 pindexNew->nUndoPos = 0;
1930 pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
1931 setBlockIndexValid.insert(pindexNew);
1933 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew));
1936 if (!ConnectBestBlock())
1939 if (pindexNew == pindexBest)
1941 // Notify UI to display prev block's coinbase if it was ours
1942 static uint256 hashPrevBestCoinBase;
1943 UpdatedTransaction(hashPrevBestCoinBase);
1944 hashPrevBestCoinBase = GetTxHash(0);
1947 pblocktree->Flush();
1949 uiInterface.NotifyBlocksChanged();
1954 bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown = false)
1956 bool fUpdatedLast = false;
1958 LOCK(cs_LastBlockFile);
1961 if (nLastBlockFile != pos.nFile) {
1962 nLastBlockFile = pos.nFile;
1963 infoLastBlockFile.SetNull();
1964 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile);
1965 fUpdatedLast = true;
1968 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
1969 printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
1972 infoLastBlockFile.SetNull();
1973 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
1974 fUpdatedLast = true;
1976 pos.nFile = nLastBlockFile;
1977 pos.nPos = infoLastBlockFile.nSize;
1980 infoLastBlockFile.nSize += nAddSize;
1981 infoLastBlockFile.AddBlock(nHeight, nTime);
1984 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
1985 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
1986 if (nNewChunks > nOldChunks) {
1987 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
1988 FILE *file = OpenBlockFile(pos);
1990 printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
1991 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
1996 return error("FindBlockPos() : out of disk space");
2000 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2001 return error("FindBlockPos() : cannot write updated block info");
2003 pblocktree->WriteLastBlockFile(nLastBlockFile);
2008 bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2012 LOCK(cs_LastBlockFile);
2014 unsigned int nNewSize;
2015 if (nFile == nLastBlockFile) {
2016 pos.nPos = infoLastBlockFile.nUndoSize;
2017 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2018 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2019 return error("FindUndoPos() : cannot write updated block info");
2021 CBlockFileInfo info;
2022 if (!pblocktree->ReadBlockFileInfo(nFile, info))
2023 return error("FindUndoPos() : cannot read block info");
2024 pos.nPos = info.nUndoSize;
2025 nNewSize = (info.nUndoSize += nAddSize);
2026 if (!pblocktree->WriteBlockFileInfo(nFile, info))
2027 return error("FindUndoPos() : cannot write updated block info");
2030 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2031 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2032 if (nNewChunks > nOldChunks) {
2033 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2034 FILE *file = OpenUndoFile(pos);
2036 printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2037 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2042 return error("FindUndoPos() : out of disk space");
2049 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
2051 // These are checks that are independent of context
2052 // that can be verified before saving an orphan block.
2055 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2056 return DoS(100, error("CheckBlock() : size limits failed"));
2058 // Check proof of work matches claimed amount
2059 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2060 return DoS(50, error("CheckBlock() : proof of work failed"));
2063 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2064 return error("CheckBlock() : block timestamp too far in the future");
2066 // First transaction must be coinbase, the rest must not be
2067 if (vtx.empty() || !vtx[0].IsCoinBase())
2068 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2069 for (unsigned int i = 1; i < vtx.size(); i++)
2070 if (vtx[i].IsCoinBase())
2071 return DoS(100, error("CheckBlock() : more than one coinbase"));
2073 // Check transactions
2074 BOOST_FOREACH(const CTransaction& tx, vtx)
2075 if (!tx.CheckTransaction())
2076 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2078 // Build the merkle tree already. We need it anyway later, and it makes the
2079 // block cache the transaction hashes, which means they don't need to be
2080 // recalculated many times during this block's validation.
2083 // Check for duplicate txids. This is caught by ConnectInputs(),
2084 // but catching it earlier avoids a potential DoS attack:
2085 set<uint256> uniqueTx;
2086 for (unsigned int i=0; i<vtx.size(); i++) {
2087 uniqueTx.insert(GetTxHash(i));
2089 if (uniqueTx.size() != vtx.size())
2090 return DoS(100, error("CheckBlock() : duplicate transaction"));
2092 unsigned int nSigOps = 0;
2093 BOOST_FOREACH(const CTransaction& tx, vtx)
2095 nSigOps += tx.GetLegacySigOpCount();
2097 if (nSigOps > MAX_BLOCK_SIGOPS)
2098 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2100 // Check merkle root
2101 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2102 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2107 bool CBlock::AcceptBlock(CDiskBlockPos *dbp)
2109 // Check for duplicate
2110 uint256 hash = GetHash();
2111 if (mapBlockIndex.count(hash))
2112 return error("AcceptBlock() : block already in mapBlockIndex");
2114 // Get prev block index
2115 CBlockIndex* pindexPrev = NULL;
2117 if (hash != hashGenesisBlock) {
2118 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2119 if (mi == mapBlockIndex.end())
2120 return DoS(10, error("AcceptBlock() : prev block not found"));
2121 pindexPrev = (*mi).second;
2122 nHeight = pindexPrev->nHeight+1;
2124 // Check proof of work
2125 if (nBits != GetNextWorkRequired(pindexPrev, this))
2126 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
2128 // Check timestamp against prev
2129 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
2130 return error("AcceptBlock() : block's timestamp is too early");
2132 // Check that all transactions are finalized
2133 BOOST_FOREACH(const CTransaction& tx, vtx)
2134 if (!tx.IsFinal(nHeight, GetBlockTime()))
2135 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2137 // Check that the block chain matches the known block chain up to a checkpoint
2138 if (!Checkpoints::CheckBlock(nHeight, hash))
2139 return DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
2141 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2144 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
2145 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
2147 return error("AcceptBlock() : rejected nVersion=1 block");
2150 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2153 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2154 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
2155 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
2157 CScript expect = CScript() << nHeight;
2158 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2159 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2164 // Write block to history file
2165 unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
2166 CDiskBlockPos blockPos;
2169 if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, nTime, dbp != NULL))
2170 return error("AcceptBlock() : FindBlockPos failed");
2172 if (!WriteToDisk(blockPos))
2173 return error("AcceptBlock() : WriteToDisk failed");
2174 if (!AddToBlockIndex(blockPos))
2175 return error("AcceptBlock() : AddToBlockIndex failed");
2177 // Relay inventory, but don't relay old inventory during initial block download
2178 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2179 if (hashBestChain == hash)
2182 BOOST_FOREACH(CNode* pnode, vNodes)
2183 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2184 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2190 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2192 unsigned int nFound = 0;
2193 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2195 if (pstart->nVersion >= minVersion)
2197 pstart = pstart->pprev;
2199 return (nFound >= nRequired);
2202 bool ProcessBlock(CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2204 // Check for duplicate
2205 uint256 hash = pblock->GetHash();
2206 if (mapBlockIndex.count(hash))
2207 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, BlockHashStr(hash).c_str());
2208 if (mapOrphanBlocks.count(hash))
2209 return error("ProcessBlock() : already have block (orphan) %s", BlockHashStr(hash).c_str());
2211 // Preliminary checks
2212 if (!pblock->CheckBlock())
2213 return error("ProcessBlock() : CheckBlock FAILED");
2215 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
2216 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
2218 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2219 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2223 pfrom->Misbehaving(100);
2224 return error("ProcessBlock() : block with timestamp before last checkpoint");
2227 bnNewBlock.SetCompact(pblock->nBits);
2229 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
2230 if (bnNewBlock > bnRequired)
2233 pfrom->Misbehaving(100);
2234 return error("ProcessBlock() : block with too little proof-of-work");
2239 // If we don't already have its previous block, shunt it off to holding area until we get it
2240 if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
2242 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", BlockHashStr(pblock->hashPrevBlock).c_str());
2244 // Accept orphans as long as there is a node to request its parents from
2246 CBlock* pblock2 = new CBlock(*pblock);
2247 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2248 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2250 // Ask this guy to fill in what we're missing
2251 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2257 if (!pblock->AcceptBlock(dbp))
2258 return error("ProcessBlock() : AcceptBlock FAILED");
2260 // Recursively process any orphan blocks that depended on this one
2261 vector<uint256> vWorkQueue;
2262 vWorkQueue.push_back(hash);
2263 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2265 uint256 hashPrev = vWorkQueue[i];
2266 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2267 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2270 CBlock* pblockOrphan = (*mi).second;
2271 if (pblockOrphan->AcceptBlock())
2272 vWorkQueue.push_back(pblockOrphan->GetHash());
2273 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2274 delete pblockOrphan;
2276 mapOrphanBlocksByPrev.erase(hashPrev);
2279 printf("ProcessBlock: ACCEPTED\n");
2290 CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
2292 header = block.GetBlockHeader();
2294 vector<bool> vMatch;
2295 vector<uint256> vHashes;
2297 vMatch.reserve(block.vtx.size());
2298 vHashes.reserve(block.vtx.size());
2300 for (unsigned int i = 0; i < block.vtx.size(); i++)
2302 uint256 hash = block.vtx[i].GetHash();
2303 if (filter.IsRelevantAndUpdate(block.vtx[i], hash))
2305 vMatch.push_back(true);
2306 vMatchedTxn.push_back(make_pair(i, hash));
2309 vMatch.push_back(false);
2310 vHashes.push_back(hash);
2313 txn = CPartialMerkleTree(vHashes, vMatch);
2323 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
2325 // hash at height 0 is the txids themself
2328 // calculate left hash
2329 uint256 left = CalcHash(height-1, pos*2, vTxid), right;
2330 // calculate right hash if not beyong the end of the array - copy left hash otherwise1
2331 if (pos*2+1 < CalcTreeWidth(height-1))
2332 right = CalcHash(height-1, pos*2+1, vTxid);
2335 // combine subhashes
2336 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2340 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
2341 // determine whether this node is the parent of at least one matched txid
2342 bool fParentOfMatch = false;
2343 for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
2344 fParentOfMatch |= vMatch[p];
2345 // store as flag bit
2346 vBits.push_back(fParentOfMatch);
2347 if (height==0 || !fParentOfMatch) {
2348 // if at height 0, or nothing interesting below, store hash and stop
2349 vHash.push_back(CalcHash(height, pos, vTxid));
2351 // otherwise, don't store any hash, but descend into the subtrees
2352 TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
2353 if (pos*2+1 < CalcTreeWidth(height-1))
2354 TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
2358 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
2359 if (nBitsUsed >= vBits.size()) {
2360 // overflowed the bits array - failure
2364 bool fParentOfMatch = vBits[nBitsUsed++];
2365 if (height==0 || !fParentOfMatch) {
2366 // if at height 0, or nothing interesting below, use stored hash and do not descend
2367 if (nHashUsed >= vHash.size()) {
2368 // overflowed the hash array - failure
2372 const uint256 &hash = vHash[nHashUsed++];
2373 if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
2374 vMatch.push_back(hash);
2377 // otherwise, descend into the subtrees to extract matched txids and hashes
2378 uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
2379 if (pos*2+1 < CalcTreeWidth(height-1))
2380 right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
2383 // and combine them before returning
2384 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2388 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
2393 // calculate height of tree
2395 while (CalcTreeWidth(nHeight) > 1)
2398 // traverse the partial tree
2399 TraverseAndBuild(nHeight, 0, vTxid, vMatch);
2402 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
2404 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
2406 // An empty set will not work
2407 if (nTransactions == 0)
2409 // check for excessively high numbers of transactions
2410 if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
2412 // there can never be more hashes provided than one for every txid
2413 if (vHash.size() > nTransactions)
2415 // there must be at least one bit per node in the partial tree, and at least one node per hash
2416 if (vBits.size() < vHash.size())
2418 // calculate height of tree
2420 while (CalcTreeWidth(nHeight) > 1)
2422 // traverse the partial tree
2423 unsigned int nBitsUsed = 0, nHashUsed = 0;
2424 uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
2425 // verify that no problems occured during the tree traversal
2428 // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
2429 if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
2431 // verify that all hashes were consumed
2432 if (nHashUsed != vHash.size())
2434 return hashMerkleRoot;
2444 bool CheckDiskSpace(uint64 nAdditionalBytes)
2446 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2448 // Check for nMinDiskSpace bytes (currently 50MB)
2449 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2452 string strMessage = _("Error: Disk space is low!");
2453 strMiscWarning = strMessage;
2454 printf("*** %s\n", strMessage.c_str());
2455 uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR);
2462 CCriticalSection cs_LastBlockFile;
2463 CBlockFileInfo infoLastBlockFile;
2464 int nLastBlockFile = 0;
2466 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2470 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2471 boost::filesystem::create_directories(path.parent_path());
2472 FILE* file = fopen(path.string().c_str(), "rb+");
2473 if (!file && !fReadOnly)
2474 file = fopen(path.string().c_str(), "wb+");
2476 printf("Unable to open file %s\n", path.string().c_str());
2480 if (fseek(file, pos.nPos, SEEK_SET)) {
2481 printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2489 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2490 return OpenDiskFile(pos, "blk", fReadOnly);
2493 FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2494 return OpenDiskFile(pos, "rev", fReadOnly);
2497 CBlockIndex * InsertBlockIndex(uint256 hash)
2503 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2504 if (mi != mapBlockIndex.end())
2505 return (*mi).second;
2508 CBlockIndex* pindexNew = new CBlockIndex();
2510 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
2511 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2512 pindexNew->phashBlock = &((*mi).first);
2517 bool static LoadBlockIndexDB()
2519 if (!pblocktree->LoadBlockIndexGuts())
2522 if (fRequestShutdown)
2525 // Calculate bnChainWork
2526 vector<pair<int, CBlockIndex*> > vSortedByHeight;
2527 vSortedByHeight.reserve(mapBlockIndex.size());
2528 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2530 CBlockIndex* pindex = item.second;
2531 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2533 sort(vSortedByHeight.begin(), vSortedByHeight.end());
2534 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2536 CBlockIndex* pindex = item.second;
2537 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
2538 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2539 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
2540 setBlockIndexValid.insert(pindex);
2543 // Load block file info
2544 pblocktree->ReadLastBlockFile(nLastBlockFile);
2545 printf("LoadBlockIndex(): last block file = %i\n", nLastBlockFile);
2546 if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2547 printf("LoadBlockIndex(): last block file: %s\n", infoLastBlockFile.ToString().c_str());
2549 // Load bnBestInvalidWork, OK if it doesn't exist
2550 pblocktree->ReadBestInvalidWork(bnBestInvalidWork);
2552 // Check whether we need to continue reindexing
2553 bool fReindexing = false;
2554 pblocktree->ReadReindexing(fReindexing);
2555 fReindex |= fReindexing;
2557 // Load hashBestChain pointer to end of best chain
2558 pindexBest = pcoinsTip->GetBestBlock();
2559 if (pindexBest == NULL)
2561 hashBestChain = pindexBest->GetBlockHash();
2562 nBestHeight = pindexBest->nHeight;
2563 bnBestChainWork = pindexBest->bnChainWork;
2565 // set 'next' pointers in best chain
2566 CBlockIndex *pindex = pindexBest;
2567 while(pindex != NULL && pindex->pprev != NULL) {
2568 CBlockIndex *pindexPrev = pindex->pprev;
2569 pindexPrev->pnext = pindex;
2570 pindex = pindexPrev;
2572 printf("LoadBlockIndex(): hashBestChain=%s height=%d date=%s\n",
2573 BlockHashStr(hashBestChain).c_str(), nBestHeight,
2574 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2580 if (pindexBest == NULL || pindexBest->pprev == NULL)
2583 // Verify blocks in the best chain
2584 int nCheckLevel = GetArg("-checklevel", 3);
2585 int nCheckDepth = GetArg( "-checkblocks", 2500);
2586 if (nCheckDepth == 0)
2587 nCheckDepth = 1000000000; // suffices until the year 19000
2588 if (nCheckDepth > nBestHeight)
2589 nCheckDepth = nBestHeight;
2590 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2591 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2592 CCoinsViewCache coins(*pcoinsTip, true);
2593 CBlockIndex* pindexState = pindexBest;
2594 CBlockIndex* pindexFailure = NULL;
2595 int nGoodTransactions = 0;
2596 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
2598 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
2601 // check level 0: read from disk
2602 if (!block.ReadFromDisk(pindex))
2603 return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2604 // check level 1: verify block validity
2605 if (nCheckLevel >= 1 && !block.CheckBlock())
2606 return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2607 // check level 2: verify undo validity
2608 if (nCheckLevel >= 2 && pindex) {
2610 CDiskBlockPos pos = pindex->GetUndoPos();
2611 if (!pos.IsNull()) {
2612 if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
2613 return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2616 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
2617 if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
2619 if (!block.DisconnectBlock(pindex, coins, &fClean))
2620 return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2621 pindexState = pindex->pprev;
2623 nGoodTransactions = 0;
2624 pindexFailure = pindex;
2626 nGoodTransactions += block.vtx.size();
2630 return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", pindexBest->nHeight - pindexFailure->nHeight + 1, nGoodTransactions);
2632 // check level 4: try reconnecting blocks
2633 if (nCheckLevel >= 4) {
2634 CBlockIndex *pindex = pindexState;
2635 while (pindex != pindexBest && !fRequestShutdown) {
2636 pindex = pindex->pnext;
2638 if (!block.ReadFromDisk(pindex))
2639 return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2640 if (!block.ConnectBlock(pindex, coins))
2641 return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2645 printf("No coin database inconsistencies in last %i blocks (%i transactions)\n", pindexBest->nHeight - pindexState->nHeight, nGoodTransactions);
2650 bool LoadBlockIndex()
2654 pchMessageStart[0] = 0x0b;
2655 pchMessageStart[1] = 0x11;
2656 pchMessageStart[2] = 0x09;
2657 pchMessageStart[3] = 0x07;
2658 hashGenesisBlock = uint256("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943");
2665 // Load block index from databases
2667 if (!LoadBlockIndexDB())
2671 // Init with genesis block
2673 if (mapBlockIndex.empty())
2676 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
2677 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2678 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
2679 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
2680 // vMerkleTree: 4a5e1e
2683 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
2685 txNew.vin.resize(1);
2686 txNew.vout.resize(1);
2687 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2688 txNew.vout[0].nValue = 50 * COIN;
2689 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
2691 block.vtx.push_back(txNew);
2692 block.hashPrevBlock = 0;
2693 block.hashMerkleRoot = block.BuildMerkleTree();
2695 block.nTime = 1231006505;
2696 block.nBits = 0x1d00ffff;
2697 block.nNonce = 2083236893;
2701 block.nTime = 1296688602;
2702 block.nNonce = 414098458;
2706 uint256 hash = block.GetHash();
2707 printf("%s\n", hash.ToString().c_str());
2708 printf("%s\n", hashGenesisBlock.ToString().c_str());
2709 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
2710 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
2712 assert(hash == hashGenesisBlock);
2714 // Start new block file
2715 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2716 CDiskBlockPos blockPos;
2717 if (!FindBlockPos(blockPos, nBlockSize+8, 0, block.nTime))
2718 return error("AcceptBlock() : FindBlockPos failed");
2719 if (!block.WriteToDisk(blockPos))
2720 return error("LoadBlockIndex() : writing genesis block to disk failed");
2721 if (!block.AddToBlockIndex(blockPos))
2722 return error("LoadBlockIndex() : genesis block not accepted");
2730 void PrintBlockTree()
2732 // pre-compute tree structure
2733 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2734 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2736 CBlockIndex* pindex = (*mi).second;
2737 mapNext[pindex->pprev].push_back(pindex);
2739 //while (rand() % 3 == 0)
2740 // mapNext[pindex->pprev].push_back(pindex);
2743 vector<pair<int, CBlockIndex*> > vStack;
2744 vStack.push_back(make_pair(0, pindexGenesisBlock));
2747 while (!vStack.empty())
2749 int nCol = vStack.back().first;
2750 CBlockIndex* pindex = vStack.back().second;
2753 // print split or gap
2754 if (nCol > nPrevCol)
2756 for (int i = 0; i < nCol-1; i++)
2760 else if (nCol < nPrevCol)
2762 for (int i = 0; i < nCol; i++)
2769 for (int i = 0; i < nCol; i++)
2774 block.ReadFromDisk(pindex);
2775 printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
2777 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2778 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
2781 PrintWallets(block);
2783 // put the main time-chain first
2784 vector<CBlockIndex*>& vNext = mapNext[pindex];
2785 for (unsigned int i = 0; i < vNext.size(); i++)
2787 if (vNext[i]->pnext)
2789 swap(vNext[0], vNext[i]);
2795 for (unsigned int i = 0; i < vNext.size(); i++)
2796 vStack.push_back(make_pair(nCol+i, vNext[i]));
2800 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
2802 int64 nStart = GetTimeMillis();
2806 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
2807 uint64 nStartByte = 0;
2809 // (try to) skip already indexed part
2810 CBlockFileInfo info;
2811 if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) {
2812 nStartByte = info.nSize;
2813 blkdat.Seek(info.nSize);
2816 uint64 nRewind = blkdat.GetPos();
2817 while (blkdat.good() && !blkdat.eof() && !fRequestShutdown) {
2818 blkdat.SetPos(nRewind);
2819 nRewind++; // start one byte further next time, in case of failure
2820 blkdat.SetLimit(); // remove former limit
2821 unsigned int nSize = 0;
2824 unsigned char buf[4];
2825 blkdat.FindByte(pchMessageStart[0]);
2826 nRewind = blkdat.GetPos()+1;
2827 blkdat >> FLATDATA(buf);
2828 if (memcmp(buf, pchMessageStart, 4))
2832 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
2834 } catch (std::exception &e) {
2835 // no valid block header found; don't complain
2840 uint64 nBlockPos = blkdat.GetPos();
2841 blkdat.SetLimit(nBlockPos + nSize);
2844 nRewind = blkdat.GetPos();
2847 if (nBlockPos >= nStartByte) {
2850 dbp->nPos = nBlockPos;
2851 if (ProcessBlock(NULL, &block, dbp))
2854 } catch (std::exception &e) {
2855 printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__);
2861 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2874 //////////////////////////////////////////////////////////////////////////////
2879 extern map<uint256, CAlert> mapAlerts;
2880 extern CCriticalSection cs_mapAlerts;
2882 string GetWarnings(string strFor)
2885 string strStatusBar;
2888 if (GetBoolArg("-testsafemode"))
2891 if (!CLIENT_VERSION_IS_RELEASE)
2892 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
2894 // Misc warnings like out of disk space and clock is wrong
2895 if (strMiscWarning != "")
2898 strStatusBar = strMiscWarning;
2901 // Longer invalid proof-of-work chain
2902 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2905 strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");
2911 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2913 const CAlert& alert = item.second;
2914 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2916 nPriority = alert.nPriority;
2917 strStatusBar = alert.strStatusBar;
2922 if (strFor == "statusbar")
2923 return strStatusBar;
2924 else if (strFor == "rpc")
2926 assert(!"GetWarnings() : invalid parameter");
2937 //////////////////////////////////////////////////////////////////////////////
2943 bool static AlreadyHave(const CInv& inv)
2949 bool txInMap = false;
2952 txInMap = mempool.exists(inv.hash);
2954 return txInMap || mapOrphanTransactions.count(inv.hash) ||
2955 pcoinsTip->HaveCoins(inv.hash);
2958 return mapBlockIndex.count(inv.hash) ||
2959 mapOrphanBlocks.count(inv.hash);
2961 // Don't know what it is, just say we already got one
2968 // The message start string is designed to be unlikely to occur in normal data.
2969 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
2970 // a large 4-byte int at any alignment.
2971 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2974 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2976 RandAddSeedPerfmon();
2978 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
2979 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2981 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2989 if (strCommand == "version")
2991 // Each connection can only send one version message
2992 if (pfrom->nVersion != 0)
2994 pfrom->Misbehaving(1);
3002 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3003 if (pfrom->nVersion < MIN_PROTO_VERSION)
3005 // Since February 20, 2012, the protocol is initiated at version 209,
3006 // and earlier versions are no longer supported
3007 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3008 pfrom->fDisconnect = true;
3012 if (pfrom->nVersion == 10300)
3013 pfrom->nVersion = 300;
3015 vRecv >> addrFrom >> nNonce;
3017 vRecv >> pfrom->strSubVer;
3019 vRecv >> pfrom->nStartingHeight;
3021 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3023 pfrom->fRelayTxes = true;
3025 if (pfrom->fInbound && addrMe.IsRoutable())
3027 pfrom->addrLocal = addrMe;
3031 // Disconnect if we connected to ourself
3032 if (nNonce == nLocalHostNonce && nNonce > 1)
3034 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3035 pfrom->fDisconnect = true;
3039 // Be shy and don't send version until we hear
3040 if (pfrom->fInbound)
3041 pfrom->PushVersion();
3043 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3045 AddTimeData(pfrom->addr, nTime);
3048 pfrom->PushMessage("verack");
3049 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3051 if (!pfrom->fInbound)
3053 // Advertise our address
3054 if (!fNoListen && !IsInitialBlockDownload())
3056 CAddress addr = GetLocalAddress(&pfrom->addr);
3057 if (addr.IsRoutable())
3058 pfrom->PushAddress(addr);
3061 // Get recent addresses
3062 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3064 pfrom->PushMessage("getaddr");
3065 pfrom->fGetAddr = true;
3067 addrman.Good(pfrom->addr);
3069 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3071 addrman.Add(addrFrom, addrFrom);
3072 addrman.Good(addrFrom);
3076 // Ask the first connected node for block updates
3077 static int nAskedForBlocks = 0;
3078 if (!pfrom->fClient && !pfrom->fOneShot && !fImporting && !fReindex &&
3079 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3080 (pfrom->nVersion < NOBLKS_VERSION_START ||
3081 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3082 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3085 pfrom->PushGetBlocks(pindexBest, uint256(0));
3091 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3092 item.second.RelayTo(pfrom);
3095 pfrom->fSuccessfullyConnected = true;
3097 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());
3099 cPeerBlockCounts.input(pfrom->nStartingHeight);
3103 else if (pfrom->nVersion == 0)
3105 // Must have a version message before anything else
3106 pfrom->Misbehaving(1);
3111 else if (strCommand == "verack")
3113 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3117 else if (strCommand == "addr")
3119 vector<CAddress> vAddr;
3122 // Don't want addr from older versions unless seeding
3123 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3125 if (vAddr.size() > 1000)
3127 pfrom->Misbehaving(20);
3128 return error("message addr size() = %"PRIszu"", vAddr.size());
3131 // Store the new addresses
3132 vector<CAddress> vAddrOk;
3133 int64 nNow = GetAdjustedTime();
3134 int64 nSince = nNow - 10 * 60;
3135 BOOST_FOREACH(CAddress& addr, vAddr)
3139 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3140 addr.nTime = nNow - 5 * 24 * 60 * 60;
3141 pfrom->AddAddressKnown(addr);
3142 bool fReachable = IsReachable(addr);
3143 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3145 // Relay to a limited number of other nodes
3148 // Use deterministic randomness to send to the same nodes for 24 hours
3149 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3150 static uint256 hashSalt;
3152 hashSalt = GetRandHash();
3153 uint64 hashAddr = addr.GetHash();
3154 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3155 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3156 multimap<uint256, CNode*> mapMix;
3157 BOOST_FOREACH(CNode* pnode, vNodes)
3159 if (pnode->nVersion < CADDR_TIME_VERSION)
3161 unsigned int nPointer;
3162 memcpy(&nPointer, &pnode, sizeof(nPointer));
3163 uint256 hashKey = hashRand ^ nPointer;
3164 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3165 mapMix.insert(make_pair(hashKey, pnode));
3167 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3168 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3169 ((*mi).second)->PushAddress(addr);
3172 // Do not store addresses outside our network
3174 vAddrOk.push_back(addr);
3176 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3177 if (vAddr.size() < 1000)
3178 pfrom->fGetAddr = false;
3179 if (pfrom->fOneShot)
3180 pfrom->fDisconnect = true;
3184 else if (strCommand == "inv")
3188 if (vInv.size() > MAX_INV_SZ)
3190 pfrom->Misbehaving(20);
3191 return error("message inv size() = %"PRIszu"", vInv.size());
3194 // find last block in inv vector
3195 unsigned int nLastBlock = (unsigned int)(-1);
3196 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3197 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3198 nLastBlock = vInv.size() - 1 - nInv;
3202 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3204 const CInv &inv = vInv[nInv];
3208 pfrom->AddInventoryKnown(inv);
3210 bool fAlreadyHave = AlreadyHave(inv);
3212 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3214 if (!fAlreadyHave) {
3215 if (!fImporting && !fReindex)
3217 } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3218 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3219 } else if (nInv == nLastBlock) {
3220 // In case we are on a very long side-chain, it is possible that we already have
3221 // the last block in an inv bundle sent in response to getblocks. Try to detect
3222 // this situation and push another getblocks to continue.
3223 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3225 printf("force request: %s\n", inv.ToString().c_str());
3228 // Track requests for our stuff
3229 Inventory(inv.hash);
3234 else if (strCommand == "getdata")
3238 if (vInv.size() > MAX_INV_SZ)
3240 pfrom->Misbehaving(20);
3241 return error("message getdata size() = %"PRIszu"", vInv.size());
3244 if (fDebugNet || (vInv.size() != 1))
3245 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3247 BOOST_FOREACH(const CInv& inv, vInv)
3251 if (fDebugNet || (vInv.size() == 1))
3252 printf("received getdata for: %s\n", inv.ToString().c_str());
3254 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3256 // Send block from disk
3257 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3258 if (mi != mapBlockIndex.end())
3261 block.ReadFromDisk((*mi).second);
3262 if (inv.type == MSG_BLOCK)
3263 pfrom->PushMessage("block", block);
3264 else // MSG_FILTERED_BLOCK)
3266 LOCK(pfrom->cs_filter);
3269 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3270 pfrom->PushMessage("merkleblock", merkleBlock);
3271 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3272 // This avoids hurting performance by pointlessly requiring a round-trip
3273 // Note that there is currently no way for a node to request any single transactions we didnt send here -
3274 // they must either disconnect and retry or request the full block.
3275 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3276 // however we MUST always provide at least what the remote peer needs
3277 typedef std::pair<unsigned int, uint256> PairType;
3278 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3279 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3280 pfrom->PushMessage("tx", block.vtx[pair.first]);
3286 // Trigger them to send a getblocks request for the next batch of inventory
3287 if (inv.hash == pfrom->hashContinue)
3289 // Bypass PushInventory, this must send even if redundant,
3290 // and we want it right after the last block so they don't
3291 // wait for other stuff first.
3293 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
3294 pfrom->PushMessage("inv", vInv);
3295 pfrom->hashContinue = 0;
3299 else if (inv.IsKnownType())
3301 // Send stream from relay memory
3302 bool pushed = false;
3305 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3306 if (mi != mapRelay.end()) {
3307 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3311 if (!pushed && inv.type == MSG_TX) {
3313 if (mempool.exists(inv.hash)) {
3314 CTransaction tx = mempool.lookup(inv.hash);
3315 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3318 pfrom->PushMessage("tx", ss);
3323 // Track requests for our stuff
3324 Inventory(inv.hash);
3329 else if (strCommand == "getblocks")
3331 CBlockLocator locator;
3333 vRecv >> locator >> hashStop;
3335 // Find the last block the caller has in the main chain
3336 CBlockIndex* pindex = locator.GetBlockIndex();
3338 // Send the rest of the chain
3340 pindex = pindex->pnext;
3342 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), BlockHashStr(hashStop).c_str(), nLimit);
3343 for (; pindex; pindex = pindex->pnext)
3345 if (pindex->GetBlockHash() == hashStop)
3347 printf(" getblocks stopping at %d %s\n", pindex->nHeight, BlockHashStr(pindex->GetBlockHash()).c_str());
3350 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3353 // When this block is requested, we'll send an inv that'll make them
3354 // getblocks the next batch of inventory.
3355 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, BlockHashStr(pindex->GetBlockHash()).c_str());
3356 pfrom->hashContinue = pindex->GetBlockHash();
3363 else if (strCommand == "getheaders")
3365 CBlockLocator locator;
3367 vRecv >> locator >> hashStop;
3369 CBlockIndex* pindex = NULL;
3370 if (locator.IsNull())
3372 // If locator is null, return the hashStop block
3373 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3374 if (mi == mapBlockIndex.end())
3376 pindex = (*mi).second;
3380 // Find the last block the caller has in the main chain
3381 pindex = locator.GetBlockIndex();
3383 pindex = pindex->pnext;
3386 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3387 vector<CBlock> vHeaders;
3389 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), BlockHashStr(hashStop).c_str());
3390 for (; pindex; pindex = pindex->pnext)
3392 vHeaders.push_back(pindex->GetBlockHeader());
3393 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3396 pfrom->PushMessage("headers", vHeaders);
3400 else if (strCommand == "tx")
3402 vector<uint256> vWorkQueue;
3403 vector<uint256> vEraseQueue;
3404 CDataStream vMsg(vRecv);
3408 CInv inv(MSG_TX, tx.GetHash());
3409 pfrom->AddInventoryKnown(inv);
3411 bool fMissingInputs = false;
3412 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
3414 SyncWithWallets(inv.hash, tx, NULL, true);
3415 RelayTransaction(tx, inv.hash, vMsg);
3416 mapAlreadyAskedFor.erase(inv);
3417 vWorkQueue.push_back(inv.hash);
3418 vEraseQueue.push_back(inv.hash);
3420 // Recursively process any orphan transactions that depended on this one
3421 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3423 uint256 hashPrev = vWorkQueue[i];
3424 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3425 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3428 const CDataStream& vMsg = *((*mi).second);
3430 CDataStream(vMsg) >> tx;
3431 CInv inv(MSG_TX, tx.GetHash());
3432 bool fMissingInputs2 = false;
3434 if (tx.AcceptToMemoryPool(true, &fMissingInputs2))
3436 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3437 SyncWithWallets(inv.hash, tx, NULL, true);
3438 RelayTransaction(tx, inv.hash, vMsg);
3439 mapAlreadyAskedFor.erase(inv);
3440 vWorkQueue.push_back(inv.hash);
3441 vEraseQueue.push_back(inv.hash);
3443 else if (!fMissingInputs2)
3446 vEraseQueue.push_back(inv.hash);
3447 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3452 BOOST_FOREACH(uint256 hash, vEraseQueue)
3453 EraseOrphanTx(hash);
3455 else if (fMissingInputs)
3459 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3460 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3462 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3464 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3468 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
3473 printf("received block %s\n", BlockHashStr(block.GetHash()).c_str());
3476 CInv inv(MSG_BLOCK, block.GetHash());
3477 pfrom->AddInventoryKnown(inv);
3479 if (ProcessBlock(pfrom, &block))
3480 mapAlreadyAskedFor.erase(inv);
3481 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3485 else if (strCommand == "getaddr")
3487 pfrom->vAddrToSend.clear();
3488 vector<CAddress> vAddr = addrman.GetAddr();
3489 BOOST_FOREACH(const CAddress &addr, vAddr)
3490 pfrom->PushAddress(addr);
3494 else if (strCommand == "mempool")
3496 std::vector<uint256> vtxid;
3497 LOCK2(mempool.cs, pfrom->cs_filter);
3498 mempool.queryHashes(vtxid);
3500 BOOST_FOREACH(uint256& hash, vtxid) {
3501 CInv inv(MSG_TX, hash);
3502 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(mempool.lookup(hash), hash)) ||
3504 vInv.push_back(inv);
3505 if (vInv.size() == MAX_INV_SZ)
3508 if (vInv.size() > 0)
3509 pfrom->PushMessage("inv", vInv);
3513 else if (strCommand == "ping")
3515 if (pfrom->nVersion > BIP0031_VERSION)
3519 // Echo the message back with the nonce. This allows for two useful features:
3521 // 1) A remote node can quickly check if the connection is operational
3522 // 2) Remote nodes can measure the latency of the network thread. If this node
3523 // is overloaded it won't respond to pings quickly and the remote node can
3524 // avoid sending us more work, like chain download requests.
3526 // The nonce stops the remote getting confused between different pings: without
3527 // it, if the remote node sends a ping once per second and this node takes 5
3528 // seconds to respond to each, the 5th ping the remote sends would appear to
3529 // return very quickly.
3530 pfrom->PushMessage("pong", nonce);
3535 else if (strCommand == "alert")
3540 uint256 alertHash = alert.GetHash();
3541 if (pfrom->setKnown.count(alertHash) == 0)
3543 if (alert.ProcessAlert())
3546 pfrom->setKnown.insert(alertHash);
3549 BOOST_FOREACH(CNode* pnode, vNodes)
3550 alert.RelayTo(pnode);
3554 // Small DoS penalty so peers that send us lots of
3555 // duplicate/expired/invalid-signature/whatever alerts
3556 // eventually get banned.
3557 // This isn't a Misbehaving(100) (immediate ban) because the
3558 // peer might be an older or different implementation with
3559 // a different signature key, etc.
3560 pfrom->Misbehaving(10);
3566 else if (strCommand == "filterload")
3568 CBloomFilter filter;
3571 if (!filter.IsWithinSizeConstraints())
3572 // There is no excuse for sending a too-large filter
3573 pfrom->Misbehaving(100);
3576 LOCK(pfrom->cs_filter);
3577 delete pfrom->pfilter;
3578 pfrom->pfilter = new CBloomFilter(filter);
3580 pfrom->fRelayTxes = true;
3584 else if (strCommand == "filteradd")
3586 vector<unsigned char> vData;
3589 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
3590 // and thus, the maximum size any matched object can have) in a filteradd message
3591 if (vData.size() > 520)
3593 pfrom->Misbehaving(100);
3595 LOCK(pfrom->cs_filter);
3597 pfrom->pfilter->insert(vData);
3599 pfrom->Misbehaving(100);
3604 else if (strCommand == "filterclear")
3606 LOCK(pfrom->cs_filter);
3607 delete pfrom->pfilter;
3608 pfrom->pfilter = NULL;
3609 pfrom->fRelayTxes = true;
3615 // Ignore unknown commands for extensibility
3619 // Update the last seen time for this node's address
3620 if (pfrom->fNetworkNode)
3621 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3622 AddressCurrentlyConnected(pfrom->addr);
3628 bool ProcessMessages(CNode* pfrom)
3630 CDataStream& vRecv = pfrom->vRecv;
3634 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3638 // (4) message start
3647 // Don't bother if send buffer is too full to respond anyway
3648 if (pfrom->vSend.size() >= SendBufferSize())
3651 // Scan for message start
3652 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3653 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3654 if (vRecv.end() - pstart < nHeaderSize)
3656 if ((int)vRecv.size() > nHeaderSize)
3658 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3659 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3663 if (pstart - vRecv.begin() > 0)
3664 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3665 vRecv.erase(vRecv.begin(), pstart);
3668 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3673 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3676 string strCommand = hdr.GetCommand();
3679 unsigned int nMessageSize = hdr.nMessageSize;
3680 if (nMessageSize > MAX_SIZE)
3682 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3685 if (nMessageSize > vRecv.size())
3687 // Rewind and wait for rest of message
3688 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3693 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3694 unsigned int nChecksum = 0;
3695 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3696 if (nChecksum != hdr.nChecksum)
3698 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3699 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3703 // Copy message to its own buffer
3704 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3705 vRecv.ignore(nMessageSize);
3713 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3718 catch (std::ios_base::failure& e)
3720 if (strstr(e.what(), "end of data"))
3722 // Allow exceptions from under-length message on vRecv
3723 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());
3725 else if (strstr(e.what(), "size too large"))
3727 // Allow exceptions from over-long size
3728 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3732 PrintExceptionContinue(&e, "ProcessMessages()");
3735 catch (std::exception& e) {
3736 PrintExceptionContinue(&e, "ProcessMessages()");
3738 PrintExceptionContinue(NULL, "ProcessMessages()");
3742 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3750 bool SendMessages(CNode* pto, bool fSendTrickle)
3752 TRY_LOCK(cs_main, lockMain);
3754 // Don't send anything until we get their version message
3755 if (pto->nVersion == 0)
3758 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3760 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3762 if (pto->nVersion > BIP0031_VERSION)
3763 pto->PushMessage("ping", nonce);
3765 pto->PushMessage("ping");
3768 // Resend wallet transactions that haven't gotten in a block yet
3769 ResendWalletTransactions();
3771 // Address refresh broadcast
3772 static int64 nLastRebroadcast;
3773 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3777 BOOST_FOREACH(CNode* pnode, vNodes)
3779 // Periodically clear setAddrKnown to allow refresh broadcasts
3780 if (nLastRebroadcast)
3781 pnode->setAddrKnown.clear();
3783 // Rebroadcast our address
3786 CAddress addr = GetLocalAddress(&pnode->addr);
3787 if (addr.IsRoutable())
3788 pnode->PushAddress(addr);
3792 nLastRebroadcast = GetTime();
3800 vector<CAddress> vAddr;
3801 vAddr.reserve(pto->vAddrToSend.size());
3802 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3804 // returns true if wasn't already contained in the set
3805 if (pto->setAddrKnown.insert(addr).second)
3807 vAddr.push_back(addr);
3808 // receiver rejects addr messages larger than 1000
3809 if (vAddr.size() >= 1000)
3811 pto->PushMessage("addr", vAddr);
3816 pto->vAddrToSend.clear();
3818 pto->PushMessage("addr", vAddr);
3823 // Message: inventory
3826 vector<CInv> vInvWait;
3828 LOCK(pto->cs_inventory);
3829 vInv.reserve(pto->vInventoryToSend.size());
3830 vInvWait.reserve(pto->vInventoryToSend.size());
3831 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3833 if (pto->setInventoryKnown.count(inv))
3836 // trickle out tx inv to protect privacy
3837 if (inv.type == MSG_TX && !fSendTrickle)
3839 // 1/4 of tx invs blast to all immediately
3840 static uint256 hashSalt;
3842 hashSalt = GetRandHash();
3843 uint256 hashRand = inv.hash ^ hashSalt;
3844 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3845 bool fTrickleWait = ((hashRand & 3) != 0);
3847 // always trickle our own transactions
3851 if (GetTransaction(inv.hash, wtx))
3853 fTrickleWait = true;
3858 vInvWait.push_back(inv);
3863 // returns true if wasn't already contained in the set
3864 if (pto->setInventoryKnown.insert(inv).second)
3866 vInv.push_back(inv);
3867 if (vInv.size() >= 1000)
3869 pto->PushMessage("inv", vInv);
3874 pto->vInventoryToSend = vInvWait;
3877 pto->PushMessage("inv", vInv);
3883 vector<CInv> vGetData;
3884 int64 nNow = GetTime() * 1000000;
3885 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3887 const CInv& inv = (*pto->mapAskFor.begin()).second;
3888 if (!AlreadyHave(inv))
3891 printf("sending getdata: %s\n", inv.ToString().c_str());
3892 vGetData.push_back(inv);
3893 if (vGetData.size() >= 1000)
3895 pto->PushMessage("getdata", vGetData);
3898 mapAlreadyAskedFor[inv] = nNow;
3900 pto->mapAskFor.erase(pto->mapAskFor.begin());
3902 if (!vGetData.empty())
3903 pto->PushMessage("getdata", vGetData);
3922 //////////////////////////////////////////////////////////////////////////////
3927 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3929 unsigned char* pdata = (unsigned char*)pbuffer;
3930 unsigned int blocks = 1 + ((len + 8) / 64);
3931 unsigned char* pend = pdata + 64 * blocks;
3932 memset(pdata + len, 0, 64 * blocks - len);
3934 unsigned int bits = len * 8;
3935 pend[-1] = (bits >> 0) & 0xff;
3936 pend[-2] = (bits >> 8) & 0xff;
3937 pend[-3] = (bits >> 16) & 0xff;
3938 pend[-4] = (bits >> 24) & 0xff;
3942 static const unsigned int pSHA256InitState[8] =
3943 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3945 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3948 unsigned char data[64];
3952 for (int i = 0; i < 16; i++)
3953 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3955 for (int i = 0; i < 8; i++)
3956 ctx.h[i] = ((uint32_t*)pinit)[i];
3958 SHA256_Update(&ctx, data, sizeof(data));
3959 for (int i = 0; i < 8; i++)
3960 ((uint32_t*)pstate)[i] = ctx.h[i];
3964 // ScanHash scans nonces looking for a hash with at least some zero bits.
3965 // It operates on big endian data. Caller does the byte reversing.
3966 // All input buffers are 16-byte aligned. nNonce is usually preserved
3967 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3968 // the block is rebuilt and nNonce starts over at zero.
3970 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3972 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3976 // Hash pdata using pmidstate as the starting state into
3977 // pre-formatted buffer phash1, then hash phash1 into phash
3979 SHA256Transform(phash1, pdata, pmidstate);
3980 SHA256Transform(phash, phash1, pSHA256InitState);
3982 // Return the nonce if the hash has at least some zero bits,
3983 // caller will check if it has enough to reach the target
3984 if (((unsigned short*)phash)[14] == 0)
3987 // If nothing found after trying for a while, return -1
3988 if ((nNonce & 0xffff) == 0)
3990 nHashesDone = 0xffff+1;
3991 return (unsigned int) -1;
3996 // Some explaining would be appreciated
4001 set<uint256> setDependsOn;
4005 COrphan(CTransaction* ptxIn)
4008 dPriority = dFeePerKb = 0;
4013 printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
4014 ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
4015 BOOST_FOREACH(uint256 hash, setDependsOn)
4016 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
4021 uint64 nLastBlockTx = 0;
4022 uint64 nLastBlockSize = 0;
4024 // We want to sort transactions by priority and fee, so:
4025 typedef boost::tuple<double, double, CTransaction*> TxPriority;
4026 class TxPriorityCompare
4030 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
4031 bool operator()(const TxPriority& a, const TxPriority& b)
4035 if (a.get<1>() == b.get<1>())
4036 return a.get<0>() < b.get<0>();
4037 return a.get<1>() < b.get<1>();
4041 if (a.get<0>() == b.get<0>())
4042 return a.get<1>() < b.get<1>();
4043 return a.get<0>() < b.get<0>();
4048 CBlockTemplate* CreateNewBlock(CReserveKey& reservekey)
4051 auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
4052 if(!pblocktemplate.get())
4054 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
4056 // Create coinbase tx
4058 txNew.vin.resize(1);
4059 txNew.vin[0].prevout.SetNull();
4060 txNew.vout.resize(1);
4061 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
4063 // Add our coinbase tx as first transaction
4064 pblock->vtx.push_back(txNew);
4065 pblocktemplate->vTxFees.push_back(-1); // updated at end
4066 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
4068 // Largest block you're willing to create:
4069 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
4070 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
4071 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
4073 // How much of the block should be dedicated to high-priority transactions,
4074 // included regardless of the fees they pay
4075 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
4076 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
4078 // Minimum block size you want to create; block will be filled with free transactions
4079 // until there are no more or the block reaches this size:
4080 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
4081 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
4083 // Fee-per-kilobyte amount considered the same as "free"
4084 // Be careful setting this: if you set it to zero then
4085 // a transaction spammer can cheaply fill blocks using
4086 // 1-satoshi-fee transactions. It should be set above the real
4087 // cost to you of processing a transaction.
4088 int64 nMinTxFee = MIN_TX_FEE;
4089 if (mapArgs.count("-mintxfee"))
4090 ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
4092 // Collect memory pool transactions into the block
4095 LOCK2(cs_main, mempool.cs);
4096 CBlockIndex* pindexPrev = pindexBest;
4097 CCoinsViewCache view(*pcoinsTip, true);
4099 // Priority order to process transactions
4100 list<COrphan> vOrphan; // list memory doesn't move
4101 map<uint256, vector<COrphan*> > mapDependers;
4102 bool fPrintPriority = GetBoolArg("-printpriority");
4104 // This vector will be sorted into a priority queue:
4105 vector<TxPriority> vecPriority;
4106 vecPriority.reserve(mempool.mapTx.size());
4107 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
4109 CTransaction& tx = (*mi).second;
4110 if (tx.IsCoinBase() || !tx.IsFinal())
4113 COrphan* porphan = NULL;
4114 double dPriority = 0;
4116 bool fMissingInputs = false;
4117 BOOST_FOREACH(const CTxIn& txin, tx.vin)
4119 // Read prev transaction
4121 if (!view.GetCoins(txin.prevout.hash, coins))
4123 // This should never happen; all transactions in the memory
4124 // pool should connect to either transactions in the chain
4125 // or other transactions in the memory pool.
4126 if (!mempool.mapTx.count(txin.prevout.hash))
4128 printf("ERROR: mempool transaction missing input\n");
4129 if (fDebug) assert("mempool transaction missing input" == 0);
4130 fMissingInputs = true;
4136 // Has to wait for dependencies
4139 // Use list for automatic deletion
4140 vOrphan.push_back(COrphan(&tx));
4141 porphan = &vOrphan.back();
4143 mapDependers[txin.prevout.hash].push_back(porphan);
4144 porphan->setDependsOn.insert(txin.prevout.hash);
4145 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
4149 int64 nValueIn = coins.vout[txin.prevout.n].nValue;
4150 nTotalIn += nValueIn;
4152 int nConf = pindexPrev->nHeight - coins.nHeight + 1;
4154 dPriority += (double)nValueIn * nConf;
4156 if (fMissingInputs) continue;
4158 // Priority is sum(valuein * age) / txsize
4159 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4160 dPriority /= nTxSize;
4162 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
4163 // client code rounds up the size to the nearest 1K. That's good, because it gives an
4164 // incentive to create smaller transactions.
4165 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
4169 porphan->dPriority = dPriority;
4170 porphan->dFeePerKb = dFeePerKb;
4173 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
4176 // Collect transactions into block
4177 uint64 nBlockSize = 1000;
4178 uint64 nBlockTx = 0;
4179 int nBlockSigOps = 100;
4180 bool fSortedByFee = (nBlockPrioritySize <= 0);
4182 TxPriorityCompare comparer(fSortedByFee);
4183 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4185 while (!vecPriority.empty())
4187 // Take highest priority transaction off the priority queue:
4188 double dPriority = vecPriority.front().get<0>();
4189 double dFeePerKb = vecPriority.front().get<1>();
4190 CTransaction& tx = *(vecPriority.front().get<2>());
4192 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
4193 vecPriority.pop_back();
4195 // second layer cached modifications just for this transaction
4196 CCoinsViewCache viewTemp(view, true);
4199 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4200 if (nBlockSize + nTxSize >= nBlockMaxSize)
4203 // Legacy limits on sigOps:
4204 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
4205 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4208 // Skip free transactions if we're past the minimum block size:
4209 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
4212 // Prioritize by fee once past the priority size or we run out of high-priority
4214 if (!fSortedByFee &&
4215 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
4217 fSortedByFee = true;
4218 comparer = TxPriorityCompare(fSortedByFee);
4219 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4222 if (!tx.HaveInputs(viewTemp))
4225 int64 nTxFees = tx.GetValueIn(viewTemp)-tx.GetValueOut();
4227 nTxSigOps += tx.GetP2SHSigOpCount(viewTemp);
4228 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4231 if (!tx.CheckInputs(viewTemp, true, SCRIPT_VERIFY_P2SH))
4235 uint256 hash = tx.GetHash();
4236 if (!tx.UpdateCoins(viewTemp, txundo, pindexPrev->nHeight+1, hash))
4239 // push changes from the second layer cache to the first one
4243 pblock->vtx.push_back(tx);
4244 pblocktemplate->vTxFees.push_back(nTxFees);
4245 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
4246 nBlockSize += nTxSize;
4248 nBlockSigOps += nTxSigOps;
4253 printf("priority %.1f feeperkb %.1f txid %s\n",
4254 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
4257 // Add transactions that depend on this one to the priority queue
4258 if (mapDependers.count(hash))
4260 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
4262 if (!porphan->setDependsOn.empty())
4264 porphan->setDependsOn.erase(hash);
4265 if (porphan->setDependsOn.empty())
4267 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
4268 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
4275 nLastBlockTx = nBlockTx;
4276 nLastBlockSize = nBlockSize;
4277 printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
4279 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
4280 pblocktemplate->vTxFees[0] = -nFees;
4283 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
4284 pblock->UpdateTime(pindexPrev);
4285 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
4287 pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
4288 pblocktemplate->vTxSigOps[0] = pblock->vtx[0].GetLegacySigOpCount();
4290 CBlockIndex indexDummy(*pblock);
4291 indexDummy.pprev = pindexPrev;
4292 indexDummy.nHeight = pindexPrev->nHeight + 1;
4293 CCoinsViewCache viewNew(*pcoinsTip, true);
4294 if (!pblock->ConnectBlock(&indexDummy, viewNew, true))
4295 throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
4298 return pblocktemplate.release();
4302 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
4304 // Update nExtraNonce
4305 static uint256 hashPrevBlock;
4306 if (hashPrevBlock != pblock->hashPrevBlock)
4309 hashPrevBlock = pblock->hashPrevBlock;
4312 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4313 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4314 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
4316 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
4320 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
4323 // Pre-build hash buffers
4330 uint256 hashPrevBlock;
4331 uint256 hashMerkleRoot;
4334 unsigned int nNonce;
4337 unsigned char pchPadding0[64];
4339 unsigned char pchPadding1[64];
4342 memset(&tmp, 0, sizeof(tmp));
4344 tmp.block.nVersion = pblock->nVersion;
4345 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
4346 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
4347 tmp.block.nTime = pblock->nTime;
4348 tmp.block.nBits = pblock->nBits;
4349 tmp.block.nNonce = pblock->nNonce;
4351 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
4352 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
4354 // Byte swap all the input buffer
4355 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
4356 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
4358 // Precalc the first half of the first hash, which stays constant
4359 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
4361 memcpy(pdata, &tmp.block, 128);
4362 memcpy(phash1, &tmp.hash1, 64);
4366 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
4368 uint256 hash = pblock->GetHash();
4369 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4371 if (hash > hashTarget)
4375 printf("BitcoinMiner:\n");
4376 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
4378 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
4383 if (pblock->hashPrevBlock != hashBestChain)
4384 return error("BitcoinMiner : generated block is stale");
4386 // Remove key from key pool
4387 reservekey.KeepKey();
4389 // Track how many getdata requests this block gets
4391 LOCK(wallet.cs_wallet);
4392 wallet.mapRequestCount[pblock->GetHash()] = 0;
4395 // Process this block the same as if we had received it from another node
4396 if (!ProcessBlock(NULL, pblock))
4397 return error("BitcoinMiner : ProcessBlock, block not accepted");
4403 void static ThreadBitcoinMiner(void* parg);
4405 static bool fGenerateBitcoins = false;
4406 static bool fLimitProcessors = false;
4407 static int nLimitProcessors = -1;
4409 void static BitcoinMiner(CWallet *pwallet)
4411 printf("BitcoinMiner started\n");
4412 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4414 // Make this thread recognisable as the mining thread
4415 RenameThread("bitcoin-miner");
4417 // Each thread has its own key and counter
4418 CReserveKey reservekey(pwallet);
4419 unsigned int nExtraNonce = 0;
4421 while (fGenerateBitcoins)
4425 while (vNodes.empty() || IsInitialBlockDownload())
4430 if (!fGenerateBitcoins)
4438 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
4439 CBlockIndex* pindexPrev = pindexBest;
4441 auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(reservekey));
4442 if (!pblocktemplate.get())
4444 CBlock *pblock = &pblocktemplate->block;
4445 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
4447 printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
4448 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
4452 // Pre-build hash buffers
4454 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
4455 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
4456 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
4458 FormatHashBuffers(pblock, pmidstate, pdata, phash1);
4460 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
4461 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
4462 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
4468 int64 nStart = GetTime();
4469 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4471 uint256& hash = *alignup<16>(hashbuf);
4474 unsigned int nHashesDone = 0;
4475 unsigned int nNonceFound;
4478 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
4479 (char*)&hash, nHashesDone);
4481 // Check if something found
4482 if (nNonceFound != (unsigned int) -1)
4484 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
4485 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
4487 if (hash <= hashTarget)
4490 pblock->nNonce = ByteReverse(nNonceFound);
4491 assert(hash == pblock->GetHash());
4493 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4494 CheckWork(pblock, *pwalletMain, reservekey);
4495 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4501 static int64 nHashCounter;
4502 if (nHPSTimerStart == 0)
4504 nHPSTimerStart = GetTimeMillis();
4508 nHashCounter += nHashesDone;
4509 if (GetTimeMillis() - nHPSTimerStart > 4000)
4511 static CCriticalSection cs;
4514 if (GetTimeMillis() - nHPSTimerStart > 4000)
4516 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
4517 nHPSTimerStart = GetTimeMillis();
4519 static int64 nLogTime;
4520 if (GetTime() - nLogTime > 30 * 60)
4522 nLogTime = GetTime();
4523 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
4529 // Check for stop or if block needs to be rebuilt
4532 if (!fGenerateBitcoins)
4534 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4538 if (nBlockNonce >= 0xffff0000)
4540 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4542 if (pindexPrev != pindexBest)
4545 // Update nTime every few seconds
4546 pblock->UpdateTime(pindexPrev);
4547 nBlockTime = ByteReverse(pblock->nTime);
4550 // Changing pblock->nTime can change work required on testnet:
4551 nBlockBits = ByteReverse(pblock->nBits);
4552 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4558 void static ThreadBitcoinMiner(void* parg)
4560 CWallet* pwallet = (CWallet*)parg;
4563 vnThreadsRunning[THREAD_MINER]++;
4564 BitcoinMiner(pwallet);
4565 vnThreadsRunning[THREAD_MINER]--;
4567 catch (std::exception& e) {
4568 vnThreadsRunning[THREAD_MINER]--;
4569 PrintException(&e, "ThreadBitcoinMiner()");
4571 vnThreadsRunning[THREAD_MINER]--;
4572 PrintException(NULL, "ThreadBitcoinMiner()");
4575 if (vnThreadsRunning[THREAD_MINER] == 0)
4577 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4581 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4583 fGenerateBitcoins = fGenerate;
4584 nLimitProcessors = GetArg("-genproclimit", -1);
4585 if (nLimitProcessors == 0)
4586 fGenerateBitcoins = false;
4587 fLimitProcessors = (nLimitProcessors != -1);
4591 int nProcessors = boost::thread::hardware_concurrency();
4592 printf("%d processors\n", nProcessors);
4593 if (nProcessors < 1)
4595 if (fLimitProcessors && nProcessors > nLimitProcessors)
4596 nProcessors = nLimitProcessors;
4597 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4598 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4599 for (int i = 0; i < nAddThreads; i++)
4601 if (!NewThread(ThreadBitcoinMiner, pwallet))
4602 printf("Error: NewThread(ThreadBitcoinMiner) failed\n");
4608 // Amount compression:
4609 // * If the amount is 0, output 0
4610 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
4611 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
4612 // * call the result n
4613 // * output 1 + 10*(9*n + d - 1) + e
4614 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
4615 // (this is decodable, as d is in [1-9] and e is in [0-9])
4617 uint64 CTxOutCompressor::CompressAmount(uint64 n)
4622 while (((n % 10) == 0) && e < 9) {
4628 assert(d >= 1 && d <= 9);
4630 return 1 + (n*9 + d - 1)*10 + e;
4632 return 1 + (n - 1)*10 + 9;
4636 uint64 CTxOutCompressor::DecompressAmount(uint64 x)
4638 // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
4642 // x = 10*(9*n + d - 1) + e
4648 int d = (x % 9) + 1;