1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #include "checkpoints.h"
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
14 using namespace boost;
20 // Name of client reported in the 'version' message. Report the same name
21 // for both bitcoind and bitcoin-qt, to make it harder for attackers to
22 // target servers or GUI users specifically.
23 const std::string CLIENT_NAME("bitcoin-qt");
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
30 static map<uint256, CTransaction> mapTransactions;
31 CCriticalSection cs_mapTransactions;
32 unsigned int nTransactionsUpdated = 0;
33 map<COutPoint, CInPoint> mapNextTx;
35 map<uint256, CBlockIndex*> mapBlockIndex;
36 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
37 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
38 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
39 CBlockIndex* pindexGenesisBlock = NULL;
41 CBigNum bnBestChainWork = 0;
42 CBigNum bnBestInvalidWork = 0;
43 uint256 hashBestChain = 0;
44 CBlockIndex* pindexBest = NULL;
45 int64 nTimeBestReceived = 0;
47 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
49 map<uint256, CBlock*> mapOrphanBlocks;
50 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
52 map<uint256, CDataStream*> mapOrphanTransactions;
53 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
60 int fGenerateBitcoins = false;
61 int64 nTransactionFee = 0;
62 int fLimitProcessors = false;
63 int nLimitProcessors = 1;
64 int fMinimizeToTray = true;
65 int fMinimizeOnClose = true;
73 //////////////////////////////////////////////////////////////////////////////
75 // dispatching functions
78 // These functions dispatch to one or all registered wallets
81 void RegisterWallet(CWallet* pwalletIn)
83 CRITICAL_BLOCK(cs_setpwalletRegistered)
85 setpwalletRegistered.insert(pwalletIn);
89 void UnregisterWallet(CWallet* pwalletIn)
91 CRITICAL_BLOCK(cs_setpwalletRegistered)
93 setpwalletRegistered.erase(pwalletIn);
97 // check whether the passed transaction is from us
98 bool static IsFromMe(CTransaction& tx)
100 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
101 if (pwallet->IsFromMe(tx))
106 // get the wallet transaction with the given hash (if it exists)
107 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
109 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
110 if (pwallet->GetTransaction(hashTx,wtx))
115 // erases transaction with the given hash from all wallets
116 void static EraseFromWallets(uint256 hash)
118 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
119 pwallet->EraseFromWallet(hash);
122 // make sure all wallets know about the given transaction, in the given block
123 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
125 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
129 // notify wallets about a new best chain
130 void static SetBestChain(const CBlockLocator& loc)
132 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
133 pwallet->SetBestChain(loc);
136 // notify wallets about an updated transaction
137 void static UpdatedTransaction(const uint256& hashTx)
139 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
140 pwallet->UpdatedTransaction(hashTx);
144 void static PrintWallets(const CBlock& block)
146 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
147 pwallet->PrintWallet(block);
150 // notify wallets about an incoming inventory (for request counts)
151 void static Inventory(const uint256& hash)
153 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
154 pwallet->Inventory(hash);
157 // ask wallets to resend their transactions
158 void static ResendWalletTransactions()
160 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
161 pwallet->ResendWalletTransactions();
170 //////////////////////////////////////////////////////////////////////////////
172 // mapOrphanTransactions
175 void static AddOrphanTx(const CDataStream& vMsg)
178 CDataStream(vMsg) >> tx;
179 uint256 hash = tx.GetHash();
180 if (mapOrphanTransactions.count(hash))
182 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
183 BOOST_FOREACH(const CTxIn& txin, tx.vin)
184 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
187 void static EraseOrphanTx(uint256 hash)
189 if (!mapOrphanTransactions.count(hash))
191 const CDataStream* pvMsg = mapOrphanTransactions[hash];
193 CDataStream(*pvMsg) >> tx;
194 BOOST_FOREACH(const CTxIn& txin, tx.vin)
196 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
197 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
199 if ((*mi).second == pvMsg)
200 mapOrphanTransactionsByPrev.erase(mi++);
206 mapOrphanTransactions.erase(hash);
216 //////////////////////////////////////////////////////////////////////////////
218 // CTransaction and CTxIndex
221 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
224 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
226 if (!ReadFromDisk(txindexRet.pos))
228 if (prevout.n >= vout.size())
236 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
239 return ReadFromDisk(txdb, prevout, txindex);
242 bool CTransaction::ReadFromDisk(COutPoint prevout)
246 return ReadFromDisk(txdb, prevout, txindex);
251 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
263 // Load the block this tx is in
265 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
267 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
272 // Update the tx's hashBlock
273 hashBlock = pblock->GetHash();
275 // Locate the transaction
276 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
277 if (pblock->vtx[nIndex] == *(CTransaction*)this)
279 if (nIndex == pblock->vtx.size())
281 vMerkleBranch.clear();
283 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
287 // Fill in merkle branch
288 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
291 // Is the tx in a block that's in the main chain
292 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
293 if (mi == mapBlockIndex.end())
295 CBlockIndex* pindex = (*mi).second;
296 if (!pindex || !pindex->IsInMainChain())
299 return pindexBest->nHeight - pindex->nHeight + 1;
308 bool CTransaction::CheckTransaction() const
310 // Basic checks that don't depend on any context
312 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
314 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
316 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
317 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
319 // Check for negative or overflow output values
321 BOOST_FOREACH(const CTxOut& txout, vout)
323 if (txout.nValue < 0)
324 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
325 if (txout.nValue > MAX_MONEY)
326 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
327 nValueOut += txout.nValue;
328 if (!MoneyRange(nValueOut))
329 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
332 // Check for duplicate inputs
333 set<COutPoint> vInOutPoints;
334 BOOST_FOREACH(const CTxIn& txin, vin)
336 if (vInOutPoints.count(txin.prevout))
338 vInOutPoints.insert(txin.prevout);
343 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
344 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
348 BOOST_FOREACH(const CTxIn& txin, vin)
349 if (txin.prevout.IsNull())
350 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
356 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
359 *pfMissingInputs = false;
361 if (!CheckTransaction())
362 return error("AcceptToMemoryPool() : CheckTransaction failed");
364 // Coinbase is only valid in a block, not as a loose transaction
366 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
368 // To help v0.1.5 clients who would see it as a negative number
369 if ((int64)nLockTime > INT_MAX)
370 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
373 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
374 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
375 // attacks disallow transactions with more than one SigOp per 34 bytes.
376 // 34 bytes because a TxOut is:
377 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
378 if (GetSigOpCount() > nSize / 34 || nSize < 100)
379 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
381 // Rather not work on nonstandard transactions (unless -testnet)
382 if (!fTestNet && !IsStandard())
383 return error("AcceptToMemoryPool() : nonstandard transaction type");
385 // Do we already have it?
386 uint256 hash = GetHash();
387 CRITICAL_BLOCK(cs_mapTransactions)
388 if (mapTransactions.count(hash))
391 if (txdb.ContainsTx(hash))
394 // Check for conflicts with in-memory transactions
395 CTransaction* ptxOld = NULL;
396 for (int i = 0; i < vin.size(); i++)
398 COutPoint outpoint = vin[i].prevout;
399 if (mapNextTx.count(outpoint))
401 // Disable replacement feature for now
404 // Allow replacing with a newer version of the same transaction
407 ptxOld = mapNextTx[outpoint].ptx;
408 if (ptxOld->IsFinal())
410 if (!IsNewerThan(*ptxOld))
412 for (int i = 0; i < vin.size(); i++)
414 COutPoint outpoint = vin[i].prevout;
415 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
424 // Check against previous transactions
425 map<uint256, CTxIndex> mapUnused;
427 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
430 *pfMissingInputs = true;
431 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
434 // Don't accept it if it can't get into a block
435 if (nFees < GetMinFee(1000, true, true))
436 return error("AcceptToMemoryPool() : not enough fees");
438 // Continuously rate-limit free transactions
439 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
440 // be annoying or make other's transactions take longer to confirm.
441 if (nFees < MIN_RELAY_TX_FEE)
443 static CCriticalSection cs;
444 static double dFreeCount;
445 static int64 nLastTime;
446 int64 nNow = GetTime();
450 // Use an exponentially decaying ~10-minute window:
451 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
453 // -limitfreerelay unit is thousand-bytes-per-minute
454 // At default rate it would take over a month to fill 1GB
455 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
456 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
458 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
464 // Store transaction in memory
465 CRITICAL_BLOCK(cs_mapTransactions)
469 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
470 ptxOld->RemoveFromMemoryPool();
472 AddToMemoryPoolUnchecked();
475 ///// are we sure this is ok when loading transactions or restoring block txes
476 // If updated, erase old tx from wallet
478 EraseFromWallets(ptxOld->GetHash());
480 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
484 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
487 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
490 bool CTransaction::AddToMemoryPoolUnchecked()
492 // Add to memory pool without checking anything. Don't call this directly,
493 // call AcceptToMemoryPool to properly check the transaction first.
494 CRITICAL_BLOCK(cs_mapTransactions)
496 uint256 hash = GetHash();
497 mapTransactions[hash] = *this;
498 for (int i = 0; i < vin.size(); i++)
499 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
500 nTransactionsUpdated++;
506 bool CTransaction::RemoveFromMemoryPool()
508 // Remove transaction from memory pool
509 CRITICAL_BLOCK(cs_mapTransactions)
511 BOOST_FOREACH(const CTxIn& txin, vin)
512 mapNextTx.erase(txin.prevout);
513 mapTransactions.erase(GetHash());
514 nTransactionsUpdated++;
524 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
526 if (hashBlock == 0 || nIndex == -1)
529 // Find the block it claims to be in
530 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
531 if (mi == mapBlockIndex.end())
533 CBlockIndex* pindex = (*mi).second;
534 if (!pindex || !pindex->IsInMainChain())
537 // Make sure the merkle branch connects to this block
538 if (!fMerkleVerified)
540 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
542 fMerkleVerified = true;
545 nHeightRet = pindex->nHeight;
546 return pindexBest->nHeight - pindex->nHeight + 1;
550 int CMerkleTx::GetBlocksToMaturity() const
554 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
558 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
562 if (!IsInMainChain() && !ClientConnectInputs())
564 return CTransaction::AcceptToMemoryPool(txdb, false);
568 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
572 bool CMerkleTx::AcceptToMemoryPool()
575 return AcceptToMemoryPool(txdb);
580 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
582 CRITICAL_BLOCK(cs_mapTransactions)
584 // Add previous supporting transactions first
585 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
587 if (!tx.IsCoinBase())
589 uint256 hash = tx.GetHash();
590 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
591 tx.AcceptToMemoryPool(txdb, fCheckInputs);
594 return AcceptToMemoryPool(txdb, fCheckInputs);
599 bool CWalletTx::AcceptWalletTransaction()
602 return AcceptWalletTransaction(txdb);
605 int CTxIndex::GetDepthInMainChain() const
609 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
611 // Find the block in the index
612 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
613 if (mi == mapBlockIndex.end())
615 CBlockIndex* pindex = (*mi).second;
616 if (!pindex || !pindex->IsInMainChain())
618 return 1 + nBestHeight - pindex->nHeight;
630 //////////////////////////////////////////////////////////////////////////////
632 // CBlock and CBlockIndex
635 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
637 if (!fReadTransactions)
639 *this = pindex->GetBlockHeader();
642 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
644 if (GetHash() != pindex->GetBlockHash())
645 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
649 uint256 static GetOrphanRoot(const CBlock* pblock)
651 // Work back to the first block in the orphan chain
652 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
653 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
654 return pblock->GetHash();
657 int64 static GetBlockValue(int nHeight, int64 nFees)
659 int64 nSubsidy = 50 * COIN;
661 // Subsidy is cut in half every 4 years
662 nSubsidy >>= (nHeight / 210000);
664 return nSubsidy + nFees;
667 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
668 static const int64 nTargetSpacing = 10 * 60;
669 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
672 // minimum amount of work that could possibly be required nTime after
673 // minimum work required was nBase
675 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
678 bnResult.SetCompact(nBase);
679 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
681 // Maximum 400% adjustment...
683 // ... in best-case exactly 4-times-normal target time
684 nTime -= nTargetTimespan*4;
686 if (bnResult > bnProofOfWorkLimit)
687 bnResult = bnProofOfWorkLimit;
688 return bnResult.GetCompact();
691 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
695 if (pindexLast == NULL)
696 return bnProofOfWorkLimit.GetCompact();
698 // Only change once per interval
699 if ((pindexLast->nHeight+1) % nInterval != 0)
700 return pindexLast->nBits;
702 // Go back by what we want to be 14 days worth of blocks
703 const CBlockIndex* pindexFirst = pindexLast;
704 for (int i = 0; pindexFirst && i < nInterval-1; i++)
705 pindexFirst = pindexFirst->pprev;
708 // Limit adjustment step
709 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
710 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
711 if (nActualTimespan < nTargetTimespan/4)
712 nActualTimespan = nTargetTimespan/4;
713 if (nActualTimespan > nTargetTimespan*4)
714 nActualTimespan = nTargetTimespan*4;
718 bnNew.SetCompact(pindexLast->nBits);
719 bnNew *= nActualTimespan;
720 bnNew /= nTargetTimespan;
722 if (bnNew > bnProofOfWorkLimit)
723 bnNew = bnProofOfWorkLimit;
726 printf("GetNextWorkRequired RETARGET\n");
727 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
728 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
729 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
731 return bnNew.GetCompact();
734 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
737 bnTarget.SetCompact(nBits);
740 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
741 return error("CheckProofOfWork() : nBits below minimum work");
743 // Check proof of work matches claimed amount
744 if (hash > bnTarget.getuint256())
745 return error("CheckProofOfWork() : hash doesn't match nBits");
750 // Return maximum amount of blocks that other nodes claim to have
751 int GetNumBlocksOfPeers()
753 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
756 bool IsInitialBlockDownload()
758 if (pindexBest == NULL || nBestHeight < (Checkpoints::GetTotalBlocksEstimate()-nInitialBlockThreshold))
760 static int64 nLastUpdate;
761 static CBlockIndex* pindexLastBest;
762 if (pindexBest != pindexLastBest)
764 pindexLastBest = pindexBest;
765 nLastUpdate = GetTime();
767 return (GetTime() - nLastUpdate < 10 &&
768 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
771 void static InvalidChainFound(CBlockIndex* pindexNew)
773 if (pindexNew->bnChainWork > bnBestInvalidWork)
775 bnBestInvalidWork = pindexNew->bnChainWork;
776 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
779 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());
780 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
781 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
782 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
795 bool CTransaction::DisconnectInputs(CTxDB& txdb)
797 // Relinquish previous transactions' spent pointers
800 BOOST_FOREACH(const CTxIn& txin, vin)
802 COutPoint prevout = txin.prevout;
804 // Get prev txindex from disk
806 if (!txdb.ReadTxIndex(prevout.hash, txindex))
807 return error("DisconnectInputs() : ReadTxIndex failed");
809 if (prevout.n >= txindex.vSpent.size())
810 return error("DisconnectInputs() : prevout.n out of range");
812 // Mark outpoint as not spent
813 txindex.vSpent[prevout.n].SetNull();
816 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
817 return error("DisconnectInputs() : UpdateTxIndex failed");
821 // Remove transaction from index
822 if (!txdb.EraseTxIndex(*this))
823 return error("DisconnectInputs() : EraseTxPos failed");
829 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
830 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
832 // Take over previous transactions' spent pointers
833 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
834 // fMiner is true when called from the internal bitcoin miner
835 // ... both are false when called from CTransaction::AcceptToMemoryPool
839 for (int i = 0; i < vin.size(); i++)
841 COutPoint prevout = vin[i].prevout;
846 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
848 // Get txindex from current proposed changes
849 txindex = mapTestPool[prevout.hash];
853 // Read txindex from txdb
854 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
856 if (!fFound && (fBlock || fMiner))
857 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
861 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
863 // Get prev tx from single transactions in memory
864 CRITICAL_BLOCK(cs_mapTransactions)
866 if (!mapTransactions.count(prevout.hash))
867 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
868 txPrev = mapTransactions[prevout.hash];
871 txindex.vSpent.resize(txPrev.vout.size());
875 // Get prev tx from disk
876 if (!txPrev.ReadFromDisk(txindex.pos))
877 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
880 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
881 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()));
883 // If prev is coinbase, check that it's matured
884 if (txPrev.IsCoinBase())
885 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
886 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
887 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
889 // Skip ECDSA signature verification when connecting blocks (fBlock=true) during initial download
890 // (before the last blockchain checkpoint). This is safe because block merkle hashes are
891 // still computed and checked, and any change will be caught at the next checkpoint.
892 if (!(fBlock && IsInitialBlockDownload()))
894 if (!VerifySignature(txPrev, *this, i))
895 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
897 // Check for conflicts (double-spend)
898 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
899 // for an attacker to attempt to split the network.
900 if (!txindex.vSpent[prevout.n].IsNull())
901 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());
903 // Check for negative or overflow input values
904 nValueIn += txPrev.vout[prevout.n].nValue;
905 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
906 return DoS(100, error("ConnectInputs() : txin values out of range"));
908 // Mark outpoints as spent
909 txindex.vSpent[prevout.n] = posThisTx;
912 if (fBlock || fMiner)
914 mapTestPool[prevout.hash] = txindex;
918 if (nValueIn < GetValueOut())
919 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
921 // Tally transaction fees
922 int64 nTxFee = nValueIn - GetValueOut();
924 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
925 if (nTxFee < nMinFee)
928 if (!MoneyRange(nFees))
929 return DoS(100, error("ConnectInputs() : nFees out of range"));
934 // Add transaction to changes
935 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
939 // Add transaction to test pool
940 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
947 bool CTransaction::ClientConnectInputs()
952 // Take over previous transactions' spent pointers
953 CRITICAL_BLOCK(cs_mapTransactions)
956 for (int i = 0; i < vin.size(); i++)
958 // Get prev tx from single transactions in memory
959 COutPoint prevout = vin[i].prevout;
960 if (!mapTransactions.count(prevout.hash))
962 CTransaction& txPrev = mapTransactions[prevout.hash];
964 if (prevout.n >= txPrev.vout.size())
968 if (!VerifySignature(txPrev, *this, i))
969 return error("ConnectInputs() : VerifySignature failed");
971 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
972 ///// this has to go away now that posNext is gone
973 // // Check for conflicts
974 // if (!txPrev.vout[prevout.n].posNext.IsNull())
975 // return error("ConnectInputs() : prev tx already used");
977 // // Flag outpoints as used
978 // txPrev.vout[prevout.n].posNext = posThisTx;
980 nValueIn += txPrev.vout[prevout.n].nValue;
982 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
983 return error("ClientConnectInputs() : txin values out of range");
985 if (GetValueOut() > nValueIn)
995 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
997 // Disconnect in reverse order
998 for (int i = vtx.size()-1; i >= 0; i--)
999 if (!vtx[i].DisconnectInputs(txdb))
1002 // Update block index on disk without changing it in memory.
1003 // The memory index structure will be changed after the db commits.
1006 CDiskBlockIndex blockindexPrev(pindex->pprev);
1007 blockindexPrev.hashNext = 0;
1008 if (!txdb.WriteBlockIndex(blockindexPrev))
1009 return error("DisconnectBlock() : WriteBlockIndex failed");
1015 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1017 // Check it again in case a previous version let a bad block in
1021 //// issue here: it doesn't know the version
1022 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1024 map<uint256, CTxIndex> mapQueuedChanges;
1026 BOOST_FOREACH(CTransaction& tx, vtx)
1028 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1029 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1031 if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false))
1034 // Write queued txindex changes
1035 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1037 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1038 return error("ConnectBlock() : UpdateTxIndex failed");
1041 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1044 // Update block index on disk without changing it in memory.
1045 // The memory index structure will be changed after the db commits.
1048 CDiskBlockIndex blockindexPrev(pindex->pprev);
1049 blockindexPrev.hashNext = pindex->GetBlockHash();
1050 if (!txdb.WriteBlockIndex(blockindexPrev))
1051 return error("ConnectBlock() : WriteBlockIndex failed");
1054 // Watch for transactions paying to me
1055 BOOST_FOREACH(CTransaction& tx, vtx)
1056 SyncWithWallets(tx, this, true);
1061 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1063 printf("REORGANIZE\n");
1066 CBlockIndex* pfork = pindexBest;
1067 CBlockIndex* plonger = pindexNew;
1068 while (pfork != plonger)
1070 while (plonger->nHeight > pfork->nHeight)
1071 if (!(plonger = plonger->pprev))
1072 return error("Reorganize() : plonger->pprev is null");
1073 if (pfork == plonger)
1075 if (!(pfork = pfork->pprev))
1076 return error("Reorganize() : pfork->pprev is null");
1079 // List of what to disconnect
1080 vector<CBlockIndex*> vDisconnect;
1081 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1082 vDisconnect.push_back(pindex);
1084 // List of what to connect
1085 vector<CBlockIndex*> vConnect;
1086 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1087 vConnect.push_back(pindex);
1088 reverse(vConnect.begin(), vConnect.end());
1090 // Disconnect shorter branch
1091 vector<CTransaction> vResurrect;
1092 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1095 if (!block.ReadFromDisk(pindex))
1096 return error("Reorganize() : ReadFromDisk for disconnect failed");
1097 if (!block.DisconnectBlock(txdb, pindex))
1098 return error("Reorganize() : DisconnectBlock failed");
1100 // Queue memory transactions to resurrect
1101 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1102 if (!tx.IsCoinBase())
1103 vResurrect.push_back(tx);
1106 // Connect longer branch
1107 vector<CTransaction> vDelete;
1108 for (int i = 0; i < vConnect.size(); i++)
1110 CBlockIndex* pindex = vConnect[i];
1112 if (!block.ReadFromDisk(pindex))
1113 return error("Reorganize() : ReadFromDisk for connect failed");
1114 if (!block.ConnectBlock(txdb, pindex))
1118 return error("Reorganize() : ConnectBlock failed");
1121 // Queue memory transactions to delete
1122 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1123 vDelete.push_back(tx);
1125 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1126 return error("Reorganize() : WriteHashBestChain failed");
1128 // Make sure it's successfully written to disk before changing memory structure
1129 if (!txdb.TxnCommit())
1130 return error("Reorganize() : TxnCommit failed");
1132 // Disconnect shorter branch
1133 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1135 pindex->pprev->pnext = NULL;
1137 // Connect longer branch
1138 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1140 pindex->pprev->pnext = pindex;
1142 // Resurrect memory transactions that were in the disconnected branch
1143 BOOST_FOREACH(CTransaction& tx, vResurrect)
1144 tx.AcceptToMemoryPool(txdb, false);
1146 // Delete redundant memory transactions that are in the connected branch
1147 BOOST_FOREACH(CTransaction& tx, vDelete)
1148 tx.RemoveFromMemoryPool();
1154 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1156 uint256 hash = GetHash();
1159 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1161 txdb.WriteHashBestChain(hash);
1162 if (!txdb.TxnCommit())
1163 return error("SetBestChain() : TxnCommit failed");
1164 pindexGenesisBlock = pindexNew;
1166 else if (hashPrevBlock == hashBestChain)
1168 // Adding to current best branch
1169 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1172 InvalidChainFound(pindexNew);
1173 return error("SetBestChain() : ConnectBlock failed");
1175 if (!txdb.TxnCommit())
1176 return error("SetBestChain() : TxnCommit failed");
1178 // Add to current best branch
1179 pindexNew->pprev->pnext = pindexNew;
1181 // Delete redundant memory transactions
1182 BOOST_FOREACH(CTransaction& tx, vtx)
1183 tx.RemoveFromMemoryPool();
1188 if (!Reorganize(txdb, pindexNew))
1191 InvalidChainFound(pindexNew);
1192 return error("SetBestChain() : Reorganize failed");
1196 // Update best block in wallet (so we can detect restored wallets)
1197 if (!IsInitialBlockDownload())
1199 const CBlockLocator locator(pindexNew);
1200 ::SetBestChain(locator);
1204 hashBestChain = hash;
1205 pindexBest = pindexNew;
1206 nBestHeight = pindexBest->nHeight;
1207 bnBestChainWork = pindexNew->bnChainWork;
1208 nTimeBestReceived = GetTime();
1209 nTransactionsUpdated++;
1210 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1216 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1218 // Check for duplicate
1219 uint256 hash = GetHash();
1220 if (mapBlockIndex.count(hash))
1221 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1223 // Construct new block index object
1224 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1226 return error("AddToBlockIndex() : new CBlockIndex failed");
1227 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1228 pindexNew->phashBlock = &((*mi).first);
1229 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1230 if (miPrev != mapBlockIndex.end())
1232 pindexNew->pprev = (*miPrev).second;
1233 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1235 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1239 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1240 if (!txdb.TxnCommit())
1244 if (pindexNew->bnChainWork > bnBestChainWork)
1245 if (!SetBestChain(txdb, pindexNew))
1250 if (pindexNew == pindexBest)
1252 // Notify UI to display prev block's coinbase if it was ours
1253 static uint256 hashPrevBestCoinBase;
1254 UpdatedTransaction(hashPrevBestCoinBase);
1255 hashPrevBestCoinBase = vtx[0].GetHash();
1265 bool CBlock::CheckBlock() const
1267 // These are checks that are independent of context
1268 // that can be verified before saving an orphan block.
1271 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1272 return DoS(100, error("CheckBlock() : size limits failed"));
1274 // Check proof of work matches claimed amount
1275 if (!CheckProofOfWork(GetHash(), nBits))
1276 return DoS(50, error("CheckBlock() : proof of work failed"));
1279 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1280 return error("CheckBlock() : block timestamp too far in the future");
1282 // First transaction must be coinbase, the rest must not be
1283 if (vtx.empty() || !vtx[0].IsCoinBase())
1284 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1285 for (int i = 1; i < vtx.size(); i++)
1286 if (vtx[i].IsCoinBase())
1287 return DoS(100, error("CheckBlock() : more than one coinbase"));
1289 // Check transactions
1290 BOOST_FOREACH(const CTransaction& tx, vtx)
1291 if (!tx.CheckTransaction())
1292 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1294 // Check that it's not full of nonstandard transactions
1295 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1296 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1299 if (hashMerkleRoot != BuildMerkleTree())
1300 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1305 bool CBlock::AcceptBlock()
1307 // Check for duplicate
1308 uint256 hash = GetHash();
1309 if (mapBlockIndex.count(hash))
1310 return error("AcceptBlock() : block already in mapBlockIndex");
1312 // Get prev block index
1313 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1314 if (mi == mapBlockIndex.end())
1315 return DoS(10, error("AcceptBlock() : prev block not found"));
1316 CBlockIndex* pindexPrev = (*mi).second;
1317 int nHeight = pindexPrev->nHeight+1;
1319 // Check proof of work
1320 if (nBits != GetNextWorkRequired(pindexPrev))
1321 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1323 // Check timestamp against prev
1324 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1325 return error("AcceptBlock() : block's timestamp is too early");
1327 // Check that all transactions are finalized
1328 BOOST_FOREACH(const CTransaction& tx, vtx)
1329 if (!tx.IsFinal(nHeight, GetBlockTime()))
1330 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1332 // Check that the block chain matches the known block chain up to a checkpoint
1333 if (!Checkpoints::CheckBlock(nHeight, hash))
1334 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1336 // Write block to history file
1337 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1338 return error("AcceptBlock() : out of disk space");
1339 unsigned int nFile = -1;
1340 unsigned int nBlockPos = 0;
1341 if (!WriteToDisk(nFile, nBlockPos))
1342 return error("AcceptBlock() : WriteToDisk failed");
1343 if (!AddToBlockIndex(nFile, nBlockPos))
1344 return error("AcceptBlock() : AddToBlockIndex failed");
1346 // Relay inventory, but don't relay old inventory during initial block download
1347 if (hashBestChain == hash)
1348 CRITICAL_BLOCK(cs_vNodes)
1349 BOOST_FOREACH(CNode* pnode, vNodes)
1350 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1351 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1356 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1358 // Check for duplicate
1359 uint256 hash = pblock->GetHash();
1360 if (mapBlockIndex.count(hash))
1361 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1362 if (mapOrphanBlocks.count(hash))
1363 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1365 // Preliminary checks
1366 if (!pblock->CheckBlock())
1367 return error("ProcessBlock() : CheckBlock FAILED");
1369 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1370 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1372 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1373 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1376 pfrom->Misbehaving(100);
1377 return error("ProcessBlock() : block with timestamp before last checkpoint");
1380 bnNewBlock.SetCompact(pblock->nBits);
1382 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1383 if (bnNewBlock > bnRequired)
1385 pfrom->Misbehaving(100);
1386 return error("ProcessBlock() : block with too little proof-of-work");
1391 // If don't already have its previous block, shunt it off to holding area until we get it
1392 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1394 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1395 CBlock* pblock2 = new CBlock(*pblock);
1396 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1397 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1399 // Ask this guy to fill in what we're missing
1401 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1406 if (!pblock->AcceptBlock())
1407 return error("ProcessBlock() : AcceptBlock FAILED");
1409 // Recursively process any orphan blocks that depended on this one
1410 vector<uint256> vWorkQueue;
1411 vWorkQueue.push_back(hash);
1412 for (int i = 0; i < vWorkQueue.size(); i++)
1414 uint256 hashPrev = vWorkQueue[i];
1415 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1416 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1419 CBlock* pblockOrphan = (*mi).second;
1420 if (pblockOrphan->AcceptBlock())
1421 vWorkQueue.push_back(pblockOrphan->GetHash());
1422 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1423 delete pblockOrphan;
1425 mapOrphanBlocksByPrev.erase(hashPrev);
1428 printf("ProcessBlock: ACCEPTED\n");
1439 bool CheckDiskSpace(uint64 nAdditionalBytes)
1441 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1443 // Check for 15MB because database could create another 10MB log file at any time
1444 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1447 string strMessage = _("Warning: Disk space is low ");
1448 strMiscWarning = strMessage;
1449 printf("*** %s\n", strMessage.c_str());
1450 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1451 CreateThread(Shutdown, NULL);
1457 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1461 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1464 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1466 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1475 static unsigned int nCurrentBlockFile = 1;
1477 FILE* AppendBlockFile(unsigned int& nFileRet)
1482 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1485 if (fseek(file, 0, SEEK_END) != 0)
1487 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1488 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1490 nFileRet = nCurrentBlockFile;
1494 nCurrentBlockFile++;
1498 bool LoadBlockIndex(bool fAllowNew)
1502 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1503 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1504 pchMessageStart[0] = 0xfa;
1505 pchMessageStart[1] = 0xbf;
1506 pchMessageStart[2] = 0xb5;
1507 pchMessageStart[3] = 0xda;
1514 if (!txdb.LoadBlockIndex())
1519 // Init with genesis block
1521 if (mapBlockIndex.empty())
1527 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1528 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1529 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1530 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1531 // vMerkleTree: 4a5e1e
1534 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1536 txNew.vin.resize(1);
1537 txNew.vout.resize(1);
1538 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1539 txNew.vout[0].nValue = 50 * COIN;
1540 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1542 block.vtx.push_back(txNew);
1543 block.hashPrevBlock = 0;
1544 block.hashMerkleRoot = block.BuildMerkleTree();
1546 block.nTime = 1231006505;
1547 block.nBits = 0x1d00ffff;
1548 block.nNonce = 2083236893;
1552 block.nTime = 1296688602;
1553 block.nBits = 0x1d07fff8;
1554 block.nNonce = 384568319;
1558 printf("%s\n", block.GetHash().ToString().c_str());
1559 printf("%s\n", hashGenesisBlock.ToString().c_str());
1560 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1561 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1563 assert(block.GetHash() == hashGenesisBlock);
1565 // Start new block file
1567 unsigned int nBlockPos;
1568 if (!block.WriteToDisk(nFile, nBlockPos))
1569 return error("LoadBlockIndex() : writing genesis block to disk failed");
1570 if (!block.AddToBlockIndex(nFile, nBlockPos))
1571 return error("LoadBlockIndex() : genesis block not accepted");
1579 void PrintBlockTree()
1581 // precompute tree structure
1582 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1583 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1585 CBlockIndex* pindex = (*mi).second;
1586 mapNext[pindex->pprev].push_back(pindex);
1588 //while (rand() % 3 == 0)
1589 // mapNext[pindex->pprev].push_back(pindex);
1592 vector<pair<int, CBlockIndex*> > vStack;
1593 vStack.push_back(make_pair(0, pindexGenesisBlock));
1596 while (!vStack.empty())
1598 int nCol = vStack.back().first;
1599 CBlockIndex* pindex = vStack.back().second;
1602 // print split or gap
1603 if (nCol > nPrevCol)
1605 for (int i = 0; i < nCol-1; i++)
1609 else if (nCol < nPrevCol)
1611 for (int i = 0; i < nCol; i++)
1618 for (int i = 0; i < nCol; i++)
1623 block.ReadFromDisk(pindex);
1624 printf("%d (%u,%u) %s %s tx %d",
1628 block.GetHash().ToString().substr(0,20).c_str(),
1629 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1632 PrintWallets(block);
1634 // put the main timechain first
1635 vector<CBlockIndex*>& vNext = mapNext[pindex];
1636 for (int i = 0; i < vNext.size(); i++)
1638 if (vNext[i]->pnext)
1640 swap(vNext[0], vNext[i]);
1646 for (int i = 0; i < vNext.size(); i++)
1647 vStack.push_back(make_pair(nCol+i, vNext[i]));
1660 //////////////////////////////////////////////////////////////////////////////
1665 map<uint256, CAlert> mapAlerts;
1666 CCriticalSection cs_mapAlerts;
1668 string GetWarnings(string strFor)
1671 string strStatusBar;
1673 if (GetBoolArg("-testsafemode"))
1676 // Misc warnings like out of disk space and clock is wrong
1677 if (strMiscWarning != "")
1680 strStatusBar = strMiscWarning;
1683 // Longer invalid proof-of-work chain
1684 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1687 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1691 CRITICAL_BLOCK(cs_mapAlerts)
1693 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1695 const CAlert& alert = item.second;
1696 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1698 nPriority = alert.nPriority;
1699 strStatusBar = alert.strStatusBar;
1704 if (strFor == "statusbar")
1705 return strStatusBar;
1706 else if (strFor == "rpc")
1708 assert(!"GetWarnings() : invalid parameter");
1712 bool CAlert::ProcessAlert()
1714 if (!CheckSignature())
1719 CRITICAL_BLOCK(cs_mapAlerts)
1721 // Cancel previous alerts
1722 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1724 const CAlert& alert = (*mi).second;
1727 printf("cancelling alert %d\n", alert.nID);
1728 mapAlerts.erase(mi++);
1730 else if (!alert.IsInEffect())
1732 printf("expiring alert %d\n", alert.nID);
1733 mapAlerts.erase(mi++);
1739 // Check if this alert has been cancelled
1740 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1742 const CAlert& alert = item.second;
1743 if (alert.Cancels(*this))
1745 printf("alert already cancelled by %d\n", alert.nID);
1751 mapAlerts.insert(make_pair(GetHash(), *this));
1754 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1766 //////////////////////////////////////////////////////////////////////////////
1772 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1776 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1777 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1779 // Don't know what it is, just say we already got one
1786 // The message start string is designed to be unlikely to occur in normal data.
1787 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1788 // a large 4-byte int at any alignment.
1789 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1792 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1794 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1795 RandAddSeedPerfmon();
1797 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1798 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1800 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1802 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1810 if (strCommand == "version")
1812 // Each connection can only send one version message
1813 if (pfrom->nVersion != 0)
1815 pfrom->Misbehaving(1);
1823 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1824 if (pfrom->nVersion == 10300)
1825 pfrom->nVersion = 300;
1826 if (pfrom->nVersion >= 106 && !vRecv.empty())
1827 vRecv >> addrFrom >> nNonce;
1828 if (pfrom->nVersion >= 106 && !vRecv.empty())
1829 vRecv >> pfrom->strSubVer;
1830 if (pfrom->nVersion >= 209 && !vRecv.empty())
1831 vRecv >> pfrom->nStartingHeight;
1833 if (pfrom->nVersion == 0)
1836 // Disconnect if we connected to ourself
1837 if (nNonce == nLocalHostNonce && nNonce > 1)
1839 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1840 pfrom->fDisconnect = true;
1844 // Be shy and don't send version until we hear
1845 if (pfrom->fInbound)
1846 pfrom->PushVersion();
1848 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1850 AddTimeData(pfrom->addr.ip, nTime);
1853 if (pfrom->nVersion >= 209)
1854 pfrom->PushMessage("verack");
1855 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1856 if (pfrom->nVersion < 209)
1857 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1859 if (!pfrom->fInbound)
1861 // Advertise our address
1862 if (addrLocalHost.IsRoutable() && !fUseProxy)
1864 CAddress addr(addrLocalHost);
1865 addr.nTime = GetAdjustedTime();
1866 pfrom->PushAddress(addr);
1869 // Get recent addresses
1870 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
1872 pfrom->PushMessage("getaddr");
1873 pfrom->fGetAddr = true;
1877 // Ask the first connected node for block updates
1878 static int nAskedForBlocks;
1879 if (!pfrom->fClient &&
1880 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
1881 (nAskedForBlocks < 1 || vNodes.size() <= 1))
1884 pfrom->PushGetBlocks(pindexBest, uint256(0));
1888 CRITICAL_BLOCK(cs_mapAlerts)
1889 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1890 item.second.RelayTo(pfrom);
1892 pfrom->fSuccessfullyConnected = true;
1894 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1896 cPeerBlockCounts.input(pfrom->nStartingHeight);
1900 else if (pfrom->nVersion == 0)
1902 // Must have a version message before anything else
1903 pfrom->Misbehaving(1);
1908 else if (strCommand == "verack")
1910 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1914 else if (strCommand == "addr")
1916 vector<CAddress> vAddr;
1919 // Don't want addr from older versions unless seeding
1920 if (pfrom->nVersion < 209)
1922 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
1924 if (vAddr.size() > 1000)
1926 pfrom->Misbehaving(20);
1927 return error("message addr size() = %d", vAddr.size());
1930 // Store the new addresses
1933 int64 nNow = GetAdjustedTime();
1934 int64 nSince = nNow - 10 * 60;
1935 BOOST_FOREACH(CAddress& addr, vAddr)
1939 // ignore IPv6 for now, since it isn't implemented anyway
1942 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1943 addr.nTime = nNow - 5 * 24 * 60 * 60;
1944 AddAddress(addr, 2 * 60 * 60, &addrDB);
1945 pfrom->AddAddressKnown(addr);
1946 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1948 // Relay to a limited number of other nodes
1949 CRITICAL_BLOCK(cs_vNodes)
1951 // Use deterministic randomness to send to the same nodes for 24 hours
1952 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
1953 static uint256 hashSalt;
1955 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1956 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
1957 hashRand = Hash(BEGIN(hashRand), END(hashRand));
1958 multimap<uint256, CNode*> mapMix;
1959 BOOST_FOREACH(CNode* pnode, vNodes)
1961 if (pnode->nVersion < 31402)
1963 unsigned int nPointer;
1964 memcpy(&nPointer, &pnode, sizeof(nPointer));
1965 uint256 hashKey = hashRand ^ nPointer;
1966 hashKey = Hash(BEGIN(hashKey), END(hashKey));
1967 mapMix.insert(make_pair(hashKey, pnode));
1969 int nRelayNodes = 2;
1970 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1971 ((*mi).second)->PushAddress(addr);
1975 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
1976 if (vAddr.size() < 1000)
1977 pfrom->fGetAddr = false;
1981 else if (strCommand == "inv")
1985 if (vInv.size() > 50000)
1987 pfrom->Misbehaving(20);
1988 return error("message inv size() = %d", vInv.size());
1992 BOOST_FOREACH(const CInv& inv, vInv)
1996 pfrom->AddInventoryKnown(inv);
1998 bool fAlreadyHave = AlreadyHave(txdb, inv);
2000 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2004 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2005 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2007 // Track requests for our stuff
2008 Inventory(inv.hash);
2013 else if (strCommand == "getdata")
2017 if (vInv.size() > 50000)
2019 pfrom->Misbehaving(20);
2020 return error("message getdata size() = %d", vInv.size());
2023 BOOST_FOREACH(const CInv& inv, vInv)
2027 printf("received getdata for: %s\n", inv.ToString().c_str());
2029 if (inv.type == MSG_BLOCK)
2031 // Send block from disk
2032 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2033 if (mi != mapBlockIndex.end())
2036 block.ReadFromDisk((*mi).second);
2037 pfrom->PushMessage("block", block);
2039 // Trigger them to send a getblocks request for the next batch of inventory
2040 if (inv.hash == pfrom->hashContinue)
2042 // Bypass PushInventory, this must send even if redundant,
2043 // and we want it right after the last block so they don't
2044 // wait for other stuff first.
2046 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2047 pfrom->PushMessage("inv", vInv);
2048 pfrom->hashContinue = 0;
2052 else if (inv.IsKnownType())
2054 // Send stream from relay memory
2055 CRITICAL_BLOCK(cs_mapRelay)
2057 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2058 if (mi != mapRelay.end())
2059 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2063 // Track requests for our stuff
2064 Inventory(inv.hash);
2069 else if (strCommand == "getblocks")
2071 CBlockLocator locator;
2073 vRecv >> locator >> hashStop;
2075 // Find the last block the caller has in the main chain
2076 CBlockIndex* pindex = locator.GetBlockIndex();
2078 // Send the rest of the chain
2080 pindex = pindex->pnext;
2081 int nLimit = 500 + locator.GetDistanceBack();
2082 unsigned int nBytes = 0;
2083 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2084 for (; pindex; pindex = pindex->pnext)
2086 if (pindex->GetBlockHash() == hashStop)
2088 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2091 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2093 block.ReadFromDisk(pindex, true);
2094 nBytes += block.GetSerializeSize(SER_NETWORK);
2095 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2097 // When this block is requested, we'll send an inv that'll make them
2098 // getblocks the next batch of inventory.
2099 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2100 pfrom->hashContinue = pindex->GetBlockHash();
2107 else if (strCommand == "getheaders")
2109 CBlockLocator locator;
2111 vRecv >> locator >> hashStop;
2113 CBlockIndex* pindex = NULL;
2114 if (locator.IsNull())
2116 // If locator is null, return the hashStop block
2117 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2118 if (mi == mapBlockIndex.end())
2120 pindex = (*mi).second;
2124 // Find the last block the caller has in the main chain
2125 pindex = locator.GetBlockIndex();
2127 pindex = pindex->pnext;
2130 vector<CBlock> vHeaders;
2131 int nLimit = 2000 + locator.GetDistanceBack();
2132 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2133 for (; pindex; pindex = pindex->pnext)
2135 vHeaders.push_back(pindex->GetBlockHeader());
2136 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2139 pfrom->PushMessage("headers", vHeaders);
2143 else if (strCommand == "tx")
2145 vector<uint256> vWorkQueue;
2146 CDataStream vMsg(vRecv);
2150 CInv inv(MSG_TX, tx.GetHash());
2151 pfrom->AddInventoryKnown(inv);
2153 bool fMissingInputs = false;
2154 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2156 SyncWithWallets(tx, NULL, true);
2157 RelayMessage(inv, vMsg);
2158 mapAlreadyAskedFor.erase(inv);
2159 vWorkQueue.push_back(inv.hash);
2161 // Recursively process any orphan transactions that depended on this one
2162 for (int i = 0; i < vWorkQueue.size(); i++)
2164 uint256 hashPrev = vWorkQueue[i];
2165 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2166 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2169 const CDataStream& vMsg = *((*mi).second);
2171 CDataStream(vMsg) >> tx;
2172 CInv inv(MSG_TX, tx.GetHash());
2174 if (tx.AcceptToMemoryPool(true))
2176 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2177 SyncWithWallets(tx, NULL, true);
2178 RelayMessage(inv, vMsg);
2179 mapAlreadyAskedFor.erase(inv);
2180 vWorkQueue.push_back(inv.hash);
2185 BOOST_FOREACH(uint256 hash, vWorkQueue)
2186 EraseOrphanTx(hash);
2188 else if (fMissingInputs)
2190 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2193 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2197 else if (strCommand == "block")
2202 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2205 CInv inv(MSG_BLOCK, block.GetHash());
2206 pfrom->AddInventoryKnown(inv);
2208 if (ProcessBlock(pfrom, &block))
2209 mapAlreadyAskedFor.erase(inv);
2210 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2214 else if (strCommand == "getaddr")
2216 // Nodes rebroadcast an addr every 24 hours
2217 pfrom->vAddrToSend.clear();
2218 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2219 CRITICAL_BLOCK(cs_mapAddresses)
2221 unsigned int nCount = 0;
2222 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2224 const CAddress& addr = item.second;
2225 if (addr.nTime > nSince)
2228 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2230 const CAddress& addr = item.second;
2231 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2232 pfrom->PushAddress(addr);
2238 else if (strCommand == "checkorder")
2243 if (!GetBoolArg("-allowreceivebyip"))
2245 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2252 /// we have a chance to check the order here
2254 // Keep giving the same key to the same ip until they use it
2255 if (!mapReuseKey.count(pfrom->addr.ip))
2256 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2258 // Send back approval of order and pubkey to use
2259 CScript scriptPubKey;
2260 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2261 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2265 else if (strCommand == "reply")
2270 CRequestTracker tracker;
2271 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2273 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2274 if (mi != pfrom->mapRequests.end())
2276 tracker = (*mi).second;
2277 pfrom->mapRequests.erase(mi);
2280 if (!tracker.IsNull())
2281 tracker.fn(tracker.param1, vRecv);
2285 else if (strCommand == "ping")
2290 else if (strCommand == "alert")
2295 if (alert.ProcessAlert())
2298 pfrom->setKnown.insert(alert.GetHash());
2299 CRITICAL_BLOCK(cs_vNodes)
2300 BOOST_FOREACH(CNode* pnode, vNodes)
2301 alert.RelayTo(pnode);
2308 // Ignore unknown commands for extensibility
2312 // Update the last seen time for this node's address
2313 if (pfrom->fNetworkNode)
2314 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2315 AddressCurrentlyConnected(pfrom->addr);
2321 bool ProcessMessages(CNode* pfrom)
2323 CDataStream& vRecv = pfrom->vRecv;
2327 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2331 // (4) message start
2340 // Scan for message start
2341 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2342 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2343 if (vRecv.end() - pstart < nHeaderSize)
2345 if (vRecv.size() > nHeaderSize)
2347 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2348 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2352 if (pstart - vRecv.begin() > 0)
2353 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2354 vRecv.erase(vRecv.begin(), pstart);
2357 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2362 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2365 string strCommand = hdr.GetCommand();
2368 unsigned int nMessageSize = hdr.nMessageSize;
2369 if (nMessageSize > MAX_SIZE)
2371 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2374 if (nMessageSize > vRecv.size())
2376 // Rewind and wait for rest of message
2377 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2382 if (vRecv.GetVersion() >= 209)
2384 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2385 unsigned int nChecksum = 0;
2386 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2387 if (nChecksum != hdr.nChecksum)
2389 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2390 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2395 // Copy message to its own buffer
2396 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2397 vRecv.ignore(nMessageSize);
2403 CRITICAL_BLOCK(cs_main)
2404 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2408 catch (std::ios_base::failure& e)
2410 if (strstr(e.what(), "end of data"))
2412 // Allow exceptions from underlength message on vRecv
2413 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());
2415 else if (strstr(e.what(), "size too large"))
2417 // Allow exceptions from overlong size
2418 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2422 PrintExceptionContinue(&e, "ProcessMessage()");
2425 catch (std::exception& e) {
2426 PrintExceptionContinue(&e, "ProcessMessage()");
2428 PrintExceptionContinue(NULL, "ProcessMessage()");
2432 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2440 bool SendMessages(CNode* pto, bool fSendTrickle)
2442 CRITICAL_BLOCK(cs_main)
2444 // Don't send anything until we get their version message
2445 if (pto->nVersion == 0)
2449 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2450 pto->PushMessage("ping");
2452 // Resend wallet transactions that haven't gotten in a block yet
2453 ResendWalletTransactions();
2455 // Address refresh broadcast
2456 static int64 nLastRebroadcast;
2457 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2459 nLastRebroadcast = GetTime();
2460 CRITICAL_BLOCK(cs_vNodes)
2462 BOOST_FOREACH(CNode* pnode, vNodes)
2464 // Periodically clear setAddrKnown to allow refresh broadcasts
2465 pnode->setAddrKnown.clear();
2467 // Rebroadcast our address
2468 if (addrLocalHost.IsRoutable() && !fUseProxy)
2470 CAddress addr(addrLocalHost);
2471 addr.nTime = GetAdjustedTime();
2472 pnode->PushAddress(addr);
2478 // Clear out old addresses periodically so it's not too much work at once
2479 static int64 nLastClear;
2480 if (nLastClear == 0)
2481 nLastClear = GetTime();
2482 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2484 nLastClear = GetTime();
2485 CRITICAL_BLOCK(cs_mapAddresses)
2488 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2489 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2490 mi != mapAddresses.end();)
2492 const CAddress& addr = (*mi).second;
2493 if (addr.nTime < nSince)
2495 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2497 addrdb.EraseAddress(addr);
2498 mapAddresses.erase(mi++);
2512 vector<CAddress> vAddr;
2513 vAddr.reserve(pto->vAddrToSend.size());
2514 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2516 // returns true if wasn't already contained in the set
2517 if (pto->setAddrKnown.insert(addr).second)
2519 vAddr.push_back(addr);
2520 // receiver rejects addr messages larger than 1000
2521 if (vAddr.size() >= 1000)
2523 pto->PushMessage("addr", vAddr);
2528 pto->vAddrToSend.clear();
2530 pto->PushMessage("addr", vAddr);
2535 // Message: inventory
2538 vector<CInv> vInvWait;
2539 CRITICAL_BLOCK(pto->cs_inventory)
2541 vInv.reserve(pto->vInventoryToSend.size());
2542 vInvWait.reserve(pto->vInventoryToSend.size());
2543 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2545 if (pto->setInventoryKnown.count(inv))
2548 // trickle out tx inv to protect privacy
2549 if (inv.type == MSG_TX && !fSendTrickle)
2551 // 1/4 of tx invs blast to all immediately
2552 static uint256 hashSalt;
2554 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2555 uint256 hashRand = inv.hash ^ hashSalt;
2556 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2557 bool fTrickleWait = ((hashRand & 3) != 0);
2559 // always trickle our own transactions
2563 if (GetTransaction(inv.hash, wtx))
2565 fTrickleWait = true;
2570 vInvWait.push_back(inv);
2575 // returns true if wasn't already contained in the set
2576 if (pto->setInventoryKnown.insert(inv).second)
2578 vInv.push_back(inv);
2579 if (vInv.size() >= 1000)
2581 pto->PushMessage("inv", vInv);
2586 pto->vInventoryToSend = vInvWait;
2589 pto->PushMessage("inv", vInv);
2595 vector<CInv> vGetData;
2596 int64 nNow = GetTime() * 1000000;
2598 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2600 const CInv& inv = (*pto->mapAskFor.begin()).second;
2601 if (!AlreadyHave(txdb, inv))
2603 printf("sending getdata: %s\n", inv.ToString().c_str());
2604 vGetData.push_back(inv);
2605 if (vGetData.size() >= 1000)
2607 pto->PushMessage("getdata", vGetData);
2611 mapAlreadyAskedFor[inv] = nNow;
2612 pto->mapAskFor.erase(pto->mapAskFor.begin());
2614 if (!vGetData.empty())
2615 pto->PushMessage("getdata", vGetData);
2634 //////////////////////////////////////////////////////////////////////////////
2639 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2641 unsigned char* pdata = (unsigned char*)pbuffer;
2642 unsigned int blocks = 1 + ((len + 8) / 64);
2643 unsigned char* pend = pdata + 64 * blocks;
2644 memset(pdata + len, 0, 64 * blocks - len);
2646 unsigned int bits = len * 8;
2647 pend[-1] = (bits >> 0) & 0xff;
2648 pend[-2] = (bits >> 8) & 0xff;
2649 pend[-3] = (bits >> 16) & 0xff;
2650 pend[-4] = (bits >> 24) & 0xff;
2654 static const unsigned int pSHA256InitState[8] =
2655 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2657 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2660 unsigned char data[64];
2664 for (int i = 0; i < 16; i++)
2665 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2667 for (int i = 0; i < 8; i++)
2668 ctx.h[i] = ((uint32_t*)pinit)[i];
2670 SHA256_Update(&ctx, data, sizeof(data));
2671 for (int i = 0; i < 8; i++)
2672 ((uint32_t*)pstate)[i] = ctx.h[i];
2676 // ScanHash scans nonces looking for a hash with at least some zero bits.
2677 // It operates on big endian data. Caller does the byte reversing.
2678 // All input buffers are 16-byte aligned. nNonce is usually preserved
2679 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2680 // the block is rebuilt and nNonce starts over at zero.
2682 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2684 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2688 // Hash pdata using pmidstate as the starting state into
2689 // preformatted buffer phash1, then hash phash1 into phash
2691 SHA256Transform(phash1, pdata, pmidstate);
2692 SHA256Transform(phash, phash1, pSHA256InitState);
2694 // Return the nonce if the hash has at least some zero bits,
2695 // caller will check if it has enough to reach the target
2696 if (((unsigned short*)phash)[14] == 0)
2699 // If nothing found after trying for a while, return -1
2700 if ((nNonce & 0xffff) == 0)
2702 nHashesDone = 0xffff+1;
2708 // Some explaining would be appreciated
2713 set<uint256> setDependsOn;
2716 COrphan(CTransaction* ptxIn)
2724 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2725 BOOST_FOREACH(uint256 hash, setDependsOn)
2726 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2731 CBlock* CreateNewBlock(CReserveKey& reservekey)
2733 CBlockIndex* pindexPrev = pindexBest;
2736 auto_ptr<CBlock> pblock(new CBlock());
2740 // Create coinbase tx
2742 txNew.vin.resize(1);
2743 txNew.vin[0].prevout.SetNull();
2744 txNew.vout.resize(1);
2745 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2747 // Add our coinbase tx as first transaction
2748 pblock->vtx.push_back(txNew);
2750 // Collect memory pool transactions into the block
2752 CRITICAL_BLOCK(cs_main)
2753 CRITICAL_BLOCK(cs_mapTransactions)
2757 // Priority order to process transactions
2758 list<COrphan> vOrphan; // list memory doesn't move
2759 map<uint256, vector<COrphan*> > mapDependers;
2760 multimap<double, CTransaction*> mapPriority;
2761 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2763 CTransaction& tx = (*mi).second;
2764 if (tx.IsCoinBase() || !tx.IsFinal())
2767 COrphan* porphan = NULL;
2768 double dPriority = 0;
2769 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2771 // Read prev transaction
2772 CTransaction txPrev;
2774 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2776 // Has to wait for dependencies
2779 // Use list for automatic deletion
2780 vOrphan.push_back(COrphan(&tx));
2781 porphan = &vOrphan.back();
2783 mapDependers[txin.prevout.hash].push_back(porphan);
2784 porphan->setDependsOn.insert(txin.prevout.hash);
2787 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2789 // Read block header
2790 int nConf = txindex.GetDepthInMainChain();
2792 dPriority += (double)nValueIn * nConf;
2794 if (fDebug && GetBoolArg("-printpriority"))
2795 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2798 // Priority is sum(valuein * age) / txsize
2799 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2802 porphan->dPriority = dPriority;
2804 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2806 if (fDebug && GetBoolArg("-printpriority"))
2808 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2815 // Collect transactions into block
2816 map<uint256, CTxIndex> mapTestPool;
2817 uint64 nBlockSize = 1000;
2818 int nBlockSigOps = 100;
2819 while (!mapPriority.empty())
2821 // Take highest priority transaction off priority queue
2822 double dPriority = -(*mapPriority.begin()).first;
2823 CTransaction& tx = *(*mapPriority.begin()).second;
2824 mapPriority.erase(mapPriority.begin());
2827 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2828 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2830 int nTxSigOps = tx.GetSigOpCount();
2831 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2834 // Transaction fee required depends on block size
2835 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2836 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true);
2838 // Connecting shouldn't fail due to dependency on other memory pool transactions
2839 // because we're already processing them in order of dependency
2840 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2841 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
2843 swap(mapTestPool, mapTestPoolTmp);
2846 pblock->vtx.push_back(tx);
2847 nBlockSize += nTxSize;
2848 nBlockSigOps += nTxSigOps;
2850 // Add transactions that depend on this one to the priority queue
2851 uint256 hash = tx.GetHash();
2852 if (mapDependers.count(hash))
2854 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2856 if (!porphan->setDependsOn.empty())
2858 porphan->setDependsOn.erase(hash);
2859 if (porphan->setDependsOn.empty())
2860 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2866 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2869 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
2870 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2871 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2872 pblock->nBits = GetNextWorkRequired(pindexPrev);
2875 return pblock.release();
2879 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
2881 // Update nExtraNonce
2882 static uint256 hashPrevBlock;
2883 if (hashPrevBlock != pblock->hashPrevBlock)
2886 hashPrevBlock = pblock->hashPrevBlock;
2889 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
2890 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2894 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
2897 // Prebuild hash buffers
2904 uint256 hashPrevBlock;
2905 uint256 hashMerkleRoot;
2908 unsigned int nNonce;
2911 unsigned char pchPadding0[64];
2913 unsigned char pchPadding1[64];
2916 memset(&tmp, 0, sizeof(tmp));
2918 tmp.block.nVersion = pblock->nVersion;
2919 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
2920 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
2921 tmp.block.nTime = pblock->nTime;
2922 tmp.block.nBits = pblock->nBits;
2923 tmp.block.nNonce = pblock->nNonce;
2925 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2926 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2928 // Byte swap all the input buffer
2929 for (int i = 0; i < sizeof(tmp)/4; i++)
2930 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2932 // Precalc the first half of the first hash, which stays constant
2933 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
2935 memcpy(pdata, &tmp.block, 128);
2936 memcpy(phash1, &tmp.hash1, 64);
2940 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
2942 uint256 hash = pblock->GetHash();
2943 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2945 if (hash > hashTarget)
2949 printf("BitcoinMiner:\n");
2950 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2952 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2953 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2956 CRITICAL_BLOCK(cs_main)
2958 if (pblock->hashPrevBlock != hashBestChain)
2959 return error("BitcoinMiner : generated block is stale");
2961 // Remove key from key pool
2962 reservekey.KeepKey();
2964 // Track how many getdata requests this block gets
2965 CRITICAL_BLOCK(wallet.cs_wallet)
2966 wallet.mapRequestCount[pblock->GetHash()] = 0;
2968 // Process this block the same as if we had received it from another node
2969 if (!ProcessBlock(NULL, pblock))
2970 return error("BitcoinMiner : ProcessBlock, block not accepted");
2976 void static ThreadBitcoinMiner(void* parg);
2978 void static BitcoinMiner(CWallet *pwallet)
2980 printf("BitcoinMiner started\n");
2981 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2983 // Each thread has its own key and counter
2984 CReserveKey reservekey(pwallet);
2985 unsigned int nExtraNonce = 0;
2987 while (fGenerateBitcoins)
2989 if (AffinityBugWorkaround(ThreadBitcoinMiner))
2993 while (vNodes.empty() || IsInitialBlockDownload())
2998 if (!fGenerateBitcoins)
3006 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3007 CBlockIndex* pindexPrev = pindexBest;
3009 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3012 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3014 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3018 // Prebuild hash buffers
3020 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3021 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3022 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3024 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3026 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3027 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3033 int64 nStart = GetTime();
3034 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3036 uint256& hash = *alignup<16>(hashbuf);
3039 unsigned int nHashesDone = 0;
3040 unsigned int nNonceFound;
3043 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3044 (char*)&hash, nHashesDone);
3046 // Check if something found
3047 if (nNonceFound != -1)
3049 for (int i = 0; i < sizeof(hash)/4; i++)
3050 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3052 if (hash <= hashTarget)
3055 pblock->nNonce = ByteReverse(nNonceFound);
3056 assert(hash == pblock->GetHash());
3058 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3059 CheckWork(pblock.get(), *pwalletMain, reservekey);
3060 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3066 static int64 nHashCounter;
3067 if (nHPSTimerStart == 0)
3069 nHPSTimerStart = GetTimeMillis();
3073 nHashCounter += nHashesDone;
3074 if (GetTimeMillis() - nHPSTimerStart > 4000)
3076 static CCriticalSection cs;
3079 if (GetTimeMillis() - nHPSTimerStart > 4000)
3081 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3082 nHPSTimerStart = GetTimeMillis();
3084 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3085 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3086 static int64 nLogTime;
3087 if (GetTime() - nLogTime > 30 * 60)
3089 nLogTime = GetTime();
3090 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3091 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3097 // Check for stop or if block needs to be rebuilt
3100 if (!fGenerateBitcoins)
3102 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3106 if (nBlockNonce >= 0xffff0000)
3108 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3110 if (pindexPrev != pindexBest)
3113 // Update nTime every few seconds
3114 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3115 nBlockTime = ByteReverse(pblock->nTime);
3120 void static ThreadBitcoinMiner(void* parg)
3122 CWallet* pwallet = (CWallet*)parg;
3125 vnThreadsRunning[3]++;
3126 BitcoinMiner(pwallet);
3127 vnThreadsRunning[3]--;
3129 catch (std::exception& e) {
3130 vnThreadsRunning[3]--;
3131 PrintException(&e, "ThreadBitcoinMiner()");
3133 vnThreadsRunning[3]--;
3134 PrintException(NULL, "ThreadBitcoinMiner()");
3136 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3138 if (vnThreadsRunning[3] == 0)
3140 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3144 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3146 if (fGenerateBitcoins != fGenerate)
3148 fGenerateBitcoins = fGenerate;
3149 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3152 if (fGenerateBitcoins)
3154 int nProcessors = boost::thread::hardware_concurrency();
3155 printf("%d processors\n", nProcessors);
3156 if (nProcessors < 1)
3158 if (fLimitProcessors && nProcessors > nLimitProcessors)
3159 nProcessors = nLimitProcessors;
3160 int nAddThreads = nProcessors - vnThreadsRunning[3];
3161 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3162 for (int i = 0; i < nAddThreads; i++)
3164 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3165 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");