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 <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
15 using namespace boost;
21 CCriticalSection cs_setpwalletRegistered;
22 set<CWallet*> setpwalletRegistered;
24 CCriticalSection cs_main;
26 static map<uint256, CTransaction> mapTransactions;
27 CCriticalSection cs_mapTransactions;
28 unsigned int nTransactionsUpdated = 0;
29 map<COutPoint, CInPoint> mapNextTx;
31 map<uint256, CBlockIndex*> mapBlockIndex;
32 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
33 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
34 CBlockIndex* pindexGenesisBlock = NULL;
36 CBigNum bnBestChainWork = 0;
37 CBigNum bnBestInvalidWork = 0;
38 uint256 hashBestChain = 0;
39 CBlockIndex* pindexBest = NULL;
40 int64 nTimeBestReceived = 0;
42 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
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;
68 //////////////////////////////////////////////////////////////////////////////
70 // dispatching functions
73 // These functions dispatch to one or all registered wallets
76 void RegisterWallet(CWallet* pwalletIn)
78 CRITICAL_BLOCK(cs_setpwalletRegistered)
80 setpwalletRegistered.insert(pwalletIn);
84 void UnregisterWallet(CWallet* pwalletIn)
86 CRITICAL_BLOCK(cs_setpwalletRegistered)
88 setpwalletRegistered.erase(pwalletIn);
92 // check whether the passed transaction is from us
93 bool static IsFromMe(CTransaction& tx)
95 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
96 if (pwallet->IsFromMe(tx))
101 // get the wallet transaction with the given hash (if it exists)
102 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
104 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
105 if (pwallet->GetTransaction(hashTx,wtx))
110 // erases transaction with the given hash from all wallets
111 void static EraseFromWallets(uint256 hash)
113 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
114 pwallet->EraseFromWallet(hash);
117 // make sure all wallets know about the given transaction, in the given block
118 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
120 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
121 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
124 // notify wallets about a new best chain
125 void static SetBestChain(const CBlockLocator& loc)
127 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
128 pwallet->SetBestChain(loc);
131 // notify wallets about an updated transaction
132 void static UpdatedTransaction(const uint256& hashTx)
134 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
135 pwallet->UpdatedTransaction(hashTx);
139 void static PrintWallets(const CBlock& block)
141 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
142 pwallet->PrintWallet(block);
145 // notify wallets about an incoming inventory (for request counts)
146 void static Inventory(const uint256& hash)
148 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
149 pwallet->Inventory(hash);
152 // ask wallets to resend their transactions
153 void static ResendWalletTransactions()
155 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
156 pwallet->ResendWalletTransactions();
165 //////////////////////////////////////////////////////////////////////////////
167 // mapOrphanTransactions
170 void AddOrphanTx(const CDataStream& vMsg)
173 CDataStream(vMsg) >> tx;
174 uint256 hash = tx.GetHash();
175 if (mapOrphanTransactions.count(hash))
178 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
179 BOOST_FOREACH(const CTxIn& txin, tx.vin)
180 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
183 void static EraseOrphanTx(uint256 hash)
185 if (!mapOrphanTransactions.count(hash))
187 const CDataStream* pvMsg = mapOrphanTransactions[hash];
189 CDataStream(*pvMsg) >> tx;
190 BOOST_FOREACH(const CTxIn& txin, tx.vin)
192 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
193 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
195 if ((*mi).second == pvMsg)
196 mapOrphanTransactionsByPrev.erase(mi++);
202 mapOrphanTransactions.erase(hash);
205 int LimitOrphanTxSize(int nMaxOrphans)
208 while (mapOrphanTransactions.size() > nMaxOrphans)
210 // Evict a random orphan:
211 std::vector<unsigned char> randbytes(32);
212 RAND_bytes(&randbytes[0], 32);
213 uint256 randomhash(randbytes);
214 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
215 if (it == mapOrphanTransactions.end())
216 it = mapOrphanTransactions.begin();
217 EraseOrphanTx(it->first);
229 //////////////////////////////////////////////////////////////////////////////
231 // CTransaction and CTxIndex
234 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
237 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
239 if (!ReadFromDisk(txindexRet.pos))
241 if (prevout.n >= vout.size())
249 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
252 return ReadFromDisk(txdb, prevout, txindex);
255 bool CTransaction::ReadFromDisk(COutPoint prevout)
259 return ReadFromDisk(txdb, prevout, txindex);
264 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
276 // Load the block this tx is in
278 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
280 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
285 // Update the tx's hashBlock
286 hashBlock = pblock->GetHash();
288 // Locate the transaction
289 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
290 if (pblock->vtx[nIndex] == *(CTransaction*)this)
292 if (nIndex == pblock->vtx.size())
294 vMerkleBranch.clear();
296 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
300 // Fill in merkle branch
301 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
304 // Is the tx in a block that's in the main chain
305 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
306 if (mi == mapBlockIndex.end())
308 CBlockIndex* pindex = (*mi).second;
309 if (!pindex || !pindex->IsInMainChain())
312 return pindexBest->nHeight - pindex->nHeight + 1;
321 bool CTransaction::CheckTransaction() const
323 // Basic checks that don't depend on any context
325 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
327 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
329 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
330 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
332 // Check for negative or overflow output values
334 BOOST_FOREACH(const CTxOut& txout, vout)
336 if (txout.nValue < 0)
337 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
338 if (txout.nValue > MAX_MONEY)
339 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
340 nValueOut += txout.nValue;
341 if (!MoneyRange(nValueOut))
342 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
345 // Check for duplicate inputs
346 set<COutPoint> vInOutPoints;
347 BOOST_FOREACH(const CTxIn& txin, vin)
349 if (vInOutPoints.count(txin.prevout))
351 vInOutPoints.insert(txin.prevout);
356 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
357 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
361 BOOST_FOREACH(const CTxIn& txin, vin)
362 if (txin.prevout.IsNull())
363 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
369 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
372 *pfMissingInputs = false;
374 if (!CheckTransaction())
375 return error("AcceptToMemoryPool() : CheckTransaction failed");
377 // Coinbase is only valid in a block, not as a loose transaction
379 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
381 // To help v0.1.5 clients who would see it as a negative number
382 if ((int64)nLockTime > INT_MAX)
383 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
385 // Rather not work on nonstandard transactions (unless -testnet)
386 if (!fTestNet && !IsStandard())
387 return error("AcceptToMemoryPool() : nonstandard transaction type");
389 // Do we already have it?
390 uint256 hash = GetHash();
391 CRITICAL_BLOCK(cs_mapTransactions)
392 if (mapTransactions.count(hash))
395 if (txdb.ContainsTx(hash))
398 // Check for conflicts with in-memory transactions
399 CTransaction* ptxOld = NULL;
400 for (unsigned int i = 0; i < vin.size(); i++)
402 COutPoint outpoint = vin[i].prevout;
403 if (mapNextTx.count(outpoint))
405 // Disable replacement feature for now
408 // Allow replacing with a newer version of the same transaction
411 ptxOld = mapNextTx[outpoint].ptx;
412 if (ptxOld->IsFinal())
414 if (!IsNewerThan(*ptxOld))
416 for (unsigned int i = 0; i < vin.size(); i++)
418 COutPoint outpoint = vin[i].prevout;
419 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
429 map<uint256, CTxIndex> mapUnused;
430 bool fInvalid = false;
431 if (!FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
434 return error("AcceptToMemoryPool() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
436 *pfMissingInputs = true;
437 return error("AcceptToMemoryPool() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
441 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
442 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
443 // attacks disallow transactions with more than one SigOp per 34 bytes.
444 // 34 bytes because a TxOut is:
445 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
446 if (GetSigOpCount() > nSize / 34 || nSize < 100)
447 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
449 int64 nFees = GetValueIn(mapInputs)-GetValueOut();
451 // Don't accept it if it can't get into a block
452 if (nFees < GetMinFee(1000, true, true))
453 return error("AcceptToMemoryPool() : not enough fees");
455 // Continuously rate-limit free transactions
456 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
457 // be annoying or make other's transactions take longer to confirm.
458 if (nFees < MIN_RELAY_TX_FEE)
460 static CCriticalSection cs;
461 static double dFreeCount;
462 static int64 nLastTime;
463 int64 nNow = GetTime();
467 // Use an exponentially decaying ~10-minute window:
468 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
470 // -limitfreerelay unit is thousand-bytes-per-minute
471 // At default rate it would take over a month to fill 1GB
472 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
473 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
475 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
480 // Check against previous transactions
481 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
482 if (!ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
484 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
488 // Store transaction in memory
489 CRITICAL_BLOCK(cs_mapTransactions)
493 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
494 ptxOld->RemoveFromMemoryPool();
496 AddToMemoryPoolUnchecked();
499 ///// are we sure this is ok when loading transactions or restoring block txes
500 // If updated, erase old tx from wallet
502 EraseFromWallets(ptxOld->GetHash());
504 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
508 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
511 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
514 bool CTransaction::AddToMemoryPoolUnchecked()
516 // Add to memory pool without checking anything. Don't call this directly,
517 // call AcceptToMemoryPool to properly check the transaction first.
518 CRITICAL_BLOCK(cs_mapTransactions)
520 uint256 hash = GetHash();
521 mapTransactions[hash] = *this;
522 for (unsigned int i = 0; i < vin.size(); i++)
523 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
524 nTransactionsUpdated++;
530 bool CTransaction::RemoveFromMemoryPool()
532 // Remove transaction from memory pool
533 CRITICAL_BLOCK(cs_mapTransactions)
535 BOOST_FOREACH(const CTxIn& txin, vin)
536 mapNextTx.erase(txin.prevout);
537 mapTransactions.erase(GetHash());
538 nTransactionsUpdated++;
548 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
550 if (hashBlock == 0 || nIndex == -1)
553 // Find the block it claims to be in
554 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
555 if (mi == mapBlockIndex.end())
557 CBlockIndex* pindex = (*mi).second;
558 if (!pindex || !pindex->IsInMainChain())
561 // Make sure the merkle branch connects to this block
562 if (!fMerkleVerified)
564 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
566 fMerkleVerified = true;
569 nHeightRet = pindex->nHeight;
570 return pindexBest->nHeight - pindex->nHeight + 1;
574 int CMerkleTx::GetBlocksToMaturity() const
578 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
582 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
586 if (!IsInMainChain() && !ClientConnectInputs())
588 return CTransaction::AcceptToMemoryPool(txdb, false);
592 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
596 bool CMerkleTx::AcceptToMemoryPool()
599 return AcceptToMemoryPool(txdb);
604 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
606 CRITICAL_BLOCK(cs_mapTransactions)
608 // Add previous supporting transactions first
609 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
611 if (!tx.IsCoinBase())
613 uint256 hash = tx.GetHash();
614 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
615 tx.AcceptToMemoryPool(txdb, fCheckInputs);
618 return AcceptToMemoryPool(txdb, fCheckInputs);
623 bool CWalletTx::AcceptWalletTransaction()
626 return AcceptWalletTransaction(txdb);
629 int CTxIndex::GetDepthInMainChain() const
633 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
635 // Find the block in the index
636 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
637 if (mi == mapBlockIndex.end())
639 CBlockIndex* pindex = (*mi).second;
640 if (!pindex || !pindex->IsInMainChain())
642 return 1 + nBestHeight - pindex->nHeight;
654 //////////////////////////////////////////////////////////////////////////////
656 // CBlock and CBlockIndex
659 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
661 if (!fReadTransactions)
663 *this = pindex->GetBlockHeader();
666 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
668 if (GetHash() != pindex->GetBlockHash())
669 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
673 uint256 static GetOrphanRoot(const CBlock* pblock)
675 // Work back to the first block in the orphan chain
676 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
677 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
678 return pblock->GetHash();
681 int64 static GetBlockValue(int nHeight, int64 nFees)
683 int64 nSubsidy = 50 * COIN;
685 // Subsidy is cut in half every 4 years
686 nSubsidy >>= (nHeight / 210000);
688 return nSubsidy + nFees;
691 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
692 static const int64 nTargetSpacing = 10 * 60;
693 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
696 // minimum amount of work that could possibly be required nTime after
697 // minimum work required was nBase
699 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
701 // Testnet has min-difficulty blocks
702 // after nTargetSpacing*2 time between blocks:
703 if (fTestNet && nTime > nTargetSpacing*2)
704 return bnProofOfWorkLimit.GetCompact();
707 bnResult.SetCompact(nBase);
708 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
710 // Maximum 400% adjustment...
712 // ... in best-case exactly 4-times-normal target time
713 nTime -= nTargetTimespan*4;
715 if (bnResult > bnProofOfWorkLimit)
716 bnResult = bnProofOfWorkLimit;
717 return bnResult.GetCompact();
720 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
722 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
725 if (pindexLast == NULL)
726 return nProofOfWorkLimit;
728 // Only change once per interval
729 if ((pindexLast->nHeight+1) % nInterval != 0)
731 // Special rules for testnet after 15 Feb 2012:
732 if (fTestNet && pblock->nTime > 1329264000)
734 // If the new block's timestamp is more than 2* 10 minutes
735 // then allow mining of a min-difficulty block.
736 if (pblock->nTime - pindexLast->nTime > nTargetSpacing*2)
737 return nProofOfWorkLimit;
740 // Return the last non-special-min-difficulty-rules-block
741 const CBlockIndex* pindex = pindexLast;
742 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
743 pindex = pindex->pprev;
744 return pindex->nBits;
748 return pindexLast->nBits;
751 // Go back by what we want to be 14 days worth of blocks
752 const CBlockIndex* pindexFirst = pindexLast;
753 for (int i = 0; pindexFirst && i < nInterval-1; i++)
754 pindexFirst = pindexFirst->pprev;
757 // Limit adjustment step
758 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
759 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
760 if (nActualTimespan < nTargetTimespan/4)
761 nActualTimespan = nTargetTimespan/4;
762 if (nActualTimespan > nTargetTimespan*4)
763 nActualTimespan = nTargetTimespan*4;
767 bnNew.SetCompact(pindexLast->nBits);
768 bnNew *= nActualTimespan;
769 bnNew /= nTargetTimespan;
771 if (bnNew > bnProofOfWorkLimit)
772 bnNew = bnProofOfWorkLimit;
775 printf("GetNextWorkRequired RETARGET\n");
776 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
777 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
778 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
780 return bnNew.GetCompact();
783 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
786 bnTarget.SetCompact(nBits);
789 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
790 return error("CheckProofOfWork() : nBits below minimum work");
792 // Check proof of work matches claimed amount
793 if (hash > bnTarget.getuint256())
794 return error("CheckProofOfWork() : hash doesn't match nBits");
799 // Return maximum amount of blocks that other nodes claim to have
800 int GetNumBlocksOfPeers()
802 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
805 bool IsInitialBlockDownload()
807 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
809 static int64 nLastUpdate;
810 static CBlockIndex* pindexLastBest;
811 if (pindexBest != pindexLastBest)
813 pindexLastBest = pindexBest;
814 nLastUpdate = GetTime();
816 return (GetTime() - nLastUpdate < 10 &&
817 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
820 void static InvalidChainFound(CBlockIndex* pindexNew)
822 if (pindexNew->bnChainWork > bnBestInvalidWork)
824 bnBestInvalidWork = pindexNew->bnChainWork;
825 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
828 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());
829 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
830 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
831 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
834 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
836 nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
838 // Updating time can change work required on testnet:
840 nBits = GetNextWorkRequired(pindexPrev, this);
853 bool CTransaction::DisconnectInputs(CTxDB& txdb)
855 // Relinquish previous transactions' spent pointers
858 BOOST_FOREACH(const CTxIn& txin, vin)
860 COutPoint prevout = txin.prevout;
862 // Get prev txindex from disk
864 if (!txdb.ReadTxIndex(prevout.hash, txindex))
865 return error("DisconnectInputs() : ReadTxIndex failed");
867 if (prevout.n >= txindex.vSpent.size())
868 return error("DisconnectInputs() : prevout.n out of range");
870 // Mark outpoint as not spent
871 txindex.vSpent[prevout.n].SetNull();
874 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
875 return error("DisconnectInputs() : UpdateTxIndex failed");
879 // Remove transaction from index
880 // This can fail if a duplicate of this transaction was in a chain that got
881 // reorganized away. This is only possible if this transaction was completely
882 // spent, so erasing it would be a no-op anway.
883 txdb.EraseTxIndex(*this);
889 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
890 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
892 // FetchInputs can return false either because we just haven't seen some inputs
893 // (in which case the transaction should be stored as an orphan)
894 // or because the transaction is malformed (in which case the transaction should
895 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
899 return true; // Coinbase transactions have no inputs to fetch.
901 for (unsigned int i = 0; i < vin.size(); i++)
903 COutPoint prevout = vin[i].prevout;
904 if (inputsRet.count(prevout.hash))
905 continue; // Got it already
908 CTxIndex& txindex = inputsRet[prevout.hash].first;
910 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
912 // Get txindex from current proposed changes
913 txindex = mapTestPool.find(prevout.hash)->second;
917 // Read txindex from txdb
918 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
920 if (!fFound && (fBlock || fMiner))
921 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());
924 CTransaction& txPrev = inputsRet[prevout.hash].second;
925 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
927 // Get prev tx from single transactions in memory
928 CRITICAL_BLOCK(cs_mapTransactions)
930 if (!mapTransactions.count(prevout.hash))
931 return error("FetchInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
932 txPrev = mapTransactions[prevout.hash];
935 txindex.vSpent.resize(txPrev.vout.size());
939 // Get prev tx from disk
940 if (!txPrev.ReadFromDisk(txindex.pos))
941 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
945 // Make sure all prevout.n's are valid:
946 for (unsigned int i = 0; i < vin.size(); i++)
948 const COutPoint prevout = vin[i].prevout;
949 assert(inputsRet.count(prevout.hash) != 0);
950 const CTxIndex& txindex = inputsRet[prevout.hash].first;
951 const CTransaction& txPrev = inputsRet[prevout.hash].second;
952 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
954 // Revisit this if/when transaction replacement is implemented and allows
957 return DoS(100, 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()));
964 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
966 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
967 if (mi == inputs.end())
968 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
970 const CTransaction& txPrev = (mi->second).second;
971 if (input.prevout.n >= txPrev.vout.size())
972 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
974 return txPrev.vout[input.prevout.n];
977 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
983 for (unsigned int i = 0; i < vin.size(); i++)
985 nResult += GetOutputFor(vin[i], inputs).nValue;
991 int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
997 for (unsigned int i = 0; i < vin.size(); i++)
999 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1000 if (prevout.scriptPubKey.IsPayToScriptHash())
1001 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1006 bool CTransaction::ConnectInputs(MapPrevTx inputs,
1007 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1008 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1010 // Take over previous transactions' spent pointers
1011 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1012 // fMiner is true when called from the internal bitcoin miner
1013 // ... both are false when called from CTransaction::AcceptToMemoryPool
1018 for (unsigned int i = 0; i < vin.size(); i++)
1020 COutPoint prevout = vin[i].prevout;
1021 assert(inputs.count(prevout.hash) > 0);
1022 CTxIndex& txindex = inputs[prevout.hash].first;
1023 CTransaction& txPrev = inputs[prevout.hash].second;
1025 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1026 return DoS(100, 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()));
1028 // If prev is coinbase, check that it's matured
1029 if (txPrev.IsCoinBase())
1030 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1031 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1032 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1034 // Check for conflicts (double-spend)
1035 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1036 // for an attacker to attempt to split the network.
1037 if (!txindex.vSpent[prevout.n].IsNull())
1038 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());
1040 // Check for negative or overflow input values
1041 nValueIn += txPrev.vout[prevout.n].nValue;
1042 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1043 return DoS(100, error("ConnectInputs() : txin values out of range"));
1045 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1046 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1047 // still computed and checked, and any change will be caught at the next checkpoint.
1048 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1051 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1053 // only during transition phase for P2SH: do not invoke anti-DoS code for
1054 // potentially old clients relaying bad P2SH transactions
1055 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1056 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1058 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1062 // Mark outpoints as spent
1063 txindex.vSpent[prevout.n] = posThisTx;
1066 if (fBlock || fMiner)
1068 mapTestPool[prevout.hash] = txindex;
1072 if (nValueIn < GetValueOut())
1073 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1075 // Tally transaction fees
1076 int64 nTxFee = nValueIn - GetValueOut();
1078 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1080 if (!MoneyRange(nFees))
1081 return DoS(100, error("ConnectInputs() : nFees out of range"));
1088 bool CTransaction::ClientConnectInputs()
1093 // Take over previous transactions' spent pointers
1094 CRITICAL_BLOCK(cs_mapTransactions)
1097 for (unsigned int i = 0; i < vin.size(); i++)
1099 // Get prev tx from single transactions in memory
1100 COutPoint prevout = vin[i].prevout;
1101 if (!mapTransactions.count(prevout.hash))
1103 CTransaction& txPrev = mapTransactions[prevout.hash];
1105 if (prevout.n >= txPrev.vout.size())
1109 if (!VerifySignature(txPrev, *this, i, true, 0))
1110 return error("ConnectInputs() : VerifySignature failed");
1112 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1113 ///// this has to go away now that posNext is gone
1114 // // Check for conflicts
1115 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1116 // return error("ConnectInputs() : prev tx already used");
1118 // // Flag outpoints as used
1119 // txPrev.vout[prevout.n].posNext = posThisTx;
1121 nValueIn += txPrev.vout[prevout.n].nValue;
1123 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1124 return error("ClientConnectInputs() : txin values out of range");
1126 if (GetValueOut() > nValueIn)
1136 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1138 // Disconnect in reverse order
1139 for (int i = vtx.size()-1; i >= 0; i--)
1140 if (!vtx[i].DisconnectInputs(txdb))
1143 // Update block index on disk without changing it in memory.
1144 // The memory index structure will be changed after the db commits.
1147 CDiskBlockIndex blockindexPrev(pindex->pprev);
1148 blockindexPrev.hashNext = 0;
1149 if (!txdb.WriteBlockIndex(blockindexPrev))
1150 return error("DisconnectBlock() : WriteBlockIndex failed");
1156 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1158 // Check it again in case a previous version let a bad block in
1162 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1163 // unless those are already completely spent.
1164 // If such overwrites are allowed, coinbases and transactions depending upon those
1165 // can be duplicated to remove the ability to spend the first instance -- even after
1166 // being sent to another address.
1167 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1168 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1169 // already refuses previously-known transaction id's entirely.
1170 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1171 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1172 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1174 BOOST_FOREACH(CTransaction& tx, vtx)
1176 CTxIndex txindexOld;
1177 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1179 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1186 // P2SH didn't become active until Apr 1 2012 (Feb 15 on testnet)
1187 int64 nEvalSwitchTime = fTestNet ? 1329264000 : 1333238400;
1188 bool fStrictPayToScriptHash = (pindex->nTime >= nEvalSwitchTime);
1190 //// issue here: it doesn't know the version
1191 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1193 map<uint256, CTxIndex> mapQueuedChanges;
1196 BOOST_FOREACH(CTransaction& tx, vtx)
1198 nSigOps += tx.GetSigOpCount();
1199 if (nSigOps > MAX_BLOCK_SIGOPS)
1200 return DoS(100, error("ConnectBlock() : too many sigops"));
1202 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1203 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1206 MapPrevTx mapInputs;
1207 if (!tx.IsCoinBase())
1209 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1212 if (fStrictPayToScriptHash)
1214 // Add in sigops done by pay-to-script-hash inputs;
1215 // this is to prevent a "rogue miner" from creating
1216 // an incredibly-expensive-to-validate block.
1217 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1218 if (nSigOps > MAX_BLOCK_SIGOPS)
1219 return DoS(100, error("ConnectBlock() : too many sigops"));
1222 nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
1224 if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1228 mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
1231 // Write queued txindex changes
1232 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1234 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1235 return error("ConnectBlock() : UpdateTxIndex failed");
1238 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1241 // Update block index on disk without changing it in memory.
1242 // The memory index structure will be changed after the db commits.
1245 CDiskBlockIndex blockindexPrev(pindex->pprev);
1246 blockindexPrev.hashNext = pindex->GetBlockHash();
1247 if (!txdb.WriteBlockIndex(blockindexPrev))
1248 return error("ConnectBlock() : WriteBlockIndex failed");
1251 // Watch for transactions paying to me
1252 BOOST_FOREACH(CTransaction& tx, vtx)
1253 SyncWithWallets(tx, this, true);
1258 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1260 printf("REORGANIZE\n");
1263 CBlockIndex* pfork = pindexBest;
1264 CBlockIndex* plonger = pindexNew;
1265 while (pfork != plonger)
1267 while (plonger->nHeight > pfork->nHeight)
1268 if (!(plonger = plonger->pprev))
1269 return error("Reorganize() : plonger->pprev is null");
1270 if (pfork == plonger)
1272 if (!(pfork = pfork->pprev))
1273 return error("Reorganize() : pfork->pprev is null");
1276 // List of what to disconnect
1277 vector<CBlockIndex*> vDisconnect;
1278 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1279 vDisconnect.push_back(pindex);
1281 // List of what to connect
1282 vector<CBlockIndex*> vConnect;
1283 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1284 vConnect.push_back(pindex);
1285 reverse(vConnect.begin(), vConnect.end());
1287 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());
1288 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());
1290 // Disconnect shorter branch
1291 vector<CTransaction> vResurrect;
1292 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1295 if (!block.ReadFromDisk(pindex))
1296 return error("Reorganize() : ReadFromDisk for disconnect failed");
1297 if (!block.DisconnectBlock(txdb, pindex))
1298 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1300 // Queue memory transactions to resurrect
1301 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1302 if (!tx.IsCoinBase())
1303 vResurrect.push_back(tx);
1306 // Connect longer branch
1307 vector<CTransaction> vDelete;
1308 for (unsigned int i = 0; i < vConnect.size(); i++)
1310 CBlockIndex* pindex = vConnect[i];
1312 if (!block.ReadFromDisk(pindex))
1313 return error("Reorganize() : ReadFromDisk for connect failed");
1314 if (!block.ConnectBlock(txdb, pindex))
1318 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1321 // Queue memory transactions to delete
1322 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1323 vDelete.push_back(tx);
1325 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1326 return error("Reorganize() : WriteHashBestChain failed");
1328 // Make sure it's successfully written to disk before changing memory structure
1329 if (!txdb.TxnCommit())
1330 return error("Reorganize() : TxnCommit failed");
1332 // Disconnect shorter branch
1333 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1335 pindex->pprev->pnext = NULL;
1337 // Connect longer branch
1338 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1340 pindex->pprev->pnext = pindex;
1342 // Resurrect memory transactions that were in the disconnected branch
1343 BOOST_FOREACH(CTransaction& tx, vResurrect)
1344 tx.AcceptToMemoryPool(txdb, false);
1346 // Delete redundant memory transactions that are in the connected branch
1347 BOOST_FOREACH(CTransaction& tx, vDelete)
1348 tx.RemoveFromMemoryPool();
1350 printf("REORGANIZE: done\n");
1356 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1358 uint256 hash = GetHash();
1360 if (!txdb.TxnBegin())
1361 return error("SetBestChain() : TxnBegin failed");
1363 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1365 txdb.WriteHashBestChain(hash);
1366 if (!txdb.TxnCommit())
1367 return error("SetBestChain() : TxnCommit failed");
1368 pindexGenesisBlock = pindexNew;
1370 else if (hashPrevBlock == hashBestChain)
1372 // Adding to current best branch
1373 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1376 InvalidChainFound(pindexNew);
1377 return error("SetBestChain() : ConnectBlock failed");
1379 if (!txdb.TxnCommit())
1380 return error("SetBestChain() : TxnCommit failed");
1382 // Add to current best branch
1383 pindexNew->pprev->pnext = pindexNew;
1385 // Delete redundant memory transactions
1386 BOOST_FOREACH(CTransaction& tx, vtx)
1387 tx.RemoveFromMemoryPool();
1392 if (!Reorganize(txdb, pindexNew))
1395 InvalidChainFound(pindexNew);
1396 return error("SetBestChain() : Reorganize failed");
1400 // Update best block in wallet (so we can detect restored wallets)
1401 if (!IsInitialBlockDownload())
1403 const CBlockLocator locator(pindexNew);
1404 ::SetBestChain(locator);
1408 hashBestChain = hash;
1409 pindexBest = pindexNew;
1410 nBestHeight = pindexBest->nHeight;
1411 bnBestChainWork = pindexNew->bnChainWork;
1412 nTimeBestReceived = GetTime();
1413 nTransactionsUpdated++;
1414 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1420 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1422 // Check for duplicate
1423 uint256 hash = GetHash();
1424 if (mapBlockIndex.count(hash))
1425 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1427 // Construct new block index object
1428 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1430 return error("AddToBlockIndex() : new CBlockIndex failed");
1431 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1432 pindexNew->phashBlock = &((*mi).first);
1433 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1434 if (miPrev != mapBlockIndex.end())
1436 pindexNew->pprev = (*miPrev).second;
1437 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1439 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1442 if (!txdb.TxnBegin())
1444 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1445 if (!txdb.TxnCommit())
1449 if (pindexNew->bnChainWork > bnBestChainWork)
1450 if (!SetBestChain(txdb, pindexNew))
1455 if (pindexNew == pindexBest)
1457 // Notify UI to display prev block's coinbase if it was ours
1458 static uint256 hashPrevBestCoinBase;
1459 UpdatedTransaction(hashPrevBestCoinBase);
1460 hashPrevBestCoinBase = vtx[0].GetHash();
1470 bool CBlock::CheckBlock() const
1472 // These are checks that are independent of context
1473 // that can be verified before saving an orphan block.
1476 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1477 return DoS(100, error("CheckBlock() : size limits failed"));
1479 // Check proof of work matches claimed amount
1480 if (!CheckProofOfWork(GetHash(), nBits))
1481 return DoS(50, error("CheckBlock() : proof of work failed"));
1484 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1485 return error("CheckBlock() : block timestamp too far in the future");
1487 // First transaction must be coinbase, the rest must not be
1488 if (vtx.empty() || !vtx[0].IsCoinBase())
1489 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1490 for (unsigned int i = 1; i < vtx.size(); i++)
1491 if (vtx[i].IsCoinBase())
1492 return DoS(100, error("CheckBlock() : more than one coinbase"));
1494 // Check transactions
1495 BOOST_FOREACH(const CTransaction& tx, vtx)
1496 if (!tx.CheckTransaction())
1497 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1499 // Check for duplicate txids. This is caught by ConnectInputs(),
1500 // but catching it earlier avoids a potential DoS attack:
1501 set<uint256> uniqueTx;
1502 BOOST_FOREACH(const CTransaction& tx, vtx)
1504 uniqueTx.insert(tx.GetHash());
1506 if (uniqueTx.size() != vtx.size())
1507 return DoS(100, error("CheckBlock() : duplicate transaction"));
1509 // Check that it's not full of nonstandard transactions
1510 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1511 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1514 if (hashMerkleRoot != BuildMerkleTree())
1515 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1520 bool CBlock::AcceptBlock()
1522 // Check for duplicate
1523 uint256 hash = GetHash();
1524 if (mapBlockIndex.count(hash))
1525 return error("AcceptBlock() : block already in mapBlockIndex");
1527 // Get prev block index
1528 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1529 if (mi == mapBlockIndex.end())
1530 return DoS(10, error("AcceptBlock() : prev block not found"));
1531 CBlockIndex* pindexPrev = (*mi).second;
1532 int nHeight = pindexPrev->nHeight+1;
1534 // Check proof of work
1535 if (nBits != GetNextWorkRequired(pindexPrev, this))
1536 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1538 // Check timestamp against prev
1539 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1540 return error("AcceptBlock() : block's timestamp is too early");
1542 // Check that all transactions are finalized
1543 BOOST_FOREACH(const CTransaction& tx, vtx)
1544 if (!tx.IsFinal(nHeight, GetBlockTime()))
1545 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1547 // Check that the block chain matches the known block chain up to a checkpoint
1548 if (!Checkpoints::CheckBlock(nHeight, hash))
1549 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1551 // Write block to history file
1552 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1553 return error("AcceptBlock() : out of disk space");
1554 unsigned int nFile = -1;
1555 unsigned int nBlockPos = 0;
1556 if (!WriteToDisk(nFile, nBlockPos))
1557 return error("AcceptBlock() : WriteToDisk failed");
1558 if (!AddToBlockIndex(nFile, nBlockPos))
1559 return error("AcceptBlock() : AddToBlockIndex failed");
1561 // Relay inventory, but don't relay old inventory during initial block download
1562 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1563 if (hashBestChain == hash)
1564 CRITICAL_BLOCK(cs_vNodes)
1565 BOOST_FOREACH(CNode* pnode, vNodes)
1566 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1567 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1572 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1574 // Check for duplicate
1575 uint256 hash = pblock->GetHash();
1576 if (mapBlockIndex.count(hash))
1577 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1578 if (mapOrphanBlocks.count(hash))
1579 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1581 // Preliminary checks
1582 if (!pblock->CheckBlock())
1583 return error("ProcessBlock() : CheckBlock FAILED");
1585 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1586 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1588 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1589 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1593 pfrom->Misbehaving(100);
1594 return error("ProcessBlock() : block with timestamp before last checkpoint");
1597 bnNewBlock.SetCompact(pblock->nBits);
1599 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1600 if (bnNewBlock > bnRequired)
1603 pfrom->Misbehaving(100);
1604 return error("ProcessBlock() : block with too little proof-of-work");
1609 // If don't already have its previous block, shunt it off to holding area until we get it
1610 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1612 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1613 CBlock* pblock2 = new CBlock(*pblock);
1614 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1615 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1617 // Ask this guy to fill in what we're missing
1619 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1624 if (!pblock->AcceptBlock())
1625 return error("ProcessBlock() : AcceptBlock FAILED");
1627 // Recursively process any orphan blocks that depended on this one
1628 vector<uint256> vWorkQueue;
1629 vWorkQueue.push_back(hash);
1630 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1632 uint256 hashPrev = vWorkQueue[i];
1633 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1634 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1637 CBlock* pblockOrphan = (*mi).second;
1638 if (pblockOrphan->AcceptBlock())
1639 vWorkQueue.push_back(pblockOrphan->GetHash());
1640 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1641 delete pblockOrphan;
1643 mapOrphanBlocksByPrev.erase(hashPrev);
1646 printf("ProcessBlock: ACCEPTED\n");
1657 bool CheckDiskSpace(uint64 nAdditionalBytes)
1659 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1661 // Check for 15MB because database could create another 10MB log file at any time
1662 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1665 string strMessage = _("Warning: Disk space is low");
1666 strMiscWarning = strMessage;
1667 printf("*** %s\n", strMessage.c_str());
1668 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1675 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1679 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1682 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1684 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1693 static unsigned int nCurrentBlockFile = 1;
1695 FILE* AppendBlockFile(unsigned int& nFileRet)
1700 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1703 if (fseek(file, 0, SEEK_END) != 0)
1705 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1706 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1708 nFileRet = nCurrentBlockFile;
1712 nCurrentBlockFile++;
1716 bool LoadBlockIndex(bool fAllowNew)
1720 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1721 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1722 pchMessageStart[0] = 0xfa;
1723 pchMessageStart[1] = 0xbf;
1724 pchMessageStart[2] = 0xb5;
1725 pchMessageStart[3] = 0xda;
1732 if (!txdb.LoadBlockIndex())
1737 // Init with genesis block
1739 if (mapBlockIndex.empty())
1745 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1746 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1747 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1748 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1749 // vMerkleTree: 4a5e1e
1752 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1754 txNew.vin.resize(1);
1755 txNew.vout.resize(1);
1756 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1757 txNew.vout[0].nValue = 50 * COIN;
1758 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1760 block.vtx.push_back(txNew);
1761 block.hashPrevBlock = 0;
1762 block.hashMerkleRoot = block.BuildMerkleTree();
1764 block.nTime = 1231006505;
1765 block.nBits = 0x1d00ffff;
1766 block.nNonce = 2083236893;
1770 block.nTime = 1296688602;
1771 block.nBits = 0x1d07fff8;
1772 block.nNonce = 384568319;
1776 printf("%s\n", block.GetHash().ToString().c_str());
1777 printf("%s\n", hashGenesisBlock.ToString().c_str());
1778 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1779 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1781 assert(block.GetHash() == hashGenesisBlock);
1783 // Start new block file
1785 unsigned int nBlockPos;
1786 if (!block.WriteToDisk(nFile, nBlockPos))
1787 return error("LoadBlockIndex() : writing genesis block to disk failed");
1788 if (!block.AddToBlockIndex(nFile, nBlockPos))
1789 return error("LoadBlockIndex() : genesis block not accepted");
1797 void PrintBlockTree()
1799 // precompute tree structure
1800 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1801 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1803 CBlockIndex* pindex = (*mi).second;
1804 mapNext[pindex->pprev].push_back(pindex);
1806 //while (rand() % 3 == 0)
1807 // mapNext[pindex->pprev].push_back(pindex);
1810 vector<pair<int, CBlockIndex*> > vStack;
1811 vStack.push_back(make_pair(0, pindexGenesisBlock));
1814 while (!vStack.empty())
1816 int nCol = vStack.back().first;
1817 CBlockIndex* pindex = vStack.back().second;
1820 // print split or gap
1821 if (nCol > nPrevCol)
1823 for (int i = 0; i < nCol-1; i++)
1827 else if (nCol < nPrevCol)
1829 for (int i = 0; i < nCol; i++)
1836 for (int i = 0; i < nCol; i++)
1841 block.ReadFromDisk(pindex);
1842 printf("%d (%u,%u) %s %s tx %d",
1846 block.GetHash().ToString().substr(0,20).c_str(),
1847 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1850 PrintWallets(block);
1852 // put the main timechain first
1853 vector<CBlockIndex*>& vNext = mapNext[pindex];
1854 for (unsigned int i = 0; i < vNext.size(); i++)
1856 if (vNext[i]->pnext)
1858 swap(vNext[0], vNext[i]);
1864 for (unsigned int i = 0; i < vNext.size(); i++)
1865 vStack.push_back(make_pair(nCol+i, vNext[i]));
1878 //////////////////////////////////////////////////////////////////////////////
1883 map<uint256, CAlert> mapAlerts;
1884 CCriticalSection cs_mapAlerts;
1886 string GetWarnings(string strFor)
1889 string strStatusBar;
1891 if (GetBoolArg("-testsafemode"))
1894 // Misc warnings like out of disk space and clock is wrong
1895 if (strMiscWarning != "")
1898 strStatusBar = strMiscWarning;
1901 // Longer invalid proof-of-work chain
1902 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1905 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1909 CRITICAL_BLOCK(cs_mapAlerts)
1911 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1913 const CAlert& alert = item.second;
1914 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1916 nPriority = alert.nPriority;
1917 strStatusBar = alert.strStatusBar;
1922 if (strFor == "statusbar")
1923 return strStatusBar;
1924 else if (strFor == "rpc")
1926 assert(!"GetWarnings() : invalid parameter");
1930 bool CAlert::ProcessAlert()
1932 if (!CheckSignature())
1937 CRITICAL_BLOCK(cs_mapAlerts)
1939 // Cancel previous alerts
1940 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1942 const CAlert& alert = (*mi).second;
1945 printf("cancelling alert %d\n", alert.nID);
1946 mapAlerts.erase(mi++);
1948 else if (!alert.IsInEffect())
1950 printf("expiring alert %d\n", alert.nID);
1951 mapAlerts.erase(mi++);
1957 // Check if this alert has been cancelled
1958 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1960 const CAlert& alert = item.second;
1961 if (alert.Cancels(*this))
1963 printf("alert already cancelled by %d\n", alert.nID);
1969 mapAlerts.insert(make_pair(GetHash(), *this));
1972 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1984 //////////////////////////////////////////////////////////////////////////////
1990 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1996 bool txInMap = false;
1997 CRITICAL_BLOCK(cs_mapTransactions)
1999 txInMap = (mapTransactions.count(inv.hash) != 0);
2002 mapOrphanTransactions.count(inv.hash) ||
2003 txdb.ContainsTx(inv.hash);
2006 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2008 // Don't know what it is, just say we already got one
2015 // The message start string is designed to be unlikely to occur in normal data.
2016 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2017 // a large 4-byte int at any alignment.
2018 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2021 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2023 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2024 RandAddSeedPerfmon();
2026 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2027 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2029 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2031 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2039 if (strCommand == "version")
2041 // Each connection can only send one version message
2042 if (pfrom->nVersion != 0)
2044 pfrom->Misbehaving(1);
2052 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2053 if (pfrom->nVersion == 10300)
2054 pfrom->nVersion = 300;
2055 if (pfrom->nVersion >= 106 && !vRecv.empty())
2056 vRecv >> addrFrom >> nNonce;
2057 if (pfrom->nVersion >= 106 && !vRecv.empty())
2058 vRecv >> pfrom->strSubVer;
2059 if (pfrom->nVersion >= 209 && !vRecv.empty())
2060 vRecv >> pfrom->nStartingHeight;
2062 if (pfrom->nVersion == 0)
2065 // Disconnect if we connected to ourself
2066 if (nNonce == nLocalHostNonce && nNonce > 1)
2068 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2069 pfrom->fDisconnect = true;
2073 // Be shy and don't send version until we hear
2074 if (pfrom->fInbound)
2075 pfrom->PushVersion();
2077 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2079 AddTimeData(pfrom->addr.ip, nTime);
2082 if (pfrom->nVersion >= 209)
2083 pfrom->PushMessage("verack");
2084 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2085 if (pfrom->nVersion < 209)
2086 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2088 if (!pfrom->fInbound)
2090 // Advertise our address
2091 if (addrLocalHost.IsRoutable() && !fUseProxy)
2093 CAddress addr(addrLocalHost);
2094 addr.nTime = GetAdjustedTime();
2095 pfrom->PushAddress(addr);
2098 // Get recent addresses
2099 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2101 pfrom->PushMessage("getaddr");
2102 pfrom->fGetAddr = true;
2106 // Ask the first connected node for block updates
2107 static int nAskedForBlocks = 0;
2108 if (!pfrom->fClient &&
2109 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
2110 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2113 pfrom->PushGetBlocks(pindexBest, uint256(0));
2117 CRITICAL_BLOCK(cs_mapAlerts)
2118 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2119 item.second.RelayTo(pfrom);
2121 pfrom->fSuccessfullyConnected = true;
2123 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2125 cPeerBlockCounts.input(pfrom->nStartingHeight);
2129 else if (pfrom->nVersion == 0)
2131 // Must have a version message before anything else
2132 pfrom->Misbehaving(1);
2137 else if (strCommand == "verack")
2139 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2143 else if (strCommand == "addr")
2145 vector<CAddress> vAddr;
2148 // Don't want addr from older versions unless seeding
2149 if (pfrom->nVersion < 209)
2151 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2153 if (vAddr.size() > 1000)
2155 pfrom->Misbehaving(20);
2156 return error("message addr size() = %d", vAddr.size());
2159 // Store the new addresses
2162 int64 nNow = GetAdjustedTime();
2163 int64 nSince = nNow - 10 * 60;
2164 BOOST_FOREACH(CAddress& addr, vAddr)
2168 // ignore IPv6 for now, since it isn't implemented anyway
2171 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2172 addr.nTime = nNow - 5 * 24 * 60 * 60;
2173 AddAddress(addr, 2 * 60 * 60, &addrDB);
2174 pfrom->AddAddressKnown(addr);
2175 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2177 // Relay to a limited number of other nodes
2178 CRITICAL_BLOCK(cs_vNodes)
2180 // Use deterministic randomness to send to the same nodes for 24 hours
2181 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2182 static uint256 hashSalt;
2184 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2185 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2186 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2187 multimap<uint256, CNode*> mapMix;
2188 BOOST_FOREACH(CNode* pnode, vNodes)
2190 if (pnode->nVersion < 31402)
2192 unsigned int nPointer;
2193 memcpy(&nPointer, &pnode, sizeof(nPointer));
2194 uint256 hashKey = hashRand ^ nPointer;
2195 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2196 mapMix.insert(make_pair(hashKey, pnode));
2198 int nRelayNodes = 2;
2199 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2200 ((*mi).second)->PushAddress(addr);
2204 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
2205 if (vAddr.size() < 1000)
2206 pfrom->fGetAddr = false;
2210 else if (strCommand == "inv")
2214 if (vInv.size() > 50000)
2216 pfrom->Misbehaving(20);
2217 return error("message inv size() = %d", vInv.size());
2220 // find last block in inv vector
2221 unsigned int nLastBlock = (unsigned int)(-1);
2222 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
2223 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
2224 nLastBlock = vInv.size() - 1 - nInv;
2229 for (int nInv = 0; nInv < vInv.size(); nInv++)
2231 const CInv &inv = vInv[nInv];
2235 pfrom->AddInventoryKnown(inv);
2237 bool fAlreadyHave = AlreadyHave(txdb, inv);
2239 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2243 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
2244 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2245 } else if (nInv == nLastBlock) {
2246 // In case we are on a very long side-chain, it is possible that we already have
2247 // the last block in an inv bundle sent in response to getblocks. Try to detect
2248 // this situation and push another getblocks to continue.
2249 std::vector<CInv> vGetData(1,inv);
2250 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
2252 printf("force request: %s\n", inv.ToString().c_str());
2255 // Track requests for our stuff
2256 Inventory(inv.hash);
2261 else if (strCommand == "getdata")
2265 if (vInv.size() > 50000)
2267 pfrom->Misbehaving(20);
2268 return error("message getdata size() = %d", vInv.size());
2271 BOOST_FOREACH(const CInv& inv, vInv)
2275 printf("received getdata for: %s\n", inv.ToString().c_str());
2277 if (inv.type == MSG_BLOCK)
2279 // Send block from disk
2280 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2281 if (mi != mapBlockIndex.end())
2284 block.ReadFromDisk((*mi).second);
2285 pfrom->PushMessage("block", block);
2287 // Trigger them to send a getblocks request for the next batch of inventory
2288 if (inv.hash == pfrom->hashContinue)
2290 // Bypass PushInventory, this must send even if redundant,
2291 // and we want it right after the last block so they don't
2292 // wait for other stuff first.
2294 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2295 pfrom->PushMessage("inv", vInv);
2296 pfrom->hashContinue = 0;
2300 else if (inv.IsKnownType())
2302 // Send stream from relay memory
2303 CRITICAL_BLOCK(cs_mapRelay)
2305 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2306 if (mi != mapRelay.end())
2307 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2311 // Track requests for our stuff
2312 Inventory(inv.hash);
2317 else if (strCommand == "getblocks")
2319 CBlockLocator locator;
2321 vRecv >> locator >> hashStop;
2323 // Find the last block the caller has in the main chain
2324 CBlockIndex* pindex = locator.GetBlockIndex();
2326 // Send the rest of the chain
2328 pindex = pindex->pnext;
2329 int nLimit = 500 + locator.GetDistanceBack();
2330 unsigned int nBytes = 0;
2331 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2332 for (; pindex; pindex = pindex->pnext)
2334 if (pindex->GetBlockHash() == hashStop)
2336 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2339 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2341 block.ReadFromDisk(pindex, true);
2342 nBytes += block.GetSerializeSize(SER_NETWORK);
2343 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2345 // When this block is requested, we'll send an inv that'll make them
2346 // getblocks the next batch of inventory.
2347 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2348 pfrom->hashContinue = pindex->GetBlockHash();
2355 else if (strCommand == "getheaders")
2357 CBlockLocator locator;
2359 vRecv >> locator >> hashStop;
2361 CBlockIndex* pindex = NULL;
2362 if (locator.IsNull())
2364 // If locator is null, return the hashStop block
2365 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2366 if (mi == mapBlockIndex.end())
2368 pindex = (*mi).second;
2372 // Find the last block the caller has in the main chain
2373 pindex = locator.GetBlockIndex();
2375 pindex = pindex->pnext;
2378 vector<CBlock> vHeaders;
2379 int nLimit = 2000 + locator.GetDistanceBack();
2380 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2381 for (; pindex; pindex = pindex->pnext)
2383 vHeaders.push_back(pindex->GetBlockHeader());
2384 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2387 pfrom->PushMessage("headers", vHeaders);
2391 else if (strCommand == "tx")
2393 vector<uint256> vWorkQueue;
2394 CDataStream vMsg(vRecv);
2398 CInv inv(MSG_TX, tx.GetHash());
2399 pfrom->AddInventoryKnown(inv);
2401 bool fMissingInputs = false;
2402 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2404 SyncWithWallets(tx, NULL, true);
2405 RelayMessage(inv, vMsg);
2406 mapAlreadyAskedFor.erase(inv);
2407 vWorkQueue.push_back(inv.hash);
2409 // Recursively process any orphan transactions that depended on this one
2410 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2412 uint256 hashPrev = vWorkQueue[i];
2413 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2414 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2417 const CDataStream& vMsg = *((*mi).second);
2419 CDataStream(vMsg) >> tx;
2420 CInv inv(MSG_TX, tx.GetHash());
2422 if (tx.AcceptToMemoryPool(true))
2424 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2425 SyncWithWallets(tx, NULL, true);
2426 RelayMessage(inv, vMsg);
2427 mapAlreadyAskedFor.erase(inv);
2428 vWorkQueue.push_back(inv.hash);
2433 BOOST_FOREACH(uint256 hash, vWorkQueue)
2434 EraseOrphanTx(hash);
2436 else if (fMissingInputs)
2438 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2441 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2442 int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
2444 printf("mapOrphan overflow, removed %d tx\n", nEvicted);
2446 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2450 else if (strCommand == "block")
2455 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2458 CInv inv(MSG_BLOCK, block.GetHash());
2459 pfrom->AddInventoryKnown(inv);
2461 if (ProcessBlock(pfrom, &block))
2462 mapAlreadyAskedFor.erase(inv);
2463 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2467 else if (strCommand == "getaddr")
2469 // Nodes rebroadcast an addr every 24 hours
2470 pfrom->vAddrToSend.clear();
2471 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2472 CRITICAL_BLOCK(cs_mapAddresses)
2474 unsigned int nCount = 0;
2475 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2477 const CAddress& addr = item.second;
2478 if (addr.nTime > nSince)
2481 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2483 const CAddress& addr = item.second;
2484 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2485 pfrom->PushAddress(addr);
2491 else if (strCommand == "checkorder")
2496 if (!GetBoolArg("-allowreceivebyip"))
2498 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2505 /// we have a chance to check the order here
2507 // Keep giving the same key to the same ip until they use it
2508 if (!mapReuseKey.count(pfrom->addr.ip))
2509 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2511 // Send back approval of order and pubkey to use
2512 CScript scriptPubKey;
2513 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2514 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2518 else if (strCommand == "reply")
2523 CRequestTracker tracker;
2524 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2526 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2527 if (mi != pfrom->mapRequests.end())
2529 tracker = (*mi).second;
2530 pfrom->mapRequests.erase(mi);
2533 if (!tracker.IsNull())
2534 tracker.fn(tracker.param1, vRecv);
2538 else if (strCommand == "ping")
2543 else if (strCommand == "alert")
2548 if (alert.ProcessAlert())
2551 pfrom->setKnown.insert(alert.GetHash());
2552 CRITICAL_BLOCK(cs_vNodes)
2553 BOOST_FOREACH(CNode* pnode, vNodes)
2554 alert.RelayTo(pnode);
2561 // Ignore unknown commands for extensibility
2565 // Update the last seen time for this node's address
2566 if (pfrom->fNetworkNode)
2567 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2568 AddressCurrentlyConnected(pfrom->addr);
2574 bool ProcessMessages(CNode* pfrom)
2576 CDataStream& vRecv = pfrom->vRecv;
2580 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2584 // (4) message start
2593 // Scan for message start
2594 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2595 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2596 if (vRecv.end() - pstart < nHeaderSize)
2598 if (vRecv.size() > nHeaderSize)
2600 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2601 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2605 if (pstart - vRecv.begin() > 0)
2606 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2607 vRecv.erase(vRecv.begin(), pstart);
2610 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2615 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2618 string strCommand = hdr.GetCommand();
2621 unsigned int nMessageSize = hdr.nMessageSize;
2622 if (nMessageSize > MAX_SIZE)
2624 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2627 if (nMessageSize > vRecv.size())
2629 // Rewind and wait for rest of message
2630 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2635 if (vRecv.GetVersion() >= 209)
2637 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2638 unsigned int nChecksum = 0;
2639 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2640 if (nChecksum != hdr.nChecksum)
2642 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2643 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2648 // Copy message to its own buffer
2649 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2650 vRecv.ignore(nMessageSize);
2656 CRITICAL_BLOCK(cs_main)
2657 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2661 catch (std::ios_base::failure& e)
2663 if (strstr(e.what(), "end of data"))
2665 // Allow exceptions from underlength message on vRecv
2666 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());
2668 else if (strstr(e.what(), "size too large"))
2670 // Allow exceptions from overlong size
2671 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2675 PrintExceptionContinue(&e, "ProcessMessages()");
2678 catch (std::exception& e) {
2679 PrintExceptionContinue(&e, "ProcessMessages()");
2681 PrintExceptionContinue(NULL, "ProcessMessages()");
2685 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2693 bool SendMessages(CNode* pto, bool fSendTrickle)
2695 TRY_CRITICAL_BLOCK(cs_main)
2697 // Don't send anything until we get their version message
2698 if (pto->nVersion == 0)
2702 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2703 pto->PushMessage("ping");
2705 // Resend wallet transactions that haven't gotten in a block yet
2706 ResendWalletTransactions();
2708 // Address refresh broadcast
2709 static int64 nLastRebroadcast;
2710 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2712 nLastRebroadcast = GetTime();
2713 CRITICAL_BLOCK(cs_vNodes)
2715 BOOST_FOREACH(CNode* pnode, vNodes)
2717 // Periodically clear setAddrKnown to allow refresh broadcasts
2718 pnode->setAddrKnown.clear();
2720 // Rebroadcast our address
2721 if (addrLocalHost.IsRoutable() && !fUseProxy)
2723 CAddress addr(addrLocalHost);
2724 addr.nTime = GetAdjustedTime();
2725 pnode->PushAddress(addr);
2731 // Clear out old addresses periodically so it's not too much work at once
2732 static int64 nLastClear;
2733 if (nLastClear == 0)
2734 nLastClear = GetTime();
2735 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2737 nLastClear = GetTime();
2738 CRITICAL_BLOCK(cs_mapAddresses)
2741 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2742 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2743 mi != mapAddresses.end();)
2745 const CAddress& addr = (*mi).second;
2746 if (addr.nTime < nSince)
2748 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2750 addrdb.EraseAddress(addr);
2751 mapAddresses.erase(mi++);
2765 vector<CAddress> vAddr;
2766 vAddr.reserve(pto->vAddrToSend.size());
2767 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2769 // returns true if wasn't already contained in the set
2770 if (pto->setAddrKnown.insert(addr).second)
2772 vAddr.push_back(addr);
2773 // receiver rejects addr messages larger than 1000
2774 if (vAddr.size() >= 1000)
2776 pto->PushMessage("addr", vAddr);
2781 pto->vAddrToSend.clear();
2783 pto->PushMessage("addr", vAddr);
2788 // Message: inventory
2791 vector<CInv> vInvWait;
2792 CRITICAL_BLOCK(pto->cs_inventory)
2794 vInv.reserve(pto->vInventoryToSend.size());
2795 vInvWait.reserve(pto->vInventoryToSend.size());
2796 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2798 if (pto->setInventoryKnown.count(inv))
2801 // trickle out tx inv to protect privacy
2802 if (inv.type == MSG_TX && !fSendTrickle)
2804 // 1/4 of tx invs blast to all immediately
2805 static uint256 hashSalt;
2807 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2808 uint256 hashRand = inv.hash ^ hashSalt;
2809 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2810 bool fTrickleWait = ((hashRand & 3) != 0);
2812 // always trickle our own transactions
2816 if (GetTransaction(inv.hash, wtx))
2818 fTrickleWait = true;
2823 vInvWait.push_back(inv);
2828 // returns true if wasn't already contained in the set
2829 if (pto->setInventoryKnown.insert(inv).second)
2831 vInv.push_back(inv);
2832 if (vInv.size() >= 1000)
2834 pto->PushMessage("inv", vInv);
2839 pto->vInventoryToSend = vInvWait;
2842 pto->PushMessage("inv", vInv);
2848 vector<CInv> vGetData;
2849 int64 nNow = GetTime() * 1000000;
2851 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2853 const CInv& inv = (*pto->mapAskFor.begin()).second;
2854 if (!AlreadyHave(txdb, inv))
2856 printf("sending getdata: %s\n", inv.ToString().c_str());
2857 vGetData.push_back(inv);
2858 if (vGetData.size() >= 1000)
2860 pto->PushMessage("getdata", vGetData);
2864 mapAlreadyAskedFor[inv] = nNow;
2865 pto->mapAskFor.erase(pto->mapAskFor.begin());
2867 if (!vGetData.empty())
2868 pto->PushMessage("getdata", vGetData);
2887 //////////////////////////////////////////////////////////////////////////////
2892 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2894 unsigned char* pdata = (unsigned char*)pbuffer;
2895 unsigned int blocks = 1 + ((len + 8) / 64);
2896 unsigned char* pend = pdata + 64 * blocks;
2897 memset(pdata + len, 0, 64 * blocks - len);
2899 unsigned int bits = len * 8;
2900 pend[-1] = (bits >> 0) & 0xff;
2901 pend[-2] = (bits >> 8) & 0xff;
2902 pend[-3] = (bits >> 16) & 0xff;
2903 pend[-4] = (bits >> 24) & 0xff;
2907 static const unsigned int pSHA256InitState[8] =
2908 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2910 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2913 unsigned char data[64];
2917 for (int i = 0; i < 16; i++)
2918 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2920 for (int i = 0; i < 8; i++)
2921 ctx.h[i] = ((uint32_t*)pinit)[i];
2923 SHA256_Update(&ctx, data, sizeof(data));
2924 for (int i = 0; i < 8; i++)
2925 ((uint32_t*)pstate)[i] = ctx.h[i];
2929 // ScanHash scans nonces looking for a hash with at least some zero bits.
2930 // It operates on big endian data. Caller does the byte reversing.
2931 // All input buffers are 16-byte aligned. nNonce is usually preserved
2932 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2933 // the block is rebuilt and nNonce starts over at zero.
2935 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2937 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2941 // Hash pdata using pmidstate as the starting state into
2942 // preformatted buffer phash1, then hash phash1 into phash
2944 SHA256Transform(phash1, pdata, pmidstate);
2945 SHA256Transform(phash, phash1, pSHA256InitState);
2947 // Return the nonce if the hash has at least some zero bits,
2948 // caller will check if it has enough to reach the target
2949 if (((unsigned short*)phash)[14] == 0)
2952 // If nothing found after trying for a while, return -1
2953 if ((nNonce & 0xffff) == 0)
2955 nHashesDone = 0xffff+1;
2961 // Some explaining would be appreciated
2966 set<uint256> setDependsOn;
2969 COrphan(CTransaction* ptxIn)
2977 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2978 BOOST_FOREACH(uint256 hash, setDependsOn)
2979 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2984 CBlock* CreateNewBlock(CReserveKey& reservekey)
2986 CBlockIndex* pindexPrev = pindexBest;
2989 auto_ptr<CBlock> pblock(new CBlock());
2993 // Create coinbase tx
2995 txNew.vin.resize(1);
2996 txNew.vin[0].prevout.SetNull();
2997 txNew.vout.resize(1);
2998 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3000 // Add our coinbase tx as first transaction
3001 pblock->vtx.push_back(txNew);
3003 // Collect memory pool transactions into the block
3005 CRITICAL_BLOCK(cs_main)
3006 CRITICAL_BLOCK(cs_mapTransactions)
3010 // Priority order to process transactions
3011 list<COrphan> vOrphan; // list memory doesn't move
3012 map<uint256, vector<COrphan*> > mapDependers;
3013 multimap<double, CTransaction*> mapPriority;
3014 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3016 CTransaction& tx = (*mi).second;
3017 if (tx.IsCoinBase() || !tx.IsFinal())
3020 COrphan* porphan = NULL;
3021 double dPriority = 0;
3022 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3024 // Read prev transaction
3025 CTransaction txPrev;
3027 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3029 // Has to wait for dependencies
3032 // Use list for automatic deletion
3033 vOrphan.push_back(COrphan(&tx));
3034 porphan = &vOrphan.back();
3036 mapDependers[txin.prevout.hash].push_back(porphan);
3037 porphan->setDependsOn.insert(txin.prevout.hash);
3040 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3042 // Read block header
3043 int nConf = txindex.GetDepthInMainChain();
3045 dPriority += (double)nValueIn * nConf;
3047 if (fDebug && GetBoolArg("-printpriority"))
3048 printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3051 // Priority is sum(valuein * age) / txsize
3052 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3055 porphan->dPriority = dPriority;
3057 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3059 if (fDebug && GetBoolArg("-printpriority"))
3061 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3068 // Collect transactions into block
3069 map<uint256, CTxIndex> mapTestPool;
3070 uint64 nBlockSize = 1000;
3071 int nBlockSigOps = 100;
3072 while (!mapPriority.empty())
3074 // Take highest priority transaction off priority queue
3075 double dPriority = -(*mapPriority.begin()).first;
3076 CTransaction& tx = *(*mapPriority.begin()).second;
3077 mapPriority.erase(mapPriority.begin());
3080 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3081 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3084 // Legacy limits on sigOps:
3085 int nTxSigOps = tx.GetSigOpCount();
3086 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3089 // Transaction fee required depends on block size
3090 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3091 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
3093 // Connecting shouldn't fail due to dependency on other memory pool transactions
3094 // because we're already processing them in order of dependency
3095 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3097 MapPrevTx mapInputs;
3098 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3101 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3102 if (nTxFees < nMinFee)
3105 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3106 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3109 if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3111 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3112 swap(mapTestPool, mapTestPoolTmp);
3115 pblock->vtx.push_back(tx);
3116 nBlockSize += nTxSize;
3117 nBlockSigOps += nTxSigOps;
3120 // Add transactions that depend on this one to the priority queue
3121 uint256 hash = tx.GetHash();
3122 if (mapDependers.count(hash))
3124 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3126 if (!porphan->setDependsOn.empty())
3128 porphan->setDependsOn.erase(hash);
3129 if (porphan->setDependsOn.empty())
3130 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3136 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3139 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3140 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3141 pblock->UpdateTime(pindexPrev);
3142 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
3145 return pblock.release();
3149 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3151 // Update nExtraNonce
3152 static uint256 hashPrevBlock;
3153 if (hashPrevBlock != pblock->hashPrevBlock)
3156 hashPrevBlock = pblock->hashPrevBlock;
3159 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3160 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3164 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3167 // Prebuild hash buffers
3174 uint256 hashPrevBlock;
3175 uint256 hashMerkleRoot;
3178 unsigned int nNonce;
3181 unsigned char pchPadding0[64];
3183 unsigned char pchPadding1[64];
3186 memset(&tmp, 0, sizeof(tmp));
3188 tmp.block.nVersion = pblock->nVersion;
3189 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3190 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3191 tmp.block.nTime = pblock->nTime;
3192 tmp.block.nBits = pblock->nBits;
3193 tmp.block.nNonce = pblock->nNonce;
3195 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3196 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3198 // Byte swap all the input buffer
3199 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3200 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3202 // Precalc the first half of the first hash, which stays constant
3203 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3205 memcpy(pdata, &tmp.block, 128);
3206 memcpy(phash1, &tmp.hash1, 64);
3210 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3212 uint256 hash = pblock->GetHash();
3213 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3215 if (hash > hashTarget)
3219 printf("BitcoinMiner:\n");
3220 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3222 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3223 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3226 CRITICAL_BLOCK(cs_main)
3228 if (pblock->hashPrevBlock != hashBestChain)
3229 return error("BitcoinMiner : generated block is stale");
3231 // Remove key from key pool
3232 reservekey.KeepKey();
3234 // Track how many getdata requests this block gets
3235 CRITICAL_BLOCK(wallet.cs_wallet)
3236 wallet.mapRequestCount[pblock->GetHash()] = 0;
3238 // Process this block the same as if we had received it from another node
3239 if (!ProcessBlock(NULL, pblock))
3240 return error("BitcoinMiner : ProcessBlock, block not accepted");
3246 void static ThreadBitcoinMiner(void* parg);
3248 void static BitcoinMiner(CWallet *pwallet)
3250 printf("BitcoinMiner started\n");
3251 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3253 // Each thread has its own key and counter
3254 CReserveKey reservekey(pwallet);
3255 unsigned int nExtraNonce = 0;
3257 while (fGenerateBitcoins)
3259 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3263 while (vNodes.empty() || IsInitialBlockDownload())
3268 if (!fGenerateBitcoins)
3276 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3277 CBlockIndex* pindexPrev = pindexBest;
3279 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3282 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3284 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3288 // Prebuild hash buffers
3290 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3291 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3292 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3294 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3296 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3297 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
3298 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3304 int64 nStart = GetTime();
3305 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3307 uint256& hash = *alignup<16>(hashbuf);
3310 unsigned int nHashesDone = 0;
3311 unsigned int nNonceFound;
3314 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3315 (char*)&hash, nHashesDone);
3317 // Check if something found
3318 if (nNonceFound != -1)
3320 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
3321 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3323 if (hash <= hashTarget)
3326 pblock->nNonce = ByteReverse(nNonceFound);
3327 assert(hash == pblock->GetHash());
3329 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3330 CheckWork(pblock.get(), *pwalletMain, reservekey);
3331 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3337 static int64 nHashCounter;
3338 if (nHPSTimerStart == 0)
3340 nHPSTimerStart = GetTimeMillis();
3344 nHashCounter += nHashesDone;
3345 if (GetTimeMillis() - nHPSTimerStart > 4000)
3347 static CCriticalSection cs;
3350 if (GetTimeMillis() - nHPSTimerStart > 4000)
3352 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3353 nHPSTimerStart = GetTimeMillis();
3355 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3356 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3357 static int64 nLogTime;
3358 if (GetTime() - nLogTime > 30 * 60)
3360 nLogTime = GetTime();
3361 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3362 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3368 // Check for stop or if block needs to be rebuilt
3371 if (!fGenerateBitcoins)
3373 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3377 if (nBlockNonce >= 0xffff0000)
3379 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3381 if (pindexPrev != pindexBest)
3384 // Update nTime every few seconds
3385 pblock->UpdateTime(pindexPrev);
3386 nBlockTime = ByteReverse(pblock->nTime);
3389 // Changing pblock->nTime can change work required on testnet:
3390 nBlockBits = ByteReverse(pblock->nBits);
3391 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3397 void static ThreadBitcoinMiner(void* parg)
3399 CWallet* pwallet = (CWallet*)parg;
3402 vnThreadsRunning[3]++;
3403 BitcoinMiner(pwallet);
3404 vnThreadsRunning[3]--;
3406 catch (std::exception& e) {
3407 vnThreadsRunning[3]--;
3408 PrintException(&e, "ThreadBitcoinMiner()");
3410 vnThreadsRunning[3]--;
3411 PrintException(NULL, "ThreadBitcoinMiner()");
3413 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3415 if (vnThreadsRunning[3] == 0)
3417 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3421 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3423 if (fGenerateBitcoins != fGenerate)
3425 fGenerateBitcoins = fGenerate;
3426 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3429 if (fGenerateBitcoins)
3431 int nProcessors = boost::thread::hardware_concurrency();
3432 printf("%d processors\n", nProcessors);
3433 if (nProcessors < 1)
3435 if (fLimitProcessors && nProcessors > nLimitProcessors)
3436 nProcessors = nLimitProcessors;
3437 int nAddThreads = nProcessors - vnThreadsRunning[3];
3438 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3439 for (int i = 0; i < nAddThreads; i++)
3441 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3442 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");