1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
8 #include "cryptopp/sha.h"
9 #include <boost/filesystem.hpp>
10 #include <boost/filesystem/fstream.hpp>
13 using namespace boost;
19 CCriticalSection cs_setpwalletRegistered;
20 set<CWallet*> setpwalletRegistered;
22 CCriticalSection cs_main;
24 map<uint256, CTransaction> mapTransactions;
25 CCriticalSection cs_mapTransactions;
26 unsigned int nTransactionsUpdated = 0;
27 map<COutPoint, CInPoint> mapNextTx;
29 map<uint256, CBlockIndex*> mapBlockIndex;
30 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
31 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
32 int nTotalBlocksEstimate = 134444; // Conservative estimate of total nr of blocks on main chain
33 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
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 map<uint256, CBlock*> mapOrphanBlocks;
43 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
45 map<uint256, CDataStream*> mapOrphanTransactions;
46 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
53 int fGenerateBitcoins = false;
54 int64 nTransactionFee = 0;
55 int fLimitProcessors = false;
56 int nLimitProcessors = 1;
57 int fMinimizeToTray = true;
58 int fMinimizeOnClose = true;
71 //////////////////////////////////////////////////////////////////////////////
73 // dispatching functions
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 bool static IsFromMe(CTransaction& tx)
94 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
95 if (pwallet->IsFromMe(tx))
100 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
102 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
103 if (pwallet->GetTransaction(hashTx,wtx))
108 void static EraseFromWallets(uint256 hash)
110 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
111 pwallet->EraseFromWallet(hash);
114 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
116 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
117 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
120 void static SetBestChain(const CBlockLocator& loc)
122 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
123 pwallet->SetBestChain(loc);
126 void static UpdatedTransaction(const uint256& hashTx)
128 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
129 pwallet->UpdatedTransaction(hashTx);
132 void static PrintWallets(const CBlock& block)
134 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
135 pwallet->PrintWallet(block);
138 void static Inventory(const uint256& hash)
140 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
141 pwallet->Inventory(hash);
144 void static ResendWalletTransactions()
146 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
147 pwallet->ResendWalletTransactions();
156 //////////////////////////////////////////////////////////////////////////////
158 // mapOrphanTransactions
161 void static AddOrphanTx(const CDataStream& vMsg)
164 CDataStream(vMsg) >> tx;
165 uint256 hash = tx.GetHash();
166 if (mapOrphanTransactions.count(hash))
168 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
169 BOOST_FOREACH(const CTxIn& txin, tx.vin)
170 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
173 void static EraseOrphanTx(uint256 hash)
175 if (!mapOrphanTransactions.count(hash))
177 const CDataStream* pvMsg = mapOrphanTransactions[hash];
179 CDataStream(*pvMsg) >> tx;
180 BOOST_FOREACH(const CTxIn& txin, tx.vin)
182 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
183 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
185 if ((*mi).second == pvMsg)
186 mapOrphanTransactionsByPrev.erase(mi++);
192 mapOrphanTransactions.erase(hash);
202 //////////////////////////////////////////////////////////////////////////////
204 // CTransaction and CTxIndex
207 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
210 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
212 if (!ReadFromDisk(txindexRet.pos))
214 if (prevout.n >= vout.size())
222 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
225 return ReadFromDisk(txdb, prevout, txindex);
228 bool CTransaction::ReadFromDisk(COutPoint prevout)
232 return ReadFromDisk(txdb, prevout, txindex);
237 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
249 // Load the block this tx is in
251 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
253 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
258 // Update the tx's hashBlock
259 hashBlock = pblock->GetHash();
261 // Locate the transaction
262 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
263 if (pblock->vtx[nIndex] == *(CTransaction*)this)
265 if (nIndex == pblock->vtx.size())
267 vMerkleBranch.clear();
269 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
273 // Fill in merkle branch
274 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
277 // Is the tx in a block that's in the main chain
278 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
279 if (mi == mapBlockIndex.end())
281 CBlockIndex* pindex = (*mi).second;
282 if (!pindex || !pindex->IsInMainChain())
285 return pindexBest->nHeight - pindex->nHeight + 1;
294 bool CTransaction::CheckTransaction() const
296 // Basic checks that don't depend on any context
297 if (vin.empty() || vout.empty())
298 return error("CTransaction::CheckTransaction() : vin or vout empty");
301 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
302 return error("CTransaction::CheckTransaction() : size limits failed");
304 // Check for negative or overflow output values
306 BOOST_FOREACH(const CTxOut& txout, vout)
308 if (txout.nValue < 0)
309 return error("CTransaction::CheckTransaction() : txout.nValue negative");
310 if (txout.nValue > MAX_MONEY)
311 return error("CTransaction::CheckTransaction() : txout.nValue too high");
312 nValueOut += txout.nValue;
313 if (!MoneyRange(nValueOut))
314 return error("CTransaction::CheckTransaction() : txout total out of range");
317 // Check for duplicate inputs
318 set<COutPoint> vInOutPoints;
319 BOOST_FOREACH(const CTxIn& txin, vin)
321 if (vInOutPoints.count(txin.prevout))
323 vInOutPoints.insert(txin.prevout);
328 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
329 return error("CTransaction::CheckTransaction() : coinbase script size");
333 BOOST_FOREACH(const CTxIn& txin, vin)
334 if (txin.prevout.IsNull())
335 return error("CTransaction::CheckTransaction() : prevout is null");
341 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
344 *pfMissingInputs = false;
346 if (!CheckTransaction())
347 return error("AcceptToMemoryPool() : CheckTransaction failed");
349 // Coinbase is only valid in a block, not as a loose transaction
351 return error("AcceptToMemoryPool() : coinbase as individual tx");
353 // To help v0.1.5 clients who would see it as a negative number
354 if ((int64)nLockTime > INT_MAX)
355 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
358 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
359 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
360 // attacks disallow transactions with more than one SigOp per 34 bytes.
361 // 34 bytes because a TxOut is:
362 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
363 if (GetSigOpCount() > nSize / 34 || nSize < 100)
364 return error("AcceptToMemoryPool() : nonstandard transaction");
366 // Rather not work on nonstandard transactions (unless -testnet)
367 if (!fTestNet && !IsStandard())
368 return error("AcceptToMemoryPool() : nonstandard transaction type");
370 // Do we already have it?
371 uint256 hash = GetHash();
372 CRITICAL_BLOCK(cs_mapTransactions)
373 if (mapTransactions.count(hash))
376 if (txdb.ContainsTx(hash))
379 // Check for conflicts with in-memory transactions
380 CTransaction* ptxOld = NULL;
381 for (int i = 0; i < vin.size(); i++)
383 COutPoint outpoint = vin[i].prevout;
384 if (mapNextTx.count(outpoint))
386 // Disable replacement feature for now
389 // Allow replacing with a newer version of the same transaction
392 ptxOld = mapNextTx[outpoint].ptx;
393 if (ptxOld->IsFinal())
395 if (!IsNewerThan(*ptxOld))
397 for (int i = 0; i < vin.size(); i++)
399 COutPoint outpoint = vin[i].prevout;
400 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
409 // Check against previous transactions
410 map<uint256, CTxIndex> mapUnused;
412 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
415 *pfMissingInputs = true;
416 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
419 // Don't accept it if it can't get into a block
420 if (nFees < GetMinFee(1000, true, true))
421 return error("AcceptToMemoryPool() : not enough fees");
423 // Continuously rate-limit free transactions
424 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
425 // be annoying or make other's transactions take longer to confirm.
426 if (nFees < MIN_RELAY_TX_FEE)
428 static CCriticalSection cs;
429 static double dFreeCount;
430 static int64 nLastTime;
431 int64 nNow = GetTime();
435 // Use an exponentially decaying ~10-minute window:
436 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
438 // -limitfreerelay unit is thousand-bytes-per-minute
439 // At default rate it would take over a month to fill 1GB
440 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
441 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
443 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
449 // Store transaction in memory
450 CRITICAL_BLOCK(cs_mapTransactions)
454 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
455 ptxOld->RemoveFromMemoryPool();
457 AddToMemoryPoolUnchecked();
460 ///// are we sure this is ok when loading transactions or restoring block txes
461 // If updated, erase old tx from wallet
463 EraseFromWallets(ptxOld->GetHash());
465 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
469 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
472 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
475 bool CTransaction::AddToMemoryPoolUnchecked()
477 // Add to memory pool without checking anything. Don't call this directly,
478 // call AcceptToMemoryPool to properly check the transaction first.
479 CRITICAL_BLOCK(cs_mapTransactions)
481 uint256 hash = GetHash();
482 mapTransactions[hash] = *this;
483 for (int i = 0; i < vin.size(); i++)
484 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
485 nTransactionsUpdated++;
491 bool CTransaction::RemoveFromMemoryPool()
493 // Remove transaction from memory pool
494 CRITICAL_BLOCK(cs_mapTransactions)
496 BOOST_FOREACH(const CTxIn& txin, vin)
497 mapNextTx.erase(txin.prevout);
498 mapTransactions.erase(GetHash());
499 nTransactionsUpdated++;
509 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
511 if (hashBlock == 0 || nIndex == -1)
514 // Find the block it claims to be in
515 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
516 if (mi == mapBlockIndex.end())
518 CBlockIndex* pindex = (*mi).second;
519 if (!pindex || !pindex->IsInMainChain())
522 // Make sure the merkle branch connects to this block
523 if (!fMerkleVerified)
525 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
527 fMerkleVerified = true;
530 nHeightRet = pindex->nHeight;
531 return pindexBest->nHeight - pindex->nHeight + 1;
535 int CMerkleTx::GetBlocksToMaturity() const
539 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
543 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
547 if (!IsInMainChain() && !ClientConnectInputs())
549 return CTransaction::AcceptToMemoryPool(txdb, false);
553 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
557 bool CMerkleTx::AcceptToMemoryPool()
560 return AcceptToMemoryPool(txdb);
565 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
567 CRITICAL_BLOCK(cs_mapTransactions)
569 // Add previous supporting transactions first
570 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
572 if (!tx.IsCoinBase())
574 uint256 hash = tx.GetHash();
575 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
576 tx.AcceptToMemoryPool(txdb, fCheckInputs);
579 return AcceptToMemoryPool(txdb, fCheckInputs);
584 bool CWalletTx::AcceptWalletTransaction()
587 return AcceptWalletTransaction(txdb);
590 int CTxIndex::GetDepthInMainChain() const
594 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
596 // Find the block in the index
597 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
598 if (mi == mapBlockIndex.end())
600 CBlockIndex* pindex = (*mi).second;
601 if (!pindex || !pindex->IsInMainChain())
603 return 1 + nBestHeight - pindex->nHeight;
615 //////////////////////////////////////////////////////////////////////////////
617 // CBlock and CBlockIndex
620 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
622 if (!fReadTransactions)
624 *this = pindex->GetBlockHeader();
627 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
629 if (GetHash() != pindex->GetBlockHash())
630 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
634 uint256 static GetOrphanRoot(const CBlock* pblock)
636 // Work back to the first block in the orphan chain
637 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
638 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
639 return pblock->GetHash();
642 int64 static GetBlockValue(int nHeight, int64 nFees)
644 int64 nSubsidy = 50 * COIN;
646 // Subsidy is cut in half every 4 years
647 nSubsidy >>= (nHeight / 210000);
649 return nSubsidy + nFees;
652 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
654 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
655 const int64 nTargetSpacing = 10 * 60;
656 const int64 nInterval = nTargetTimespan / nTargetSpacing;
659 if (pindexLast == NULL)
660 return bnProofOfWorkLimit.GetCompact();
662 // Only change once per interval
663 if ((pindexLast->nHeight+1) % nInterval != 0)
664 return pindexLast->nBits;
666 // Go back by what we want to be 14 days worth of blocks
667 const CBlockIndex* pindexFirst = pindexLast;
668 for (int i = 0; pindexFirst && i < nInterval-1; i++)
669 pindexFirst = pindexFirst->pprev;
672 // Limit adjustment step
673 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
674 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
675 if (nActualTimespan < nTargetTimespan/4)
676 nActualTimespan = nTargetTimespan/4;
677 if (nActualTimespan > nTargetTimespan*4)
678 nActualTimespan = nTargetTimespan*4;
682 bnNew.SetCompact(pindexLast->nBits);
683 bnNew *= nActualTimespan;
684 bnNew /= nTargetTimespan;
686 if (bnNew > bnProofOfWorkLimit)
687 bnNew = bnProofOfWorkLimit;
690 printf("GetNextWorkRequired RETARGET\n");
691 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
692 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
693 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
695 return bnNew.GetCompact();
698 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
701 bnTarget.SetCompact(nBits);
704 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
705 return error("CheckProofOfWork() : nBits below minimum work");
707 // Check proof of work matches claimed amount
708 if (hash > bnTarget.getuint256())
709 return error("CheckProofOfWork() : hash doesn't match nBits");
714 // Return conservative estimate of total number of blocks, 0 if unknown
715 int GetTotalBlocksEstimate()
723 return nTotalBlocksEstimate;
727 bool IsInitialBlockDownload()
729 if (pindexBest == NULL || nBestHeight < (GetTotalBlocksEstimate()-nInitialBlockThreshold))
731 static int64 nLastUpdate;
732 static CBlockIndex* pindexLastBest;
733 if (pindexBest != pindexLastBest)
735 pindexLastBest = pindexBest;
736 nLastUpdate = GetTime();
738 return (GetTime() - nLastUpdate < 10 &&
739 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
742 void static InvalidChainFound(CBlockIndex* pindexNew)
744 if (pindexNew->bnChainWork > bnBestInvalidWork)
746 bnBestInvalidWork = pindexNew->bnChainWork;
747 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
750 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());
751 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
752 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
753 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
766 bool CTransaction::DisconnectInputs(CTxDB& txdb)
768 // Relinquish previous transactions' spent pointers
771 BOOST_FOREACH(const CTxIn& txin, vin)
773 COutPoint prevout = txin.prevout;
775 // Get prev txindex from disk
777 if (!txdb.ReadTxIndex(prevout.hash, txindex))
778 return error("DisconnectInputs() : ReadTxIndex failed");
780 if (prevout.n >= txindex.vSpent.size())
781 return error("DisconnectInputs() : prevout.n out of range");
783 // Mark outpoint as not spent
784 txindex.vSpent[prevout.n].SetNull();
787 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
788 return error("DisconnectInputs() : UpdateTxIndex failed");
792 // Remove transaction from index
793 if (!txdb.EraseTxIndex(*this))
794 return error("DisconnectInputs() : EraseTxPos failed");
800 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
801 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
803 // Take over previous transactions' spent pointers
807 for (int i = 0; i < vin.size(); i++)
809 COutPoint prevout = vin[i].prevout;
814 if (fMiner && mapTestPool.count(prevout.hash))
816 // Get txindex from current proposed changes
817 txindex = mapTestPool[prevout.hash];
821 // Read txindex from txdb
822 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
824 if (!fFound && (fBlock || fMiner))
825 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());
829 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
831 // Get prev tx from single transactions in memory
832 CRITICAL_BLOCK(cs_mapTransactions)
834 if (!mapTransactions.count(prevout.hash))
835 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
836 txPrev = mapTransactions[prevout.hash];
839 txindex.vSpent.resize(txPrev.vout.size());
843 // Get prev tx from disk
844 if (!txPrev.ReadFromDisk(txindex.pos))
845 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
848 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
849 return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str());
851 // If prev is coinbase, check that it's matured
852 if (txPrev.IsCoinBase())
853 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
854 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
855 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
858 if (!VerifySignature(txPrev, *this, i))
859 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
861 // Check for conflicts
862 if (!txindex.vSpent[prevout.n].IsNull())
863 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());
865 // Check for negative or overflow input values
866 nValueIn += txPrev.vout[prevout.n].nValue;
867 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
868 return error("ConnectInputs() : txin values out of range");
870 // Mark outpoints as spent
871 txindex.vSpent[prevout.n] = posThisTx;
876 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
877 return error("ConnectInputs() : UpdateTxIndex failed");
881 mapTestPool[prevout.hash] = txindex;
885 if (nValueIn < GetValueOut())
886 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
888 // Tally transaction fees
889 int64 nTxFee = nValueIn - GetValueOut();
891 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
892 if (nTxFee < nMinFee)
895 if (!MoneyRange(nFees))
896 return error("ConnectInputs() : nFees out of range");
901 // Add transaction to disk index
902 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
903 return error("ConnectInputs() : AddTxPos failed");
907 // Add transaction to test pool
908 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
915 bool CTransaction::ClientConnectInputs()
920 // Take over previous transactions' spent pointers
921 CRITICAL_BLOCK(cs_mapTransactions)
924 for (int i = 0; i < vin.size(); i++)
926 // Get prev tx from single transactions in memory
927 COutPoint prevout = vin[i].prevout;
928 if (!mapTransactions.count(prevout.hash))
930 CTransaction& txPrev = mapTransactions[prevout.hash];
932 if (prevout.n >= txPrev.vout.size())
936 if (!VerifySignature(txPrev, *this, i))
937 return error("ConnectInputs() : VerifySignature failed");
939 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
940 ///// this has to go away now that posNext is gone
941 // // Check for conflicts
942 // if (!txPrev.vout[prevout.n].posNext.IsNull())
943 // return error("ConnectInputs() : prev tx already used");
945 // // Flag outpoints as used
946 // txPrev.vout[prevout.n].posNext = posThisTx;
948 nValueIn += txPrev.vout[prevout.n].nValue;
950 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
951 return error("ClientConnectInputs() : txin values out of range");
953 if (GetValueOut() > nValueIn)
963 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
965 // Disconnect in reverse order
966 for (int i = vtx.size()-1; i >= 0; i--)
967 if (!vtx[i].DisconnectInputs(txdb))
970 // Update block index on disk without changing it in memory.
971 // The memory index structure will be changed after the db commits.
974 CDiskBlockIndex blockindexPrev(pindex->pprev);
975 blockindexPrev.hashNext = 0;
976 if (!txdb.WriteBlockIndex(blockindexPrev))
977 return error("DisconnectBlock() : WriteBlockIndex failed");
983 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
985 // Check it again in case a previous version let a bad block in
989 //// issue here: it doesn't know the version
990 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
992 map<uint256, CTxIndex> mapUnused;
994 BOOST_FOREACH(CTransaction& tx, vtx)
996 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
997 nTxPos += ::GetSerializeSize(tx, SER_DISK);
999 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1003 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1006 // Update block index on disk without changing it in memory.
1007 // The memory index structure will be changed after the db commits.
1010 CDiskBlockIndex blockindexPrev(pindex->pprev);
1011 blockindexPrev.hashNext = pindex->GetBlockHash();
1012 if (!txdb.WriteBlockIndex(blockindexPrev))
1013 return error("ConnectBlock() : WriteBlockIndex failed");
1016 // Watch for transactions paying to me
1017 BOOST_FOREACH(CTransaction& tx, vtx)
1018 SyncWithWallets(tx, this, true);
1023 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1025 printf("REORGANIZE\n");
1028 CBlockIndex* pfork = pindexBest;
1029 CBlockIndex* plonger = pindexNew;
1030 while (pfork != plonger)
1032 while (plonger->nHeight > pfork->nHeight)
1033 if (!(plonger = plonger->pprev))
1034 return error("Reorganize() : plonger->pprev is null");
1035 if (pfork == plonger)
1037 if (!(pfork = pfork->pprev))
1038 return error("Reorganize() : pfork->pprev is null");
1041 // List of what to disconnect
1042 vector<CBlockIndex*> vDisconnect;
1043 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1044 vDisconnect.push_back(pindex);
1046 // List of what to connect
1047 vector<CBlockIndex*> vConnect;
1048 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1049 vConnect.push_back(pindex);
1050 reverse(vConnect.begin(), vConnect.end());
1052 // Disconnect shorter branch
1053 vector<CTransaction> vResurrect;
1054 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1057 if (!block.ReadFromDisk(pindex))
1058 return error("Reorganize() : ReadFromDisk for disconnect failed");
1059 if (!block.DisconnectBlock(txdb, pindex))
1060 return error("Reorganize() : DisconnectBlock failed");
1062 // Queue memory transactions to resurrect
1063 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1064 if (!tx.IsCoinBase())
1065 vResurrect.push_back(tx);
1068 // Connect longer branch
1069 vector<CTransaction> vDelete;
1070 for (int i = 0; i < vConnect.size(); i++)
1072 CBlockIndex* pindex = vConnect[i];
1074 if (!block.ReadFromDisk(pindex))
1075 return error("Reorganize() : ReadFromDisk for connect failed");
1076 if (!block.ConnectBlock(txdb, pindex))
1080 return error("Reorganize() : ConnectBlock failed");
1083 // Queue memory transactions to delete
1084 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1085 vDelete.push_back(tx);
1087 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1088 return error("Reorganize() : WriteHashBestChain failed");
1090 // Make sure it's successfully written to disk before changing memory structure
1091 if (!txdb.TxnCommit())
1092 return error("Reorganize() : TxnCommit failed");
1094 // Disconnect shorter branch
1095 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1097 pindex->pprev->pnext = NULL;
1099 // Connect longer branch
1100 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1102 pindex->pprev->pnext = pindex;
1104 // Resurrect memory transactions that were in the disconnected branch
1105 BOOST_FOREACH(CTransaction& tx, vResurrect)
1106 tx.AcceptToMemoryPool(txdb, false);
1108 // Delete redundant memory transactions that are in the connected branch
1109 BOOST_FOREACH(CTransaction& tx, vDelete)
1110 tx.RemoveFromMemoryPool();
1116 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1118 uint256 hash = GetHash();
1121 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1123 txdb.WriteHashBestChain(hash);
1124 if (!txdb.TxnCommit())
1125 return error("SetBestChain() : TxnCommit failed");
1126 pindexGenesisBlock = pindexNew;
1128 else if (hashPrevBlock == hashBestChain)
1130 // Adding to current best branch
1131 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1134 InvalidChainFound(pindexNew);
1135 return error("SetBestChain() : ConnectBlock failed");
1137 if (!txdb.TxnCommit())
1138 return error("SetBestChain() : TxnCommit failed");
1140 // Add to current best branch
1141 pindexNew->pprev->pnext = pindexNew;
1143 // Delete redundant memory transactions
1144 BOOST_FOREACH(CTransaction& tx, vtx)
1145 tx.RemoveFromMemoryPool();
1150 if (!Reorganize(txdb, pindexNew))
1153 InvalidChainFound(pindexNew);
1154 return error("SetBestChain() : Reorganize failed");
1158 // Update best block in wallet (so we can detect restored wallets)
1159 if (!IsInitialBlockDownload())
1161 const CBlockLocator locator(pindexNew);
1162 ::SetBestChain(locator);
1166 hashBestChain = hash;
1167 pindexBest = pindexNew;
1168 nBestHeight = pindexBest->nHeight;
1169 bnBestChainWork = pindexNew->bnChainWork;
1170 nTimeBestReceived = GetTime();
1171 nTransactionsUpdated++;
1172 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1178 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1180 // Check for duplicate
1181 uint256 hash = GetHash();
1182 if (mapBlockIndex.count(hash))
1183 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1185 // Construct new block index object
1186 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1188 return error("AddToBlockIndex() : new CBlockIndex failed");
1189 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1190 pindexNew->phashBlock = &((*mi).first);
1191 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1192 if (miPrev != mapBlockIndex.end())
1194 pindexNew->pprev = (*miPrev).second;
1195 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1197 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1201 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1202 if (!txdb.TxnCommit())
1206 if (pindexNew->bnChainWork > bnBestChainWork)
1207 if (!SetBestChain(txdb, pindexNew))
1212 if (pindexNew == pindexBest)
1214 // Notify UI to display prev block's coinbase if it was ours
1215 static uint256 hashPrevBestCoinBase;
1216 UpdatedTransaction(hashPrevBestCoinBase);
1217 hashPrevBestCoinBase = vtx[0].GetHash();
1227 bool CBlock::CheckBlock() const
1229 // These are checks that are independent of context
1230 // that can be verified before saving an orphan block.
1233 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1234 return error("CheckBlock() : size limits failed");
1236 // Check proof of work matches claimed amount
1237 if (!CheckProofOfWork(GetHash(), nBits))
1238 return error("CheckBlock() : proof of work failed");
1241 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1242 return error("CheckBlock() : block timestamp too far in the future");
1244 // First transaction must be coinbase, the rest must not be
1245 if (vtx.empty() || !vtx[0].IsCoinBase())
1246 return error("CheckBlock() : first tx is not coinbase");
1247 for (int i = 1; i < vtx.size(); i++)
1248 if (vtx[i].IsCoinBase())
1249 return error("CheckBlock() : more than one coinbase");
1251 // Check transactions
1252 BOOST_FOREACH(const CTransaction& tx, vtx)
1253 if (!tx.CheckTransaction())
1254 return error("CheckBlock() : CheckTransaction failed");
1256 // Check that it's not full of nonstandard transactions
1257 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1258 return error("CheckBlock() : too many nonstandard transactions");
1261 if (hashMerkleRoot != BuildMerkleTree())
1262 return error("CheckBlock() : hashMerkleRoot mismatch");
1267 bool CBlock::AcceptBlock()
1269 // Check for duplicate
1270 uint256 hash = GetHash();
1271 if (mapBlockIndex.count(hash))
1272 return error("AcceptBlock() : block already in mapBlockIndex");
1274 // Get prev block index
1275 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1276 if (mi == mapBlockIndex.end())
1277 return error("AcceptBlock() : prev block not found");
1278 CBlockIndex* pindexPrev = (*mi).second;
1279 int nHeight = pindexPrev->nHeight+1;
1281 // Check proof of work
1282 if (nBits != GetNextWorkRequired(pindexPrev))
1283 return error("AcceptBlock() : incorrect proof of work");
1285 // Check timestamp against prev
1286 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1287 return error("AcceptBlock() : block's timestamp is too early");
1289 // Check that all transactions are finalized
1290 BOOST_FOREACH(const CTransaction& tx, vtx)
1291 if (!tx.IsFinal(nHeight, GetBlockTime()))
1292 return error("AcceptBlock() : contains a non-final transaction");
1294 // Check that the block chain matches the known block chain up to a checkpoint
1296 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1297 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1298 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1299 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1300 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) ||
1301 (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) ||
1302 (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")) ||
1303 (nHeight == 134444 && hash != uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")))
1304 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1306 // Write block to history file
1307 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1308 return error("AcceptBlock() : out of disk space");
1309 unsigned int nFile = -1;
1310 unsigned int nBlockPos = 0;
1311 if (!WriteToDisk(nFile, nBlockPos))
1312 return error("AcceptBlock() : WriteToDisk failed");
1313 if (!AddToBlockIndex(nFile, nBlockPos))
1314 return error("AcceptBlock() : AddToBlockIndex failed");
1316 // Relay inventory, but don't relay old inventory during initial block download
1317 if (hashBestChain == hash)
1318 CRITICAL_BLOCK(cs_vNodes)
1319 BOOST_FOREACH(CNode* pnode, vNodes)
1320 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 134444))
1321 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1326 bool static ProcessBlock(CNode* pfrom, CBlock* pblock)
1328 // Check for duplicate
1329 uint256 hash = pblock->GetHash();
1330 if (mapBlockIndex.count(hash))
1331 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1332 if (mapOrphanBlocks.count(hash))
1333 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1335 // Preliminary checks
1336 if (!pblock->CheckBlock())
1337 return error("ProcessBlock() : CheckBlock FAILED");
1339 // If don't already have its previous block, shunt it off to holding area until we get it
1340 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1342 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1343 CBlock* pblock2 = new CBlock(*pblock);
1344 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1345 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1347 // Ask this guy to fill in what we're missing
1349 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1354 if (!pblock->AcceptBlock())
1355 return error("ProcessBlock() : AcceptBlock FAILED");
1357 // Recursively process any orphan blocks that depended on this one
1358 vector<uint256> vWorkQueue;
1359 vWorkQueue.push_back(hash);
1360 for (int i = 0; i < vWorkQueue.size(); i++)
1362 uint256 hashPrev = vWorkQueue[i];
1363 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1364 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1367 CBlock* pblockOrphan = (*mi).second;
1368 if (pblockOrphan->AcceptBlock())
1369 vWorkQueue.push_back(pblockOrphan->GetHash());
1370 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1371 delete pblockOrphan;
1373 mapOrphanBlocksByPrev.erase(hashPrev);
1376 printf("ProcessBlock: ACCEPTED\n");
1387 template<typename Stream>
1388 bool static ScanMessageStart(Stream& s)
1390 // Scan ahead to the next pchMessageStart, which should normally be immediately
1391 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1393 short prevmask = s.exceptions(0);
1394 const char* p = BEGIN(pchMessageStart);
1404 s.exceptions(prevmask);
1408 p = BEGIN(pchMessageStart);
1411 if (++p == END(pchMessageStart))
1414 s.exceptions(prevmask);
1423 s.exceptions(prevmask);
1428 bool CheckDiskSpace(uint64 nAdditionalBytes)
1430 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1432 // Check for 15MB because database could create another 10MB log file at any time
1433 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1436 string strMessage = _("Warning: Disk space is low ");
1437 strMiscWarning = strMessage;
1438 printf("*** %s\n", strMessage.c_str());
1439 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1440 CreateThread(Shutdown, NULL);
1446 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1450 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1453 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1455 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1464 static unsigned int nCurrentBlockFile = 1;
1466 FILE* AppendBlockFile(unsigned int& nFileRet)
1471 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1474 if (fseek(file, 0, SEEK_END) != 0)
1476 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1477 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1479 nFileRet = nCurrentBlockFile;
1483 nCurrentBlockFile++;
1487 bool LoadBlockIndex(bool fAllowNew)
1491 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1492 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1493 pchMessageStart[0] = 0xfa;
1494 pchMessageStart[1] = 0xbf;
1495 pchMessageStart[2] = 0xb5;
1496 pchMessageStart[3] = 0xda;
1503 if (!txdb.LoadBlockIndex())
1508 // Init with genesis block
1510 if (mapBlockIndex.empty())
1516 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1517 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1518 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1519 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1520 // vMerkleTree: 4a5e1e
1523 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1525 txNew.vin.resize(1);
1526 txNew.vout.resize(1);
1527 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1528 txNew.vout[0].nValue = 50 * COIN;
1529 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1531 block.vtx.push_back(txNew);
1532 block.hashPrevBlock = 0;
1533 block.hashMerkleRoot = block.BuildMerkleTree();
1535 block.nTime = 1231006505;
1536 block.nBits = 0x1d00ffff;
1537 block.nNonce = 2083236893;
1541 block.nTime = 1296688602;
1542 block.nBits = 0x1d07fff8;
1543 block.nNonce = 384568319;
1547 printf("%s\n", block.GetHash().ToString().c_str());
1548 printf("%s\n", hashGenesisBlock.ToString().c_str());
1549 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1550 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1552 assert(block.GetHash() == hashGenesisBlock);
1554 // Start new block file
1556 unsigned int nBlockPos;
1557 if (!block.WriteToDisk(nFile, nBlockPos))
1558 return error("LoadBlockIndex() : writing genesis block to disk failed");
1559 if (!block.AddToBlockIndex(nFile, nBlockPos))
1560 return error("LoadBlockIndex() : genesis block not accepted");
1568 void PrintBlockTree()
1570 // precompute tree structure
1571 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1572 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1574 CBlockIndex* pindex = (*mi).second;
1575 mapNext[pindex->pprev].push_back(pindex);
1577 //while (rand() % 3 == 0)
1578 // mapNext[pindex->pprev].push_back(pindex);
1581 vector<pair<int, CBlockIndex*> > vStack;
1582 vStack.push_back(make_pair(0, pindexGenesisBlock));
1585 while (!vStack.empty())
1587 int nCol = vStack.back().first;
1588 CBlockIndex* pindex = vStack.back().second;
1591 // print split or gap
1592 if (nCol > nPrevCol)
1594 for (int i = 0; i < nCol-1; i++)
1598 else if (nCol < nPrevCol)
1600 for (int i = 0; i < nCol; i++)
1607 for (int i = 0; i < nCol; i++)
1612 block.ReadFromDisk(pindex);
1613 printf("%d (%u,%u) %s %s tx %d",
1617 block.GetHash().ToString().substr(0,20).c_str(),
1618 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1621 PrintWallets(block);
1623 // put the main timechain first
1624 vector<CBlockIndex*>& vNext = mapNext[pindex];
1625 for (int i = 0; i < vNext.size(); i++)
1627 if (vNext[i]->pnext)
1629 swap(vNext[0], vNext[i]);
1635 for (int i = 0; i < vNext.size(); i++)
1636 vStack.push_back(make_pair(nCol+i, vNext[i]));
1649 //////////////////////////////////////////////////////////////////////////////
1654 map<uint256, CAlert> mapAlerts;
1655 CCriticalSection cs_mapAlerts;
1657 string GetWarnings(string strFor)
1660 string strStatusBar;
1662 if (GetBoolArg("-testsafemode"))
1665 // Misc warnings like out of disk space and clock is wrong
1666 if (strMiscWarning != "")
1669 strStatusBar = strMiscWarning;
1672 // Longer invalid proof-of-work chain
1673 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1676 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1680 CRITICAL_BLOCK(cs_mapAlerts)
1682 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1684 const CAlert& alert = item.second;
1685 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1687 nPriority = alert.nPriority;
1688 strStatusBar = alert.strStatusBar;
1693 if (strFor == "statusbar")
1694 return strStatusBar;
1695 else if (strFor == "rpc")
1697 assert(!"GetWarnings() : invalid parameter");
1701 bool CAlert::ProcessAlert()
1703 if (!CheckSignature())
1708 CRITICAL_BLOCK(cs_mapAlerts)
1710 // Cancel previous alerts
1711 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1713 const CAlert& alert = (*mi).second;
1716 printf("cancelling alert %d\n", alert.nID);
1717 mapAlerts.erase(mi++);
1719 else if (!alert.IsInEffect())
1721 printf("expiring alert %d\n", alert.nID);
1722 mapAlerts.erase(mi++);
1728 // Check if this alert has been cancelled
1729 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1731 const CAlert& alert = item.second;
1732 if (alert.Cancels(*this))
1734 printf("alert already cancelled by %d\n", alert.nID);
1740 mapAlerts.insert(make_pair(GetHash(), *this));
1743 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1755 //////////////////////////////////////////////////////////////////////////////
1761 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1765 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1766 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1768 // Don't know what it is, just say we already got one
1775 // The message start string is designed to be unlikely to occur in normal data.
1776 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1777 // a large 4-byte int at any alignment.
1778 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1781 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1783 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1784 RandAddSeedPerfmon();
1786 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1787 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1788 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1790 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1798 if (strCommand == "version")
1800 // Each connection can only send one version message
1801 if (pfrom->nVersion != 0)
1808 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1809 if (pfrom->nVersion == 10300)
1810 pfrom->nVersion = 300;
1811 if (pfrom->nVersion >= 106 && !vRecv.empty())
1812 vRecv >> addrFrom >> nNonce;
1813 if (pfrom->nVersion >= 106 && !vRecv.empty())
1814 vRecv >> pfrom->strSubVer;
1815 if (pfrom->nVersion >= 209 && !vRecv.empty())
1816 vRecv >> pfrom->nStartingHeight;
1818 if (pfrom->nVersion == 0)
1821 // Disconnect if we connected to ourself
1822 if (nNonce == nLocalHostNonce && nNonce > 1)
1824 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1825 pfrom->fDisconnect = true;
1829 // Be shy and don't send version until we hear
1830 if (pfrom->fInbound)
1831 pfrom->PushVersion();
1833 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1835 AddTimeData(pfrom->addr.ip, nTime);
1838 if (pfrom->nVersion >= 209)
1839 pfrom->PushMessage("verack");
1840 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1841 if (pfrom->nVersion < 209)
1842 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1844 if (!pfrom->fInbound)
1846 // Advertise our address
1847 if (addrLocalHost.IsRoutable() && !fUseProxy)
1849 CAddress addr(addrLocalHost);
1850 addr.nTime = GetAdjustedTime();
1851 pfrom->PushAddress(addr);
1854 // Get recent addresses
1855 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
1857 pfrom->PushMessage("getaddr");
1858 pfrom->fGetAddr = true;
1862 // Ask the first connected node for block updates
1863 static int nAskedForBlocks;
1864 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
1867 pfrom->PushGetBlocks(pindexBest, uint256(0));
1871 CRITICAL_BLOCK(cs_mapAlerts)
1872 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1873 item.second.RelayTo(pfrom);
1875 pfrom->fSuccessfullyConnected = true;
1877 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1878 if(pfrom->nStartingHeight > nTotalBlocksEstimate)
1880 nTotalBlocksEstimate = pfrom->nStartingHeight;
1885 else if (pfrom->nVersion == 0)
1887 // Must have a version message before anything else
1892 else if (strCommand == "verack")
1894 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1898 else if (strCommand == "addr")
1900 vector<CAddress> vAddr;
1903 // Don't want addr from older versions unless seeding
1904 if (pfrom->nVersion < 209)
1906 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
1908 if (vAddr.size() > 1000)
1909 return error("message addr size() = %d", vAddr.size());
1911 // Store the new addresses
1914 int64 nNow = GetAdjustedTime();
1915 int64 nSince = nNow - 10 * 60;
1916 BOOST_FOREACH(CAddress& addr, vAddr)
1920 // ignore IPv6 for now, since it isn't implemented anyway
1923 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1924 addr.nTime = nNow - 5 * 24 * 60 * 60;
1925 AddAddress(addr, 2 * 60 * 60, &addrDB);
1926 pfrom->AddAddressKnown(addr);
1927 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1929 // Relay to a limited number of other nodes
1930 CRITICAL_BLOCK(cs_vNodes)
1932 // Use deterministic randomness to send to the same nodes for 24 hours
1933 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
1934 static uint256 hashSalt;
1936 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1937 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
1938 hashRand = Hash(BEGIN(hashRand), END(hashRand));
1939 multimap<uint256, CNode*> mapMix;
1940 BOOST_FOREACH(CNode* pnode, vNodes)
1942 if (pnode->nVersion < 31402)
1944 unsigned int nPointer;
1945 memcpy(&nPointer, &pnode, sizeof(nPointer));
1946 uint256 hashKey = hashRand ^ nPointer;
1947 hashKey = Hash(BEGIN(hashKey), END(hashKey));
1948 mapMix.insert(make_pair(hashKey, pnode));
1950 int nRelayNodes = 2;
1951 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1952 ((*mi).second)->PushAddress(addr);
1956 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
1957 if (vAddr.size() < 1000)
1958 pfrom->fGetAddr = false;
1962 else if (strCommand == "inv")
1966 if (vInv.size() > 50000)
1967 return error("message inv size() = %d", vInv.size());
1970 BOOST_FOREACH(const CInv& inv, vInv)
1974 pfrom->AddInventoryKnown(inv);
1976 bool fAlreadyHave = AlreadyHave(txdb, inv);
1977 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
1981 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
1982 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
1984 // Track requests for our stuff
1985 Inventory(inv.hash);
1990 else if (strCommand == "getdata")
1994 if (vInv.size() > 50000)
1995 return error("message getdata size() = %d", vInv.size());
1997 BOOST_FOREACH(const CInv& inv, vInv)
2001 printf("received getdata for: %s\n", inv.ToString().c_str());
2003 if (inv.type == MSG_BLOCK)
2005 // Send block from disk
2006 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2007 if (mi != mapBlockIndex.end())
2010 block.ReadFromDisk((*mi).second);
2011 pfrom->PushMessage("block", block);
2013 // Trigger them to send a getblocks request for the next batch of inventory
2014 if (inv.hash == pfrom->hashContinue)
2016 // Bypass PushInventory, this must send even if redundant,
2017 // and we want it right after the last block so they don't
2018 // wait for other stuff first.
2020 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2021 pfrom->PushMessage("inv", vInv);
2022 pfrom->hashContinue = 0;
2026 else if (inv.IsKnownType())
2028 // Send stream from relay memory
2029 CRITICAL_BLOCK(cs_mapRelay)
2031 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2032 if (mi != mapRelay.end())
2033 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2037 // Track requests for our stuff
2038 Inventory(inv.hash);
2043 else if (strCommand == "getblocks")
2045 CBlockLocator locator;
2047 vRecv >> locator >> hashStop;
2049 // Find the last block the caller has in the main chain
2050 CBlockIndex* pindex = locator.GetBlockIndex();
2052 // Send the rest of the chain
2054 pindex = pindex->pnext;
2055 int nLimit = 500 + locator.GetDistanceBack();
2056 unsigned int nBytes = 0;
2057 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2058 for (; pindex; pindex = pindex->pnext)
2060 if (pindex->GetBlockHash() == hashStop)
2062 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2065 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2067 block.ReadFromDisk(pindex, true);
2068 nBytes += block.GetSerializeSize(SER_NETWORK);
2069 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2071 // When this block is requested, we'll send an inv that'll make them
2072 // getblocks the next batch of inventory.
2073 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2074 pfrom->hashContinue = pindex->GetBlockHash();
2081 else if (strCommand == "getheaders")
2083 CBlockLocator locator;
2085 vRecv >> locator >> hashStop;
2087 CBlockIndex* pindex = NULL;
2088 if (locator.IsNull())
2090 // If locator is null, return the hashStop block
2091 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2092 if (mi == mapBlockIndex.end())
2094 pindex = (*mi).second;
2098 // Find the last block the caller has in the main chain
2099 pindex = locator.GetBlockIndex();
2101 pindex = pindex->pnext;
2104 vector<CBlock> vHeaders;
2105 int nLimit = 2000 + locator.GetDistanceBack();
2106 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2107 for (; pindex; pindex = pindex->pnext)
2109 vHeaders.push_back(pindex->GetBlockHeader());
2110 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2113 pfrom->PushMessage("headers", vHeaders);
2117 else if (strCommand == "tx")
2119 vector<uint256> vWorkQueue;
2120 CDataStream vMsg(vRecv);
2124 CInv inv(MSG_TX, tx.GetHash());
2125 pfrom->AddInventoryKnown(inv);
2127 bool fMissingInputs = false;
2128 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2130 SyncWithWallets(tx, NULL, true);
2131 RelayMessage(inv, vMsg);
2132 mapAlreadyAskedFor.erase(inv);
2133 vWorkQueue.push_back(inv.hash);
2135 // Recursively process any orphan transactions that depended on this one
2136 for (int i = 0; i < vWorkQueue.size(); i++)
2138 uint256 hashPrev = vWorkQueue[i];
2139 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2140 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2143 const CDataStream& vMsg = *((*mi).second);
2145 CDataStream(vMsg) >> tx;
2146 CInv inv(MSG_TX, tx.GetHash());
2148 if (tx.AcceptToMemoryPool(true))
2150 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2151 SyncWithWallets(tx, NULL, true);
2152 RelayMessage(inv, vMsg);
2153 mapAlreadyAskedFor.erase(inv);
2154 vWorkQueue.push_back(inv.hash);
2159 BOOST_FOREACH(uint256 hash, vWorkQueue)
2160 EraseOrphanTx(hash);
2162 else if (fMissingInputs)
2164 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2170 else if (strCommand == "block")
2175 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2178 CInv inv(MSG_BLOCK, block.GetHash());
2179 pfrom->AddInventoryKnown(inv);
2181 if (ProcessBlock(pfrom, &block))
2182 mapAlreadyAskedFor.erase(inv);
2186 else if (strCommand == "getaddr")
2188 // Nodes rebroadcast an addr every 24 hours
2189 pfrom->vAddrToSend.clear();
2190 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2191 CRITICAL_BLOCK(cs_mapAddresses)
2193 unsigned int nCount = 0;
2194 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2196 const CAddress& addr = item.second;
2197 if (addr.nTime > nSince)
2200 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2202 const CAddress& addr = item.second;
2203 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2204 pfrom->PushAddress(addr);
2210 else if (strCommand == "checkorder")
2215 if (!GetBoolArg("-allowreceivebyip"))
2217 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2224 /// we have a chance to check the order here
2226 // Keep giving the same key to the same ip until they use it
2227 if (!mapReuseKey.count(pfrom->addr.ip))
2228 mapReuseKey[pfrom->addr.ip] = pwalletMain->GetOrReuseKeyFromPool();
2230 // Send back approval of order and pubkey to use
2231 CScript scriptPubKey;
2232 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2233 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2237 else if (strCommand == "reply")
2242 CRequestTracker tracker;
2243 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2245 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2246 if (mi != pfrom->mapRequests.end())
2248 tracker = (*mi).second;
2249 pfrom->mapRequests.erase(mi);
2252 if (!tracker.IsNull())
2253 tracker.fn(tracker.param1, vRecv);
2257 else if (strCommand == "ping")
2262 else if (strCommand == "alert")
2267 if (alert.ProcessAlert())
2270 pfrom->setKnown.insert(alert.GetHash());
2271 CRITICAL_BLOCK(cs_vNodes)
2272 BOOST_FOREACH(CNode* pnode, vNodes)
2273 alert.RelayTo(pnode);
2280 // Ignore unknown commands for extensibility
2284 // Update the last seen time for this node's address
2285 if (pfrom->fNetworkNode)
2286 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2287 AddressCurrentlyConnected(pfrom->addr);
2293 bool ProcessMessages(CNode* pfrom)
2295 CDataStream& vRecv = pfrom->vRecv;
2299 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2303 // (4) message start
2312 // Scan for message start
2313 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2314 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2315 if (vRecv.end() - pstart < nHeaderSize)
2317 if (vRecv.size() > nHeaderSize)
2319 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2320 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2324 if (pstart - vRecv.begin() > 0)
2325 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2326 vRecv.erase(vRecv.begin(), pstart);
2329 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2334 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2337 string strCommand = hdr.GetCommand();
2340 unsigned int nMessageSize = hdr.nMessageSize;
2341 if (nMessageSize > MAX_SIZE)
2343 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2346 if (nMessageSize > vRecv.size())
2348 // Rewind and wait for rest of message
2349 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2354 if (vRecv.GetVersion() >= 209)
2356 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2357 unsigned int nChecksum = 0;
2358 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2359 if (nChecksum != hdr.nChecksum)
2361 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2362 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2367 // Copy message to its own buffer
2368 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2369 vRecv.ignore(nMessageSize);
2375 CRITICAL_BLOCK(cs_main)
2376 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2380 catch (std::ios_base::failure& e)
2382 if (strstr(e.what(), "end of data"))
2384 // Allow exceptions from underlength message on vRecv
2385 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());
2387 else if (strstr(e.what(), "size too large"))
2389 // Allow exceptions from overlong size
2390 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2394 PrintExceptionContinue(&e, "ProcessMessage()");
2397 catch (std::exception& e) {
2398 PrintExceptionContinue(&e, "ProcessMessage()");
2400 PrintExceptionContinue(NULL, "ProcessMessage()");
2404 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2412 bool SendMessages(CNode* pto, bool fSendTrickle)
2414 CRITICAL_BLOCK(cs_main)
2416 // Don't send anything until we get their version message
2417 if (pto->nVersion == 0)
2421 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2422 pto->PushMessage("ping");
2424 // Resend wallet transactions that haven't gotten in a block yet
2425 ResendWalletTransactions();
2427 // Address refresh broadcast
2428 static int64 nLastRebroadcast;
2429 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2431 nLastRebroadcast = GetTime();
2432 CRITICAL_BLOCK(cs_vNodes)
2434 BOOST_FOREACH(CNode* pnode, vNodes)
2436 // Periodically clear setAddrKnown to allow refresh broadcasts
2437 pnode->setAddrKnown.clear();
2439 // Rebroadcast our address
2440 if (addrLocalHost.IsRoutable() && !fUseProxy)
2442 CAddress addr(addrLocalHost);
2443 addr.nTime = GetAdjustedTime();
2444 pnode->PushAddress(addr);
2450 // Clear out old addresses periodically so it's not too much work at once
2451 static int64 nLastClear;
2452 if (nLastClear == 0)
2453 nLastClear = GetTime();
2454 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2456 nLastClear = GetTime();
2457 CRITICAL_BLOCK(cs_mapAddresses)
2460 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2461 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2462 mi != mapAddresses.end();)
2464 const CAddress& addr = (*mi).second;
2465 if (addr.nTime < nSince)
2467 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2469 addrdb.EraseAddress(addr);
2470 mapAddresses.erase(mi++);
2484 vector<CAddress> vAddr;
2485 vAddr.reserve(pto->vAddrToSend.size());
2486 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2488 // returns true if wasn't already contained in the set
2489 if (pto->setAddrKnown.insert(addr).second)
2491 vAddr.push_back(addr);
2492 // receiver rejects addr messages larger than 1000
2493 if (vAddr.size() >= 1000)
2495 pto->PushMessage("addr", vAddr);
2500 pto->vAddrToSend.clear();
2502 pto->PushMessage("addr", vAddr);
2507 // Message: inventory
2510 vector<CInv> vInvWait;
2511 CRITICAL_BLOCK(pto->cs_inventory)
2513 vInv.reserve(pto->vInventoryToSend.size());
2514 vInvWait.reserve(pto->vInventoryToSend.size());
2515 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2517 if (pto->setInventoryKnown.count(inv))
2520 // trickle out tx inv to protect privacy
2521 if (inv.type == MSG_TX && !fSendTrickle)
2523 // 1/4 of tx invs blast to all immediately
2524 static uint256 hashSalt;
2526 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2527 uint256 hashRand = inv.hash ^ hashSalt;
2528 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2529 bool fTrickleWait = ((hashRand & 3) != 0);
2531 // always trickle our own transactions
2535 if (GetTransaction(inv.hash, wtx))
2537 fTrickleWait = true;
2542 vInvWait.push_back(inv);
2547 // returns true if wasn't already contained in the set
2548 if (pto->setInventoryKnown.insert(inv).second)
2550 vInv.push_back(inv);
2551 if (vInv.size() >= 1000)
2553 pto->PushMessage("inv", vInv);
2558 pto->vInventoryToSend = vInvWait;
2561 pto->PushMessage("inv", vInv);
2567 vector<CInv> vGetData;
2568 int64 nNow = GetTime() * 1000000;
2570 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2572 const CInv& inv = (*pto->mapAskFor.begin()).second;
2573 if (!AlreadyHave(txdb, inv))
2575 printf("sending getdata: %s\n", inv.ToString().c_str());
2576 vGetData.push_back(inv);
2577 if (vGetData.size() >= 1000)
2579 pto->PushMessage("getdata", vGetData);
2583 mapAlreadyAskedFor[inv] = nNow;
2584 pto->mapAskFor.erase(pto->mapAskFor.begin());
2586 if (!vGetData.empty())
2587 pto->PushMessage("getdata", vGetData);
2606 //////////////////////////////////////////////////////////////////////////////
2611 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2613 unsigned char* pdata = (unsigned char*)pbuffer;
2614 unsigned int blocks = 1 + ((len + 8) / 64);
2615 unsigned char* pend = pdata + 64 * blocks;
2616 memset(pdata + len, 0, 64 * blocks - len);
2618 unsigned int bits = len * 8;
2619 pend[-1] = (bits >> 0) & 0xff;
2620 pend[-2] = (bits >> 8) & 0xff;
2621 pend[-3] = (bits >> 16) & 0xff;
2622 pend[-4] = (bits >> 24) & 0xff;
2626 using CryptoPP::ByteReverse;
2628 static const unsigned int pSHA256InitState[8] =
2629 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2631 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2633 memcpy(pstate, pinit, 32);
2634 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2638 // ScanHash scans nonces looking for a hash with at least some zero bits.
2639 // It operates on big endian data. Caller does the byte reversing.
2640 // All input buffers are 16-byte aligned. nNonce is usually preserved
2641 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2642 // the block is rebuilt and nNonce starts over at zero.
2644 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2646 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2650 // Hash pdata using pmidstate as the starting state into
2651 // preformatted buffer phash1, then hash phash1 into phash
2653 SHA256Transform(phash1, pdata, pmidstate);
2654 SHA256Transform(phash, phash1, pSHA256InitState);
2656 // Return the nonce if the hash has at least some zero bits,
2657 // caller will check if it has enough to reach the target
2658 if (((unsigned short*)phash)[14] == 0)
2661 // If nothing found after trying for a while, return -1
2662 if ((nNonce & 0xffff) == 0)
2664 nHashesDone = 0xffff+1;
2675 set<uint256> setDependsOn;
2678 COrphan(CTransaction* ptxIn)
2686 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2687 BOOST_FOREACH(uint256 hash, setDependsOn)
2688 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2693 CBlock* CreateNewBlock(CReserveKey& reservekey)
2695 CBlockIndex* pindexPrev = pindexBest;
2698 auto_ptr<CBlock> pblock(new CBlock());
2702 // Create coinbase tx
2704 txNew.vin.resize(1);
2705 txNew.vin[0].prevout.SetNull();
2706 txNew.vout.resize(1);
2707 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2709 // Add our coinbase tx as first transaction
2710 pblock->vtx.push_back(txNew);
2712 // Collect memory pool transactions into the block
2714 CRITICAL_BLOCK(cs_main)
2715 CRITICAL_BLOCK(cs_mapTransactions)
2719 // Priority order to process transactions
2720 list<COrphan> vOrphan; // list memory doesn't move
2721 map<uint256, vector<COrphan*> > mapDependers;
2722 multimap<double, CTransaction*> mapPriority;
2723 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2725 CTransaction& tx = (*mi).second;
2726 if (tx.IsCoinBase() || !tx.IsFinal())
2729 COrphan* porphan = NULL;
2730 double dPriority = 0;
2731 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2733 // Read prev transaction
2734 CTransaction txPrev;
2736 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2738 // Has to wait for dependencies
2741 // Use list for automatic deletion
2742 vOrphan.push_back(COrphan(&tx));
2743 porphan = &vOrphan.back();
2745 mapDependers[txin.prevout.hash].push_back(porphan);
2746 porphan->setDependsOn.insert(txin.prevout.hash);
2749 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2751 // Read block header
2752 int nConf = txindex.GetDepthInMainChain();
2754 dPriority += (double)nValueIn * nConf;
2756 if (fDebug && GetBoolArg("-printpriority"))
2757 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2760 // Priority is sum(valuein * age) / txsize
2761 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2764 porphan->dPriority = dPriority;
2766 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2768 if (fDebug && GetBoolArg("-printpriority"))
2770 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2777 // Collect transactions into block
2778 map<uint256, CTxIndex> mapTestPool;
2779 uint64 nBlockSize = 1000;
2780 int nBlockSigOps = 100;
2781 while (!mapPriority.empty())
2783 // Take highest priority transaction off priority queue
2784 double dPriority = -(*mapPriority.begin()).first;
2785 CTransaction& tx = *(*mapPriority.begin()).second;
2786 mapPriority.erase(mapPriority.begin());
2789 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2790 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2792 int nTxSigOps = tx.GetSigOpCount();
2793 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2796 // Transaction fee required depends on block size
2797 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2798 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true);
2800 // Connecting shouldn't fail due to dependency on other memory pool transactions
2801 // because we're already processing them in order of dependency
2802 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2803 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
2805 swap(mapTestPool, mapTestPoolTmp);
2808 pblock->vtx.push_back(tx);
2809 nBlockSize += nTxSize;
2810 nBlockSigOps += nTxSigOps;
2812 // Add transactions that depend on this one to the priority queue
2813 uint256 hash = tx.GetHash();
2814 if (mapDependers.count(hash))
2816 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2818 if (!porphan->setDependsOn.empty())
2820 porphan->setDependsOn.erase(hash);
2821 if (porphan->setDependsOn.empty())
2822 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2828 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2831 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
2832 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2833 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2834 pblock->nBits = GetNextWorkRequired(pindexPrev);
2837 return pblock.release();
2841 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
2843 // Update nExtraNonce
2844 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2845 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
2850 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
2851 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2855 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
2858 // Prebuild hash buffers
2865 uint256 hashPrevBlock;
2866 uint256 hashMerkleRoot;
2869 unsigned int nNonce;
2872 unsigned char pchPadding0[64];
2874 unsigned char pchPadding1[64];
2877 memset(&tmp, 0, sizeof(tmp));
2879 tmp.block.nVersion = pblock->nVersion;
2880 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
2881 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
2882 tmp.block.nTime = pblock->nTime;
2883 tmp.block.nBits = pblock->nBits;
2884 tmp.block.nNonce = pblock->nNonce;
2886 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2887 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2889 // Byte swap all the input buffer
2890 for (int i = 0; i < sizeof(tmp)/4; i++)
2891 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2893 // Precalc the first half of the first hash, which stays constant
2894 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
2896 memcpy(pdata, &tmp.block, 128);
2897 memcpy(phash1, &tmp.hash1, 64);
2901 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
2903 uint256 hash = pblock->GetHash();
2904 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2906 if (hash > hashTarget)
2910 printf("BitcoinMiner:\n");
2911 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2913 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2914 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2917 CRITICAL_BLOCK(cs_main)
2919 if (pblock->hashPrevBlock != hashBestChain)
2920 return error("BitcoinMiner : generated block is stale");
2922 // Remove key from key pool
2923 reservekey.KeepKey();
2925 // Track how many getdata requests this block gets
2926 CRITICAL_BLOCK(wallet.cs_mapRequestCount)
2927 wallet.mapRequestCount[pblock->GetHash()] = 0;
2929 // Process this block the same as if we had received it from another node
2930 if (!ProcessBlock(NULL, pblock))
2931 return error("BitcoinMiner : ProcessBlock, block not accepted");
2938 void static ThreadBitcoinMiner(void* parg);
2940 void static BitcoinMiner(CWallet *pwallet)
2942 printf("BitcoinMiner started\n");
2943 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2945 // Each thread has its own key and counter
2946 CReserveKey reservekey(pwallet);
2947 unsigned int nExtraNonce = 0;
2948 int64 nPrevTime = 0;
2950 while (fGenerateBitcoins)
2952 if (AffinityBugWorkaround(ThreadBitcoinMiner))
2956 while (vNodes.empty() || IsInitialBlockDownload())
2961 if (!fGenerateBitcoins)
2969 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2970 CBlockIndex* pindexPrev = pindexBest;
2972 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
2975 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
2977 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2981 // Prebuild hash buffers
2983 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
2984 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
2985 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
2987 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
2989 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
2990 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
2996 int64 nStart = GetTime();
2997 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2999 uint256& hash = *alignup<16>(hashbuf);
3002 unsigned int nHashesDone = 0;
3003 unsigned int nNonceFound;
3006 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3007 (char*)&hash, nHashesDone);
3009 // Check if something found
3010 if (nNonceFound != -1)
3012 for (int i = 0; i < sizeof(hash)/4; i++)
3013 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3015 if (hash <= hashTarget)
3018 pblock->nNonce = ByteReverse(nNonceFound);
3019 assert(hash == pblock->GetHash());
3021 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3022 CheckWork(pblock.get(), *pwalletMain, reservekey);
3023 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3029 static int64 nHashCounter;
3030 if (nHPSTimerStart == 0)
3032 nHPSTimerStart = GetTimeMillis();
3036 nHashCounter += nHashesDone;
3037 if (GetTimeMillis() - nHPSTimerStart > 4000)
3039 static CCriticalSection cs;
3042 if (GetTimeMillis() - nHPSTimerStart > 4000)
3044 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3045 nHPSTimerStart = GetTimeMillis();
3047 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3048 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3049 static int64 nLogTime;
3050 if (GetTime() - nLogTime > 30 * 60)
3052 nLogTime = GetTime();
3053 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3054 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3060 // Check for stop or if block needs to be rebuilt
3063 if (!fGenerateBitcoins)
3065 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3069 if (nBlockNonce >= 0xffff0000)
3071 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3073 if (pindexPrev != pindexBest)
3076 // Update nTime every few seconds
3077 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3078 nBlockTime = ByteReverse(pblock->nTime);
3083 void static ThreadBitcoinMiner(void* parg)
3085 CWallet* pwallet = (CWallet*)parg;
3088 vnThreadsRunning[3]++;
3089 BitcoinMiner(pwallet);
3090 vnThreadsRunning[3]--;
3092 catch (std::exception& e) {
3093 vnThreadsRunning[3]--;
3094 PrintException(&e, "ThreadBitcoinMiner()");
3096 vnThreadsRunning[3]--;
3097 PrintException(NULL, "ThreadBitcoinMiner()");
3099 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3101 if (vnThreadsRunning[3] == 0)
3103 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3107 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3109 if (fGenerateBitcoins != fGenerate)
3111 fGenerateBitcoins = fGenerate;
3112 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3115 if (fGenerateBitcoins)
3117 int nProcessors = boost::thread::hardware_concurrency();
3118 printf("%d processors\n", nProcessors);
3119 if (nProcessors < 1)
3121 if (fLimitProcessors && nProcessors > nLimitProcessors)
3122 nProcessors = nLimitProcessors;
3123 int nAddThreads = nProcessors - vnThreadsRunning[3];
3124 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3125 for (int i = 0; i < nAddThreads; i++)
3127 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3128 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");