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"
11 #include "cryptopp/sha.h"
12 #include <boost/filesystem.hpp>
13 #include <boost/filesystem/fstream.hpp>
16 using namespace boost;
22 CCriticalSection cs_setpwalletRegistered;
23 set<CWallet*> setpwalletRegistered;
25 CCriticalSection cs_main;
27 static map<uint256, CTransaction> mapTransactions;
28 CCriticalSection cs_mapTransactions;
29 unsigned int nTransactionsUpdated = 0;
30 map<COutPoint, CInPoint> mapNextTx;
32 map<uint256, CBlockIndex*> mapBlockIndex;
33 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
34 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
35 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
36 CBlockIndex* pindexGenesisBlock = NULL;
38 CBigNum bnBestChainWork = 0;
39 CBigNum bnBestInvalidWork = 0;
40 uint256 hashBestChain = 0;
41 CBlockIndex* pindexBest = NULL;
42 int64 nTimeBestReceived = 0;
44 map<uint256, CBlock*> mapOrphanBlocks;
45 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
47 map<uint256, CDataStream*> mapOrphanTransactions;
48 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
55 int fGenerateBitcoins = false;
56 int64 nTransactionFee = 0;
57 int fLimitProcessors = false;
58 int nLimitProcessors = 1;
59 int fMinimizeToTray = true;
60 int fMinimizeOnClose = true;
73 //////////////////////////////////////////////////////////////////////////////
75 // dispatching functions
78 void RegisterWallet(CWallet* pwalletIn)
80 CRITICAL_BLOCK(cs_setpwalletRegistered)
82 setpwalletRegistered.insert(pwalletIn);
86 void UnregisterWallet(CWallet* pwalletIn)
88 CRITICAL_BLOCK(cs_setpwalletRegistered)
90 setpwalletRegistered.erase(pwalletIn);
94 bool static IsFromMe(CTransaction& tx)
96 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
97 if (pwallet->IsFromMe(tx))
102 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
104 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
105 if (pwallet->GetTransaction(hashTx,wtx))
110 void static EraseFromWallets(uint256 hash)
112 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
113 pwallet->EraseFromWallet(hash);
116 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
118 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
119 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
122 void static SetBestChain(const CBlockLocator& loc)
124 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
125 pwallet->SetBestChain(loc);
128 void static UpdatedTransaction(const uint256& hashTx)
130 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
131 pwallet->UpdatedTransaction(hashTx);
134 void static PrintWallets(const CBlock& block)
136 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
137 pwallet->PrintWallet(block);
140 void static Inventory(const uint256& hash)
142 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
143 pwallet->Inventory(hash);
146 void static ResendWalletTransactions()
148 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
149 pwallet->ResendWalletTransactions();
158 //////////////////////////////////////////////////////////////////////////////
160 // mapOrphanTransactions
163 void AddOrphanTx(const CDataStream& vMsg)
166 CDataStream(vMsg) >> tx;
167 uint256 hash = tx.GetHash();
168 if (mapOrphanTransactions.count(hash))
171 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
172 BOOST_FOREACH(const CTxIn& txin, tx.vin)
173 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
176 void static EraseOrphanTx(uint256 hash)
178 if (!mapOrphanTransactions.count(hash))
180 const CDataStream* pvMsg = mapOrphanTransactions[hash];
182 CDataStream(*pvMsg) >> tx;
183 BOOST_FOREACH(const CTxIn& txin, tx.vin)
185 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
186 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
188 if ((*mi).second == pvMsg)
189 mapOrphanTransactionsByPrev.erase(mi++);
195 mapOrphanTransactions.erase(hash);
198 int LimitOrphanTxSize(int nMaxOrphans)
201 while (mapOrphanTransactions.size() > nMaxOrphans)
203 // Evict a random orphan:
204 std::vector<unsigned char> randbytes(32);
205 RAND_bytes(&randbytes[0], 32);
206 uint256 randomhash(randbytes);
207 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
208 if (it == mapOrphanTransactions.end())
209 it = mapOrphanTransactions.begin();
210 EraseOrphanTx(it->first);
222 //////////////////////////////////////////////////////////////////////////////
224 // CTransaction and CTxIndex
227 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
230 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
232 if (!ReadFromDisk(txindexRet.pos))
234 if (prevout.n >= vout.size())
242 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
245 return ReadFromDisk(txdb, prevout, txindex);
248 bool CTransaction::ReadFromDisk(COutPoint prevout)
252 return ReadFromDisk(txdb, prevout, txindex);
257 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
269 // Load the block this tx is in
271 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
273 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
278 // Update the tx's hashBlock
279 hashBlock = pblock->GetHash();
281 // Locate the transaction
282 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
283 if (pblock->vtx[nIndex] == *(CTransaction*)this)
285 if (nIndex == pblock->vtx.size())
287 vMerkleBranch.clear();
289 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
293 // Fill in merkle branch
294 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
297 // Is the tx in a block that's in the main chain
298 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
299 if (mi == mapBlockIndex.end())
301 CBlockIndex* pindex = (*mi).second;
302 if (!pindex || !pindex->IsInMainChain())
305 return pindexBest->nHeight - pindex->nHeight + 1;
314 bool CTransaction::CheckTransaction() const
316 // Basic checks that don't depend on any context
318 return error("CTransaction::CheckTransaction() : vin empty");
320 return error("CTransaction::CheckTransaction() : vout empty");
322 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
323 return error("CTransaction::CheckTransaction() : size limits failed");
325 // Check for negative or overflow output values
327 BOOST_FOREACH(const CTxOut& txout, vout)
329 if (txout.nValue < 0)
330 return error("CTransaction::CheckTransaction() : txout.nValue negative");
331 if (txout.nValue > MAX_MONEY)
332 return error("CTransaction::CheckTransaction() : txout.nValue too high");
333 nValueOut += txout.nValue;
334 if (!MoneyRange(nValueOut))
335 return error("CTransaction::CheckTransaction() : txout total out of range");
338 // Check for duplicate inputs
339 set<COutPoint> vInOutPoints;
340 BOOST_FOREACH(const CTxIn& txin, vin)
342 if (vInOutPoints.count(txin.prevout))
344 vInOutPoints.insert(txin.prevout);
349 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
350 return error("CTransaction::CheckTransaction() : coinbase script size");
354 BOOST_FOREACH(const CTxIn& txin, vin)
355 if (txin.prevout.IsNull())
356 return error("CTransaction::CheckTransaction() : prevout is null");
362 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
365 *pfMissingInputs = false;
367 if (!CheckTransaction())
368 return error("AcceptToMemoryPool() : CheckTransaction failed");
370 // Coinbase is only valid in a block, not as a loose transaction
372 return error("AcceptToMemoryPool() : coinbase as individual tx");
374 // To help v0.1.5 clients who would see it as a negative number
375 if ((int64)nLockTime > INT_MAX)
376 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
378 // Rather not work on nonstandard transactions (unless -testnet)
379 if (!fTestNet && !IsStandard())
380 return error("AcceptToMemoryPool() : nonstandard transaction type");
382 // Do we already have it?
383 uint256 hash = GetHash();
384 CRITICAL_BLOCK(cs_mapTransactions)
385 if (mapTransactions.count(hash))
388 if (txdb.ContainsTx(hash))
391 // Check for conflicts with in-memory transactions
392 CTransaction* ptxOld = NULL;
393 for (unsigned int i = 0; i < vin.size(); i++)
395 COutPoint outpoint = vin[i].prevout;
396 if (mapNextTx.count(outpoint))
398 // Disable replacement feature for now
401 // Allow replacing with a newer version of the same transaction
404 ptxOld = mapNextTx[outpoint].ptx;
405 if (ptxOld->IsFinal())
407 if (!IsNewerThan(*ptxOld))
409 for (unsigned int i = 0; i < vin.size(); i++)
411 COutPoint outpoint = vin[i].prevout;
412 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
422 map<uint256, CTxIndex> mapUnused;
423 bool fInvalid = false;
424 if (!FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
427 return error("AcceptToMemoryPool() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
429 *pfMissingInputs = true;
430 return error("AcceptToMemoryPool() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
434 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
435 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
436 // attacks disallow transactions with more than one SigOp per 34 bytes.
437 // 34 bytes because a TxOut is:
438 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
439 if (GetSigOpCount() > nSize / 34 || nSize < 100)
440 return error("AcceptToMemoryPool() : nonstandard transaction");
442 int64 nFees = GetValueIn(mapInputs)-GetValueOut();
444 // Don't accept it if it can't get into a block
445 if (nFees < GetMinFee(1000, true, true))
446 return error("AcceptToMemoryPool() : not enough fees");
448 // Continuously rate-limit free transactions
449 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
450 // be annoying or make other's transactions take longer to confirm.
451 if (nFees < MIN_RELAY_TX_FEE)
453 static CCriticalSection cs;
454 static double dFreeCount;
455 static int64 nLastTime;
456 int64 nNow = GetTime();
460 // Use an exponentially decaying ~10-minute window:
461 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
463 // -limitfreerelay unit is thousand-bytes-per-minute
464 // At default rate it would take over a month to fill 1GB
465 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
466 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
468 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
473 // Check against previous transactions
474 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
475 if (!ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
477 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
481 // Store transaction in memory
482 CRITICAL_BLOCK(cs_mapTransactions)
486 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
487 ptxOld->RemoveFromMemoryPool();
489 AddToMemoryPoolUnchecked();
492 ///// are we sure this is ok when loading transactions or restoring block txes
493 // If updated, erase old tx from wallet
495 EraseFromWallets(ptxOld->GetHash());
497 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
501 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
504 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
507 bool CTransaction::AddToMemoryPoolUnchecked()
509 // Add to memory pool without checking anything. Don't call this directly,
510 // call AcceptToMemoryPool to properly check the transaction first.
511 CRITICAL_BLOCK(cs_mapTransactions)
513 uint256 hash = GetHash();
514 mapTransactions[hash] = *this;
515 for (unsigned int i = 0; i < vin.size(); i++)
516 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
517 nTransactionsUpdated++;
523 bool CTransaction::RemoveFromMemoryPool()
525 // Remove transaction from memory pool
526 CRITICAL_BLOCK(cs_mapTransactions)
528 BOOST_FOREACH(const CTxIn& txin, vin)
529 mapNextTx.erase(txin.prevout);
530 mapTransactions.erase(GetHash());
531 nTransactionsUpdated++;
541 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
543 if (hashBlock == 0 || nIndex == -1)
546 // Find the block it claims to be in
547 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
548 if (mi == mapBlockIndex.end())
550 CBlockIndex* pindex = (*mi).second;
551 if (!pindex || !pindex->IsInMainChain())
554 // Make sure the merkle branch connects to this block
555 if (!fMerkleVerified)
557 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
559 fMerkleVerified = true;
562 nHeightRet = pindex->nHeight;
563 return pindexBest->nHeight - pindex->nHeight + 1;
567 int CMerkleTx::GetBlocksToMaturity() const
571 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
575 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
579 if (!IsInMainChain() && !ClientConnectInputs())
581 return CTransaction::AcceptToMemoryPool(txdb, false);
585 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
589 bool CMerkleTx::AcceptToMemoryPool()
592 return AcceptToMemoryPool(txdb);
597 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
599 CRITICAL_BLOCK(cs_mapTransactions)
601 // Add previous supporting transactions first
602 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
604 if (!tx.IsCoinBase())
606 uint256 hash = tx.GetHash();
607 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
608 tx.AcceptToMemoryPool(txdb, fCheckInputs);
611 return AcceptToMemoryPool(txdb, fCheckInputs);
616 bool CWalletTx::AcceptWalletTransaction()
619 return AcceptWalletTransaction(txdb);
622 int CTxIndex::GetDepthInMainChain() const
626 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
628 // Find the block in the index
629 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
630 if (mi == mapBlockIndex.end())
632 CBlockIndex* pindex = (*mi).second;
633 if (!pindex || !pindex->IsInMainChain())
635 return 1 + nBestHeight - pindex->nHeight;
647 //////////////////////////////////////////////////////////////////////////////
649 // CBlock and CBlockIndex
652 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
654 if (!fReadTransactions)
656 *this = pindex->GetBlockHeader();
659 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
661 if (GetHash() != pindex->GetBlockHash())
662 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
666 uint256 static GetOrphanRoot(const CBlock* pblock)
668 // Work back to the first block in the orphan chain
669 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
670 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
671 return pblock->GetHash();
674 int64 static GetBlockValue(int nHeight, int64 nFees)
676 int64 nSubsidy = 50 * COIN;
678 // Subsidy is cut in half every 4 years
679 nSubsidy >>= (nHeight / 210000);
681 return nSubsidy + nFees;
684 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
685 static const int64 nTargetSpacing = 10 * 60;
686 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
689 // minimum amount of work that could possibly be required nTime after
690 // minimum work required was nBase
692 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
694 // Testnet has min-difficulty blocks
695 // after nTargetSpacing*2 time between blocks:
696 if (fTestNet && nTime > nTargetSpacing*2)
697 return bnProofOfWorkLimit.GetCompact();
700 bnResult.SetCompact(nBase);
701 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
703 // Maximum 400% adjustment...
705 // ... in best-case exactly 4-times-normal target time
706 nTime -= nTargetTimespan*4;
708 if (bnResult > bnProofOfWorkLimit)
709 bnResult = bnProofOfWorkLimit;
710 return bnResult.GetCompact();
713 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
715 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
718 if (pindexLast == NULL)
719 return nProofOfWorkLimit;
721 // Only change once per interval
722 if ((pindexLast->nHeight+1) % nInterval != 0)
724 // Special rules for testnet after 15 Feb 2012:
725 if (fTestNet && pblock->nTime > 1329264000)
727 // If the new block's timestamp is more than 2* 10 minutes
728 // then allow mining of a min-difficulty block.
729 if (pblock->nTime - pindexLast->nTime > nTargetSpacing*2)
730 return nProofOfWorkLimit;
733 // Return the last non-special-min-difficulty-rules-block
734 const CBlockIndex* pindex = pindexLast;
735 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
736 pindex = pindex->pprev;
737 return pindex->nBits;
741 return pindexLast->nBits;
744 // Go back by what we want to be 14 days worth of blocks
745 const CBlockIndex* pindexFirst = pindexLast;
746 for (int i = 0; pindexFirst && i < nInterval-1; i++)
747 pindexFirst = pindexFirst->pprev;
750 // Limit adjustment step
751 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
752 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
753 if (nActualTimespan < nTargetTimespan/4)
754 nActualTimespan = nTargetTimespan/4;
755 if (nActualTimespan > nTargetTimespan*4)
756 nActualTimespan = nTargetTimespan*4;
760 bnNew.SetCompact(pindexLast->nBits);
761 bnNew *= nActualTimespan;
762 bnNew /= nTargetTimespan;
764 if (bnNew > bnProofOfWorkLimit)
765 bnNew = bnProofOfWorkLimit;
768 printf("GetNextWorkRequired RETARGET\n");
769 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
770 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
771 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
773 return bnNew.GetCompact();
776 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
779 bnTarget.SetCompact(nBits);
782 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
783 return error("CheckProofOfWork() : nBits below minimum work");
785 // Check proof of work matches claimed amount
786 if (hash > bnTarget.getuint256())
787 return error("CheckProofOfWork() : hash doesn't match nBits");
792 bool IsInitialBlockDownload()
794 if (pindexBest == NULL || nBestHeight < (Checkpoints::GetTotalBlocksEstimate()-nInitialBlockThreshold))
796 static int64 nLastUpdate;
797 static CBlockIndex* pindexLastBest;
798 if (pindexBest != pindexLastBest)
800 pindexLastBest = pindexBest;
801 nLastUpdate = GetTime();
803 return (GetTime() - nLastUpdate < 10 &&
804 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
807 void static InvalidChainFound(CBlockIndex* pindexNew)
809 if (pindexNew->bnChainWork > bnBestInvalidWork)
811 bnBestInvalidWork = pindexNew->bnChainWork;
812 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
815 printf("InvalidChainFound: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
816 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
817 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
818 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
821 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
823 nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
825 // Updating time can change work required on testnet:
827 nBits = GetNextWorkRequired(pindexPrev, this);
840 bool CTransaction::DisconnectInputs(CTxDB& txdb)
842 // Relinquish previous transactions' spent pointers
845 BOOST_FOREACH(const CTxIn& txin, vin)
847 COutPoint prevout = txin.prevout;
849 // Get prev txindex from disk
851 if (!txdb.ReadTxIndex(prevout.hash, txindex))
852 return error("DisconnectInputs() : ReadTxIndex failed");
854 if (prevout.n >= txindex.vSpent.size())
855 return error("DisconnectInputs() : prevout.n out of range");
857 // Mark outpoint as not spent
858 txindex.vSpent[prevout.n].SetNull();
861 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
862 return error("DisconnectInputs() : UpdateTxIndex failed");
866 // Remove transaction from index
867 // This can fail if a duplicate of this transaction was in a chain that got
868 // reorganized away. This is only possible if this transaction was completely
869 // spent, so erasing it would be a no-op anway.
870 txdb.EraseTxIndex(*this);
876 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
877 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
879 // FetchInputs can return false either because we just haven't seen some inputs
880 // (in which case the transaction should be stored as an orphan)
881 // or because the transaction is malformed (in which case the transaction should
882 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
886 return true; // Coinbase transactions have no inputs to fetch.
888 for (unsigned int i = 0; i < vin.size(); i++)
890 COutPoint prevout = vin[i].prevout;
891 if (inputsRet.count(prevout.hash))
892 continue; // Got it already
895 CTxIndex& txindex = inputsRet[prevout.hash].first;
897 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
899 // Get txindex from current proposed changes
900 txindex = mapTestPool.find(prevout.hash)->second;
904 // Read txindex from txdb
905 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
907 if (!fFound && (fBlock || fMiner))
908 return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
911 CTransaction& txPrev = inputsRet[prevout.hash].second;
912 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
914 // Get prev tx from single transactions in memory
915 CRITICAL_BLOCK(cs_mapTransactions)
917 if (!mapTransactions.count(prevout.hash))
918 return error("FetchInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
919 txPrev = mapTransactions[prevout.hash];
922 txindex.vSpent.resize(txPrev.vout.size());
926 // Get prev tx from disk
927 if (!txPrev.ReadFromDisk(txindex.pos))
928 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
932 // Make sure all prevout.n's are valid:
933 for (unsigned int i = 0; i < vin.size(); i++)
935 const COutPoint prevout = vin[i].prevout;
936 assert(inputsRet.count(prevout.hash) != 0);
937 const CTxIndex& txindex = inputsRet[prevout.hash].first;
938 const CTransaction& txPrev = inputsRet[prevout.hash].second;
939 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
941 // Revisit this if/when transaction replacement is implemented and allows
944 return error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str());
951 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
953 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
954 if (mi == inputs.end())
955 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
957 const CTransaction& txPrev = (mi->second).second;
958 if (input.prevout.n >= txPrev.vout.size())
959 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
961 return txPrev.vout[input.prevout.n];
964 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
970 for (unsigned int i = 0; i < vin.size(); i++)
972 nResult += GetOutputFor(vin[i], inputs).nValue;
978 int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
984 for (unsigned int i = 0; i < vin.size(); i++)
986 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
987 if (prevout.scriptPubKey.IsPayToScriptHash())
988 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
993 bool CTransaction::ConnectInputs(MapPrevTx inputs,
994 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
995 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
997 // Take over previous transactions' spent pointers
998 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
999 // fMiner is true when called from the internal bitcoin miner
1000 // ... both are false when called from CTransaction::AcceptToMemoryPool
1005 for (unsigned int i = 0; i < vin.size(); i++)
1007 COutPoint prevout = vin[i].prevout;
1008 assert(inputs.count(prevout.hash) > 0);
1009 CTxIndex& txindex = inputs[prevout.hash].first;
1010 CTransaction& txPrev = inputs[prevout.hash].second;
1012 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1013 return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str());
1015 // If prev is coinbase, check that it's matured
1016 if (txPrev.IsCoinBase())
1017 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1018 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1019 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1021 // Check for conflicts (double-spend)
1022 if (!txindex.vSpent[prevout.n].IsNull())
1023 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
1025 // Check for negative or overflow input values
1026 nValueIn += txPrev.vout[prevout.n].nValue;
1027 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1028 return error("ConnectInputs() : txin values out of range");
1031 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1033 // only during transition phase for P2SH: do not invoke (external)
1034 // anti-DoS code for potentially old clients relaying bad P2SH
1036 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1037 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1039 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1042 // Mark outpoints as spent
1043 txindex.vSpent[prevout.n] = posThisTx;
1046 if (fBlock || fMiner)
1048 mapTestPool[prevout.hash] = txindex;
1052 if (nValueIn < GetValueOut())
1053 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1055 // Tally transaction fees
1056 int64 nTxFee = nValueIn - GetValueOut();
1058 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1060 if (!MoneyRange(nFees))
1061 return error("ConnectInputs() : nFees out of range");
1068 bool CTransaction::ClientConnectInputs()
1073 // Take over previous transactions' spent pointers
1074 CRITICAL_BLOCK(cs_mapTransactions)
1077 for (unsigned int i = 0; i < vin.size(); i++)
1079 // Get prev tx from single transactions in memory
1080 COutPoint prevout = vin[i].prevout;
1081 if (!mapTransactions.count(prevout.hash))
1083 CTransaction& txPrev = mapTransactions[prevout.hash];
1085 if (prevout.n >= txPrev.vout.size())
1089 if (!VerifySignature(txPrev, *this, i, true, 0))
1090 return error("ConnectInputs() : VerifySignature failed");
1092 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1093 ///// this has to go away now that posNext is gone
1094 // // Check for conflicts
1095 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1096 // return error("ConnectInputs() : prev tx already used");
1098 // // Flag outpoints as used
1099 // txPrev.vout[prevout.n].posNext = posThisTx;
1101 nValueIn += txPrev.vout[prevout.n].nValue;
1103 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1104 return error("ClientConnectInputs() : txin values out of range");
1106 if (GetValueOut() > nValueIn)
1116 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1118 // Disconnect in reverse order
1119 for (int i = vtx.size()-1; i >= 0; i--)
1120 if (!vtx[i].DisconnectInputs(txdb))
1123 // Update block index on disk without changing it in memory.
1124 // The memory index structure will be changed after the db commits.
1127 CDiskBlockIndex blockindexPrev(pindex->pprev);
1128 blockindexPrev.hashNext = 0;
1129 if (!txdb.WriteBlockIndex(blockindexPrev))
1130 return error("DisconnectBlock() : WriteBlockIndex failed");
1136 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1138 // Check it again in case a previous version let a bad block in
1142 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1143 // unless those are already completely spent.
1144 // If such overwrites are allowed, coinbases and transactions depending upon those
1145 // can be duplicated to remove the ability to spend the first instance -- even after
1146 // being sent to another address.
1147 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1148 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1149 // already refuses previously-known transaction id's entirely.
1150 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1151 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1152 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1154 BOOST_FOREACH(CTransaction& tx, vtx)
1156 CTxIndex txindexOld;
1157 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1159 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1166 // P2SH didn't become active until Apr 1 2012 (Feb 15 on testnet)
1167 int64 nEvalSwitchTime = fTestNet ? 1329264000 : 1333238400;
1168 bool fStrictPayToScriptHash = (pindex->nTime >= nEvalSwitchTime);
1170 //// issue here: it doesn't know the version
1171 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1173 map<uint256, CTxIndex> mapQueuedChanges;
1176 BOOST_FOREACH(CTransaction& tx, vtx)
1178 nSigOps += tx.GetSigOpCount();
1179 if (nSigOps > MAX_BLOCK_SIGOPS)
1180 return error("ConnectBlock() : too many sigops");
1182 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1183 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1186 MapPrevTx mapInputs;
1187 if (!tx.IsCoinBase())
1189 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1192 if (fStrictPayToScriptHash)
1194 // Add in sigops done by pay-to-script-hash inputs;
1195 // this is to prevent a "rogue miner" from creating
1196 // an incredibly-expensive-to-validate block.
1197 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1198 if (nSigOps > MAX_BLOCK_SIGOPS)
1199 return error("ConnectBlock() : too many sigops");
1202 nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
1204 if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1208 mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
1211 // Write queued txindex changes
1212 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1214 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1215 return error("ConnectBlock() : UpdateTxIndex failed");
1218 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1221 // Update block index on disk without changing it in memory.
1222 // The memory index structure will be changed after the db commits.
1225 CDiskBlockIndex blockindexPrev(pindex->pprev);
1226 blockindexPrev.hashNext = pindex->GetBlockHash();
1227 if (!txdb.WriteBlockIndex(blockindexPrev))
1228 return error("ConnectBlock() : WriteBlockIndex failed");
1231 // Watch for transactions paying to me
1232 BOOST_FOREACH(CTransaction& tx, vtx)
1233 SyncWithWallets(tx, this, true);
1238 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1240 printf("REORGANIZE\n");
1243 CBlockIndex* pfork = pindexBest;
1244 CBlockIndex* plonger = pindexNew;
1245 while (pfork != plonger)
1247 while (plonger->nHeight > pfork->nHeight)
1248 if (!(plonger = plonger->pprev))
1249 return error("Reorganize() : plonger->pprev is null");
1250 if (pfork == plonger)
1252 if (!(pfork = pfork->pprev))
1253 return error("Reorganize() : pfork->pprev is null");
1256 // List of what to disconnect
1257 vector<CBlockIndex*> vDisconnect;
1258 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1259 vDisconnect.push_back(pindex);
1261 // List of what to connect
1262 vector<CBlockIndex*> vConnect;
1263 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1264 vConnect.push_back(pindex);
1265 reverse(vConnect.begin(), vConnect.end());
1267 printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
1268 printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
1270 // Disconnect shorter branch
1271 vector<CTransaction> vResurrect;
1272 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1275 if (!block.ReadFromDisk(pindex))
1276 return error("Reorganize() : ReadFromDisk for disconnect failed");
1277 if (!block.DisconnectBlock(txdb, pindex))
1278 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1280 // Queue memory transactions to resurrect
1281 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1282 if (!tx.IsCoinBase())
1283 vResurrect.push_back(tx);
1286 // Connect longer branch
1287 vector<CTransaction> vDelete;
1288 for (unsigned int i = 0; i < vConnect.size(); i++)
1290 CBlockIndex* pindex = vConnect[i];
1292 if (!block.ReadFromDisk(pindex))
1293 return error("Reorganize() : ReadFromDisk for connect failed");
1294 if (!block.ConnectBlock(txdb, pindex))
1298 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1301 // Queue memory transactions to delete
1302 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1303 vDelete.push_back(tx);
1305 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1306 return error("Reorganize() : WriteHashBestChain failed");
1308 // Make sure it's successfully written to disk before changing memory structure
1309 if (!txdb.TxnCommit())
1310 return error("Reorganize() : TxnCommit failed");
1312 // Disconnect shorter branch
1313 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1315 pindex->pprev->pnext = NULL;
1317 // Connect longer branch
1318 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1320 pindex->pprev->pnext = pindex;
1322 // Resurrect memory transactions that were in the disconnected branch
1323 BOOST_FOREACH(CTransaction& tx, vResurrect)
1324 tx.AcceptToMemoryPool(txdb, false);
1326 // Delete redundant memory transactions that are in the connected branch
1327 BOOST_FOREACH(CTransaction& tx, vDelete)
1328 tx.RemoveFromMemoryPool();
1330 printf("REORGANIZE: done\n");
1336 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1338 uint256 hash = GetHash();
1340 if (!txdb.TxnBegin())
1341 return error("SetBestChain() : TxnBegin failed");
1343 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1345 txdb.WriteHashBestChain(hash);
1346 if (!txdb.TxnCommit())
1347 return error("SetBestChain() : TxnCommit failed");
1348 pindexGenesisBlock = pindexNew;
1350 else if (hashPrevBlock == hashBestChain)
1352 // Adding to current best branch
1353 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1356 InvalidChainFound(pindexNew);
1357 return error("SetBestChain() : ConnectBlock failed");
1359 if (!txdb.TxnCommit())
1360 return error("SetBestChain() : TxnCommit failed");
1362 // Add to current best branch
1363 pindexNew->pprev->pnext = pindexNew;
1365 // Delete redundant memory transactions
1366 BOOST_FOREACH(CTransaction& tx, vtx)
1367 tx.RemoveFromMemoryPool();
1372 if (!Reorganize(txdb, pindexNew))
1375 InvalidChainFound(pindexNew);
1376 return error("SetBestChain() : Reorganize failed");
1380 // Update best block in wallet (so we can detect restored wallets)
1381 if (!IsInitialBlockDownload())
1383 const CBlockLocator locator(pindexNew);
1384 ::SetBestChain(locator);
1388 hashBestChain = hash;
1389 pindexBest = pindexNew;
1390 nBestHeight = pindexBest->nHeight;
1391 bnBestChainWork = pindexNew->bnChainWork;
1392 nTimeBestReceived = GetTime();
1393 nTransactionsUpdated++;
1394 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1400 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1402 // Check for duplicate
1403 uint256 hash = GetHash();
1404 if (mapBlockIndex.count(hash))
1405 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1407 // Construct new block index object
1408 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1410 return error("AddToBlockIndex() : new CBlockIndex failed");
1411 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1412 pindexNew->phashBlock = &((*mi).first);
1413 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1414 if (miPrev != mapBlockIndex.end())
1416 pindexNew->pprev = (*miPrev).second;
1417 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1419 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1422 if (!txdb.TxnBegin())
1424 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1425 if (!txdb.TxnCommit())
1429 if (pindexNew->bnChainWork > bnBestChainWork)
1430 if (!SetBestChain(txdb, pindexNew))
1435 if (pindexNew == pindexBest)
1437 // Notify UI to display prev block's coinbase if it was ours
1438 static uint256 hashPrevBestCoinBase;
1439 UpdatedTransaction(hashPrevBestCoinBase);
1440 hashPrevBestCoinBase = vtx[0].GetHash();
1450 bool CBlock::CheckBlock() const
1452 // These are checks that are independent of context
1453 // that can be verified before saving an orphan block.
1456 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1457 return error("CheckBlock() : size limits failed");
1459 // Check proof of work matches claimed amount
1460 if (!CheckProofOfWork(GetHash(), nBits))
1461 return error("CheckBlock() : proof of work failed");
1464 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1465 return error("CheckBlock() : block timestamp too far in the future");
1467 // First transaction must be coinbase, the rest must not be
1468 if (vtx.empty() || !vtx[0].IsCoinBase())
1469 return error("CheckBlock() : first tx is not coinbase");
1470 for (unsigned int i = 1; i < vtx.size(); i++)
1471 if (vtx[i].IsCoinBase())
1472 return error("CheckBlock() : more than one coinbase");
1474 // Check transactions
1475 BOOST_FOREACH(const CTransaction& tx, vtx)
1476 if (!tx.CheckTransaction())
1477 return error("CheckBlock() : CheckTransaction failed");
1479 // Check for duplicate txids. This is caught by ConnectInputs(),
1480 // but catching it earlier avoids a potential DoS attack:
1481 set<uint256> uniqueTx;
1482 BOOST_FOREACH(const CTransaction& tx, vtx)
1484 uniqueTx.insert(tx.GetHash());
1486 if (uniqueTx.size() != vtx.size())
1487 return error("CheckBlock() : duplicate transaction");
1489 // Check that it's not full of nonstandard transactions
1490 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1491 return error("CheckBlock() : out-of-bounds SigOpCount");
1494 if (hashMerkleRoot != BuildMerkleTree())
1495 return error("CheckBlock() : hashMerkleRoot mismatch");
1500 bool CBlock::AcceptBlock()
1502 // Check for duplicate
1503 uint256 hash = GetHash();
1504 if (mapBlockIndex.count(hash))
1505 return error("AcceptBlock() : block already in mapBlockIndex");
1507 // Get prev block index
1508 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1509 if (mi == mapBlockIndex.end())
1510 return error("AcceptBlock() : prev block not found");
1511 CBlockIndex* pindexPrev = (*mi).second;
1512 int nHeight = pindexPrev->nHeight+1;
1514 // Check proof of work
1515 if (nBits != GetNextWorkRequired(pindexPrev, this))
1516 return error("AcceptBlock() : incorrect proof of work");
1518 // Check timestamp against prev
1519 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1520 return error("AcceptBlock() : block's timestamp is too early");
1522 // Check that all transactions are finalized
1523 BOOST_FOREACH(const CTransaction& tx, vtx)
1524 if (!tx.IsFinal(nHeight, GetBlockTime()))
1525 return error("AcceptBlock() : contains a non-final transaction");
1527 // Check that the block chain matches the known block chain up to a checkpoint
1528 if (!Checkpoints::CheckBlock(nHeight, hash))
1529 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1531 // Write block to history file
1532 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1533 return error("AcceptBlock() : out of disk space");
1534 unsigned int nFile = -1;
1535 unsigned int nBlockPos = 0;
1536 if (!WriteToDisk(nFile, nBlockPos))
1537 return error("AcceptBlock() : WriteToDisk failed");
1538 if (!AddToBlockIndex(nFile, nBlockPos))
1539 return error("AcceptBlock() : AddToBlockIndex failed");
1541 // Relay inventory, but don't relay old inventory during initial block download
1542 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1543 if (hashBestChain == hash)
1544 CRITICAL_BLOCK(cs_vNodes)
1545 BOOST_FOREACH(CNode* pnode, vNodes)
1546 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1547 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1552 bool static ProcessBlock(CNode* pfrom, CBlock* pblock)
1554 // Check for duplicate
1555 uint256 hash = pblock->GetHash();
1556 if (mapBlockIndex.count(hash))
1557 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1558 if (mapOrphanBlocks.count(hash))
1559 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1561 // Preliminary checks
1562 if (!pblock->CheckBlock())
1563 return error("ProcessBlock() : CheckBlock FAILED");
1565 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1566 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1568 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1569 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1572 return error("ProcessBlock() : block with timestamp before last checkpoint");
1575 bnNewBlock.SetCompact(pblock->nBits);
1577 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1578 if (bnNewBlock > bnRequired)
1580 return error("ProcessBlock() : block with too little proof-of-work");
1585 // If don't already have its previous block, shunt it off to holding area until we get it
1586 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1588 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1589 CBlock* pblock2 = new CBlock(*pblock);
1590 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1591 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1593 // Ask this guy to fill in what we're missing
1595 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1600 if (!pblock->AcceptBlock())
1601 return error("ProcessBlock() : AcceptBlock FAILED");
1603 // Recursively process any orphan blocks that depended on this one
1604 vector<uint256> vWorkQueue;
1605 vWorkQueue.push_back(hash);
1606 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1608 uint256 hashPrev = vWorkQueue[i];
1609 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1610 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1613 CBlock* pblockOrphan = (*mi).second;
1614 if (pblockOrphan->AcceptBlock())
1615 vWorkQueue.push_back(pblockOrphan->GetHash());
1616 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1617 delete pblockOrphan;
1619 mapOrphanBlocksByPrev.erase(hashPrev);
1622 printf("ProcessBlock: ACCEPTED\n");
1633 bool CheckDiskSpace(uint64 nAdditionalBytes)
1635 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1637 // Check for 15MB because database could create another 10MB log file at any time
1638 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1641 string strMessage = _("Warning: Disk space is low");
1642 strMiscWarning = strMessage;
1643 printf("*** %s\n", strMessage.c_str());
1644 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1645 CreateThread(Shutdown, NULL);
1651 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1655 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1658 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1660 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1669 static unsigned int nCurrentBlockFile = 1;
1671 FILE* AppendBlockFile(unsigned int& nFileRet)
1676 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1679 if (fseek(file, 0, SEEK_END) != 0)
1681 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1682 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1684 nFileRet = nCurrentBlockFile;
1688 nCurrentBlockFile++;
1692 bool LoadBlockIndex(bool fAllowNew)
1696 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1697 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1698 pchMessageStart[0] = 0xfa;
1699 pchMessageStart[1] = 0xbf;
1700 pchMessageStart[2] = 0xb5;
1701 pchMessageStart[3] = 0xda;
1708 if (!txdb.LoadBlockIndex())
1713 // Init with genesis block
1715 if (mapBlockIndex.empty())
1721 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1722 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1723 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1724 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1725 // vMerkleTree: 4a5e1e
1728 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1730 txNew.vin.resize(1);
1731 txNew.vout.resize(1);
1732 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1733 txNew.vout[0].nValue = 50 * COIN;
1734 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1736 block.vtx.push_back(txNew);
1737 block.hashPrevBlock = 0;
1738 block.hashMerkleRoot = block.BuildMerkleTree();
1740 block.nTime = 1231006505;
1741 block.nBits = 0x1d00ffff;
1742 block.nNonce = 2083236893;
1746 block.nTime = 1296688602;
1747 block.nBits = 0x1d07fff8;
1748 block.nNonce = 384568319;
1752 printf("%s\n", block.GetHash().ToString().c_str());
1753 printf("%s\n", hashGenesisBlock.ToString().c_str());
1754 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1755 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1757 assert(block.GetHash() == hashGenesisBlock);
1759 // Start new block file
1761 unsigned int nBlockPos;
1762 if (!block.WriteToDisk(nFile, nBlockPos))
1763 return error("LoadBlockIndex() : writing genesis block to disk failed");
1764 if (!block.AddToBlockIndex(nFile, nBlockPos))
1765 return error("LoadBlockIndex() : genesis block not accepted");
1773 void PrintBlockTree()
1775 // precompute tree structure
1776 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1777 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1779 CBlockIndex* pindex = (*mi).second;
1780 mapNext[pindex->pprev].push_back(pindex);
1782 //while (rand() % 3 == 0)
1783 // mapNext[pindex->pprev].push_back(pindex);
1786 vector<pair<int, CBlockIndex*> > vStack;
1787 vStack.push_back(make_pair(0, pindexGenesisBlock));
1790 while (!vStack.empty())
1792 int nCol = vStack.back().first;
1793 CBlockIndex* pindex = vStack.back().second;
1796 // print split or gap
1797 if (nCol > nPrevCol)
1799 for (int i = 0; i < nCol-1; i++)
1803 else if (nCol < nPrevCol)
1805 for (int i = 0; i < nCol; i++)
1812 for (int i = 0; i < nCol; i++)
1817 block.ReadFromDisk(pindex);
1818 printf("%d (%u,%u) %s %s tx %d",
1822 block.GetHash().ToString().substr(0,20).c_str(),
1823 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1826 PrintWallets(block);
1828 // put the main timechain first
1829 vector<CBlockIndex*>& vNext = mapNext[pindex];
1830 for (unsigned int i = 0; i < vNext.size(); i++)
1832 if (vNext[i]->pnext)
1834 swap(vNext[0], vNext[i]);
1840 for (unsigned int i = 0; i < vNext.size(); i++)
1841 vStack.push_back(make_pair(nCol+i, vNext[i]));
1854 //////////////////////////////////////////////////////////////////////////////
1859 map<uint256, CAlert> mapAlerts;
1860 CCriticalSection cs_mapAlerts;
1862 string GetWarnings(string strFor)
1865 string strStatusBar;
1867 if (GetBoolArg("-testsafemode"))
1870 // Misc warnings like out of disk space and clock is wrong
1871 if (strMiscWarning != "")
1874 strStatusBar = strMiscWarning;
1877 // Longer invalid proof-of-work chain
1878 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1881 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1885 CRITICAL_BLOCK(cs_mapAlerts)
1887 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1889 const CAlert& alert = item.second;
1890 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1892 nPriority = alert.nPriority;
1893 strStatusBar = alert.strStatusBar;
1898 if (strFor == "statusbar")
1899 return strStatusBar;
1900 else if (strFor == "rpc")
1902 assert(!"GetWarnings() : invalid parameter");
1906 bool CAlert::ProcessAlert()
1908 if (!CheckSignature())
1913 CRITICAL_BLOCK(cs_mapAlerts)
1915 // Cancel previous alerts
1916 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1918 const CAlert& alert = (*mi).second;
1921 printf("cancelling alert %d\n", alert.nID);
1922 mapAlerts.erase(mi++);
1924 else if (!alert.IsInEffect())
1926 printf("expiring alert %d\n", alert.nID);
1927 mapAlerts.erase(mi++);
1933 // Check if this alert has been cancelled
1934 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1936 const CAlert& alert = item.second;
1937 if (alert.Cancels(*this))
1939 printf("alert already cancelled by %d\n", alert.nID);
1945 mapAlerts.insert(make_pair(GetHash(), *this));
1948 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1960 //////////////////////////////////////////////////////////////////////////////
1966 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1972 bool txInMap = false;
1973 CRITICAL_BLOCK(cs_mapTransactions)
1975 txInMap = (mapTransactions.count(inv.hash) != 0);
1978 mapOrphanTransactions.count(inv.hash) ||
1979 txdb.ContainsTx(inv.hash);
1982 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1984 // Don't know what it is, just say we already got one
1991 // The message start string is designed to be unlikely to occur in normal data.
1992 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1993 // a large 4-byte int at any alignment.
1994 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1997 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1999 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2000 RandAddSeedPerfmon();
2002 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2003 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2005 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2007 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2015 if (strCommand == "version")
2017 // Each connection can only send one version message
2018 if (pfrom->nVersion != 0)
2025 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2026 if (pfrom->nVersion == 10300)
2027 pfrom->nVersion = 300;
2028 if (pfrom->nVersion >= 106 && !vRecv.empty())
2029 vRecv >> addrFrom >> nNonce;
2030 if (pfrom->nVersion >= 106 && !vRecv.empty())
2031 vRecv >> pfrom->strSubVer;
2032 if (pfrom->nVersion >= 209 && !vRecv.empty())
2033 vRecv >> pfrom->nStartingHeight;
2035 if (pfrom->nVersion == 0)
2038 // Disconnect if we connected to ourself
2039 if (nNonce == nLocalHostNonce && nNonce > 1)
2041 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2042 pfrom->fDisconnect = true;
2046 // Be shy and don't send version until we hear
2047 if (pfrom->fInbound)
2048 pfrom->PushVersion();
2050 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2052 AddTimeData(pfrom->addr.ip, nTime);
2055 if (pfrom->nVersion >= 209)
2056 pfrom->PushMessage("verack");
2057 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2058 if (pfrom->nVersion < 209)
2059 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2061 if (!pfrom->fInbound)
2063 // Advertise our address
2064 if (addrLocalHost.IsRoutable() && !fUseProxy)
2066 CAddress addr(addrLocalHost);
2067 addr.nTime = GetAdjustedTime();
2068 pfrom->PushAddress(addr);
2071 // Get recent addresses
2072 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2074 pfrom->PushMessage("getaddr");
2075 pfrom->fGetAddr = true;
2079 // Ask the first connected node for block updates
2080 static int nAskedForBlocks = 0;
2081 if (!pfrom->fClient &&
2082 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
2083 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2086 pfrom->PushGetBlocks(pindexBest, uint256(0));
2090 CRITICAL_BLOCK(cs_mapAlerts)
2091 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2092 item.second.RelayTo(pfrom);
2094 pfrom->fSuccessfullyConnected = true;
2096 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2100 else if (pfrom->nVersion == 0)
2102 // Must have a version message before anything else
2107 else if (strCommand == "verack")
2109 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2113 else if (strCommand == "addr")
2115 vector<CAddress> vAddr;
2118 // Don't want addr from older versions unless seeding
2119 if (pfrom->nVersion < 209)
2121 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2123 if (vAddr.size() > 1000)
2124 return error("message addr size() = %d", vAddr.size());
2126 // Store the new addresses
2129 int64 nNow = GetAdjustedTime();
2130 int64 nSince = nNow - 10 * 60;
2131 BOOST_FOREACH(CAddress& addr, vAddr)
2135 // ignore IPv6 for now, since it isn't implemented anyway
2138 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2139 addr.nTime = nNow - 5 * 24 * 60 * 60;
2140 AddAddress(addr, 2 * 60 * 60, &addrDB);
2141 pfrom->AddAddressKnown(addr);
2142 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2144 // Relay to a limited number of other nodes
2145 CRITICAL_BLOCK(cs_vNodes)
2147 // Use deterministic randomness to send to the same nodes for 24 hours
2148 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2149 static uint256 hashSalt;
2151 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2152 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2153 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2154 multimap<uint256, CNode*> mapMix;
2155 BOOST_FOREACH(CNode* pnode, vNodes)
2157 if (pnode->nVersion < 31402)
2159 unsigned int nPointer;
2160 memcpy(&nPointer, &pnode, sizeof(nPointer));
2161 uint256 hashKey = hashRand ^ nPointer;
2162 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2163 mapMix.insert(make_pair(hashKey, pnode));
2165 int nRelayNodes = 2;
2166 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2167 ((*mi).second)->PushAddress(addr);
2171 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
2172 if (vAddr.size() < 1000)
2173 pfrom->fGetAddr = false;
2177 else if (strCommand == "inv")
2181 if (vInv.size() > 50000)
2182 return error("message inv size() = %d", vInv.size());
2184 // find last block in inv vector
2185 unsigned int nLastBlock = (unsigned int)(-1);
2186 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
2187 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
2188 nLastBlock = vInv.size() - 1 - nInv;
2193 for (int nInv = 0; nInv < vInv.size(); nInv++)
2195 const CInv &inv = vInv[nInv];
2199 pfrom->AddInventoryKnown(inv);
2201 bool fAlreadyHave = AlreadyHave(txdb, inv);
2203 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2207 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
2208 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2209 } else if (nInv == nLastBlock) {
2210 // In case we are on a very long side-chain, it is possible that we already have
2211 // the last block in an inv bundle sent in response to getblocks. Try to detect
2212 // this situation and push another getblocks to continue.
2213 std::vector<CInv> vGetData(1,inv);
2214 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
2216 printf("force request: %s\n", inv.ToString().c_str());
2219 // Track requests for our stuff
2220 Inventory(inv.hash);
2225 else if (strCommand == "getdata")
2229 if (vInv.size() > 50000)
2230 return error("message getdata size() = %d", vInv.size());
2232 BOOST_FOREACH(const CInv& inv, vInv)
2236 printf("received getdata for: %s\n", inv.ToString().c_str());
2238 if (inv.type == MSG_BLOCK)
2240 // Send block from disk
2241 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2242 if (mi != mapBlockIndex.end())
2245 block.ReadFromDisk((*mi).second);
2246 pfrom->PushMessage("block", block);
2248 // Trigger them to send a getblocks request for the next batch of inventory
2249 if (inv.hash == pfrom->hashContinue)
2251 // Bypass PushInventory, this must send even if redundant,
2252 // and we want it right after the last block so they don't
2253 // wait for other stuff first.
2255 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2256 pfrom->PushMessage("inv", vInv);
2257 pfrom->hashContinue = 0;
2261 else if (inv.IsKnownType())
2263 // Send stream from relay memory
2264 CRITICAL_BLOCK(cs_mapRelay)
2266 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2267 if (mi != mapRelay.end())
2268 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2272 // Track requests for our stuff
2273 Inventory(inv.hash);
2278 else if (strCommand == "getblocks")
2280 CBlockLocator locator;
2282 vRecv >> locator >> hashStop;
2284 // Find the last block the caller has in the main chain
2285 CBlockIndex* pindex = locator.GetBlockIndex();
2287 // Send the rest of the chain
2289 pindex = pindex->pnext;
2290 int nLimit = 500 + locator.GetDistanceBack();
2291 unsigned int nBytes = 0;
2292 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2293 for (; pindex; pindex = pindex->pnext)
2295 if (pindex->GetBlockHash() == hashStop)
2297 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2300 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2302 block.ReadFromDisk(pindex, true);
2303 nBytes += block.GetSerializeSize(SER_NETWORK);
2304 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2306 // When this block is requested, we'll send an inv that'll make them
2307 // getblocks the next batch of inventory.
2308 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2309 pfrom->hashContinue = pindex->GetBlockHash();
2316 else if (strCommand == "getheaders")
2318 CBlockLocator locator;
2320 vRecv >> locator >> hashStop;
2322 CBlockIndex* pindex = NULL;
2323 if (locator.IsNull())
2325 // If locator is null, return the hashStop block
2326 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2327 if (mi == mapBlockIndex.end())
2329 pindex = (*mi).second;
2333 // Find the last block the caller has in the main chain
2334 pindex = locator.GetBlockIndex();
2336 pindex = pindex->pnext;
2339 vector<CBlock> vHeaders;
2340 int nLimit = 2000 + locator.GetDistanceBack();
2341 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2342 for (; pindex; pindex = pindex->pnext)
2344 vHeaders.push_back(pindex->GetBlockHeader());
2345 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2348 pfrom->PushMessage("headers", vHeaders);
2352 else if (strCommand == "tx")
2354 vector<uint256> vWorkQueue;
2355 CDataStream vMsg(vRecv);
2359 CInv inv(MSG_TX, tx.GetHash());
2360 pfrom->AddInventoryKnown(inv);
2362 bool fMissingInputs = false;
2363 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2365 SyncWithWallets(tx, NULL, true);
2366 RelayMessage(inv, vMsg);
2367 mapAlreadyAskedFor.erase(inv);
2368 vWorkQueue.push_back(inv.hash);
2370 // Recursively process any orphan transactions that depended on this one
2371 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2373 uint256 hashPrev = vWorkQueue[i];
2374 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2375 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2378 const CDataStream& vMsg = *((*mi).second);
2380 CDataStream(vMsg) >> tx;
2381 CInv inv(MSG_TX, tx.GetHash());
2383 if (tx.AcceptToMemoryPool(true))
2385 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2386 SyncWithWallets(tx, NULL, true);
2387 RelayMessage(inv, vMsg);
2388 mapAlreadyAskedFor.erase(inv);
2389 vWorkQueue.push_back(inv.hash);
2394 BOOST_FOREACH(uint256 hash, vWorkQueue)
2395 EraseOrphanTx(hash);
2397 else if (fMissingInputs)
2399 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2402 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2403 int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
2405 printf("mapOrphan overflow, removed %d tx\n", nEvicted);
2410 else if (strCommand == "block")
2415 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2418 CInv inv(MSG_BLOCK, block.GetHash());
2419 pfrom->AddInventoryKnown(inv);
2421 if (ProcessBlock(pfrom, &block))
2422 mapAlreadyAskedFor.erase(inv);
2426 else if (strCommand == "getaddr")
2428 // Nodes rebroadcast an addr every 24 hours
2429 pfrom->vAddrToSend.clear();
2430 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2431 CRITICAL_BLOCK(cs_mapAddresses)
2433 unsigned int nCount = 0;
2434 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2436 const CAddress& addr = item.second;
2437 if (addr.nTime > nSince)
2440 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2442 const CAddress& addr = item.second;
2443 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2444 pfrom->PushAddress(addr);
2450 else if (strCommand == "checkorder")
2455 if (!GetBoolArg("-allowreceivebyip"))
2457 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2464 /// we have a chance to check the order here
2466 // Keep giving the same key to the same ip until they use it
2467 if (!mapReuseKey.count(pfrom->addr.ip))
2468 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2470 // Send back approval of order and pubkey to use
2471 CScript scriptPubKey;
2472 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2473 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2477 else if (strCommand == "reply")
2482 CRequestTracker tracker;
2483 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2485 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2486 if (mi != pfrom->mapRequests.end())
2488 tracker = (*mi).second;
2489 pfrom->mapRequests.erase(mi);
2492 if (!tracker.IsNull())
2493 tracker.fn(tracker.param1, vRecv);
2497 else if (strCommand == "ping")
2502 else if (strCommand == "alert")
2507 if (alert.ProcessAlert())
2510 pfrom->setKnown.insert(alert.GetHash());
2511 CRITICAL_BLOCK(cs_vNodes)
2512 BOOST_FOREACH(CNode* pnode, vNodes)
2513 alert.RelayTo(pnode);
2520 // Ignore unknown commands for extensibility
2524 // Update the last seen time for this node's address
2525 if (pfrom->fNetworkNode)
2526 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2527 AddressCurrentlyConnected(pfrom->addr);
2533 bool ProcessMessages(CNode* pfrom)
2535 CDataStream& vRecv = pfrom->vRecv;
2539 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2543 // (4) message start
2552 // Scan for message start
2553 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2554 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2555 if (vRecv.end() - pstart < nHeaderSize)
2557 if (vRecv.size() > nHeaderSize)
2559 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2560 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2564 if (pstart - vRecv.begin() > 0)
2565 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2566 vRecv.erase(vRecv.begin(), pstart);
2569 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2574 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2577 string strCommand = hdr.GetCommand();
2580 unsigned int nMessageSize = hdr.nMessageSize;
2581 if (nMessageSize > MAX_SIZE)
2583 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2586 if (nMessageSize > vRecv.size())
2588 // Rewind and wait for rest of message
2589 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2594 if (vRecv.GetVersion() >= 209)
2596 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2597 unsigned int nChecksum = 0;
2598 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2599 if (nChecksum != hdr.nChecksum)
2601 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2602 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2607 // Copy message to its own buffer
2608 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2609 vRecv.ignore(nMessageSize);
2615 CRITICAL_BLOCK(cs_main)
2616 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2620 catch (std::ios_base::failure& e)
2622 if (strstr(e.what(), "end of data"))
2624 // Allow exceptions from underlength message on vRecv
2625 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
2627 else if (strstr(e.what(), "size too large"))
2629 // Allow exceptions from overlong size
2630 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2634 PrintExceptionContinue(&e, "ProcessMessage()");
2637 catch (std::exception& e) {
2638 PrintExceptionContinue(&e, "ProcessMessage()");
2640 PrintExceptionContinue(NULL, "ProcessMessage()");
2644 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2652 bool SendMessages(CNode* pto, bool fSendTrickle)
2654 TRY_CRITICAL_BLOCK(cs_main)
2656 // Don't send anything until we get their version message
2657 if (pto->nVersion == 0)
2661 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2662 pto->PushMessage("ping");
2664 // Resend wallet transactions that haven't gotten in a block yet
2665 ResendWalletTransactions();
2667 // Address refresh broadcast
2668 static int64 nLastRebroadcast;
2669 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2671 nLastRebroadcast = GetTime();
2672 CRITICAL_BLOCK(cs_vNodes)
2674 BOOST_FOREACH(CNode* pnode, vNodes)
2676 // Periodically clear setAddrKnown to allow refresh broadcasts
2677 pnode->setAddrKnown.clear();
2679 // Rebroadcast our address
2680 if (addrLocalHost.IsRoutable() && !fUseProxy)
2682 CAddress addr(addrLocalHost);
2683 addr.nTime = GetAdjustedTime();
2684 pnode->PushAddress(addr);
2690 // Clear out old addresses periodically so it's not too much work at once
2691 static int64 nLastClear;
2692 if (nLastClear == 0)
2693 nLastClear = GetTime();
2694 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2696 nLastClear = GetTime();
2697 CRITICAL_BLOCK(cs_mapAddresses)
2700 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2701 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2702 mi != mapAddresses.end();)
2704 const CAddress& addr = (*mi).second;
2705 if (addr.nTime < nSince)
2707 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2709 addrdb.EraseAddress(addr);
2710 mapAddresses.erase(mi++);
2724 vector<CAddress> vAddr;
2725 vAddr.reserve(pto->vAddrToSend.size());
2726 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2728 // returns true if wasn't already contained in the set
2729 if (pto->setAddrKnown.insert(addr).second)
2731 vAddr.push_back(addr);
2732 // receiver rejects addr messages larger than 1000
2733 if (vAddr.size() >= 1000)
2735 pto->PushMessage("addr", vAddr);
2740 pto->vAddrToSend.clear();
2742 pto->PushMessage("addr", vAddr);
2747 // Message: inventory
2750 vector<CInv> vInvWait;
2751 CRITICAL_BLOCK(pto->cs_inventory)
2753 vInv.reserve(pto->vInventoryToSend.size());
2754 vInvWait.reserve(pto->vInventoryToSend.size());
2755 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2757 if (pto->setInventoryKnown.count(inv))
2760 // trickle out tx inv to protect privacy
2761 if (inv.type == MSG_TX && !fSendTrickle)
2763 // 1/4 of tx invs blast to all immediately
2764 static uint256 hashSalt;
2766 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2767 uint256 hashRand = inv.hash ^ hashSalt;
2768 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2769 bool fTrickleWait = ((hashRand & 3) != 0);
2771 // always trickle our own transactions
2775 if (GetTransaction(inv.hash, wtx))
2777 fTrickleWait = true;
2782 vInvWait.push_back(inv);
2787 // returns true if wasn't already contained in the set
2788 if (pto->setInventoryKnown.insert(inv).second)
2790 vInv.push_back(inv);
2791 if (vInv.size() >= 1000)
2793 pto->PushMessage("inv", vInv);
2798 pto->vInventoryToSend = vInvWait;
2801 pto->PushMessage("inv", vInv);
2807 vector<CInv> vGetData;
2808 int64 nNow = GetTime() * 1000000;
2810 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2812 const CInv& inv = (*pto->mapAskFor.begin()).second;
2813 if (!AlreadyHave(txdb, inv))
2815 printf("sending getdata: %s\n", inv.ToString().c_str());
2816 vGetData.push_back(inv);
2817 if (vGetData.size() >= 1000)
2819 pto->PushMessage("getdata", vGetData);
2823 mapAlreadyAskedFor[inv] = nNow;
2824 pto->mapAskFor.erase(pto->mapAskFor.begin());
2826 if (!vGetData.empty())
2827 pto->PushMessage("getdata", vGetData);
2846 //////////////////////////////////////////////////////////////////////////////
2851 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2853 unsigned char* pdata = (unsigned char*)pbuffer;
2854 unsigned int blocks = 1 + ((len + 8) / 64);
2855 unsigned char* pend = pdata + 64 * blocks;
2856 memset(pdata + len, 0, 64 * blocks - len);
2858 unsigned int bits = len * 8;
2859 pend[-1] = (bits >> 0) & 0xff;
2860 pend[-2] = (bits >> 8) & 0xff;
2861 pend[-3] = (bits >> 16) & 0xff;
2862 pend[-4] = (bits >> 24) & 0xff;
2866 using CryptoPP::ByteReverse;
2868 static const unsigned int pSHA256InitState[8] =
2869 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2871 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2873 memcpy(pstate, pinit, 32);
2874 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2878 // ScanHash scans nonces looking for a hash with at least some zero bits.
2879 // It operates on big endian data. Caller does the byte reversing.
2880 // All input buffers are 16-byte aligned. nNonce is usually preserved
2881 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2882 // the block is rebuilt and nNonce starts over at zero.
2884 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2886 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2890 // Hash pdata using pmidstate as the starting state into
2891 // preformatted buffer phash1, then hash phash1 into phash
2893 SHA256Transform(phash1, pdata, pmidstate);
2894 SHA256Transform(phash, phash1, pSHA256InitState);
2896 // Return the nonce if the hash has at least some zero bits,
2897 // caller will check if it has enough to reach the target
2898 if (((unsigned short*)phash)[14] == 0)
2901 // If nothing found after trying for a while, return -1
2902 if ((nNonce & 0xffff) == 0)
2904 nHashesDone = 0xffff+1;
2910 // Some explaining would be appreciated
2915 set<uint256> setDependsOn;
2918 COrphan(CTransaction* ptxIn)
2926 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2927 BOOST_FOREACH(uint256 hash, setDependsOn)
2928 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2933 CBlock* CreateNewBlock(CReserveKey& reservekey)
2935 CBlockIndex* pindexPrev = pindexBest;
2938 auto_ptr<CBlock> pblock(new CBlock());
2942 // Create coinbase tx
2944 txNew.vin.resize(1);
2945 txNew.vin[0].prevout.SetNull();
2946 txNew.vout.resize(1);
2947 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2949 // Add our coinbase tx as first transaction
2950 pblock->vtx.push_back(txNew);
2952 // Collect memory pool transactions into the block
2954 CRITICAL_BLOCK(cs_main)
2955 CRITICAL_BLOCK(cs_mapTransactions)
2959 // Priority order to process transactions
2960 list<COrphan> vOrphan; // list memory doesn't move
2961 map<uint256, vector<COrphan*> > mapDependers;
2962 multimap<double, CTransaction*> mapPriority;
2963 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2965 CTransaction& tx = (*mi).second;
2966 if (tx.IsCoinBase() || !tx.IsFinal())
2969 COrphan* porphan = NULL;
2970 double dPriority = 0;
2971 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2973 // Read prev transaction
2974 CTransaction txPrev;
2976 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2978 // Has to wait for dependencies
2981 // Use list for automatic deletion
2982 vOrphan.push_back(COrphan(&tx));
2983 porphan = &vOrphan.back();
2985 mapDependers[txin.prevout.hash].push_back(porphan);
2986 porphan->setDependsOn.insert(txin.prevout.hash);
2989 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2991 // Read block header
2992 int nConf = txindex.GetDepthInMainChain();
2994 dPriority += (double)nValueIn * nConf;
2996 if (fDebug && GetBoolArg("-printpriority"))
2997 printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3000 // Priority is sum(valuein * age) / txsize
3001 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3004 porphan->dPriority = dPriority;
3006 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3008 if (fDebug && GetBoolArg("-printpriority"))
3010 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3017 // Collect transactions into block
3018 map<uint256, CTxIndex> mapTestPool;
3019 uint64 nBlockSize = 1000;
3020 int nBlockSigOps = 100;
3021 while (!mapPriority.empty())
3023 // Take highest priority transaction off priority queue
3024 double dPriority = -(*mapPriority.begin()).first;
3025 CTransaction& tx = *(*mapPriority.begin()).second;
3026 mapPriority.erase(mapPriority.begin());
3029 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3030 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3033 // Legacy limits on sigOps:
3034 int nTxSigOps = tx.GetSigOpCount();
3035 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3038 // Transaction fee required depends on block size
3039 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3040 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
3042 // Connecting shouldn't fail due to dependency on other memory pool transactions
3043 // because we're already processing them in order of dependency
3044 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3046 MapPrevTx mapInputs;
3047 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3050 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3051 if (nTxFees < nMinFee)
3054 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3055 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3058 if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3060 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3061 swap(mapTestPool, mapTestPoolTmp);
3064 pblock->vtx.push_back(tx);
3065 nBlockSize += nTxSize;
3066 nBlockSigOps += nTxSigOps;
3069 // Add transactions that depend on this one to the priority queue
3070 uint256 hash = tx.GetHash();
3071 if (mapDependers.count(hash))
3073 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3075 if (!porphan->setDependsOn.empty())
3077 porphan->setDependsOn.erase(hash);
3078 if (porphan->setDependsOn.empty())
3079 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3085 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3088 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3089 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3090 pblock->UpdateTime(pindexPrev);
3091 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
3094 return pblock.release();
3098 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3100 // Update nExtraNonce
3101 static uint256 hashPrevBlock;
3102 if (hashPrevBlock != pblock->hashPrevBlock)
3105 hashPrevBlock = pblock->hashPrevBlock;
3108 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3109 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3113 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3116 // Prebuild hash buffers
3123 uint256 hashPrevBlock;
3124 uint256 hashMerkleRoot;
3127 unsigned int nNonce;
3130 unsigned char pchPadding0[64];
3132 unsigned char pchPadding1[64];
3135 memset(&tmp, 0, sizeof(tmp));
3137 tmp.block.nVersion = pblock->nVersion;
3138 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3139 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3140 tmp.block.nTime = pblock->nTime;
3141 tmp.block.nBits = pblock->nBits;
3142 tmp.block.nNonce = pblock->nNonce;
3144 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3145 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3147 // Byte swap all the input buffer
3148 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3149 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3151 // Precalc the first half of the first hash, which stays constant
3152 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3154 memcpy(pdata, &tmp.block, 128);
3155 memcpy(phash1, &tmp.hash1, 64);
3159 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3161 uint256 hash = pblock->GetHash();
3162 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3164 if (hash > hashTarget)
3168 printf("BitcoinMiner:\n");
3169 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3171 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3172 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3175 CRITICAL_BLOCK(cs_main)
3177 if (pblock->hashPrevBlock != hashBestChain)
3178 return error("BitcoinMiner : generated block is stale");
3180 // Remove key from key pool
3181 reservekey.KeepKey();
3183 // Track how many getdata requests this block gets
3184 CRITICAL_BLOCK(wallet.cs_wallet)
3185 wallet.mapRequestCount[pblock->GetHash()] = 0;
3187 // Process this block the same as if we had received it from another node
3188 if (!ProcessBlock(NULL, pblock))
3189 return error("BitcoinMiner : ProcessBlock, block not accepted");
3196 void static ThreadBitcoinMiner(void* parg);
3198 void static BitcoinMiner(CWallet *pwallet)
3200 printf("BitcoinMiner started\n");
3201 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3203 // Each thread has its own key and counter
3204 CReserveKey reservekey(pwallet);
3205 unsigned int nExtraNonce = 0;
3207 while (fGenerateBitcoins)
3209 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3213 while (vNodes.empty() || IsInitialBlockDownload())
3218 if (!fGenerateBitcoins)
3226 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3227 CBlockIndex* pindexPrev = pindexBest;
3229 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3232 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3234 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3238 // Prebuild hash buffers
3240 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3241 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3242 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3244 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3246 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3247 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
3248 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3254 int64 nStart = GetTime();
3255 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3257 uint256& hash = *alignup<16>(hashbuf);
3260 unsigned int nHashesDone = 0;
3261 unsigned int nNonceFound;
3264 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3265 (char*)&hash, nHashesDone);
3267 // Check if something found
3268 if (nNonceFound != -1)
3270 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
3271 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3273 if (hash <= hashTarget)
3276 pblock->nNonce = ByteReverse(nNonceFound);
3277 assert(hash == pblock->GetHash());
3279 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3280 CheckWork(pblock.get(), *pwalletMain, reservekey);
3281 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3287 static int64 nHashCounter;
3288 if (nHPSTimerStart == 0)
3290 nHPSTimerStart = GetTimeMillis();
3294 nHashCounter += nHashesDone;
3295 if (GetTimeMillis() - nHPSTimerStart > 4000)
3297 static CCriticalSection cs;
3300 if (GetTimeMillis() - nHPSTimerStart > 4000)
3302 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3303 nHPSTimerStart = GetTimeMillis();
3305 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3306 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3307 static int64 nLogTime;
3308 if (GetTime() - nLogTime > 30 * 60)
3310 nLogTime = GetTime();
3311 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3312 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3318 // Check for stop or if block needs to be rebuilt
3321 if (!fGenerateBitcoins)
3323 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3327 if (nBlockNonce >= 0xffff0000)
3329 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3331 if (pindexPrev != pindexBest)
3334 // Update nTime every few seconds
3335 pblock->UpdateTime(pindexPrev);
3336 nBlockTime = ByteReverse(pblock->nTime);
3339 // Changing pblock->nTime can change work required on testnet:
3340 nBlockBits = ByteReverse(pblock->nBits);
3341 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3347 void static ThreadBitcoinMiner(void* parg)
3349 CWallet* pwallet = (CWallet*)parg;
3352 vnThreadsRunning[3]++;
3353 BitcoinMiner(pwallet);
3354 vnThreadsRunning[3]--;
3356 catch (std::exception& e) {
3357 vnThreadsRunning[3]--;
3358 PrintException(&e, "ThreadBitcoinMiner()");
3360 vnThreadsRunning[3]--;
3361 PrintException(NULL, "ThreadBitcoinMiner()");
3363 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3365 if (vnThreadsRunning[3] == 0)
3367 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3371 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3373 if (fGenerateBitcoins != fGenerate)
3375 fGenerateBitcoins = fGenerate;
3376 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3379 if (fGenerateBitcoins)
3381 int nProcessors = boost::thread::hardware_concurrency();
3382 printf("%d processors\n", nProcessors);
3383 if (nProcessors < 1)
3385 if (fLimitProcessors && nProcessors > nLimitProcessors)
3386 nProcessors = nLimitProcessors;
3387 int nAddThreads = nProcessors - vnThreadsRunning[3];
3388 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3389 for (int i = 0; i < nAddThreads; i++)
3391 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3392 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");