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 <boost/algorithm/string/replace.hpp>
14 #include <boost/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
18 using namespace boost;
24 CCriticalSection cs_setpwalletRegistered;
25 set<CWallet*> setpwalletRegistered;
27 CCriticalSection cs_main;
30 unsigned int nTransactionsUpdated = 0;
32 map<uint256, CBlockIndex*> mapBlockIndex;
33 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
34 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
35 CBlockIndex* pindexGenesisBlock = NULL;
37 CBigNum bnBestChainWork = 0;
38 CBigNum bnBestInvalidWork = 0;
39 uint256 hashBestChain = 0;
40 CBlockIndex* pindexBest = NULL;
41 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
42 int64 nTimeBestReceived = 0;
43 bool fImporting = false;
45 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
47 map<uint256, CBlock*> mapOrphanBlocks;
48 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
50 map<uint256, CDataStream*> mapOrphanTransactions;
51 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
53 // Constant stuff for coinbase transactions we create:
54 CScript COINBASE_FLAGS;
56 const string strMessageMagic = "Bitcoin Signed Message:\n";
62 int64 nTransactionFee = 0;
66 //////////////////////////////////////////////////////////////////////////////
68 // dispatching functions
71 // These functions dispatch to one or all registered wallets
74 void RegisterWallet(CWallet* pwalletIn)
77 LOCK(cs_setpwalletRegistered);
78 setpwalletRegistered.insert(pwalletIn);
82 void UnregisterWallet(CWallet* pwalletIn)
85 LOCK(cs_setpwalletRegistered);
86 setpwalletRegistered.erase(pwalletIn);
90 // check whether the passed transaction is from us
91 bool static IsFromMe(CTransaction& tx)
93 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
94 if (pwallet->IsFromMe(tx))
99 // get the wallet transaction with the given hash (if it exists)
100 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
102 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
103 if (pwallet->GetTransaction(hashTx,wtx))
108 // erases transaction with the given hash from all wallets
109 void static EraseFromWallets(uint256 hash)
111 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
112 pwallet->EraseFromWallet(hash);
115 // make sure all wallets know about the given transaction, in the given block
116 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate)
118 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
119 pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
122 // notify wallets about a new best chain
123 void static SetBestChain(const CBlockLocator& loc)
125 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126 pwallet->SetBestChain(loc);
129 // notify wallets about an updated transaction
130 void static UpdatedTransaction(const uint256& hashTx)
132 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
133 pwallet->UpdatedTransaction(hashTx);
137 void static PrintWallets(const CBlock& block)
139 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
140 pwallet->PrintWallet(block);
143 // notify wallets about an incoming inventory (for request counts)
144 void static Inventory(const uint256& hash)
146 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
147 pwallet->Inventory(hash);
150 // ask wallets to resend their transactions
151 void static ResendWalletTransactions()
153 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
154 pwallet->ResendWalletTransactions();
163 //////////////////////////////////////////////////////////////////////////////
165 // CCoinsView implementations
168 bool CCoinsView::GetCoins(uint256 txid, CCoins &coins) { return false; }
169 bool CCoinsView::SetCoins(uint256 txid, const CCoins &coins) { return false; }
170 bool CCoinsView::HaveCoins(uint256 txid) { return false; }
171 CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
172 bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
173 bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
174 bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
177 CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
178 bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); }
179 bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
180 bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); }
181 CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
182 bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
183 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
184 bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
185 bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); }
187 CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
189 bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) {
190 if (cacheCoins.count(txid)) {
191 coins = cacheCoins[txid];
194 if (base->GetCoins(txid, coins)) {
195 cacheCoins[txid] = coins;
201 std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(uint256 txid) {
202 std::map<uint256,CCoins>::iterator it = cacheCoins.find(txid);
203 if (it != cacheCoins.end())
206 if (!base->GetCoins(txid,tmp))
208 std::pair<std::map<uint256,CCoins>::iterator,bool> ret = cacheCoins.insert(std::make_pair(txid, tmp));
212 CCoins &CCoinsViewCache::GetCoins(uint256 txid) {
213 std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
214 assert(it != cacheCoins.end());
218 bool CCoinsViewCache::SetCoins(uint256 txid, const CCoins &coins) {
219 cacheCoins[txid] = coins;
223 bool CCoinsViewCache::HaveCoins(uint256 txid) {
224 return FetchCoins(txid) != cacheCoins.end();
227 CBlockIndex *CCoinsViewCache::GetBestBlock() {
228 if (pindexTip == NULL)
229 pindexTip = base->GetBestBlock();
233 bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
238 bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
239 for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
240 cacheCoins[it->first] = it->second;
245 bool CCoinsViewCache::Flush() {
246 bool fOk = base->BatchWrite(cacheCoins, pindexTip);
252 unsigned int CCoinsViewCache::GetCacheSize() {
253 return cacheCoins.size();
256 /** CCoinsView that brings transactions from a memorypool into view.
257 It does not check for spendings by memory pool transactions. */
258 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
260 bool CCoinsViewMemPool::GetCoins(uint256 txid, CCoins &coins) {
261 if (base->GetCoins(txid, coins))
263 if (mempool.exists(txid)) {
264 const CTransaction &tx = mempool.lookup(txid);
265 coins = CCoins(tx, MEMPOOL_HEIGHT);
271 bool CCoinsViewMemPool::HaveCoins(uint256 txid) {
272 return mempool.exists(txid) || base->HaveCoins(txid);
275 CCoinsViewCache *pcoinsTip = NULL;
276 CBlockTreeDB *pblocktree = NULL;
278 //////////////////////////////////////////////////////////////////////////////
280 // mapOrphanTransactions
283 bool AddOrphanTx(const CDataStream& vMsg)
286 CDataStream(vMsg) >> tx;
287 uint256 hash = tx.GetHash();
288 if (mapOrphanTransactions.count(hash))
291 CDataStream* pvMsg = new CDataStream(vMsg);
293 // Ignore big transactions, to avoid a
294 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
295 // large transaction with a missing parent then we assume
296 // it will rebroadcast it later, after the parent transaction(s)
297 // have been mined or received.
298 // 10,000 orphans, each of which is at most 5,000 bytes big is
299 // at most 500 megabytes of orphans:
300 if (pvMsg->size() > 5000)
302 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
307 mapOrphanTransactions[hash] = pvMsg;
308 BOOST_FOREACH(const CTxIn& txin, tx.vin)
309 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
311 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
312 mapOrphanTransactions.size());
316 void static EraseOrphanTx(uint256 hash)
318 if (!mapOrphanTransactions.count(hash))
320 const CDataStream* pvMsg = mapOrphanTransactions[hash];
322 CDataStream(*pvMsg) >> tx;
323 BOOST_FOREACH(const CTxIn& txin, tx.vin)
325 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
326 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
327 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
330 mapOrphanTransactions.erase(hash);
333 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
335 unsigned int nEvicted = 0;
336 while (mapOrphanTransactions.size() > nMaxOrphans)
338 // Evict a random orphan:
339 uint256 randomhash = GetRandHash();
340 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
341 if (it == mapOrphanTransactions.end())
342 it = mapOrphanTransactions.begin();
343 EraseOrphanTx(it->first);
355 //////////////////////////////////////////////////////////////////////////////
360 bool CTransaction::IsStandard() const
362 if (nVersion > CTransaction::CURRENT_VERSION)
365 BOOST_FOREACH(const CTxIn& txin, vin)
367 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
368 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
369 // ~65-byte public keys, plus a few script ops.
370 if (txin.scriptSig.size() > 500)
372 if (!txin.scriptSig.IsPushOnly())
375 BOOST_FOREACH(const CTxOut& txout, vout) {
376 if (!::IsStandard(txout.scriptPubKey))
378 if (txout.nValue == 0)
385 // Check transaction inputs, and make sure any
386 // pay-to-script-hash transactions are evaluating IsStandard scripts
388 // Why bother? To avoid denial-of-service attacks; an attacker
389 // can submit a standard HASH... OP_EQUAL transaction,
390 // which will get accepted into blocks. The redemption
391 // script can be anything; an attacker could use a very
392 // expensive-to-check-upon-redemption script like:
393 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
395 bool CTransaction::AreInputsStandard(CCoinsViewCache& mapInputs) const
398 return true; // Coinbases don't use vin normally
400 for (unsigned int i = 0; i < vin.size(); i++)
402 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
404 vector<vector<unsigned char> > vSolutions;
405 txnouttype whichType;
406 // get the scriptPubKey corresponding to this input:
407 const CScript& prevScript = prev.scriptPubKey;
408 if (!Solver(prevScript, whichType, vSolutions))
410 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
411 if (nArgsExpected < 0)
414 // Transactions with extra stuff in their scriptSigs are
415 // non-standard. Note that this EvalScript() call will
416 // be quick, because if there are any operations
417 // beside "push data" in the scriptSig the
418 // IsStandard() call returns false
419 vector<vector<unsigned char> > stack;
420 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
423 if (whichType == TX_SCRIPTHASH)
427 CScript subscript(stack.back().begin(), stack.back().end());
428 vector<vector<unsigned char> > vSolutions2;
429 txnouttype whichType2;
430 if (!Solver(subscript, whichType2, vSolutions2))
432 if (whichType2 == TX_SCRIPTHASH)
436 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
439 nArgsExpected += tmpExpected;
442 if (stack.size() != (unsigned int)nArgsExpected)
450 CTransaction::GetLegacySigOpCount() const
452 unsigned int nSigOps = 0;
453 BOOST_FOREACH(const CTxIn& txin, vin)
455 nSigOps += txin.scriptSig.GetSigOpCount(false);
457 BOOST_FOREACH(const CTxOut& txout, vout)
459 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
465 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
476 if (pblock == NULL) {
478 if (pcoinsTip->GetCoins(GetHash(), coins)) {
479 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
481 if (!blockTmp.ReadFromDisk(pindex))
489 // Update the tx's hashBlock
490 hashBlock = pblock->GetHash();
492 // Locate the transaction
493 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
494 if (pblock->vtx[nIndex] == *(CTransaction*)this)
496 if (nIndex == (int)pblock->vtx.size())
498 vMerkleBranch.clear();
500 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
504 // Fill in merkle branch
505 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
509 // Is the tx in a block that's in the main chain
510 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
511 if (mi == mapBlockIndex.end())
513 CBlockIndex* pindex = (*mi).second;
514 if (!pindex || !pindex->IsInMainChain())
517 return pindexBest->nHeight - pindex->nHeight + 1;
526 bool CTransaction::CheckTransaction() const
528 // Basic checks that don't depend on any context
530 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
532 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
534 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
535 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
537 // Check for negative or overflow output values
539 BOOST_FOREACH(const CTxOut& txout, vout)
541 if (txout.nValue < 0)
542 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
543 if (txout.nValue > MAX_MONEY)
544 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
545 nValueOut += txout.nValue;
546 if (!MoneyRange(nValueOut))
547 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
550 // Check for duplicate inputs
551 set<COutPoint> vInOutPoints;
552 BOOST_FOREACH(const CTxIn& txin, vin)
554 if (vInOutPoints.count(txin.prevout))
556 vInOutPoints.insert(txin.prevout);
561 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
562 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
566 BOOST_FOREACH(const CTxIn& txin, vin)
567 if (txin.prevout.IsNull())
568 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
574 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
575 enum GetMinFee_mode mode) const
577 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
578 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
580 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
581 unsigned int nNewBlockSize = nBlockSize + nBytes;
582 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
588 // Transactions under 10K are free
589 // (about 4500 BTC if made of 50 BTC inputs)
595 // Free transaction area
596 if (nNewBlockSize < 27000)
601 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
602 if (nMinFee < nBaseFee)
604 BOOST_FOREACH(const CTxOut& txout, vout)
605 if (txout.nValue < CENT)
609 // Raise the price as the block approaches full
610 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
612 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
614 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
617 if (!MoneyRange(nMinFee))
622 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
626 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
628 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
629 while (it != mapNextTx.end() && it->first.hash == hashTx) {
630 coins.Spend(it->first.n); // and remove those outputs from coins
635 bool CTxMemPool::accept(CTransaction &tx, bool fCheckInputs,
636 bool* pfMissingInputs)
639 *pfMissingInputs = false;
641 if (!tx.CheckTransaction())
642 return error("CTxMemPool::accept() : CheckTransaction failed");
644 // Coinbase is only valid in a block, not as a loose transaction
646 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
648 // To help v0.1.5 clients who would see it as a negative number
649 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
650 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
652 // Rather not work on nonstandard transactions (unless -testnet)
653 if (!fTestNet && !tx.IsStandard())
654 return error("CTxMemPool::accept() : nonstandard transaction type");
656 // is it already in the memory pool?
657 uint256 hash = tx.GetHash();
660 if (mapTx.count(hash))
664 // Check for conflicts with in-memory transactions
665 CTransaction* ptxOld = NULL;
666 for (unsigned int i = 0; i < tx.vin.size(); i++)
668 COutPoint outpoint = tx.vin[i].prevout;
669 if (mapNextTx.count(outpoint))
671 // Disable replacement feature for now
674 // Allow replacing with a newer version of the same transaction
677 ptxOld = mapNextTx[outpoint].ptx;
678 if (ptxOld->IsFinal())
680 if (!tx.IsNewerThan(*ptxOld))
682 for (unsigned int i = 0; i < tx.vin.size(); i++)
684 COutPoint outpoint = tx.vin[i].prevout;
685 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
695 CCoinsViewCache view(dummy);
699 CCoinsViewMemPool viewMemPool(*pcoinsTip, *this);
700 view.SetBackend(viewMemPool);
702 // do we already have it?
703 if (view.HaveCoins(hash))
706 // do all inputs exist?
707 // Note that this does not check for the presence of actual outputs (see the next check for that),
708 // only helps filling in pfMissingInputs (to determine missing vs spent).
709 BOOST_FOREACH(const CTxIn txin, tx.vin) {
710 if (!view.HaveCoins(txin.prevout.hash)) {
712 *pfMissingInputs = true;
717 // are the actual inputs available?
718 if (!tx.HaveInputs(view))
719 return error("CTxMemPool::accept() : inputs already spent");
721 // Bring the best block into scope
724 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
725 view.SetBackend(dummy);
728 // Check for non-standard pay-to-script-hash in inputs
729 if (!tx.AreInputsStandard(view) && !fTestNet)
730 return error("CTxMemPool::accept() : nonstandard transaction input");
732 // Note: if you modify this code to accept non-standard transactions, then
733 // you should add code here to check that the transaction does a
734 // reasonable number of ECDSA signature verifications.
736 int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
737 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
739 // Don't accept it if it can't get into a block
740 int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
741 if (nFees < txMinFee)
742 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
743 hash.ToString().c_str(),
746 // Continuously rate-limit free transactions
747 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
748 // be annoying or make others' transactions take longer to confirm.
749 if (nFees < MIN_RELAY_TX_FEE)
751 static CCriticalSection cs;
752 static double dFreeCount;
753 static int64 nLastTime;
754 int64 nNow = GetTime();
757 // Use an exponentially decaying ~10-minute window:
758 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
760 // -limitfreerelay unit is thousand-bytes-per-minute
761 // At default rate it would take over a month to fill 1GB
762 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
763 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
765 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
770 // Check against previous transactions
771 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
772 if (!tx.CheckInputs(view, CS_ALWAYS, true, false))
774 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
778 // Store transaction in memory
783 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
786 addUnchecked(hash, tx);
789 ///// are we sure this is ok when loading transactions or restoring block txes
790 // If updated, erase old tx from wallet
792 EraseFromWallets(ptxOld->GetHash());
794 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
795 hash.ToString().substr(0,10).c_str(),
800 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
802 return mempool.accept(*this, fCheckInputs, pfMissingInputs);
805 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
807 // Add to memory pool without checking anything. Don't call this directly,
808 // call CTxMemPool::accept to properly check the transaction first.
811 for (unsigned int i = 0; i < tx.vin.size(); i++)
812 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
813 nTransactionsUpdated++;
819 bool CTxMemPool::remove(CTransaction &tx)
821 // Remove transaction from memory pool
824 uint256 hash = tx.GetHash();
825 if (mapTx.count(hash))
827 BOOST_FOREACH(const CTxIn& txin, tx.vin)
828 mapNextTx.erase(txin.prevout);
830 nTransactionsUpdated++;
836 void CTxMemPool::clear()
841 ++nTransactionsUpdated;
844 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
849 vtxid.reserve(mapTx.size());
850 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
851 vtxid.push_back((*mi).first);
857 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
859 if (hashBlock == 0 || nIndex == -1)
862 // Find the block it claims to be in
863 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
864 if (mi == mapBlockIndex.end())
866 CBlockIndex* pindex = (*mi).second;
867 if (!pindex || !pindex->IsInMainChain())
870 // Make sure the merkle branch connects to this block
871 if (!fMerkleVerified)
873 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
875 fMerkleVerified = true;
879 return pindexBest->nHeight - pindex->nHeight + 1;
883 int CMerkleTx::GetBlocksToMaturity() const
887 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
891 bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs)
895 if (!IsInMainChain() && !ClientCheckInputs())
897 return CTransaction::AcceptToMemoryPool(false);
901 return CTransaction::AcceptToMemoryPool(fCheckInputs);
907 bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
911 // Add previous supporting transactions first
912 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
914 if (!tx.IsCoinBase())
916 uint256 hash = tx.GetHash();
917 if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
918 tx.AcceptToMemoryPool(fCheckInputs);
921 return AcceptToMemoryPool(fCheckInputs);
927 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
928 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
930 CBlockIndex *pindexSlow = NULL;
935 if (mempool.exists(hash))
937 txOut = mempool.lookup(hash);
942 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
945 CCoinsViewCache &view = *pcoinsTip;
947 if (view.GetCoins(hash, coins))
948 nHeight = coins.nHeight;
951 pindexSlow = FindBlockByHeight(nHeight);
957 if (block.ReadFromDisk(pindexSlow)) {
958 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
959 if (tx.GetHash() == hash) {
961 hashBlock = pindexSlow->GetBlockHash();
976 //////////////////////////////////////////////////////////////////////////////
978 // CBlock and CBlockIndex
981 static CBlockIndex* pblockindexFBBHLast;
982 CBlockIndex* FindBlockByHeight(int nHeight)
984 CBlockIndex *pblockindex;
985 if (nHeight < nBestHeight / 2)
986 pblockindex = pindexGenesisBlock;
988 pblockindex = pindexBest;
989 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
990 pblockindex = pblockindexFBBHLast;
991 while (pblockindex->nHeight > nHeight)
992 pblockindex = pblockindex->pprev;
993 while (pblockindex->nHeight < nHeight)
994 pblockindex = pblockindex->pnext;
995 pblockindexFBBHLast = pblockindex;
999 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1001 if (!fReadTransactions)
1003 *this = pindex->GetBlockHeader();
1006 if (!ReadFromDisk(pindex->GetBlockPos(), fReadTransactions))
1008 if (GetHash() != pindex->GetBlockHash())
1009 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1013 uint256 static GetOrphanRoot(const CBlock* pblock)
1015 // Work back to the first block in the orphan chain
1016 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1017 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1018 return pblock->GetHash();
1021 int64 static GetBlockValue(int nHeight, int64 nFees)
1023 int64 nSubsidy = 50 * COIN;
1025 // Subsidy is cut in half every 210000 blocks, which will occur approximately every 4 years
1026 nSubsidy >>= (nHeight / 210000);
1028 return nSubsidy + nFees;
1031 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1032 static const int64 nTargetSpacing = 10 * 60;
1033 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
1036 // minimum amount of work that could possibly be required nTime after
1037 // minimum work required was nBase
1039 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1041 // Testnet has min-difficulty blocks
1042 // after nTargetSpacing*2 time between blocks:
1043 if (fTestNet && nTime > nTargetSpacing*2)
1044 return bnProofOfWorkLimit.GetCompact();
1047 bnResult.SetCompact(nBase);
1048 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
1050 // Maximum 400% adjustment...
1052 // ... in best-case exactly 4-times-normal target time
1053 nTime -= nTargetTimespan*4;
1055 if (bnResult > bnProofOfWorkLimit)
1056 bnResult = bnProofOfWorkLimit;
1057 return bnResult.GetCompact();
1060 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
1062 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
1065 if (pindexLast == NULL)
1066 return nProofOfWorkLimit;
1068 // Only change once per interval
1069 if ((pindexLast->nHeight+1) % nInterval != 0)
1071 // Special difficulty rule for testnet:
1074 // If the new block's timestamp is more than 2* 10 minutes
1075 // then allow mining of a min-difficulty block.
1076 if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
1077 return nProofOfWorkLimit;
1080 // Return the last non-special-min-difficulty-rules-block
1081 const CBlockIndex* pindex = pindexLast;
1082 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
1083 pindex = pindex->pprev;
1084 return pindex->nBits;
1088 return pindexLast->nBits;
1091 // Go back by what we want to be 14 days worth of blocks
1092 const CBlockIndex* pindexFirst = pindexLast;
1093 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1094 pindexFirst = pindexFirst->pprev;
1095 assert(pindexFirst);
1097 // Limit adjustment step
1098 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1099 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1100 if (nActualTimespan < nTargetTimespan/4)
1101 nActualTimespan = nTargetTimespan/4;
1102 if (nActualTimespan > nTargetTimespan*4)
1103 nActualTimespan = nTargetTimespan*4;
1107 bnNew.SetCompact(pindexLast->nBits);
1108 bnNew *= nActualTimespan;
1109 bnNew /= nTargetTimespan;
1111 if (bnNew > bnProofOfWorkLimit)
1112 bnNew = bnProofOfWorkLimit;
1115 printf("GetNextWorkRequired RETARGET\n");
1116 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1117 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1118 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1120 return bnNew.GetCompact();
1123 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1126 bnTarget.SetCompact(nBits);
1129 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1130 return error("CheckProofOfWork() : nBits below minimum work");
1132 // Check proof of work matches claimed amount
1133 if (hash > bnTarget.getuint256())
1134 return error("CheckProofOfWork() : hash doesn't match nBits");
1139 // Return maximum amount of blocks that other nodes claim to have
1140 int GetNumBlocksOfPeers()
1142 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1145 bool IsInitialBlockDownload()
1147 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1149 static int64 nLastUpdate;
1150 static CBlockIndex* pindexLastBest;
1151 if (pindexBest != pindexLastBest)
1153 pindexLastBest = pindexBest;
1154 nLastUpdate = GetTime();
1156 return (GetTime() - nLastUpdate < 10 &&
1157 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1160 void static InvalidChainFound(CBlockIndex* pindexNew)
1162 if (pindexNew->bnChainWork > bnBestInvalidWork)
1164 bnBestInvalidWork = pindexNew->bnChainWork;
1165 pblocktree->WriteBestInvalidWork(bnBestInvalidWork);
1166 uiInterface.NotifyBlocksChanged();
1168 printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n",
1169 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1170 pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S",
1171 pindexNew->GetBlockTime()).c_str());
1172 printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n",
1173 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
1174 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1175 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1176 printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1179 void static InvalidBlockFound(CBlockIndex *pindex) {
1180 pindex->nStatus |= BLOCK_FAILED_VALID;
1181 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
1182 setBlockIndexValid.erase(pindex);
1183 InvalidChainFound(pindex);
1185 ConnectBestBlock(); // reorganise away from the failed block
1188 bool ConnectBestBlock() {
1190 CBlockIndex *pindexNewBest;
1193 std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
1194 if (it == setBlockIndexValid.rend())
1196 pindexNewBest = *it;
1199 if (pindexNewBest == pindexBest)
1200 return true; // nothing to do
1203 CBlockIndex *pindexTest = pindexNewBest;
1204 std::vector<CBlockIndex*> vAttach;
1206 if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
1207 // mark descendants failed
1208 CBlockIndex *pindexFailed = pindexNewBest;
1209 while (pindexTest != pindexFailed) {
1210 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
1211 setBlockIndexValid.erase(pindexFailed);
1212 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
1213 pindexFailed = pindexFailed->pprev;
1215 InvalidChainFound(pindexNewBest);
1219 if (pindexBest == NULL || pindexTest->bnChainWork > pindexBest->bnChainWork)
1220 vAttach.push_back(pindexTest);
1222 if (pindexTest->pprev == NULL || pindexTest->pnext != NULL) {
1223 reverse(vAttach.begin(), vAttach.end());
1224 BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach)
1225 if (!SetBestChain(pindexSwitch))
1229 pindexTest = pindexTest->pprev;
1234 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1236 nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1238 // Updating time can change work required on testnet:
1240 nBits = GetNextWorkRequired(pindexPrev, this);
1253 const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view)
1255 const CCoins &coins = view.GetCoins(input.prevout.hash);
1256 assert(coins.IsAvailable(input.prevout.n));
1257 return coins.vout[input.prevout.n];
1260 int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const
1266 for (unsigned int i = 0; i < vin.size(); i++)
1267 nResult += GetOutputFor(vin[i], inputs).nValue;
1272 unsigned int CTransaction::GetP2SHSigOpCount(CCoinsViewCache& inputs) const
1277 unsigned int nSigOps = 0;
1278 for (unsigned int i = 0; i < vin.size(); i++)
1280 const CTxOut &prevout = GetOutputFor(vin[i], inputs);
1281 if (prevout.scriptPubKey.IsPayToScriptHash())
1282 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1287 bool CTransaction::UpdateCoins(CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash) const
1289 // mark inputs spent
1290 if (!IsCoinBase()) {
1291 BOOST_FOREACH(const CTxIn &txin, vin) {
1292 CCoins &coins = inputs.GetCoins(txin.prevout.hash);
1294 if (!coins.Spend(txin.prevout, undo))
1295 return error("UpdateCoins() : cannot spend input");
1296 txundo.vprevout.push_back(undo);
1301 if (!inputs.SetCoins(txhash, CCoins(*this, nHeight)))
1302 return error("UpdateCoins() : cannot update output");
1307 bool CTransaction::HaveInputs(CCoinsViewCache &inputs) const
1309 if (!IsCoinBase()) {
1310 // first check whether information about the prevout hash is available
1311 for (unsigned int i = 0; i < vin.size(); i++) {
1312 const COutPoint &prevout = vin[i].prevout;
1313 if (!inputs.HaveCoins(prevout.hash))
1317 // then check whether the actual outputs are available
1318 for (unsigned int i = 0; i < vin.size(); i++) {
1319 const COutPoint &prevout = vin[i].prevout;
1320 const CCoins &coins = inputs.GetCoins(prevout.hash);
1321 if (!coins.IsAvailable(prevout.n))
1328 bool CTransaction::CheckInputs(CCoinsViewCache &inputs, enum CheckSig_mode csmode, bool fStrictPayToScriptHash, bool fStrictEncodings) const
1332 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1333 // for an attacker to attempt to split the network.
1334 if (!HaveInputs(inputs))
1335 return error("CheckInputs() : %s inputs unavailable", GetHash().ToString().substr(0,10).c_str());
1337 // While checking, GetBestBlock() refers to the parent block.
1338 // This is also true for mempool checks.
1339 int nSpendHeight = inputs.GetBestBlock()->nHeight + 1;
1342 for (unsigned int i = 0; i < vin.size(); i++)
1344 const COutPoint &prevout = vin[i].prevout;
1345 const CCoins &coins = inputs.GetCoins(prevout.hash);
1347 // If prev is coinbase, check that it's matured
1348 if (coins.IsCoinBase()) {
1349 if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
1350 return error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight);
1353 // Check for negative or overflow input values
1354 nValueIn += coins.vout[prevout.n].nValue;
1355 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1356 return DoS(100, error("CheckInputs() : txin values out of range"));
1360 if (nValueIn < GetValueOut())
1361 return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1363 // Tally transaction fees
1364 int64 nTxFee = nValueIn - GetValueOut();
1366 return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1368 if (!MoneyRange(nFees))
1369 return DoS(100, error("CheckInputs() : nFees out of range"));
1371 // The first loop above does all the inexpensive checks.
1372 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1373 // Helps prevent CPU exhaustion attacks.
1375 // Skip ECDSA signature verification when connecting blocks
1376 // before the last block chain checkpoint. This is safe because block merkle hashes are
1377 // still computed and checked, and any change will be caught at the next checkpoint.
1378 if (csmode == CS_ALWAYS ||
1379 (csmode == CS_AFTER_CHECKPOINT && inputs.GetBestBlock()->nHeight >= Checkpoints::GetTotalBlocksEstimate())) {
1380 for (unsigned int i = 0; i < vin.size(); i++) {
1381 const COutPoint &prevout = vin[i].prevout;
1382 const CCoins &coins = inputs.GetCoins(prevout.hash);
1385 if (!VerifySignature(coins, *this, i, fStrictPayToScriptHash, fStrictEncodings, 0)) {
1386 // only during transition phase for P2SH: do not invoke anti-DoS code for
1387 // potentially old clients relaying bad P2SH transactions
1388 if (fStrictPayToScriptHash && VerifySignature(coins, *this, i, false, fStrictEncodings, 0))
1389 return error("CheckInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1391 return DoS(100,error("CheckInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1401 bool CTransaction::ClientCheckInputs() const
1406 // Take over previous transactions' spent pointers
1410 for (unsigned int i = 0; i < vin.size(); i++)
1412 // Get prev tx from single transactions in memory
1413 COutPoint prevout = vin[i].prevout;
1414 if (!mempool.exists(prevout.hash))
1416 CTransaction& txPrev = mempool.lookup(prevout.hash);
1418 if (prevout.n >= txPrev.vout.size())
1422 if (!VerifySignature(CCoins(txPrev, -1), *this, i, true, false, 0))
1423 return error("ConnectInputs() : VerifySignature failed");
1425 ///// this is redundant with the mempool.mapNextTx stuff,
1426 ///// not sure which I want to get rid of
1427 ///// this has to go away now that posNext is gone
1428 // // Check for conflicts
1429 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1430 // return error("ConnectInputs() : prev tx already used");
1432 // // Flag outpoints as used
1433 // txPrev.vout[prevout.n].posNext = posThisTx;
1435 nValueIn += txPrev.vout[prevout.n].nValue;
1437 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1438 return error("ClientConnectInputs() : txin values out of range");
1440 if (GetValueOut() > nValueIn)
1450 bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &view)
1452 assert(pindex == view.GetBestBlock());
1454 CBlockUndo blockUndo;
1456 CDiskBlockPos pos = pindex->GetUndoPos();
1458 return error("DisconnectBlock() : no undo data available");
1459 FILE *file = OpenUndoFile(pos, true);
1461 return error("DisconnectBlock() : undo file not available");
1462 CAutoFile fileUndo(file, SER_DISK, CLIENT_VERSION);
1463 fileUndo >> blockUndo;
1466 assert(blockUndo.vtxundo.size() + 1 == vtx.size());
1468 // undo transactions in reverse order
1469 for (int i = vtx.size() - 1; i >= 0; i--) {
1470 const CTransaction &tx = vtx[i];
1471 uint256 hash = tx.GetHash();
1473 // check that all outputs are available
1474 if (!view.HaveCoins(hash))
1475 return error("DisconnectBlock() : outputs still spent? database corrupted");
1476 CCoins &outs = view.GetCoins(hash);
1478 CCoins outsBlock = CCoins(tx, pindex->nHeight);
1479 if (outs != outsBlock)
1480 return error("DisconnectBlock() : added transaction mismatch? database corrupted");
1486 if (i > 0) { // not coinbases
1487 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1488 assert(txundo.vprevout.size() == tx.vin.size());
1489 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1490 const COutPoint &out = tx.vin[j].prevout;
1491 const CTxInUndo &undo = txundo.vprevout[j];
1493 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1494 if (coins.IsPruned()) {
1495 if (undo.nHeight == 0)
1496 return error("DisconnectBlock() : undo data doesn't contain tx metadata? database corrupted");
1497 coins.fCoinBase = undo.fCoinBase;
1498 coins.nHeight = undo.nHeight;
1499 coins.nVersion = undo.nVersion;
1501 if (undo.nHeight != 0)
1502 return error("DisconnectBlock() : undo data contains unneeded tx metadata? database corrupted");
1504 if (coins.IsAvailable(out.n))
1505 return error("DisconnectBlock() : prevout output not spent? database corrupted");
1506 if (coins.vout.size() < out.n+1)
1507 coins.vout.resize(out.n+1);
1508 coins.vout[out.n] = undo.txout;
1509 if (!view.SetCoins(out.hash, coins))
1510 return error("DisconnectBlock() : cannot restore coin inputs");
1515 // move best block pointer to prevout block
1516 view.SetBestBlock(pindex->pprev);
1521 void static FlushBlockFile()
1523 LOCK(cs_LastBlockFile);
1525 CDiskBlockPos posOld;
1526 posOld.nFile = nLastBlockFile;
1529 FILE *fileOld = OpenBlockFile(posOld);
1530 FileCommit(fileOld);
1533 fileOld = OpenUndoFile(posOld);
1534 FileCommit(fileOld);
1538 bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1540 bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsViewCache &view, bool fJustCheck)
1542 // Check it again in case a previous version let a bad block in
1543 if (!CheckBlock(!fJustCheck, !fJustCheck))
1546 // verify that the view's current state corresponds to the previous block
1547 assert(pindex->pprev == view.GetBestBlock());
1549 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1550 // unless those are already completely spent.
1551 // If such overwrites are allowed, coinbases and transactions depending upon those
1552 // can be duplicated to remove the ability to spend the first instance -- even after
1553 // being sent to another address.
1554 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1555 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1556 // already refuses previously-known transaction ids entirely.
1557 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1558 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1559 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1560 // initial block download.
1561 bool fEnforceBIP30 = !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1562 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1563 if (fEnforceBIP30) {
1564 for (unsigned int i=0; i<vtx.size(); i++) {
1565 uint256 hash = GetTxHash(i);
1566 if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
1567 return error("ConnectBlock() : tried to overwrite transaction");
1571 // BIP16 didn't become active until Apr 1 2012
1572 int64 nBIP16SwitchTime = 1333238400;
1573 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1575 CBlockUndo blockundo;
1578 unsigned int nSigOps = 0;
1579 for (unsigned int i=0; i<vtx.size(); i++)
1581 const CTransaction &tx = vtx[i];
1583 nSigOps += tx.GetLegacySigOpCount();
1584 if (nSigOps > MAX_BLOCK_SIGOPS)
1585 return DoS(100, error("ConnectBlock() : too many sigops"));
1587 if (!tx.IsCoinBase())
1589 if (!tx.HaveInputs(view))
1590 return DoS(100, error("ConnectBlock() : inputs missing/spent"));
1592 if (fStrictPayToScriptHash)
1594 // Add in sigops done by pay-to-script-hash inputs;
1595 // this is to prevent a "rogue miner" from creating
1596 // an incredibly-expensive-to-validate block.
1597 nSigOps += tx.GetP2SHSigOpCount(view);
1598 if (nSigOps > MAX_BLOCK_SIGOPS)
1599 return DoS(100, error("ConnectBlock() : too many sigops"));
1602 nFees += tx.GetValueIn(view)-tx.GetValueOut();
1604 if (!tx.CheckInputs(view, CS_AFTER_CHECKPOINT, fStrictPayToScriptHash, false))
1609 if (!tx.UpdateCoins(view, txundo, pindex->nHeight, GetTxHash(i)))
1610 return error("ConnectBlock() : UpdateInputs failed");
1611 if (!tx.IsCoinBase())
1612 blockundo.vtxundo.push_back(txundo);
1615 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1621 // Write undo information to disk
1622 if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
1624 if (pindex->GetUndoPos().IsNull()) {
1626 if (!FindUndoPos(pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 8))
1627 return error("ConnectBlock() : FindUndoPos failed");
1628 if (!blockundo.WriteToDisk(pos))
1629 return error("ConnectBlock() : CBlockUndo::WriteToDisk failed");
1631 // update nUndoPos in block index
1632 pindex->nUndoPos = pos.nPos;
1633 pindex->nStatus |= BLOCK_HAVE_UNDO;
1636 pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
1638 CDiskBlockIndex blockindex(pindex);
1639 if (!pblocktree->WriteBlockIndex(blockindex))
1640 return error("ConnectBlock() : WriteBlockIndex failed");
1643 // add this block to the view's block chain
1644 if (!view.SetBestBlock(pindex))
1647 // Watch for transactions paying to me
1648 for (unsigned int i=0; i<vtx.size(); i++)
1649 SyncWithWallets(GetTxHash(i), vtx[i], this, true);
1654 bool SetBestChain(CBlockIndex* pindexNew)
1656 CCoinsViewCache &view = *pcoinsTip;
1658 // special case for attaching the genesis block
1659 // note that no ConnectBlock is called, so its coinbase output is non-spendable
1660 if (pindexGenesisBlock == NULL && pindexNew->GetBlockHash() == hashGenesisBlock)
1662 view.SetBestBlock(pindexNew);
1665 pindexGenesisBlock = pindexNew;
1666 pindexBest = pindexNew;
1667 hashBestChain = pindexNew->GetBlockHash();
1668 nBestHeight = pindexBest->nHeight;
1669 bnBestChainWork = pindexNew->bnChainWork;
1673 // Find the fork (typically, there is none)
1674 CBlockIndex* pfork = view.GetBestBlock();
1675 CBlockIndex* plonger = pindexNew;
1676 while (pfork != plonger)
1678 while (plonger->nHeight > pfork->nHeight)
1679 if (!(plonger = plonger->pprev))
1680 return error("SetBestChain() : plonger->pprev is null");
1681 if (pfork == plonger)
1683 if (!(pfork = pfork->pprev))
1684 return error("SetBestChain() : pfork->pprev is null");
1687 // List of what to disconnect (typically nothing)
1688 vector<CBlockIndex*> vDisconnect;
1689 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1690 vDisconnect.push_back(pindex);
1692 // List of what to connect (typically only pindexNew)
1693 vector<CBlockIndex*> vConnect;
1694 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1695 vConnect.push_back(pindex);
1696 reverse(vConnect.begin(), vConnect.end());
1698 if (vDisconnect.size() > 0) {
1699 printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
1700 printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
1703 // Disconnect shorter branch
1704 vector<CTransaction> vResurrect;
1705 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
1707 if (!block.ReadFromDisk(pindex))
1708 return error("SetBestBlock() : ReadFromDisk for disconnect failed");
1709 CCoinsViewCache viewTemp(view, true);
1710 if (!block.DisconnectBlock(pindex, viewTemp))
1711 return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1712 if (!viewTemp.Flush())
1713 return error("SetBestBlock() : Cache flush failed after disconnect");
1715 // Queue memory transactions to resurrect
1716 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1717 if (!tx.IsCoinBase())
1718 vResurrect.push_back(tx);
1721 // Connect longer branch
1722 vector<CTransaction> vDelete;
1723 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
1725 if (!block.ReadFromDisk(pindex))
1726 return error("SetBestBlock() : ReadFromDisk for connect failed");
1727 CCoinsViewCache viewTemp(view, true);
1728 if (!block.ConnectBlock(pindex, viewTemp)) {
1729 InvalidChainFound(pindexNew);
1730 InvalidBlockFound(pindex);
1731 return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1733 if (!viewTemp.Flush())
1734 return error("SetBestBlock() : Cache flush failed after connect");
1736 // Queue memory transactions to delete
1737 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1738 vDelete.push_back(tx);
1741 // Make sure it's successfully written to disk before changing memory structure
1742 bool fIsInitialDownload = IsInitialBlockDownload();
1743 if (!fIsInitialDownload || view.GetCacheSize()>5000) {
1750 // At this point, all changes have been done to the database.
1751 // Proceed by updating the memory structures.
1753 // Disconnect shorter branch
1754 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1756 pindex->pprev->pnext = NULL;
1758 // Connect longer branch
1759 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1761 pindex->pprev->pnext = pindex;
1763 // Resurrect memory transactions that were in the disconnected branch
1764 BOOST_FOREACH(CTransaction& tx, vResurrect)
1765 tx.AcceptToMemoryPool(false);
1767 // Delete redundant memory transactions that are in the connected branch
1768 BOOST_FOREACH(CTransaction& tx, vDelete)
1771 // Update best block in wallet (so we can detect restored wallets)
1772 if (!fIsInitialDownload)
1774 const CBlockLocator locator(pindexNew);
1775 ::SetBestChain(locator);
1779 hashBestChain = pindexNew->GetBlockHash();
1780 pindexBest = pindexNew;
1781 pblockindexFBBHLast = NULL;
1782 nBestHeight = pindexBest->nHeight;
1783 bnBestChainWork = pindexNew->bnChainWork;
1784 nTimeBestReceived = GetTime();
1785 nTransactionsUpdated++;
1786 printf("SetBestChain: new best=%s height=%d work=%s tx=%lu date=%s\n",
1787 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), (unsigned long)pindexNew->nChainTx,
1788 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1790 // Check the version of the last 100 blocks to see if we need to upgrade:
1791 if (!fIsInitialDownload)
1794 const CBlockIndex* pindex = pindexBest;
1795 for (int i = 0; i < 100 && pindex != NULL; i++)
1797 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1799 pindex = pindex->pprev;
1802 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1803 if (nUpgraded > 100/2)
1804 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1805 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1808 std::string strCmd = GetArg("-blocknotify", "");
1810 if (!fIsInitialDownload && !strCmd.empty())
1812 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1813 boost::thread t(runCommand, strCmd); // thread runs free
1820 bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
1822 // Check for duplicate
1823 uint256 hash = GetHash();
1824 if (mapBlockIndex.count(hash))
1825 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1827 // Construct new block index object
1828 CBlockIndex* pindexNew = new CBlockIndex(*this);
1830 return error("AddToBlockIndex() : new CBlockIndex failed");
1831 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1832 pindexNew->phashBlock = &((*mi).first);
1833 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1834 if (miPrev != mapBlockIndex.end())
1836 pindexNew->pprev = (*miPrev).second;
1837 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1839 pindexNew->nTx = vtx.size();
1840 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1841 pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
1842 pindexNew->nFile = pos.nFile;
1843 pindexNew->nDataPos = pos.nPos;
1844 pindexNew->nUndoPos = 0;
1845 pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
1846 setBlockIndexValid.insert(pindexNew);
1848 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew));
1851 if (!ConnectBestBlock())
1854 if (pindexNew == pindexBest)
1856 // Notify UI to display prev block's coinbase if it was ours
1857 static uint256 hashPrevBestCoinBase;
1858 UpdatedTransaction(hashPrevBestCoinBase);
1859 hashPrevBestCoinBase = GetTxHash(0);
1862 pblocktree->Flush();
1864 uiInterface.NotifyBlocksChanged();
1869 bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime)
1871 bool fUpdatedLast = false;
1873 LOCK(cs_LastBlockFile);
1875 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
1876 printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
1879 infoLastBlockFile.SetNull();
1880 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
1881 fUpdatedLast = true;
1884 pos.nFile = nLastBlockFile;
1885 pos.nPos = infoLastBlockFile.nSize;
1886 infoLastBlockFile.nSize += nAddSize;
1887 infoLastBlockFile.AddBlock(nHeight, nTime);
1889 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
1890 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
1891 if (nNewChunks > nOldChunks) {
1892 FILE *file = OpenBlockFile(pos);
1894 printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
1895 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
1900 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
1901 return error("FindBlockPos() : cannot write updated block info");
1903 pblocktree->WriteLastBlockFile(nLastBlockFile);
1908 bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
1912 LOCK(cs_LastBlockFile);
1914 unsigned int nNewSize;
1915 if (nFile == nLastBlockFile) {
1916 pos.nPos = infoLastBlockFile.nUndoSize;
1917 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
1918 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
1919 return error("FindUndoPos() : cannot write updated block info");
1921 CBlockFileInfo info;
1922 if (!pblocktree->ReadBlockFileInfo(nFile, info))
1923 return error("FindUndoPos() : cannot read block info");
1924 pos.nPos = info.nUndoSize;
1925 nNewSize = (info.nUndoSize += nAddSize);
1926 if (!pblocktree->WriteBlockFileInfo(nFile, info))
1927 return error("FindUndoPos() : cannot write updated block info");
1930 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
1931 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
1932 if (nNewChunks > nOldChunks) {
1933 FILE *file = OpenUndoFile(pos);
1935 printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
1936 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
1945 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
1947 // These are checks that are independent of context
1948 // that can be verified before saving an orphan block.
1951 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
1952 return DoS(100, error("CheckBlock() : size limits failed"));
1954 // Check proof of work matches claimed amount
1955 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
1956 return DoS(50, error("CheckBlock() : proof of work failed"));
1959 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1960 return error("CheckBlock() : block timestamp too far in the future");
1962 // First transaction must be coinbase, the rest must not be
1963 if (vtx.empty() || !vtx[0].IsCoinBase())
1964 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1965 for (unsigned int i = 1; i < vtx.size(); i++)
1966 if (vtx[i].IsCoinBase())
1967 return DoS(100, error("CheckBlock() : more than one coinbase"));
1969 // Check transactions
1970 BOOST_FOREACH(const CTransaction& tx, vtx)
1971 if (!tx.CheckTransaction())
1972 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1974 // Build the merkle tree already. We need it anyway later, and it makes the
1975 // block cache the transaction hashes, which means they don't need to be
1976 // recalculated many times during this block's validation.
1979 // Check for duplicate txids. This is caught by ConnectInputs(),
1980 // but catching it earlier avoids a potential DoS attack:
1981 set<uint256> uniqueTx;
1982 for (unsigned int i=0; i<vtx.size(); i++) {
1983 uniqueTx.insert(GetTxHash(i));
1985 if (uniqueTx.size() != vtx.size())
1986 return DoS(100, error("CheckBlock() : duplicate transaction"));
1988 unsigned int nSigOps = 0;
1989 BOOST_FOREACH(const CTransaction& tx, vtx)
1991 nSigOps += tx.GetLegacySigOpCount();
1993 if (nSigOps > MAX_BLOCK_SIGOPS)
1994 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1996 // Check merkle root
1997 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
1998 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2003 bool CBlock::AcceptBlock()
2005 // Check for duplicate
2006 uint256 hash = GetHash();
2007 if (mapBlockIndex.count(hash))
2008 return error("AcceptBlock() : block already in mapBlockIndex");
2010 // Get prev block index
2011 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2012 if (mi == mapBlockIndex.end())
2013 return DoS(10, error("AcceptBlock() : prev block not found"));
2014 CBlockIndex* pindexPrev = (*mi).second;
2015 int nHeight = pindexPrev->nHeight+1;
2017 // Check proof of work
2018 if (nBits != GetNextWorkRequired(pindexPrev, this))
2019 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
2021 // Check timestamp against prev
2022 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
2023 return error("AcceptBlock() : block's timestamp is too early");
2025 // Check that all transactions are finalized
2026 BOOST_FOREACH(const CTransaction& tx, vtx)
2027 if (!tx.IsFinal(nHeight, GetBlockTime()))
2028 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2030 // Check that the block chain matches the known block chain up to a checkpoint
2031 if (!Checkpoints::CheckBlock(nHeight, hash))
2032 return DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
2034 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2037 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
2038 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
2040 return error("AcceptBlock() : rejected nVersion=1 block");
2043 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2046 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2047 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
2048 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
2050 CScript expect = CScript() << nHeight;
2051 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2052 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2056 // Write block to history file
2057 unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
2058 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2059 return error("AcceptBlock() : out of disk space");
2060 CDiskBlockPos blockPos;
2061 if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, nTime))
2062 return error("AcceptBlock() : FindBlockPos failed");
2063 if (!WriteToDisk(blockPos))
2064 return error("AcceptBlock() : WriteToDisk failed");
2065 if (!AddToBlockIndex(blockPos))
2066 return error("AcceptBlock() : AddToBlockIndex failed");
2068 // Relay inventory, but don't relay old inventory during initial block download
2069 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2070 if (hashBestChain == hash)
2073 BOOST_FOREACH(CNode* pnode, vNodes)
2074 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2075 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2081 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2083 unsigned int nFound = 0;
2084 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2086 if (pstart->nVersion >= minVersion)
2088 pstart = pstart->pprev;
2090 return (nFound >= nRequired);
2093 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2095 // Check for duplicate
2096 uint256 hash = pblock->GetHash();
2097 if (mapBlockIndex.count(hash))
2098 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2099 if (mapOrphanBlocks.count(hash))
2100 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2102 // Preliminary checks
2103 if (!pblock->CheckBlock())
2104 return error("ProcessBlock() : CheckBlock FAILED");
2106 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
2107 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
2109 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2110 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2114 pfrom->Misbehaving(100);
2115 return error("ProcessBlock() : block with timestamp before last checkpoint");
2118 bnNewBlock.SetCompact(pblock->nBits);
2120 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
2121 if (bnNewBlock > bnRequired)
2124 pfrom->Misbehaving(100);
2125 return error("ProcessBlock() : block with too little proof-of-work");
2130 // If we don't already have its previous block, shunt it off to holding area until we get it
2131 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2133 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2135 // Accept orphans as long as there is a node to request its parents from
2137 CBlock* pblock2 = new CBlock(*pblock);
2138 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2139 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2141 // Ask this guy to fill in what we're missing
2142 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2148 if (!pblock->AcceptBlock())
2149 return error("ProcessBlock() : AcceptBlock FAILED");
2151 // Recursively process any orphan blocks that depended on this one
2152 vector<uint256> vWorkQueue;
2153 vWorkQueue.push_back(hash);
2154 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2156 uint256 hashPrev = vWorkQueue[i];
2157 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2158 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2161 CBlock* pblockOrphan = (*mi).second;
2162 if (pblockOrphan->AcceptBlock())
2163 vWorkQueue.push_back(pblockOrphan->GetHash());
2164 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2165 delete pblockOrphan;
2167 mapOrphanBlocksByPrev.erase(hashPrev);
2170 printf("ProcessBlock: ACCEPTED\n");
2181 bool CheckDiskSpace(uint64 nAdditionalBytes)
2183 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2185 // Check for nMinDiskSpace bytes (currently 50MB)
2186 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2189 string strMessage = _("Warning: Disk space is low!");
2190 strMiscWarning = strMessage;
2191 printf("*** %s\n", strMessage.c_str());
2192 uiInterface.ThreadSafeMessageBox(strMessage, "Bitcoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2199 CCriticalSection cs_LastBlockFile;
2200 CBlockFileInfo infoLastBlockFile;
2201 int nLastBlockFile = 0;
2203 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2207 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2208 boost::filesystem::create_directories(path.parent_path());
2209 FILE* file = fopen(path.string().c_str(), "rb+");
2210 if (!file && !fReadOnly)
2211 file = fopen(path.string().c_str(), "wb+");
2213 printf("Unable to open file %s\n", path.string().c_str());
2217 if (fseek(file, pos.nPos, SEEK_SET)) {
2218 printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2226 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2227 return OpenDiskFile(pos, "blk", fReadOnly);
2230 FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2231 return OpenDiskFile(pos, "rev", fReadOnly);
2234 CBlockIndex * InsertBlockIndex(uint256 hash)
2240 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2241 if (mi != mapBlockIndex.end())
2242 return (*mi).second;
2245 CBlockIndex* pindexNew = new CBlockIndex();
2247 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
2248 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2249 pindexNew->phashBlock = &((*mi).first);
2254 bool static LoadBlockIndexDB()
2256 if (!pblocktree->LoadBlockIndexGuts())
2259 if (fRequestShutdown)
2262 // Calculate bnChainWork
2263 vector<pair<int, CBlockIndex*> > vSortedByHeight;
2264 vSortedByHeight.reserve(mapBlockIndex.size());
2265 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2267 CBlockIndex* pindex = item.second;
2268 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2270 sort(vSortedByHeight.begin(), vSortedByHeight.end());
2271 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2273 CBlockIndex* pindex = item.second;
2274 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
2275 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2276 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
2277 setBlockIndexValid.insert(pindex);
2280 // Load block file info
2281 pblocktree->ReadLastBlockFile(nLastBlockFile);
2282 printf("LoadBlockIndex(): last block file = %i\n", nLastBlockFile);
2283 if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2284 printf("LoadBlockIndex(): last block file: %s\n", infoLastBlockFile.ToString().c_str());
2286 // Load hashBestChain pointer to end of best chain
2287 pindexBest = pcoinsTip->GetBestBlock();
2288 if (pindexBest == NULL)
2290 if (pindexGenesisBlock == NULL)
2293 hashBestChain = pindexBest->GetBlockHash();
2294 nBestHeight = pindexBest->nHeight;
2295 bnBestChainWork = pindexBest->bnChainWork;
2297 // set 'next' pointers in best chain
2298 CBlockIndex *pindex = pindexBest;
2299 while(pindex != NULL && pindex->pprev != NULL) {
2300 CBlockIndex *pindexPrev = pindex->pprev;
2301 pindexPrev->pnext = pindex;
2302 pindex = pindexPrev;
2304 printf("LoadBlockIndex(): hashBestChain=%s height=%d date=%s\n",
2305 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2306 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2308 // Load bnBestInvalidWork, OK if it doesn't exist
2309 pblocktree->ReadBestInvalidWork(bnBestInvalidWork);
2311 // Verify blocks in the best chain
2312 int nCheckLevel = GetArg("-checklevel", 1);
2313 int nCheckDepth = GetArg( "-checkblocks", 2500);
2314 if (nCheckDepth == 0)
2315 nCheckDepth = 1000000000; // suffices until the year 19000
2316 if (nCheckDepth > nBestHeight)
2317 nCheckDepth = nBestHeight;
2318 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2319 CBlockIndex* pindexFork = NULL;
2320 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
2322 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
2325 if (!block.ReadFromDisk(pindex))
2326 return error("LoadBlockIndex() : block.ReadFromDisk failed");
2327 // check level 1: verify block validity
2328 if (nCheckLevel>0 && !block.CheckBlock())
2330 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2331 pindexFork = pindex->pprev;
2333 // TODO: stronger verifications
2335 if (pindexFork && !fRequestShutdown)
2338 return error("LoadBlockIndex(): chain database corrupted");
2344 bool LoadBlockIndex(bool fAllowNew)
2348 pchMessageStart[0] = 0x0b;
2349 pchMessageStart[1] = 0x11;
2350 pchMessageStart[2] = 0x09;
2351 pchMessageStart[3] = 0x07;
2352 hashGenesisBlock = uint256("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943");
2356 // Load block index from databases
2358 if (!LoadBlockIndexDB())
2362 // Init with genesis block
2364 if (mapBlockIndex.empty())
2370 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
2371 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2372 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
2373 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
2374 // vMerkleTree: 4a5e1e
2377 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
2379 txNew.vin.resize(1);
2380 txNew.vout.resize(1);
2381 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2382 txNew.vout[0].nValue = 50 * COIN;
2383 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
2385 block.vtx.push_back(txNew);
2386 block.hashPrevBlock = 0;
2387 block.hashMerkleRoot = block.BuildMerkleTree();
2389 block.nTime = 1231006505;
2390 block.nBits = 0x1d00ffff;
2391 block.nNonce = 2083236893;
2395 block.nTime = 1296688602;
2396 block.nNonce = 414098458;
2400 uint256 hash = block.GetHash();
2401 printf("%s\n", hash.ToString().c_str());
2402 printf("%s\n", hashGenesisBlock.ToString().c_str());
2403 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
2404 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
2406 assert(hash == hashGenesisBlock);
2408 // Start new block file
2409 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2410 CDiskBlockPos blockPos;
2411 if (!FindBlockPos(blockPos, nBlockSize+8, 0, block.nTime))
2412 return error("AcceptBlock() : FindBlockPos failed");
2413 if (!block.WriteToDisk(blockPos))
2414 return error("LoadBlockIndex() : writing genesis block to disk failed");
2415 if (!block.AddToBlockIndex(blockPos))
2416 return error("LoadBlockIndex() : genesis block not accepted");
2424 void PrintBlockTree()
2426 // pre-compute tree structure
2427 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2428 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2430 CBlockIndex* pindex = (*mi).second;
2431 mapNext[pindex->pprev].push_back(pindex);
2433 //while (rand() % 3 == 0)
2434 // mapNext[pindex->pprev].push_back(pindex);
2437 vector<pair<int, CBlockIndex*> > vStack;
2438 vStack.push_back(make_pair(0, pindexGenesisBlock));
2441 while (!vStack.empty())
2443 int nCol = vStack.back().first;
2444 CBlockIndex* pindex = vStack.back().second;
2447 // print split or gap
2448 if (nCol > nPrevCol)
2450 for (int i = 0; i < nCol-1; i++)
2454 else if (nCol < nPrevCol)
2456 for (int i = 0; i < nCol; i++)
2463 for (int i = 0; i < nCol; i++)
2468 block.ReadFromDisk(pindex);
2469 printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
2471 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2472 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2475 PrintWallets(block);
2477 // put the main time-chain first
2478 vector<CBlockIndex*>& vNext = mapNext[pindex];
2479 for (unsigned int i = 0; i < vNext.size(); i++)
2481 if (vNext[i]->pnext)
2483 swap(vNext[0], vNext[i]);
2489 for (unsigned int i = 0; i < vNext.size(); i++)
2490 vStack.push_back(make_pair(nCol+i, vNext[i]));
2494 bool LoadExternalBlockFile(FILE* fileIn)
2496 int64 nStart = GetTimeMillis();
2501 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2502 unsigned int nPos = 0;
2503 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2505 unsigned char pchData[65536];
2507 fseek(blkdat, nPos, SEEK_SET);
2508 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2511 nPos = (unsigned int)-1;
2514 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2517 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2519 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2522 nPos += ((unsigned char*)nFind - pchData) + 1;
2525 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2526 } while(!fRequestShutdown);
2527 if (nPos == (unsigned int)-1)
2529 fseek(blkdat, nPos, SEEK_SET);
2532 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2537 if (ProcessBlock(NULL,&block))
2545 catch (std::exception &e) {
2546 printf("%s() : Deserialize or I/O error caught during load\n",
2547 __PRETTY_FUNCTION__);
2550 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2554 struct CImportingNow
2557 assert(fImporting == false);
2562 assert(fImporting == true);
2567 void ThreadImport(void *data) {
2568 std::vector<boost::filesystem::path> *vFiles = reinterpret_cast<std::vector<boost::filesystem::path>*>(data);
2570 RenameThread("bitcoin-loadblk");
2573 vnThreadsRunning[THREAD_IMPORT]++;
2576 BOOST_FOREACH(boost::filesystem::path &path, *vFiles) {
2577 FILE *file = fopen(path.string().c_str(), "rb");
2579 LoadExternalBlockFile(file);
2582 // hardcoded $DATADIR/bootstrap.dat
2583 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
2584 if (filesystem::exists(pathBootstrap)) {
2585 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
2587 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
2588 LoadExternalBlockFile(file);
2589 RenameOver(pathBootstrap, pathBootstrapOld);
2595 vnThreadsRunning[THREAD_IMPORT]--;
2607 //////////////////////////////////////////////////////////////////////////////
2612 extern map<uint256, CAlert> mapAlerts;
2613 extern CCriticalSection cs_mapAlerts;
2615 string GetWarnings(string strFor)
2618 string strStatusBar;
2620 if (GetBoolArg("-testsafemode"))
2623 // Misc warnings like out of disk space and clock is wrong
2624 if (strMiscWarning != "")
2627 strStatusBar = strMiscWarning;
2630 // Longer invalid proof-of-work chain
2631 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2634 strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");
2640 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2642 const CAlert& alert = item.second;
2643 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2645 nPriority = alert.nPriority;
2646 strStatusBar = alert.strStatusBar;
2651 if (strFor == "statusbar")
2652 return strStatusBar;
2653 else if (strFor == "rpc")
2655 assert(!"GetWarnings() : invalid parameter");
2666 //////////////////////////////////////////////////////////////////////////////
2672 bool static AlreadyHave(const CInv& inv)
2678 bool txInMap = false;
2681 txInMap = mempool.exists(inv.hash);
2683 return txInMap || mapOrphanTransactions.count(inv.hash) ||
2684 pcoinsTip->HaveCoins(inv.hash);
2687 return mapBlockIndex.count(inv.hash) ||
2688 mapOrphanBlocks.count(inv.hash);
2690 // Don't know what it is, just say we already got one
2697 // The message start string is designed to be unlikely to occur in normal data.
2698 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
2699 // a large 4-byte int at any alignment.
2700 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2703 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2705 static map<CService, CPubKey> mapReuseKey;
2706 RandAddSeedPerfmon();
2708 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
2709 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2711 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2719 if (strCommand == "version")
2721 // Each connection can only send one version message
2722 if (pfrom->nVersion != 0)
2724 pfrom->Misbehaving(1);
2732 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2733 if (pfrom->nVersion < MIN_PROTO_VERSION)
2735 // Since February 20, 2012, the protocol is initiated at version 209,
2736 // and earlier versions are no longer supported
2737 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2738 pfrom->fDisconnect = true;
2742 if (pfrom->nVersion == 10300)
2743 pfrom->nVersion = 300;
2745 vRecv >> addrFrom >> nNonce;
2747 vRecv >> pfrom->strSubVer;
2749 vRecv >> pfrom->nStartingHeight;
2751 if (pfrom->fInbound && addrMe.IsRoutable())
2753 pfrom->addrLocal = addrMe;
2757 // Disconnect if we connected to ourself
2758 if (nNonce == nLocalHostNonce && nNonce > 1)
2760 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2761 pfrom->fDisconnect = true;
2765 // Be shy and don't send version until we hear
2766 if (pfrom->fInbound)
2767 pfrom->PushVersion();
2769 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2771 AddTimeData(pfrom->addr, nTime);
2774 pfrom->PushMessage("verack");
2775 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2777 if (!pfrom->fInbound)
2779 // Advertise our address
2780 if (!fNoListen && !IsInitialBlockDownload())
2782 CAddress addr = GetLocalAddress(&pfrom->addr);
2783 if (addr.IsRoutable())
2784 pfrom->PushAddress(addr);
2787 // Get recent addresses
2788 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2790 pfrom->PushMessage("getaddr");
2791 pfrom->fGetAddr = true;
2793 addrman.Good(pfrom->addr);
2795 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2797 addrman.Add(addrFrom, addrFrom);
2798 addrman.Good(addrFrom);
2802 // Ask the first connected node for block updates
2803 static int nAskedForBlocks = 0;
2804 if (!pfrom->fClient && !pfrom->fOneShot && !fImporting &&
2805 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
2806 (pfrom->nVersion < NOBLKS_VERSION_START ||
2807 pfrom->nVersion >= NOBLKS_VERSION_END) &&
2808 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2811 pfrom->PushGetBlocks(pindexBest, uint256(0));
2817 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2818 item.second.RelayTo(pfrom);
2821 pfrom->fSuccessfullyConnected = true;
2823 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());
2825 cPeerBlockCounts.input(pfrom->nStartingHeight);
2829 else if (pfrom->nVersion == 0)
2831 // Must have a version message before anything else
2832 pfrom->Misbehaving(1);
2837 else if (strCommand == "verack")
2839 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2843 else if (strCommand == "addr")
2845 vector<CAddress> vAddr;
2848 // Don't want addr from older versions unless seeding
2849 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2851 if (vAddr.size() > 1000)
2853 pfrom->Misbehaving(20);
2854 return error("message addr size() = %"PRIszu"", vAddr.size());
2857 // Store the new addresses
2858 vector<CAddress> vAddrOk;
2859 int64 nNow = GetAdjustedTime();
2860 int64 nSince = nNow - 10 * 60;
2861 BOOST_FOREACH(CAddress& addr, vAddr)
2865 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2866 addr.nTime = nNow - 5 * 24 * 60 * 60;
2867 pfrom->AddAddressKnown(addr);
2868 bool fReachable = IsReachable(addr);
2869 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2871 // Relay to a limited number of other nodes
2874 // Use deterministic randomness to send to the same nodes for 24 hours
2875 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2876 static uint256 hashSalt;
2878 hashSalt = GetRandHash();
2879 uint64 hashAddr = addr.GetHash();
2880 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2881 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2882 multimap<uint256, CNode*> mapMix;
2883 BOOST_FOREACH(CNode* pnode, vNodes)
2885 if (pnode->nVersion < CADDR_TIME_VERSION)
2887 unsigned int nPointer;
2888 memcpy(&nPointer, &pnode, sizeof(nPointer));
2889 uint256 hashKey = hashRand ^ nPointer;
2890 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2891 mapMix.insert(make_pair(hashKey, pnode));
2893 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
2894 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2895 ((*mi).second)->PushAddress(addr);
2898 // Do not store addresses outside our network
2900 vAddrOk.push_back(addr);
2902 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
2903 if (vAddr.size() < 1000)
2904 pfrom->fGetAddr = false;
2905 if (pfrom->fOneShot)
2906 pfrom->fDisconnect = true;
2910 else if (strCommand == "inv")
2914 if (vInv.size() > MAX_INV_SZ)
2916 pfrom->Misbehaving(20);
2917 return error("message inv size() = %"PRIszu"", vInv.size());
2920 // find last block in inv vector
2921 unsigned int nLastBlock = (unsigned int)(-1);
2922 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
2923 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
2924 nLastBlock = vInv.size() - 1 - nInv;
2928 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
2930 const CInv &inv = vInv[nInv];
2934 pfrom->AddInventoryKnown(inv);
2936 bool fAlreadyHave = AlreadyHave(inv);
2938 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2940 if (!fAlreadyHave) {
2943 } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
2944 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2945 } else if (nInv == nLastBlock) {
2946 // In case we are on a very long side-chain, it is possible that we already have
2947 // the last block in an inv bundle sent in response to getblocks. Try to detect
2948 // this situation and push another getblocks to continue.
2949 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
2951 printf("force request: %s\n", inv.ToString().c_str());
2954 // Track requests for our stuff
2955 Inventory(inv.hash);
2960 else if (strCommand == "getdata")
2964 if (vInv.size() > MAX_INV_SZ)
2966 pfrom->Misbehaving(20);
2967 return error("message getdata size() = %"PRIszu"", vInv.size());
2970 if (fDebugNet || (vInv.size() != 1))
2971 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
2973 BOOST_FOREACH(const CInv& inv, vInv)
2977 if (fDebugNet || (vInv.size() == 1))
2978 printf("received getdata for: %s\n", inv.ToString().c_str());
2980 if (inv.type == MSG_BLOCK)
2982 // Send block from disk
2983 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2984 if (mi != mapBlockIndex.end())
2987 block.ReadFromDisk((*mi).second);
2988 pfrom->PushMessage("block", block);
2990 // Trigger them to send a getblocks request for the next batch of inventory
2991 if (inv.hash == pfrom->hashContinue)
2993 // Bypass PushInventory, this must send even if redundant,
2994 // and we want it right after the last block so they don't
2995 // wait for other stuff first.
2997 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2998 pfrom->PushMessage("inv", vInv);
2999 pfrom->hashContinue = 0;
3003 else if (inv.IsKnownType())
3005 // Send stream from relay memory
3006 bool pushed = false;
3009 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3010 if (mi != mapRelay.end()) {
3011 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3015 if (!pushed && inv.type == MSG_TX) {
3017 if (mempool.exists(inv.hash)) {
3018 CTransaction tx = mempool.lookup(inv.hash);
3019 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3022 pfrom->PushMessage("tx", ss);
3027 // Track requests for our stuff
3028 Inventory(inv.hash);
3033 else if (strCommand == "getblocks")
3035 CBlockLocator locator;
3037 vRecv >> locator >> hashStop;
3039 // Find the last block the caller has in the main chain
3040 CBlockIndex* pindex = locator.GetBlockIndex();
3042 // Send the rest of the chain
3044 pindex = pindex->pnext;
3046 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3047 for (; pindex; pindex = pindex->pnext)
3049 if (pindex->GetBlockHash() == hashStop)
3051 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3054 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3057 // When this block is requested, we'll send an inv that'll make them
3058 // getblocks the next batch of inventory.
3059 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3060 pfrom->hashContinue = pindex->GetBlockHash();
3067 else if (strCommand == "getheaders")
3069 CBlockLocator locator;
3071 vRecv >> locator >> hashStop;
3073 CBlockIndex* pindex = NULL;
3074 if (locator.IsNull())
3076 // If locator is null, return the hashStop block
3077 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3078 if (mi == mapBlockIndex.end())
3080 pindex = (*mi).second;
3084 // Find the last block the caller has in the main chain
3085 pindex = locator.GetBlockIndex();
3087 pindex = pindex->pnext;
3090 vector<CBlock> vHeaders;
3092 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3093 for (; pindex; pindex = pindex->pnext)
3095 vHeaders.push_back(pindex->GetBlockHeader());
3096 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3099 pfrom->PushMessage("headers", vHeaders);
3103 else if (strCommand == "tx")
3105 vector<uint256> vWorkQueue;
3106 vector<uint256> vEraseQueue;
3107 CDataStream vMsg(vRecv);
3111 CInv inv(MSG_TX, tx.GetHash());
3112 pfrom->AddInventoryKnown(inv);
3114 bool fMissingInputs = false;
3115 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
3117 SyncWithWallets(inv.hash, tx, NULL, true);
3118 RelayMessage(inv, vMsg);
3119 mapAlreadyAskedFor.erase(inv);
3120 vWorkQueue.push_back(inv.hash);
3121 vEraseQueue.push_back(inv.hash);
3123 // Recursively process any orphan transactions that depended on this one
3124 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3126 uint256 hashPrev = vWorkQueue[i];
3127 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3128 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3131 const CDataStream& vMsg = *((*mi).second);
3133 CDataStream(vMsg) >> tx;
3134 CInv inv(MSG_TX, tx.GetHash());
3135 bool fMissingInputs2 = false;
3137 if (tx.AcceptToMemoryPool(true, &fMissingInputs2))
3139 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3140 SyncWithWallets(inv.hash, tx, NULL, true);
3141 RelayMessage(inv, vMsg);
3142 mapAlreadyAskedFor.erase(inv);
3143 vWorkQueue.push_back(inv.hash);
3144 vEraseQueue.push_back(inv.hash);
3146 else if (!fMissingInputs2)
3149 vEraseQueue.push_back(inv.hash);
3150 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3155 BOOST_FOREACH(uint256 hash, vEraseQueue)
3156 EraseOrphanTx(hash);
3158 else if (fMissingInputs)
3162 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3163 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3165 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3167 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3171 else if (strCommand == "block")
3176 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3179 CInv inv(MSG_BLOCK, block.GetHash());
3180 pfrom->AddInventoryKnown(inv);
3182 if (ProcessBlock(pfrom, &block))
3183 mapAlreadyAskedFor.erase(inv);
3184 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3188 else if (strCommand == "getaddr")
3190 pfrom->vAddrToSend.clear();
3191 vector<CAddress> vAddr = addrman.GetAddr();
3192 BOOST_FOREACH(const CAddress &addr, vAddr)
3193 pfrom->PushAddress(addr);
3197 else if (strCommand == "mempool")
3199 std::vector<uint256> vtxid;
3200 mempool.queryHashes(vtxid);
3202 for (unsigned int i = 0; i < vtxid.size(); i++) {
3203 CInv inv(MSG_TX, vtxid[i]);
3204 vInv.push_back(inv);
3205 if (i == (MAX_INV_SZ - 1))
3208 if (vInv.size() > 0)
3209 pfrom->PushMessage("inv", vInv);
3213 else if (strCommand == "checkorder")
3218 if (!GetBoolArg("-allowreceivebyip"))
3220 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3227 /// we have a chance to check the order here
3229 // Keep giving the same key to the same ip until they use it
3230 if (!mapReuseKey.count(pfrom->addr))
3231 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3233 // Send back approval of order and pubkey to use
3234 CScript scriptPubKey;
3235 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3236 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3240 else if (strCommand == "reply")
3245 CRequestTracker tracker;
3247 LOCK(pfrom->cs_mapRequests);
3248 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3249 if (mi != pfrom->mapRequests.end())
3251 tracker = (*mi).second;
3252 pfrom->mapRequests.erase(mi);
3255 if (!tracker.IsNull())
3256 tracker.fn(tracker.param1, vRecv);
3260 else if (strCommand == "ping")
3262 if (pfrom->nVersion > BIP0031_VERSION)
3266 // Echo the message back with the nonce. This allows for two useful features:
3268 // 1) A remote node can quickly check if the connection is operational
3269 // 2) Remote nodes can measure the latency of the network thread. If this node
3270 // is overloaded it won't respond to pings quickly and the remote node can
3271 // avoid sending us more work, like chain download requests.
3273 // The nonce stops the remote getting confused between different pings: without
3274 // it, if the remote node sends a ping once per second and this node takes 5
3275 // seconds to respond to each, the 5th ping the remote sends would appear to
3276 // return very quickly.
3277 pfrom->PushMessage("pong", nonce);
3282 else if (strCommand == "alert")
3287 uint256 alertHash = alert.GetHash();
3288 if (pfrom->setKnown.count(alertHash) == 0)
3290 if (alert.ProcessAlert())
3293 pfrom->setKnown.insert(alertHash);
3296 BOOST_FOREACH(CNode* pnode, vNodes)
3297 alert.RelayTo(pnode);
3301 // Small DoS penalty so peers that send us lots of
3302 // duplicate/expired/invalid-signature/whatever alerts
3303 // eventually get banned.
3304 // This isn't a Misbehaving(100) (immediate ban) because the
3305 // peer might be an older or different implementation with
3306 // a different signature key, etc.
3307 pfrom->Misbehaving(10);
3315 // Ignore unknown commands for extensibility
3319 // Update the last seen time for this node's address
3320 if (pfrom->fNetworkNode)
3321 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3322 AddressCurrentlyConnected(pfrom->addr);
3328 bool ProcessMessages(CNode* pfrom)
3330 CDataStream& vRecv = pfrom->vRecv;
3334 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3338 // (4) message start
3347 // Don't bother if send buffer is too full to respond anyway
3348 if (pfrom->vSend.size() >= SendBufferSize())
3351 // Scan for message start
3352 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3353 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3354 if (vRecv.end() - pstart < nHeaderSize)
3356 if ((int)vRecv.size() > nHeaderSize)
3358 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3359 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3363 if (pstart - vRecv.begin() > 0)
3364 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3365 vRecv.erase(vRecv.begin(), pstart);
3368 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3373 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3376 string strCommand = hdr.GetCommand();
3379 unsigned int nMessageSize = hdr.nMessageSize;
3380 if (nMessageSize > MAX_SIZE)
3382 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3385 if (nMessageSize > vRecv.size())
3387 // Rewind and wait for rest of message
3388 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3393 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3394 unsigned int nChecksum = 0;
3395 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3396 if (nChecksum != hdr.nChecksum)
3398 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3399 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3403 // Copy message to its own buffer
3404 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3405 vRecv.ignore(nMessageSize);
3413 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3418 catch (std::ios_base::failure& e)
3420 if (strstr(e.what(), "end of data"))
3422 // Allow exceptions from under-length message on vRecv
3423 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());
3425 else if (strstr(e.what(), "size too large"))
3427 // Allow exceptions from over-long size
3428 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3432 PrintExceptionContinue(&e, "ProcessMessages()");
3435 catch (std::exception& e) {
3436 PrintExceptionContinue(&e, "ProcessMessages()");
3438 PrintExceptionContinue(NULL, "ProcessMessages()");
3442 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3450 bool SendMessages(CNode* pto, bool fSendTrickle)
3452 TRY_LOCK(cs_main, lockMain);
3454 // Don't send anything until we get their version message
3455 if (pto->nVersion == 0)
3458 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3460 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3462 if (pto->nVersion > BIP0031_VERSION)
3463 pto->PushMessage("ping", nonce);
3465 pto->PushMessage("ping");
3468 // Resend wallet transactions that haven't gotten in a block yet
3469 ResendWalletTransactions();
3471 // Address refresh broadcast
3472 static int64 nLastRebroadcast;
3473 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3477 BOOST_FOREACH(CNode* pnode, vNodes)
3479 // Periodically clear setAddrKnown to allow refresh broadcasts
3480 if (nLastRebroadcast)
3481 pnode->setAddrKnown.clear();
3483 // Rebroadcast our address
3486 CAddress addr = GetLocalAddress(&pnode->addr);
3487 if (addr.IsRoutable())
3488 pnode->PushAddress(addr);
3492 nLastRebroadcast = GetTime();
3500 vector<CAddress> vAddr;
3501 vAddr.reserve(pto->vAddrToSend.size());
3502 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3504 // returns true if wasn't already contained in the set
3505 if (pto->setAddrKnown.insert(addr).second)
3507 vAddr.push_back(addr);
3508 // receiver rejects addr messages larger than 1000
3509 if (vAddr.size() >= 1000)
3511 pto->PushMessage("addr", vAddr);
3516 pto->vAddrToSend.clear();
3518 pto->PushMessage("addr", vAddr);
3523 // Message: inventory
3526 vector<CInv> vInvWait;
3528 LOCK(pto->cs_inventory);
3529 vInv.reserve(pto->vInventoryToSend.size());
3530 vInvWait.reserve(pto->vInventoryToSend.size());
3531 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3533 if (pto->setInventoryKnown.count(inv))
3536 // trickle out tx inv to protect privacy
3537 if (inv.type == MSG_TX && !fSendTrickle)
3539 // 1/4 of tx invs blast to all immediately
3540 static uint256 hashSalt;
3542 hashSalt = GetRandHash();
3543 uint256 hashRand = inv.hash ^ hashSalt;
3544 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3545 bool fTrickleWait = ((hashRand & 3) != 0);
3547 // always trickle our own transactions
3551 if (GetTransaction(inv.hash, wtx))
3553 fTrickleWait = true;
3558 vInvWait.push_back(inv);
3563 // returns true if wasn't already contained in the set
3564 if (pto->setInventoryKnown.insert(inv).second)
3566 vInv.push_back(inv);
3567 if (vInv.size() >= 1000)
3569 pto->PushMessage("inv", vInv);
3574 pto->vInventoryToSend = vInvWait;
3577 pto->PushMessage("inv", vInv);
3583 vector<CInv> vGetData;
3584 int64 nNow = GetTime() * 1000000;
3585 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3587 const CInv& inv = (*pto->mapAskFor.begin()).second;
3588 if (!AlreadyHave(inv))
3591 printf("sending getdata: %s\n", inv.ToString().c_str());
3592 vGetData.push_back(inv);
3593 if (vGetData.size() >= 1000)
3595 pto->PushMessage("getdata", vGetData);
3598 mapAlreadyAskedFor[inv] = nNow;
3600 pto->mapAskFor.erase(pto->mapAskFor.begin());
3602 if (!vGetData.empty())
3603 pto->PushMessage("getdata", vGetData);
3622 //////////////////////////////////////////////////////////////////////////////
3627 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3629 unsigned char* pdata = (unsigned char*)pbuffer;
3630 unsigned int blocks = 1 + ((len + 8) / 64);
3631 unsigned char* pend = pdata + 64 * blocks;
3632 memset(pdata + len, 0, 64 * blocks - len);
3634 unsigned int bits = len * 8;
3635 pend[-1] = (bits >> 0) & 0xff;
3636 pend[-2] = (bits >> 8) & 0xff;
3637 pend[-3] = (bits >> 16) & 0xff;
3638 pend[-4] = (bits >> 24) & 0xff;
3642 static const unsigned int pSHA256InitState[8] =
3643 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3645 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3648 unsigned char data[64];
3652 for (int i = 0; i < 16; i++)
3653 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3655 for (int i = 0; i < 8; i++)
3656 ctx.h[i] = ((uint32_t*)pinit)[i];
3658 SHA256_Update(&ctx, data, sizeof(data));
3659 for (int i = 0; i < 8; i++)
3660 ((uint32_t*)pstate)[i] = ctx.h[i];
3664 // ScanHash scans nonces looking for a hash with at least some zero bits.
3665 // It operates on big endian data. Caller does the byte reversing.
3666 // All input buffers are 16-byte aligned. nNonce is usually preserved
3667 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3668 // the block is rebuilt and nNonce starts over at zero.
3670 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3672 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3676 // Hash pdata using pmidstate as the starting state into
3677 // pre-formatted buffer phash1, then hash phash1 into phash
3679 SHA256Transform(phash1, pdata, pmidstate);
3680 SHA256Transform(phash, phash1, pSHA256InitState);
3682 // Return the nonce if the hash has at least some zero bits,
3683 // caller will check if it has enough to reach the target
3684 if (((unsigned short*)phash)[14] == 0)
3687 // If nothing found after trying for a while, return -1
3688 if ((nNonce & 0xffff) == 0)
3690 nHashesDone = 0xffff+1;
3691 return (unsigned int) -1;
3696 // Some explaining would be appreciated
3701 set<uint256> setDependsOn;
3705 COrphan(CTransaction* ptxIn)
3708 dPriority = dFeePerKb = 0;
3713 printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
3714 ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
3715 BOOST_FOREACH(uint256 hash, setDependsOn)
3716 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3721 uint64 nLastBlockTx = 0;
3722 uint64 nLastBlockSize = 0;
3724 // We want to sort transactions by priority and fee, so:
3725 typedef boost::tuple<double, double, CTransaction*> TxPriority;
3726 class TxPriorityCompare
3730 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
3731 bool operator()(const TxPriority& a, const TxPriority& b)
3735 if (a.get<1>() == b.get<1>())
3736 return a.get<0>() < b.get<0>();
3737 return a.get<1>() < b.get<1>();
3741 if (a.get<0>() == b.get<0>())
3742 return a.get<1>() < b.get<1>();
3743 return a.get<0>() < b.get<0>();
3748 const char* pszDummy = "\0\0";
3749 CScript scriptDummy(std::vector<unsigned char>(pszDummy, pszDummy + sizeof(pszDummy)));
3751 CBlock* CreateNewBlock(CReserveKey& reservekey)
3753 CBlockIndex* pindexPrev = pindexBest;
3756 auto_ptr<CBlock> pblock(new CBlock());
3760 // Create coinbase tx
3762 txNew.vin.resize(1);
3763 txNew.vin[0].prevout.SetNull();
3764 txNew.vout.resize(1);
3765 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3767 // Add our coinbase tx as first transaction
3768 pblock->vtx.push_back(txNew);
3770 // Largest block you're willing to create:
3771 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
3772 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
3773 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
3775 // How much of the block should be dedicated to high-priority transactions,
3776 // included regardless of the fees they pay
3777 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
3778 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
3780 // Minimum block size you want to create; block will be filled with free transactions
3781 // until there are no more or the block reaches this size:
3782 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
3783 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
3785 // Fee-per-kilobyte amount considered the same as "free"
3786 // Be careful setting this: if you set it to zero then
3787 // a transaction spammer can cheaply fill blocks using
3788 // 1-satoshi-fee transactions. It should be set above the real
3789 // cost to you of processing a transaction.
3790 int64 nMinTxFee = MIN_TX_FEE;
3791 if (mapArgs.count("-mintxfee"))
3792 ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
3794 // Collect memory pool transactions into the block
3797 LOCK2(cs_main, mempool.cs);
3798 CCoinsViewCache view(*pcoinsTip, true);
3800 // Priority order to process transactions
3801 list<COrphan> vOrphan; // list memory doesn't move
3802 map<uint256, vector<COrphan*> > mapDependers;
3804 // This vector will be sorted into a priority queue:
3805 vector<TxPriority> vecPriority;
3806 vecPriority.reserve(mempool.mapTx.size());
3807 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3809 CTransaction& tx = (*mi).second;
3810 if (tx.IsCoinBase() || !tx.IsFinal())
3813 COrphan* porphan = NULL;
3814 double dPriority = 0;
3816 bool fMissingInputs = false;
3817 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3819 // Read prev transaction
3821 if (!view.GetCoins(txin.prevout.hash, coins))
3823 // This should never happen; all transactions in the memory
3824 // pool should connect to either transactions in the chain
3825 // or other transactions in the memory pool.
3826 if (!mempool.mapTx.count(txin.prevout.hash))
3828 printf("ERROR: mempool transaction missing input\n");
3829 if (fDebug) assert("mempool transaction missing input" == 0);
3830 fMissingInputs = true;
3836 // Has to wait for dependencies
3839 // Use list for automatic deletion
3840 vOrphan.push_back(COrphan(&tx));
3841 porphan = &vOrphan.back();
3843 mapDependers[txin.prevout.hash].push_back(porphan);
3844 porphan->setDependsOn.insert(txin.prevout.hash);
3845 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
3849 int64 nValueIn = coins.vout[txin.prevout.n].nValue;
3850 nTotalIn += nValueIn;
3852 int nConf = pindexPrev->nHeight - coins.nHeight + 1;
3854 dPriority += (double)nValueIn * nConf;
3856 if (fMissingInputs) continue;
3858 // Priority is sum(valuein * age) / txsize
3859 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3860 dPriority /= nTxSize;
3862 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
3863 // client code rounds up the size to the nearest 1K. That's good, because it gives an
3864 // incentive to create smaller transactions.
3865 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
3869 porphan->dPriority = dPriority;
3870 porphan->dFeePerKb = dFeePerKb;
3873 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
3876 // Collect transactions into block
3877 uint64 nBlockSize = 1000;
3878 uint64 nBlockTx = 0;
3879 int nBlockSigOps = 100;
3880 bool fSortedByFee = (nBlockPrioritySize <= 0);
3882 TxPriorityCompare comparer(fSortedByFee);
3883 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
3885 while (!vecPriority.empty())
3887 // Take highest priority transaction off the priority queue:
3888 double dPriority = vecPriority.front().get<0>();
3889 double dFeePerKb = vecPriority.front().get<1>();
3890 CTransaction& tx = *(vecPriority.front().get<2>());
3892 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
3893 vecPriority.pop_back();
3895 // second layer cached modifications just for this transaction
3896 CCoinsViewCache viewTemp(view, true);
3899 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3900 if (nBlockSize + nTxSize >= nBlockMaxSize)
3903 // Legacy limits on sigOps:
3904 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
3905 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3908 // Skip free transactions if we're past the minimum block size:
3909 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
3912 // Prioritize by fee once past the priority size or we run out of high-priority
3914 if (!fSortedByFee &&
3915 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
3917 fSortedByFee = true;
3918 comparer = TxPriorityCompare(fSortedByFee);
3919 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
3922 if (!tx.HaveInputs(viewTemp))
3925 int64 nTxFees = tx.GetValueIn(viewTemp)-tx.GetValueOut();
3927 nTxSigOps += tx.GetP2SHSigOpCount(viewTemp);
3928 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3931 if (!tx.CheckInputs(viewTemp, CS_ALWAYS, true, false))
3935 uint256 hash = tx.GetHash();
3936 if (!tx.UpdateCoins(viewTemp, txundo, pindexPrev->nHeight+1, hash))
3939 // push changes from the second layer cache to the first one
3943 pblock->vtx.push_back(tx);
3944 nBlockSize += nTxSize;
3946 nBlockSigOps += nTxSigOps;
3949 if (fDebug && GetBoolArg("-printpriority"))
3951 printf("priority %.1f feeperkb %.1f txid %s\n",
3952 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
3955 // Add transactions that depend on this one to the priority queue
3956 if (mapDependers.count(hash))
3958 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3960 if (!porphan->setDependsOn.empty())
3962 porphan->setDependsOn.erase(hash);
3963 if (porphan->setDependsOn.empty())
3965 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
3966 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
3973 nLastBlockTx = nBlockTx;
3974 nLastBlockSize = nBlockSize;
3975 printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
3977 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3980 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3981 pblock->UpdateTime(pindexPrev);
3982 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
3984 pblock->vtx[0].vin[0].scriptSig = scriptDummy;
3986 CBlockIndex indexDummy(*pblock);
3987 indexDummy.pprev = pindexPrev;
3988 indexDummy.nHeight = pindexPrev->nHeight + 1;
3989 CCoinsViewCache viewNew(*pcoinsTip, true);
3990 if (!pblock->ConnectBlock(&indexDummy, viewNew, true))
3991 throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
3994 return pblock.release();
3998 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
4000 // Update nExtraNonce
4001 static uint256 hashPrevBlock;
4002 if (hashPrevBlock != pblock->hashPrevBlock)
4005 hashPrevBlock = pblock->hashPrevBlock;
4008 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4009 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4010 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
4012 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
4016 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
4019 // Pre-build hash buffers
4026 uint256 hashPrevBlock;
4027 uint256 hashMerkleRoot;
4030 unsigned int nNonce;
4033 unsigned char pchPadding0[64];
4035 unsigned char pchPadding1[64];
4038 memset(&tmp, 0, sizeof(tmp));
4040 tmp.block.nVersion = pblock->nVersion;
4041 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
4042 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
4043 tmp.block.nTime = pblock->nTime;
4044 tmp.block.nBits = pblock->nBits;
4045 tmp.block.nNonce = pblock->nNonce;
4047 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
4048 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
4050 // Byte swap all the input buffer
4051 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
4052 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
4054 // Precalc the first half of the first hash, which stays constant
4055 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
4057 memcpy(pdata, &tmp.block, 128);
4058 memcpy(phash1, &tmp.hash1, 64);
4062 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
4064 uint256 hash = pblock->GetHash();
4065 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4067 if (hash > hashTarget)
4071 printf("BitcoinMiner:\n");
4072 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
4074 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
4079 if (pblock->hashPrevBlock != hashBestChain)
4080 return error("BitcoinMiner : generated block is stale");
4082 // Remove key from key pool
4083 reservekey.KeepKey();
4085 // Track how many getdata requests this block gets
4087 LOCK(wallet.cs_wallet);
4088 wallet.mapRequestCount[pblock->GetHash()] = 0;
4091 // Process this block the same as if we had received it from another node
4092 if (!ProcessBlock(NULL, pblock))
4093 return error("BitcoinMiner : ProcessBlock, block not accepted");
4099 void static ThreadBitcoinMiner(void* parg);
4101 static bool fGenerateBitcoins = false;
4102 static bool fLimitProcessors = false;
4103 static int nLimitProcessors = -1;
4105 void static BitcoinMiner(CWallet *pwallet)
4107 printf("BitcoinMiner started\n");
4108 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4110 // Make this thread recognisable as the mining thread
4111 RenameThread("bitcoin-miner");
4113 // Each thread has its own key and counter
4114 CReserveKey reservekey(pwallet);
4115 unsigned int nExtraNonce = 0;
4117 while (fGenerateBitcoins)
4121 while (vNodes.empty() || IsInitialBlockDownload())
4126 if (!fGenerateBitcoins)
4134 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
4135 CBlockIndex* pindexPrev = pindexBest;
4137 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
4140 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
4142 printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
4143 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
4147 // Pre-build hash buffers
4149 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
4150 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
4151 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
4153 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
4155 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
4156 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
4157 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
4163 int64 nStart = GetTime();
4164 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4166 uint256& hash = *alignup<16>(hashbuf);
4169 unsigned int nHashesDone = 0;
4170 unsigned int nNonceFound;
4173 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
4174 (char*)&hash, nHashesDone);
4176 // Check if something found
4177 if (nNonceFound != (unsigned int) -1)
4179 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
4180 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
4182 if (hash <= hashTarget)
4185 pblock->nNonce = ByteReverse(nNonceFound);
4186 assert(hash == pblock->GetHash());
4188 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4189 CheckWork(pblock.get(), *pwalletMain, reservekey);
4190 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4196 static int64 nHashCounter;
4197 if (nHPSTimerStart == 0)
4199 nHPSTimerStart = GetTimeMillis();
4203 nHashCounter += nHashesDone;
4204 if (GetTimeMillis() - nHPSTimerStart > 4000)
4206 static CCriticalSection cs;
4209 if (GetTimeMillis() - nHPSTimerStart > 4000)
4211 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
4212 nHPSTimerStart = GetTimeMillis();
4214 static int64 nLogTime;
4215 if (GetTime() - nLogTime > 30 * 60)
4217 nLogTime = GetTime();
4218 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
4224 // Check for stop or if block needs to be rebuilt
4227 if (!fGenerateBitcoins)
4229 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4233 if (nBlockNonce >= 0xffff0000)
4235 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4237 if (pindexPrev != pindexBest)
4240 // Update nTime every few seconds
4241 pblock->UpdateTime(pindexPrev);
4242 nBlockTime = ByteReverse(pblock->nTime);
4245 // Changing pblock->nTime can change work required on testnet:
4246 nBlockBits = ByteReverse(pblock->nBits);
4247 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4253 void static ThreadBitcoinMiner(void* parg)
4255 CWallet* pwallet = (CWallet*)parg;
4258 vnThreadsRunning[THREAD_MINER]++;
4259 BitcoinMiner(pwallet);
4260 vnThreadsRunning[THREAD_MINER]--;
4262 catch (std::exception& e) {
4263 vnThreadsRunning[THREAD_MINER]--;
4264 PrintException(&e, "ThreadBitcoinMiner()");
4266 vnThreadsRunning[THREAD_MINER]--;
4267 PrintException(NULL, "ThreadBitcoinMiner()");
4270 if (vnThreadsRunning[THREAD_MINER] == 0)
4272 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4276 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4278 fGenerateBitcoins = fGenerate;
4279 nLimitProcessors = GetArg("-genproclimit", -1);
4280 if (nLimitProcessors == 0)
4281 fGenerateBitcoins = false;
4282 fLimitProcessors = (nLimitProcessors != -1);
4286 int nProcessors = boost::thread::hardware_concurrency();
4287 printf("%d processors\n", nProcessors);
4288 if (nProcessors < 1)
4290 if (fLimitProcessors && nProcessors > nLimitProcessors)
4291 nProcessors = nLimitProcessors;
4292 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4293 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4294 for (int i = 0; i < nAddThreads; i++)
4296 if (!NewThread(ThreadBitcoinMiner, pwallet))
4297 printf("Error: NewThread(ThreadBitcoinMiner) failed\n");
4303 // Amount compression:
4304 // * If the amount is 0, output 0
4305 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
4306 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
4307 // * call the result n
4308 // * output 1 + 10*(9*n + d - 1) + e
4309 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
4310 // (this is decodable, as d is in [1-9] and e is in [0-9])
4312 uint64 CTxOutCompressor::CompressAmount(uint64 n)
4317 while (((n % 10) == 0) && e < 9) {
4323 assert(d >= 1 && d <= 9);
4325 return 1 + (n*9 + d - 1)*10 + e;
4327 return 1 + (n - 1)*10 + 9;
4331 uint64 CTxOutCompressor::DecompressAmount(uint64 x)
4333 // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
4337 // x = 10*(9*n + d - 1) + e
4343 int d = (x % 9) + 1;