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 CCriticalSection cs_mapPubKeys;
25 map<uint160, vector<unsigned char> > mapPubKeys;
27 map<uint256, CTransaction> mapTransactions;
28 CCriticalSection cs_mapTransactions;
29 unsigned int nTransactionsUpdated = 0;
30 map<COutPoint, CInPoint> mapNextTx;
32 map<uint256, CBlockIndex*> mapBlockIndex;
33 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
34 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
35 const int nTotalBlocksEstimate = 134444; // Conservative estimate of total nr of blocks on main chain
36 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
37 CBlockIndex* pindexGenesisBlock = NULL;
39 CBigNum bnBestChainWork = 0;
40 CBigNum bnBestInvalidWork = 0;
41 uint256 hashBestChain = 0;
42 CBlockIndex* pindexBest = NULL;
43 int64 nTimeBestReceived = 0;
45 map<uint256, CBlock*> mapOrphanBlocks;
46 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
48 map<uint256, CDataStream*> mapOrphanTransactions;
49 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
56 int fGenerateBitcoins = false;
57 int64 nTransactionFee = 0;
58 CAddress addrIncoming;
59 int fLimitProcessors = false;
60 int nLimitProcessors = 1;
61 int fMinimizeToTray = true;
62 int fMinimizeOnClose = true;
75 //////////////////////////////////////////////////////////////////////////////
77 // dispatching functions
80 void RegisterWallet(CWallet* pwalletIn)
82 CRITICAL_BLOCK(cs_setpwalletRegistered)
84 setpwalletRegistered.insert(pwalletIn);
88 void UnregisterWallet(CWallet* pwalletIn)
90 CRITICAL_BLOCK(cs_setpwalletRegistered)
92 setpwalletRegistered.erase(pwalletIn);
96 bool static IsFromMe(CTransaction& tx)
98 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
99 if (pwallet->IsFromMe(tx))
104 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
106 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
107 if (pwallet->GetTransaction(hashTx,wtx))
112 void static EraseFromWallets(uint256 hash)
114 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
115 pwallet->EraseFromWallet(hash);
118 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
120 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
121 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
124 void static SetBestChain(const CBlockLocator& loc)
126 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
127 pwallet->SetBestChain(loc);
130 void static UpdatedTransaction(const uint256& hashTx)
132 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
133 pwallet->UpdatedTransaction(hashTx);
136 void static PrintWallets(const CBlock& block)
138 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
139 pwallet->PrintWallet(block);
142 void static Inventory(const uint256& hash)
144 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
145 pwallet->Inventory(hash);
148 void static ResendWalletTransactions()
150 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
151 pwallet->ResendWalletTransactions();
160 //////////////////////////////////////////////////////////////////////////////
162 // mapOrphanTransactions
165 void static AddOrphanTx(const CDataStream& vMsg)
168 CDataStream(vMsg) >> tx;
169 uint256 hash = tx.GetHash();
170 if (mapOrphanTransactions.count(hash))
172 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
173 BOOST_FOREACH(const CTxIn& txin, tx.vin)
174 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
177 void static EraseOrphanTx(uint256 hash)
179 if (!mapOrphanTransactions.count(hash))
181 const CDataStream* pvMsg = mapOrphanTransactions[hash];
183 CDataStream(*pvMsg) >> tx;
184 BOOST_FOREACH(const CTxIn& txin, tx.vin)
186 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
187 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
189 if ((*mi).second == pvMsg)
190 mapOrphanTransactionsByPrev.erase(mi++);
196 mapOrphanTransactions.erase(hash);
206 //////////////////////////////////////////////////////////////////////////////
208 // CTransaction and CTxIndex
211 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
214 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
216 if (!ReadFromDisk(txindexRet.pos))
218 if (prevout.n >= vout.size())
226 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
229 return ReadFromDisk(txdb, prevout, txindex);
232 bool CTransaction::ReadFromDisk(COutPoint prevout)
236 return ReadFromDisk(txdb, prevout, txindex);
241 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
253 // Load the block this tx is in
255 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
257 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
262 // Update the tx's hashBlock
263 hashBlock = pblock->GetHash();
265 // Locate the transaction
266 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
267 if (pblock->vtx[nIndex] == *(CTransaction*)this)
269 if (nIndex == pblock->vtx.size())
271 vMerkleBranch.clear();
273 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
277 // Fill in merkle branch
278 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
281 // Is the tx in a block that's in the main chain
282 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
283 if (mi == mapBlockIndex.end())
285 CBlockIndex* pindex = (*mi).second;
286 if (!pindex || !pindex->IsInMainChain())
289 return pindexBest->nHeight - pindex->nHeight + 1;
298 bool CTransaction::CheckTransaction() const
300 // Basic checks that don't depend on any context
301 if (vin.empty() || vout.empty())
302 return error("CTransaction::CheckTransaction() : vin or vout empty");
305 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
306 return error("CTransaction::CheckTransaction() : size limits failed");
308 // Check for negative or overflow output values
310 BOOST_FOREACH(const CTxOut& txout, vout)
312 if (txout.nValue < 0)
313 return error("CTransaction::CheckTransaction() : txout.nValue negative");
314 if (txout.nValue > MAX_MONEY)
315 return error("CTransaction::CheckTransaction() : txout.nValue too high");
316 nValueOut += txout.nValue;
317 if (!MoneyRange(nValueOut))
318 return error("CTransaction::CheckTransaction() : txout total out of range");
323 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
324 return error("CTransaction::CheckTransaction() : coinbase script size");
328 BOOST_FOREACH(const CTxIn& txin, vin)
329 if (txin.prevout.IsNull())
330 return error("CTransaction::CheckTransaction() : prevout is null");
336 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
339 *pfMissingInputs = false;
341 if (!CheckTransaction())
342 return error("AcceptToMemoryPool() : CheckTransaction failed");
344 // Coinbase is only valid in a block, not as a loose transaction
346 return error("AcceptToMemoryPool() : coinbase as individual tx");
348 // To help v0.1.5 clients who would see it as a negative number
349 if ((int64)nLockTime > INT_MAX)
350 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
353 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
354 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
355 // attacks disallow transactions with more than one SigOp per 34 bytes.
356 // 34 bytes because a TxOut is:
357 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
358 if (GetSigOpCount() > nSize / 34 || nSize < 100)
359 return error("AcceptToMemoryPool() : nonstandard transaction");
361 // Rather not work on nonstandard transactions (unless -testnet)
362 if (!fTestNet && !IsStandard())
363 return error("AcceptToMemoryPool() : nonstandard transaction type");
365 // Do we already have it?
366 uint256 hash = GetHash();
367 CRITICAL_BLOCK(cs_mapTransactions)
368 if (mapTransactions.count(hash))
371 if (txdb.ContainsTx(hash))
374 // Check for conflicts with in-memory transactions
375 CTransaction* ptxOld = NULL;
376 for (int i = 0; i < vin.size(); i++)
378 COutPoint outpoint = vin[i].prevout;
379 if (mapNextTx.count(outpoint))
381 // Disable replacement feature for now
384 // Allow replacing with a newer version of the same transaction
387 ptxOld = mapNextTx[outpoint].ptx;
388 if (ptxOld->IsFinal())
390 if (!IsNewerThan(*ptxOld))
392 for (int i = 0; i < vin.size(); i++)
394 COutPoint outpoint = vin[i].prevout;
395 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
404 // Check against previous transactions
405 map<uint256, CTxIndex> mapUnused;
407 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
410 *pfMissingInputs = true;
411 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
414 // Don't accept it if it can't get into a block
415 if (nFees < GetMinFee(1000, true, true))
416 return error("AcceptToMemoryPool() : not enough fees");
418 // Continuously rate-limit free transactions
419 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
420 // be annoying or make other's transactions take longer to confirm.
421 if (nFees < MIN_RELAY_TX_FEE)
423 static CCriticalSection cs;
424 static double dFreeCount;
425 static int64 nLastTime;
426 int64 nNow = GetTime();
430 // Use an exponentially decaying ~10-minute window:
431 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
433 // -limitfreerelay unit is thousand-bytes-per-minute
434 // At default rate it would take over a month to fill 1GB
435 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
436 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
438 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
444 // Store transaction in memory
445 CRITICAL_BLOCK(cs_mapTransactions)
449 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
450 ptxOld->RemoveFromMemoryPool();
452 AddToMemoryPoolUnchecked();
455 ///// are we sure this is ok when loading transactions or restoring block txes
456 // If updated, erase old tx from wallet
458 EraseFromWallets(ptxOld->GetHash());
460 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
464 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
467 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
470 bool CTransaction::AddToMemoryPoolUnchecked()
472 // Add to memory pool without checking anything. Don't call this directly,
473 // call AcceptToMemoryPool to properly check the transaction first.
474 CRITICAL_BLOCK(cs_mapTransactions)
476 uint256 hash = GetHash();
477 mapTransactions[hash] = *this;
478 for (int i = 0; i < vin.size(); i++)
479 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
480 nTransactionsUpdated++;
486 bool CTransaction::RemoveFromMemoryPool()
488 // Remove transaction from memory pool
489 CRITICAL_BLOCK(cs_mapTransactions)
491 BOOST_FOREACH(const CTxIn& txin, vin)
492 mapNextTx.erase(txin.prevout);
493 mapTransactions.erase(GetHash());
494 nTransactionsUpdated++;
504 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
506 if (hashBlock == 0 || nIndex == -1)
509 // Find the block it claims to be in
510 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
511 if (mi == mapBlockIndex.end())
513 CBlockIndex* pindex = (*mi).second;
514 if (!pindex || !pindex->IsInMainChain())
517 // Make sure the merkle branch connects to this block
518 if (!fMerkleVerified)
520 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
522 fMerkleVerified = true;
525 nHeightRet = pindex->nHeight;
526 return pindexBest->nHeight - pindex->nHeight + 1;
530 int CMerkleTx::GetBlocksToMaturity() const
534 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
538 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
542 if (!IsInMainChain() && !ClientConnectInputs())
544 return CTransaction::AcceptToMemoryPool(txdb, false);
548 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
552 bool CMerkleTx::AcceptToMemoryPool()
555 return AcceptToMemoryPool(txdb);
560 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
562 CRITICAL_BLOCK(cs_mapTransactions)
564 // Add previous supporting transactions first
565 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
567 if (!tx.IsCoinBase())
569 uint256 hash = tx.GetHash();
570 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
571 tx.AcceptToMemoryPool(txdb, fCheckInputs);
574 return AcceptToMemoryPool(txdb, fCheckInputs);
579 bool CWalletTx::AcceptWalletTransaction()
582 return AcceptWalletTransaction(txdb);
585 int CTxIndex::GetDepthInMainChain() const
589 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
591 // Find the block in the index
592 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
593 if (mi == mapBlockIndex.end())
595 CBlockIndex* pindex = (*mi).second;
596 if (!pindex || !pindex->IsInMainChain())
598 return 1 + nBestHeight - pindex->nHeight;
610 //////////////////////////////////////////////////////////////////////////////
612 // CBlock and CBlockIndex
615 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
617 if (!fReadTransactions)
619 *this = pindex->GetBlockHeader();
622 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
624 if (GetHash() != pindex->GetBlockHash())
625 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
629 uint256 static GetOrphanRoot(const CBlock* pblock)
631 // Work back to the first block in the orphan chain
632 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
633 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
634 return pblock->GetHash();
637 int64 static GetBlockValue(int nHeight, int64 nFees)
639 int64 nSubsidy = 50 * COIN;
641 // Subsidy is cut in half every 4 years
642 nSubsidy >>= (nHeight / 210000);
644 return nSubsidy + nFees;
647 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
649 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
650 const int64 nTargetSpacing = 10 * 60;
651 const int64 nInterval = nTargetTimespan / nTargetSpacing;
654 if (pindexLast == NULL)
655 return bnProofOfWorkLimit.GetCompact();
657 // Only change once per interval
658 if ((pindexLast->nHeight+1) % nInterval != 0)
659 return pindexLast->nBits;
661 // Go back by what we want to be 14 days worth of blocks
662 const CBlockIndex* pindexFirst = pindexLast;
663 for (int i = 0; pindexFirst && i < nInterval-1; i++)
664 pindexFirst = pindexFirst->pprev;
667 // Limit adjustment step
668 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
669 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
670 if (nActualTimespan < nTargetTimespan/4)
671 nActualTimespan = nTargetTimespan/4;
672 if (nActualTimespan > nTargetTimespan*4)
673 nActualTimespan = nTargetTimespan*4;
677 bnNew.SetCompact(pindexLast->nBits);
678 bnNew *= nActualTimespan;
679 bnNew /= nTargetTimespan;
681 if (bnNew > bnProofOfWorkLimit)
682 bnNew = bnProofOfWorkLimit;
685 printf("GetNextWorkRequired RETARGET\n");
686 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
687 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
688 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
690 return bnNew.GetCompact();
693 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
696 bnTarget.SetCompact(nBits);
699 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
700 return error("CheckProofOfWork() : nBits below minimum work");
702 // Check proof of work matches claimed amount
703 if (hash > bnTarget.getuint256())
704 return error("CheckProofOfWork() : hash doesn't match nBits");
709 // Return conservative estimate of total number of blocks, 0 if unknown
710 int GetTotalBlocksEstimate()
718 return nTotalBlocksEstimate;
722 bool IsInitialBlockDownload()
724 if (pindexBest == NULL || nBestHeight < (GetTotalBlocksEstimate()-nInitialBlockThreshold))
726 static int64 nLastUpdate;
727 static CBlockIndex* pindexLastBest;
728 if (pindexBest != pindexLastBest)
730 pindexLastBest = pindexBest;
731 nLastUpdate = GetTime();
733 return (GetTime() - nLastUpdate < 10 &&
734 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
737 void static InvalidChainFound(CBlockIndex* pindexNew)
739 if (pindexNew->bnChainWork > bnBestInvalidWork)
741 bnBestInvalidWork = pindexNew->bnChainWork;
742 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
745 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());
746 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
747 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
748 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
761 bool CTransaction::DisconnectInputs(CTxDB& txdb)
763 // Relinquish previous transactions' spent pointers
766 BOOST_FOREACH(const CTxIn& txin, vin)
768 COutPoint prevout = txin.prevout;
770 // Get prev txindex from disk
772 if (!txdb.ReadTxIndex(prevout.hash, txindex))
773 return error("DisconnectInputs() : ReadTxIndex failed");
775 if (prevout.n >= txindex.vSpent.size())
776 return error("DisconnectInputs() : prevout.n out of range");
778 // Mark outpoint as not spent
779 txindex.vSpent[prevout.n].SetNull();
782 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
783 return error("DisconnectInputs() : UpdateTxIndex failed");
787 // Remove transaction from index
788 if (!txdb.EraseTxIndex(*this))
789 return error("DisconnectInputs() : EraseTxPos failed");
795 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
796 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
798 // Take over previous transactions' spent pointers
802 for (int i = 0; i < vin.size(); i++)
804 COutPoint prevout = vin[i].prevout;
809 if (fMiner && mapTestPool.count(prevout.hash))
811 // Get txindex from current proposed changes
812 txindex = mapTestPool[prevout.hash];
816 // Read txindex from txdb
817 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
819 if (!fFound && (fBlock || fMiner))
820 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());
824 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
826 // Get prev tx from single transactions in memory
827 CRITICAL_BLOCK(cs_mapTransactions)
829 if (!mapTransactions.count(prevout.hash))
830 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
831 txPrev = mapTransactions[prevout.hash];
834 txindex.vSpent.resize(txPrev.vout.size());
838 // Get prev tx from disk
839 if (!txPrev.ReadFromDisk(txindex.pos))
840 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
843 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
844 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());
846 // If prev is coinbase, check that it's matured
847 if (txPrev.IsCoinBase())
848 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
849 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
850 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
853 if (!VerifySignature(txPrev, *this, i))
854 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
856 // Check for conflicts
857 if (!txindex.vSpent[prevout.n].IsNull())
858 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());
860 // Check for negative or overflow input values
861 nValueIn += txPrev.vout[prevout.n].nValue;
862 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
863 return error("ConnectInputs() : txin values out of range");
865 // Mark outpoints as spent
866 txindex.vSpent[prevout.n] = posThisTx;
871 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
872 return error("ConnectInputs() : UpdateTxIndex failed");
876 mapTestPool[prevout.hash] = txindex;
880 if (nValueIn < GetValueOut())
881 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
883 // Tally transaction fees
884 int64 nTxFee = nValueIn - GetValueOut();
886 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
887 if (nTxFee < nMinFee)
890 if (!MoneyRange(nFees))
891 return error("ConnectInputs() : nFees out of range");
896 // Add transaction to disk index
897 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
898 return error("ConnectInputs() : AddTxPos failed");
902 // Add transaction to test pool
903 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
910 bool CTransaction::ClientConnectInputs()
915 // Take over previous transactions' spent pointers
916 CRITICAL_BLOCK(cs_mapTransactions)
919 for (int i = 0; i < vin.size(); i++)
921 // Get prev tx from single transactions in memory
922 COutPoint prevout = vin[i].prevout;
923 if (!mapTransactions.count(prevout.hash))
925 CTransaction& txPrev = mapTransactions[prevout.hash];
927 if (prevout.n >= txPrev.vout.size())
931 if (!VerifySignature(txPrev, *this, i))
932 return error("ConnectInputs() : VerifySignature failed");
934 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
935 ///// this has to go away now that posNext is gone
936 // // Check for conflicts
937 // if (!txPrev.vout[prevout.n].posNext.IsNull())
938 // return error("ConnectInputs() : prev tx already used");
940 // // Flag outpoints as used
941 // txPrev.vout[prevout.n].posNext = posThisTx;
943 nValueIn += txPrev.vout[prevout.n].nValue;
945 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
946 return error("ClientConnectInputs() : txin values out of range");
948 if (GetValueOut() > nValueIn)
958 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
960 // Disconnect in reverse order
961 for (int i = vtx.size()-1; i >= 0; i--)
962 if (!vtx[i].DisconnectInputs(txdb))
965 // Update block index on disk without changing it in memory.
966 // The memory index structure will be changed after the db commits.
969 CDiskBlockIndex blockindexPrev(pindex->pprev);
970 blockindexPrev.hashNext = 0;
971 if (!txdb.WriteBlockIndex(blockindexPrev))
972 return error("DisconnectBlock() : WriteBlockIndex failed");
978 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
980 // Check it again in case a previous version let a bad block in
984 //// issue here: it doesn't know the version
985 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
987 map<uint256, CTxIndex> mapUnused;
989 BOOST_FOREACH(CTransaction& tx, vtx)
991 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
992 nTxPos += ::GetSerializeSize(tx, SER_DISK);
994 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
998 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1001 // Update block index on disk without changing it in memory.
1002 // The memory index structure will be changed after the db commits.
1005 CDiskBlockIndex blockindexPrev(pindex->pprev);
1006 blockindexPrev.hashNext = pindex->GetBlockHash();
1007 if (!txdb.WriteBlockIndex(blockindexPrev))
1008 return error("ConnectBlock() : WriteBlockIndex failed");
1011 // Watch for transactions paying to me
1012 BOOST_FOREACH(CTransaction& tx, vtx)
1013 SyncWithWallets(tx, this, true);
1018 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1020 printf("REORGANIZE\n");
1023 CBlockIndex* pfork = pindexBest;
1024 CBlockIndex* plonger = pindexNew;
1025 while (pfork != plonger)
1027 while (plonger->nHeight > pfork->nHeight)
1028 if (!(plonger = plonger->pprev))
1029 return error("Reorganize() : plonger->pprev is null");
1030 if (pfork == plonger)
1032 if (!(pfork = pfork->pprev))
1033 return error("Reorganize() : pfork->pprev is null");
1036 // List of what to disconnect
1037 vector<CBlockIndex*> vDisconnect;
1038 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1039 vDisconnect.push_back(pindex);
1041 // List of what to connect
1042 vector<CBlockIndex*> vConnect;
1043 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1044 vConnect.push_back(pindex);
1045 reverse(vConnect.begin(), vConnect.end());
1047 // Disconnect shorter branch
1048 vector<CTransaction> vResurrect;
1049 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1052 if (!block.ReadFromDisk(pindex))
1053 return error("Reorganize() : ReadFromDisk for disconnect failed");
1054 if (!block.DisconnectBlock(txdb, pindex))
1055 return error("Reorganize() : DisconnectBlock failed");
1057 // Queue memory transactions to resurrect
1058 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1059 if (!tx.IsCoinBase())
1060 vResurrect.push_back(tx);
1063 // Connect longer branch
1064 vector<CTransaction> vDelete;
1065 for (int i = 0; i < vConnect.size(); i++)
1067 CBlockIndex* pindex = vConnect[i];
1069 if (!block.ReadFromDisk(pindex))
1070 return error("Reorganize() : ReadFromDisk for connect failed");
1071 if (!block.ConnectBlock(txdb, pindex))
1075 return error("Reorganize() : ConnectBlock failed");
1078 // Queue memory transactions to delete
1079 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1080 vDelete.push_back(tx);
1082 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1083 return error("Reorganize() : WriteHashBestChain failed");
1085 // Make sure it's successfully written to disk before changing memory structure
1086 if (!txdb.TxnCommit())
1087 return error("Reorganize() : TxnCommit failed");
1089 // Disconnect shorter branch
1090 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1092 pindex->pprev->pnext = NULL;
1094 // Connect longer branch
1095 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1097 pindex->pprev->pnext = pindex;
1099 // Resurrect memory transactions that were in the disconnected branch
1100 BOOST_FOREACH(CTransaction& tx, vResurrect)
1101 tx.AcceptToMemoryPool(txdb, false);
1103 // Delete redundant memory transactions that are in the connected branch
1104 BOOST_FOREACH(CTransaction& tx, vDelete)
1105 tx.RemoveFromMemoryPool();
1111 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1113 uint256 hash = GetHash();
1116 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1118 txdb.WriteHashBestChain(hash);
1119 if (!txdb.TxnCommit())
1120 return error("SetBestChain() : TxnCommit failed");
1121 pindexGenesisBlock = pindexNew;
1123 else if (hashPrevBlock == hashBestChain)
1125 // Adding to current best branch
1126 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1129 InvalidChainFound(pindexNew);
1130 return error("SetBestChain() : ConnectBlock failed");
1132 if (!txdb.TxnCommit())
1133 return error("SetBestChain() : TxnCommit failed");
1135 // Add to current best branch
1136 pindexNew->pprev->pnext = pindexNew;
1138 // Delete redundant memory transactions
1139 BOOST_FOREACH(CTransaction& tx, vtx)
1140 tx.RemoveFromMemoryPool();
1145 if (!Reorganize(txdb, pindexNew))
1148 InvalidChainFound(pindexNew);
1149 return error("SetBestChain() : Reorganize failed");
1153 // Update best block in wallet (so we can detect restored wallets)
1154 if (!IsInitialBlockDownload())
1156 const CBlockLocator locator(pindexNew);
1157 ::SetBestChain(locator);
1161 hashBestChain = hash;
1162 pindexBest = pindexNew;
1163 nBestHeight = pindexBest->nHeight;
1164 bnBestChainWork = pindexNew->bnChainWork;
1165 nTimeBestReceived = GetTime();
1166 nTransactionsUpdated++;
1167 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1173 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1175 // Check for duplicate
1176 uint256 hash = GetHash();
1177 if (mapBlockIndex.count(hash))
1178 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1180 // Construct new block index object
1181 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1183 return error("AddToBlockIndex() : new CBlockIndex failed");
1184 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1185 pindexNew->phashBlock = &((*mi).first);
1186 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1187 if (miPrev != mapBlockIndex.end())
1189 pindexNew->pprev = (*miPrev).second;
1190 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1192 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1196 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1197 if (!txdb.TxnCommit())
1201 if (pindexNew->bnChainWork > bnBestChainWork)
1202 if (!SetBestChain(txdb, pindexNew))
1207 if (pindexNew == pindexBest)
1209 // Notify UI to display prev block's coinbase if it was ours
1210 static uint256 hashPrevBestCoinBase;
1211 UpdatedTransaction(hashPrevBestCoinBase);
1212 hashPrevBestCoinBase = vtx[0].GetHash();
1222 bool CBlock::CheckBlock() const
1224 // These are checks that are independent of context
1225 // that can be verified before saving an orphan block.
1228 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1229 return error("CheckBlock() : size limits failed");
1231 // Check proof of work matches claimed amount
1232 if (!CheckProofOfWork(GetHash(), nBits))
1233 return error("CheckBlock() : proof of work failed");
1236 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1237 return error("CheckBlock() : block timestamp too far in the future");
1239 // First transaction must be coinbase, the rest must not be
1240 if (vtx.empty() || !vtx[0].IsCoinBase())
1241 return error("CheckBlock() : first tx is not coinbase");
1242 for (int i = 1; i < vtx.size(); i++)
1243 if (vtx[i].IsCoinBase())
1244 return error("CheckBlock() : more than one coinbase");
1246 // Check transactions
1247 BOOST_FOREACH(const CTransaction& tx, vtx)
1248 if (!tx.CheckTransaction())
1249 return error("CheckBlock() : CheckTransaction failed");
1251 // Check that it's not full of nonstandard transactions
1252 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1253 return error("CheckBlock() : too many nonstandard transactions");
1256 if (hashMerkleRoot != BuildMerkleTree())
1257 return error("CheckBlock() : hashMerkleRoot mismatch");
1262 bool CBlock::AcceptBlock()
1264 // Check for duplicate
1265 uint256 hash = GetHash();
1266 if (mapBlockIndex.count(hash))
1267 return error("AcceptBlock() : block already in mapBlockIndex");
1269 // Get prev block index
1270 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1271 if (mi == mapBlockIndex.end())
1272 return error("AcceptBlock() : prev block not found");
1273 CBlockIndex* pindexPrev = (*mi).second;
1274 int nHeight = pindexPrev->nHeight+1;
1276 // Check proof of work
1277 if (nBits != GetNextWorkRequired(pindexPrev))
1278 return error("AcceptBlock() : incorrect proof of work");
1280 // Check timestamp against prev
1281 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1282 return error("AcceptBlock() : block's timestamp is too early");
1284 // Check that all transactions are finalized
1285 BOOST_FOREACH(const CTransaction& tx, vtx)
1286 if (!tx.IsFinal(nHeight, GetBlockTime()))
1287 return error("AcceptBlock() : contains a non-final transaction");
1289 // Check that the block chain matches the known block chain up to a checkpoint
1291 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1292 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1293 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1294 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1295 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) ||
1296 (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) ||
1297 (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")) ||
1298 (nHeight == 134444 && hash != uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")))
1299 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1301 // Write block to history file
1302 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1303 return error("AcceptBlock() : out of disk space");
1304 unsigned int nFile = -1;
1305 unsigned int nBlockPos = 0;
1306 if (!WriteToDisk(nFile, nBlockPos))
1307 return error("AcceptBlock() : WriteToDisk failed");
1308 if (!AddToBlockIndex(nFile, nBlockPos))
1309 return error("AcceptBlock() : AddToBlockIndex failed");
1311 // Relay inventory, but don't relay old inventory during initial block download
1312 if (hashBestChain == hash)
1313 CRITICAL_BLOCK(cs_vNodes)
1314 BOOST_FOREACH(CNode* pnode, vNodes)
1315 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 134444))
1316 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1321 bool static ProcessBlock(CNode* pfrom, CBlock* pblock)
1323 // Check for duplicate
1324 uint256 hash = pblock->GetHash();
1325 if (mapBlockIndex.count(hash))
1326 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1327 if (mapOrphanBlocks.count(hash))
1328 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1330 // Preliminary checks
1331 if (!pblock->CheckBlock())
1332 return error("ProcessBlock() : CheckBlock FAILED");
1334 // If don't already have its previous block, shunt it off to holding area until we get it
1335 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1337 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1338 CBlock* pblock2 = new CBlock(*pblock);
1339 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1340 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1342 // Ask this guy to fill in what we're missing
1344 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1349 if (!pblock->AcceptBlock())
1350 return error("ProcessBlock() : AcceptBlock FAILED");
1352 // Recursively process any orphan blocks that depended on this one
1353 vector<uint256> vWorkQueue;
1354 vWorkQueue.push_back(hash);
1355 for (int i = 0; i < vWorkQueue.size(); i++)
1357 uint256 hashPrev = vWorkQueue[i];
1358 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1359 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1362 CBlock* pblockOrphan = (*mi).second;
1363 if (pblockOrphan->AcceptBlock())
1364 vWorkQueue.push_back(pblockOrphan->GetHash());
1365 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1366 delete pblockOrphan;
1368 mapOrphanBlocksByPrev.erase(hashPrev);
1371 printf("ProcessBlock: ACCEPTED\n");
1382 template<typename Stream>
1383 bool static ScanMessageStart(Stream& s)
1385 // Scan ahead to the next pchMessageStart, which should normally be immediately
1386 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1388 short prevmask = s.exceptions(0);
1389 const char* p = BEGIN(pchMessageStart);
1399 s.exceptions(prevmask);
1403 p = BEGIN(pchMessageStart);
1406 if (++p == END(pchMessageStart))
1409 s.exceptions(prevmask);
1418 s.exceptions(prevmask);
1423 bool CheckDiskSpace(uint64 nAdditionalBytes)
1425 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1427 // Check for 15MB because database could create another 10MB log file at any time
1428 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1431 string strMessage = _("Warning: Disk space is low ");
1432 strMiscWarning = strMessage;
1433 printf("*** %s\n", strMessage.c_str());
1434 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1435 CreateThread(Shutdown, NULL);
1441 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1445 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1448 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1450 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1459 static unsigned int nCurrentBlockFile = 1;
1461 FILE* AppendBlockFile(unsigned int& nFileRet)
1466 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1469 if (fseek(file, 0, SEEK_END) != 0)
1471 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1472 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1474 nFileRet = nCurrentBlockFile;
1478 nCurrentBlockFile++;
1482 bool LoadBlockIndex(bool fAllowNew)
1486 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1487 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1488 pchMessageStart[0] = 0xfa;
1489 pchMessageStart[1] = 0xbf;
1490 pchMessageStart[2] = 0xb5;
1491 pchMessageStart[3] = 0xda;
1498 if (!txdb.LoadBlockIndex())
1503 // Init with genesis block
1505 if (mapBlockIndex.empty())
1511 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1512 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1513 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1514 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1515 // vMerkleTree: 4a5e1e
1518 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1520 txNew.vin.resize(1);
1521 txNew.vout.resize(1);
1522 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1523 txNew.vout[0].nValue = 50 * COIN;
1524 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1526 block.vtx.push_back(txNew);
1527 block.hashPrevBlock = 0;
1528 block.hashMerkleRoot = block.BuildMerkleTree();
1530 block.nTime = 1231006505;
1531 block.nBits = 0x1d00ffff;
1532 block.nNonce = 2083236893;
1536 block.nTime = 1296688602;
1537 block.nBits = 0x1d07fff8;
1538 block.nNonce = 384568319;
1542 printf("%s\n", block.GetHash().ToString().c_str());
1543 printf("%s\n", hashGenesisBlock.ToString().c_str());
1544 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1545 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1547 assert(block.GetHash() == hashGenesisBlock);
1549 // Start new block file
1551 unsigned int nBlockPos;
1552 if (!block.WriteToDisk(nFile, nBlockPos))
1553 return error("LoadBlockIndex() : writing genesis block to disk failed");
1554 if (!block.AddToBlockIndex(nFile, nBlockPos))
1555 return error("LoadBlockIndex() : genesis block not accepted");
1563 void PrintBlockTree()
1565 // precompute tree structure
1566 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1567 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1569 CBlockIndex* pindex = (*mi).second;
1570 mapNext[pindex->pprev].push_back(pindex);
1572 //while (rand() % 3 == 0)
1573 // mapNext[pindex->pprev].push_back(pindex);
1576 vector<pair<int, CBlockIndex*> > vStack;
1577 vStack.push_back(make_pair(0, pindexGenesisBlock));
1580 while (!vStack.empty())
1582 int nCol = vStack.back().first;
1583 CBlockIndex* pindex = vStack.back().second;
1586 // print split or gap
1587 if (nCol > nPrevCol)
1589 for (int i = 0; i < nCol-1; i++)
1593 else if (nCol < nPrevCol)
1595 for (int i = 0; i < nCol; i++)
1602 for (int i = 0; i < nCol; i++)
1607 block.ReadFromDisk(pindex);
1608 printf("%d (%u,%u) %s %s tx %d",
1612 block.GetHash().ToString().substr(0,20).c_str(),
1613 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1616 PrintWallets(block);
1618 // put the main timechain first
1619 vector<CBlockIndex*>& vNext = mapNext[pindex];
1620 for (int i = 0; i < vNext.size(); i++)
1622 if (vNext[i]->pnext)
1624 swap(vNext[0], vNext[i]);
1630 for (int i = 0; i < vNext.size(); i++)
1631 vStack.push_back(make_pair(nCol+i, vNext[i]));
1644 //////////////////////////////////////////////////////////////////////////////
1649 map<uint256, CAlert> mapAlerts;
1650 CCriticalSection cs_mapAlerts;
1652 string GetWarnings(string strFor)
1655 string strStatusBar;
1657 if (GetBoolArg("-testsafemode"))
1660 // Misc warnings like out of disk space and clock is wrong
1661 if (strMiscWarning != "")
1664 strStatusBar = strMiscWarning;
1667 // Longer invalid proof-of-work chain
1668 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1671 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1675 CRITICAL_BLOCK(cs_mapAlerts)
1677 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1679 const CAlert& alert = item.second;
1680 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1682 nPriority = alert.nPriority;
1683 strStatusBar = alert.strStatusBar;
1688 if (strFor == "statusbar")
1689 return strStatusBar;
1690 else if (strFor == "rpc")
1692 assert(("GetWarnings() : invalid parameter", false));
1696 bool CAlert::ProcessAlert()
1698 if (!CheckSignature())
1703 CRITICAL_BLOCK(cs_mapAlerts)
1705 // Cancel previous alerts
1706 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1708 const CAlert& alert = (*mi).second;
1711 printf("cancelling alert %d\n", alert.nID);
1712 mapAlerts.erase(mi++);
1714 else if (!alert.IsInEffect())
1716 printf("expiring alert %d\n", alert.nID);
1717 mapAlerts.erase(mi++);
1723 // Check if this alert has been cancelled
1724 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1726 const CAlert& alert = item.second;
1727 if (alert.Cancels(*this))
1729 printf("alert already cancelled by %d\n", alert.nID);
1735 mapAlerts.insert(make_pair(GetHash(), *this));
1738 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1750 //////////////////////////////////////////////////////////////////////////////
1756 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1760 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1761 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1763 // Don't know what it is, just say we already got one
1770 // The message start string is designed to be unlikely to occur in normal data.
1771 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1772 // a large 4-byte int at any alignment.
1773 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1776 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1778 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1779 RandAddSeedPerfmon();
1781 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1782 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1783 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1785 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1793 if (strCommand == "version")
1795 // Each connection can only send one version message
1796 if (pfrom->nVersion != 0)
1803 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1804 if (pfrom->nVersion == 10300)
1805 pfrom->nVersion = 300;
1806 if (pfrom->nVersion >= 106 && !vRecv.empty())
1807 vRecv >> addrFrom >> nNonce;
1808 if (pfrom->nVersion >= 106 && !vRecv.empty())
1809 vRecv >> pfrom->strSubVer;
1810 if (pfrom->nVersion >= 209 && !vRecv.empty())
1811 vRecv >> pfrom->nStartingHeight;
1813 if (pfrom->nVersion == 0)
1816 // Disconnect if we connected to ourself
1817 if (nNonce == nLocalHostNonce && nNonce > 1)
1819 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1820 pfrom->fDisconnect = true;
1824 // Be shy and don't send version until we hear
1825 if (pfrom->fInbound)
1826 pfrom->PushVersion();
1828 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1830 AddTimeData(pfrom->addr.ip, nTime);
1833 if (pfrom->nVersion >= 209)
1834 pfrom->PushMessage("verack");
1835 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1836 if (pfrom->nVersion < 209)
1837 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1839 if (!pfrom->fInbound)
1841 // Advertise our address
1842 if (addrLocalHost.IsRoutable() && !fUseProxy)
1844 CAddress addr(addrLocalHost);
1845 addr.nTime = GetAdjustedTime();
1846 pfrom->PushAddress(addr);
1849 // Get recent addresses
1850 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
1852 pfrom->PushMessage("getaddr");
1853 pfrom->fGetAddr = true;
1857 // Ask the first connected node for block updates
1858 static int nAskedForBlocks;
1859 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
1862 pfrom->PushGetBlocks(pindexBest, uint256(0));
1866 CRITICAL_BLOCK(cs_mapAlerts)
1867 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1868 item.second.RelayTo(pfrom);
1870 pfrom->fSuccessfullyConnected = true;
1872 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1876 else if (pfrom->nVersion == 0)
1878 // Must have a version message before anything else
1883 else if (strCommand == "verack")
1885 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1889 else if (strCommand == "addr")
1891 vector<CAddress> vAddr;
1894 // Don't want addr from older versions unless seeding
1895 if (pfrom->nVersion < 209)
1897 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
1899 if (vAddr.size() > 1000)
1900 return error("message addr size() = %d", vAddr.size());
1902 // Store the new addresses
1903 int64 nNow = GetAdjustedTime();
1904 int64 nSince = nNow - 10 * 60;
1905 BOOST_FOREACH(CAddress& addr, vAddr)
1909 // ignore IPv6 for now, since it isn't implemented anyway
1912 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1913 addr.nTime = nNow - 5 * 24 * 60 * 60;
1914 AddAddress(addr, 2 * 60 * 60);
1915 pfrom->AddAddressKnown(addr);
1916 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1918 // Relay to a limited number of other nodes
1919 CRITICAL_BLOCK(cs_vNodes)
1921 // Use deterministic randomness to send to the same nodes for 24 hours
1922 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
1923 static uint256 hashSalt;
1925 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1926 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
1927 hashRand = Hash(BEGIN(hashRand), END(hashRand));
1928 multimap<uint256, CNode*> mapMix;
1929 BOOST_FOREACH(CNode* pnode, vNodes)
1931 if (pnode->nVersion < 31402)
1933 unsigned int nPointer;
1934 memcpy(&nPointer, &pnode, sizeof(nPointer));
1935 uint256 hashKey = hashRand ^ nPointer;
1936 hashKey = Hash(BEGIN(hashKey), END(hashKey));
1937 mapMix.insert(make_pair(hashKey, pnode));
1939 int nRelayNodes = 2;
1940 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1941 ((*mi).second)->PushAddress(addr);
1945 if (vAddr.size() < 1000)
1946 pfrom->fGetAddr = false;
1950 else if (strCommand == "inv")
1954 if (vInv.size() > 50000)
1955 return error("message inv size() = %d", vInv.size());
1958 BOOST_FOREACH(const CInv& inv, vInv)
1962 pfrom->AddInventoryKnown(inv);
1964 bool fAlreadyHave = AlreadyHave(txdb, inv);
1965 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
1969 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
1970 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
1972 // Track requests for our stuff
1973 Inventory(inv.hash);
1978 else if (strCommand == "getdata")
1982 if (vInv.size() > 50000)
1983 return error("message getdata size() = %d", vInv.size());
1985 BOOST_FOREACH(const CInv& inv, vInv)
1989 printf("received getdata for: %s\n", inv.ToString().c_str());
1991 if (inv.type == MSG_BLOCK)
1993 // Send block from disk
1994 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
1995 if (mi != mapBlockIndex.end())
1998 block.ReadFromDisk((*mi).second);
1999 pfrom->PushMessage("block", block);
2001 // Trigger them to send a getblocks request for the next batch of inventory
2002 if (inv.hash == pfrom->hashContinue)
2004 // Bypass PushInventory, this must send even if redundant,
2005 // and we want it right after the last block so they don't
2006 // wait for other stuff first.
2008 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2009 pfrom->PushMessage("inv", vInv);
2010 pfrom->hashContinue = 0;
2014 else if (inv.IsKnownType())
2016 // Send stream from relay memory
2017 CRITICAL_BLOCK(cs_mapRelay)
2019 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2020 if (mi != mapRelay.end())
2021 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2025 // Track requests for our stuff
2026 Inventory(inv.hash);
2031 else if (strCommand == "getblocks")
2033 CBlockLocator locator;
2035 vRecv >> locator >> hashStop;
2037 // Find the last block the caller has in the main chain
2038 CBlockIndex* pindex = locator.GetBlockIndex();
2040 // Send the rest of the chain
2042 pindex = pindex->pnext;
2043 int nLimit = 500 + locator.GetDistanceBack();
2044 unsigned int nBytes = 0;
2045 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2046 for (; pindex; pindex = pindex->pnext)
2048 if (pindex->GetBlockHash() == hashStop)
2050 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2053 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2055 block.ReadFromDisk(pindex, true);
2056 nBytes += block.GetSerializeSize(SER_NETWORK);
2057 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2059 // When this block is requested, we'll send an inv that'll make them
2060 // getblocks the next batch of inventory.
2061 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2062 pfrom->hashContinue = pindex->GetBlockHash();
2069 else if (strCommand == "getheaders")
2071 CBlockLocator locator;
2073 vRecv >> locator >> hashStop;
2075 CBlockIndex* pindex = NULL;
2076 if (locator.IsNull())
2078 // If locator is null, return the hashStop block
2079 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2080 if (mi == mapBlockIndex.end())
2082 pindex = (*mi).second;
2086 // Find the last block the caller has in the main chain
2087 pindex = locator.GetBlockIndex();
2089 pindex = pindex->pnext;
2092 vector<CBlock> vHeaders;
2093 int nLimit = 2000 + locator.GetDistanceBack();
2094 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2095 for (; pindex; pindex = pindex->pnext)
2097 vHeaders.push_back(pindex->GetBlockHeader());
2098 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2101 pfrom->PushMessage("headers", vHeaders);
2105 else if (strCommand == "tx")
2107 vector<uint256> vWorkQueue;
2108 CDataStream vMsg(vRecv);
2112 CInv inv(MSG_TX, tx.GetHash());
2113 pfrom->AddInventoryKnown(inv);
2115 bool fMissingInputs = false;
2116 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2118 SyncWithWallets(tx, NULL, true);
2119 RelayMessage(inv, vMsg);
2120 mapAlreadyAskedFor.erase(inv);
2121 vWorkQueue.push_back(inv.hash);
2123 // Recursively process any orphan transactions that depended on this one
2124 for (int i = 0; i < vWorkQueue.size(); i++)
2126 uint256 hashPrev = vWorkQueue[i];
2127 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2128 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2131 const CDataStream& vMsg = *((*mi).second);
2133 CDataStream(vMsg) >> tx;
2134 CInv inv(MSG_TX, tx.GetHash());
2136 if (tx.AcceptToMemoryPool(true))
2138 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2139 SyncWithWallets(tx, NULL, true);
2140 RelayMessage(inv, vMsg);
2141 mapAlreadyAskedFor.erase(inv);
2142 vWorkQueue.push_back(inv.hash);
2147 BOOST_FOREACH(uint256 hash, vWorkQueue)
2148 EraseOrphanTx(hash);
2150 else if (fMissingInputs)
2152 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2158 else if (strCommand == "block")
2163 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2166 CInv inv(MSG_BLOCK, block.GetHash());
2167 pfrom->AddInventoryKnown(inv);
2169 if (ProcessBlock(pfrom, &block))
2170 mapAlreadyAskedFor.erase(inv);
2174 else if (strCommand == "getaddr")
2176 // Nodes rebroadcast an addr every 24 hours
2177 pfrom->vAddrToSend.clear();
2178 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2179 CRITICAL_BLOCK(cs_mapAddresses)
2181 unsigned int nCount = 0;
2182 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2184 const CAddress& addr = item.second;
2185 if (addr.nTime > nSince)
2188 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2190 const CAddress& addr = item.second;
2191 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2192 pfrom->PushAddress(addr);
2198 else if (strCommand == "checkorder")
2203 if (!GetBoolArg("-allowreceivebyip"))
2205 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2212 /// we have a chance to check the order here
2214 // Keep giving the same key to the same ip until they use it
2215 if (!mapReuseKey.count(pfrom->addr.ip))
2216 mapReuseKey[pfrom->addr.ip] = pwalletMain->GetOrReuseKeyFromPool();
2218 // Send back approval of order and pubkey to use
2219 CScript scriptPubKey;
2220 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2221 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2225 else if (strCommand == "reply")
2230 CRequestTracker tracker;
2231 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2233 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2234 if (mi != pfrom->mapRequests.end())
2236 tracker = (*mi).second;
2237 pfrom->mapRequests.erase(mi);
2240 if (!tracker.IsNull())
2241 tracker.fn(tracker.param1, vRecv);
2245 else if (strCommand == "ping")
2250 else if (strCommand == "alert")
2255 if (alert.ProcessAlert())
2258 pfrom->setKnown.insert(alert.GetHash());
2259 CRITICAL_BLOCK(cs_vNodes)
2260 BOOST_FOREACH(CNode* pnode, vNodes)
2261 alert.RelayTo(pnode);
2268 // Ignore unknown commands for extensibility
2272 // Update the last seen time for this node's address
2273 if (pfrom->fNetworkNode)
2274 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2275 AddressCurrentlyConnected(pfrom->addr);
2281 bool ProcessMessages(CNode* pfrom)
2283 CDataStream& vRecv = pfrom->vRecv;
2287 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2291 // (4) message start
2300 // Scan for message start
2301 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2302 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2303 if (vRecv.end() - pstart < nHeaderSize)
2305 if (vRecv.size() > nHeaderSize)
2307 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2308 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2312 if (pstart - vRecv.begin() > 0)
2313 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2314 vRecv.erase(vRecv.begin(), pstart);
2317 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2322 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2325 string strCommand = hdr.GetCommand();
2328 unsigned int nMessageSize = hdr.nMessageSize;
2329 if (nMessageSize > MAX_SIZE)
2331 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2334 if (nMessageSize > vRecv.size())
2336 // Rewind and wait for rest of message
2337 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2342 if (vRecv.GetVersion() >= 209)
2344 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2345 unsigned int nChecksum = 0;
2346 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2347 if (nChecksum != hdr.nChecksum)
2349 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2350 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2355 // Copy message to its own buffer
2356 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2357 vRecv.ignore(nMessageSize);
2363 CRITICAL_BLOCK(cs_main)
2364 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2368 catch (std::ios_base::failure& e)
2370 if (strstr(e.what(), "end of data"))
2372 // Allow exceptions from underlength message on vRecv
2373 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());
2375 else if (strstr(e.what(), "size too large"))
2377 // Allow exceptions from overlong size
2378 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2382 PrintExceptionContinue(&e, "ProcessMessage()");
2385 catch (std::exception& e) {
2386 PrintExceptionContinue(&e, "ProcessMessage()");
2388 PrintExceptionContinue(NULL, "ProcessMessage()");
2392 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2400 bool SendMessages(CNode* pto, bool fSendTrickle)
2402 CRITICAL_BLOCK(cs_main)
2404 // Don't send anything until we get their version message
2405 if (pto->nVersion == 0)
2409 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2410 pto->PushMessage("ping");
2412 // Resend wallet transactions that haven't gotten in a block yet
2413 ResendWalletTransactions();
2415 // Address refresh broadcast
2416 static int64 nLastRebroadcast;
2417 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2419 nLastRebroadcast = GetTime();
2420 CRITICAL_BLOCK(cs_vNodes)
2422 BOOST_FOREACH(CNode* pnode, vNodes)
2424 // Periodically clear setAddrKnown to allow refresh broadcasts
2425 pnode->setAddrKnown.clear();
2427 // Rebroadcast our address
2428 if (addrLocalHost.IsRoutable() && !fUseProxy)
2430 CAddress addr(addrLocalHost);
2431 addr.nTime = GetAdjustedTime();
2432 pnode->PushAddress(addr);
2438 // Clear out old addresses periodically so it's not too much work at once
2439 static int64 nLastClear;
2440 if (nLastClear == 0)
2441 nLastClear = GetTime();
2442 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2444 nLastClear = GetTime();
2445 CRITICAL_BLOCK(cs_mapAddresses)
2448 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2449 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2450 mi != mapAddresses.end();)
2452 const CAddress& addr = (*mi).second;
2453 if (addr.nTime < nSince)
2455 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2457 addrdb.EraseAddress(addr);
2458 mapAddresses.erase(mi++);
2472 vector<CAddress> vAddr;
2473 vAddr.reserve(pto->vAddrToSend.size());
2474 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2476 // returns true if wasn't already contained in the set
2477 if (pto->setAddrKnown.insert(addr).second)
2479 vAddr.push_back(addr);
2480 // receiver rejects addr messages larger than 1000
2481 if (vAddr.size() >= 1000)
2483 pto->PushMessage("addr", vAddr);
2488 pto->vAddrToSend.clear();
2490 pto->PushMessage("addr", vAddr);
2495 // Message: inventory
2498 vector<CInv> vInvWait;
2499 CRITICAL_BLOCK(pto->cs_inventory)
2501 vInv.reserve(pto->vInventoryToSend.size());
2502 vInvWait.reserve(pto->vInventoryToSend.size());
2503 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2505 if (pto->setInventoryKnown.count(inv))
2508 // trickle out tx inv to protect privacy
2509 if (inv.type == MSG_TX && !fSendTrickle)
2511 // 1/4 of tx invs blast to all immediately
2512 static uint256 hashSalt;
2514 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2515 uint256 hashRand = inv.hash ^ hashSalt;
2516 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2517 bool fTrickleWait = ((hashRand & 3) != 0);
2519 // always trickle our own transactions
2523 if (GetTransaction(inv.hash, wtx))
2525 fTrickleWait = true;
2530 vInvWait.push_back(inv);
2535 // returns true if wasn't already contained in the set
2536 if (pto->setInventoryKnown.insert(inv).second)
2538 vInv.push_back(inv);
2539 if (vInv.size() >= 1000)
2541 pto->PushMessage("inv", vInv);
2546 pto->vInventoryToSend = vInvWait;
2549 pto->PushMessage("inv", vInv);
2555 vector<CInv> vGetData;
2556 int64 nNow = GetTime() * 1000000;
2558 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2560 const CInv& inv = (*pto->mapAskFor.begin()).second;
2561 if (!AlreadyHave(txdb, inv))
2563 printf("sending getdata: %s\n", inv.ToString().c_str());
2564 vGetData.push_back(inv);
2565 if (vGetData.size() >= 1000)
2567 pto->PushMessage("getdata", vGetData);
2571 pto->mapAskFor.erase(pto->mapAskFor.begin());
2573 if (!vGetData.empty())
2574 pto->PushMessage("getdata", vGetData);
2593 //////////////////////////////////////////////////////////////////////////////
2598 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2600 unsigned char* pdata = (unsigned char*)pbuffer;
2601 unsigned int blocks = 1 + ((len + 8) / 64);
2602 unsigned char* pend = pdata + 64 * blocks;
2603 memset(pdata + len, 0, 64 * blocks - len);
2605 unsigned int bits = len * 8;
2606 pend[-1] = (bits >> 0) & 0xff;
2607 pend[-2] = (bits >> 8) & 0xff;
2608 pend[-3] = (bits >> 16) & 0xff;
2609 pend[-4] = (bits >> 24) & 0xff;
2613 using CryptoPP::ByteReverse;
2615 static const unsigned int pSHA256InitState[8] =
2616 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2618 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2620 memcpy(pstate, pinit, 32);
2621 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2625 // ScanHash scans nonces looking for a hash with at least some zero bits.
2626 // It operates on big endian data. Caller does the byte reversing.
2627 // All input buffers are 16-byte aligned. nNonce is usually preserved
2628 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2629 // the block is rebuilt and nNonce starts over at zero.
2631 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2633 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2637 // Hash pdata using pmidstate as the starting state into
2638 // preformatted buffer phash1, then hash phash1 into phash
2640 SHA256Transform(phash1, pdata, pmidstate);
2641 SHA256Transform(phash, phash1, pSHA256InitState);
2643 // Return the nonce if the hash has at least some zero bits,
2644 // caller will check if it has enough to reach the target
2645 if (((unsigned short*)phash)[14] == 0)
2648 // If nothing found after trying for a while, return -1
2649 if ((nNonce & 0xffff) == 0)
2651 nHashesDone = 0xffff+1;
2662 set<uint256> setDependsOn;
2665 COrphan(CTransaction* ptxIn)
2673 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2674 BOOST_FOREACH(uint256 hash, setDependsOn)
2675 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2680 CBlock* CreateNewBlock(CReserveKey& reservekey)
2682 CBlockIndex* pindexPrev = pindexBest;
2685 auto_ptr<CBlock> pblock(new CBlock());
2689 // Create coinbase tx
2691 txNew.vin.resize(1);
2692 txNew.vin[0].prevout.SetNull();
2693 txNew.vout.resize(1);
2694 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2696 // Add our coinbase tx as first transaction
2697 pblock->vtx.push_back(txNew);
2699 // Collect memory pool transactions into the block
2701 CRITICAL_BLOCK(cs_main)
2702 CRITICAL_BLOCK(cs_mapTransactions)
2706 // Priority order to process transactions
2707 list<COrphan> vOrphan; // list memory doesn't move
2708 map<uint256, vector<COrphan*> > mapDependers;
2709 multimap<double, CTransaction*> mapPriority;
2710 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2712 CTransaction& tx = (*mi).second;
2713 if (tx.IsCoinBase() || !tx.IsFinal())
2716 COrphan* porphan = NULL;
2717 double dPriority = 0;
2718 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2720 // Read prev transaction
2721 CTransaction txPrev;
2723 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2725 // Has to wait for dependencies
2728 // Use list for automatic deletion
2729 vOrphan.push_back(COrphan(&tx));
2730 porphan = &vOrphan.back();
2732 mapDependers[txin.prevout.hash].push_back(porphan);
2733 porphan->setDependsOn.insert(txin.prevout.hash);
2736 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2738 // Read block header
2739 int nConf = txindex.GetDepthInMainChain();
2741 dPriority += (double)nValueIn * nConf;
2743 if (fDebug && GetBoolArg("-printpriority"))
2744 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2747 // Priority is sum(valuein * age) / txsize
2748 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2751 porphan->dPriority = dPriority;
2753 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2755 if (fDebug && GetBoolArg("-printpriority"))
2757 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2764 // Collect transactions into block
2765 map<uint256, CTxIndex> mapTestPool;
2766 uint64 nBlockSize = 1000;
2767 int nBlockSigOps = 100;
2768 while (!mapPriority.empty())
2770 // Take highest priority transaction off priority queue
2771 double dPriority = -(*mapPriority.begin()).first;
2772 CTransaction& tx = *(*mapPriority.begin()).second;
2773 mapPriority.erase(mapPriority.begin());
2776 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2777 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2779 int nTxSigOps = tx.GetSigOpCount();
2780 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2783 // Transaction fee required depends on block size
2784 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2785 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true);
2787 // Connecting shouldn't fail due to dependency on other memory pool transactions
2788 // because we're already processing them in order of dependency
2789 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2790 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
2792 swap(mapTestPool, mapTestPoolTmp);
2795 pblock->vtx.push_back(tx);
2796 nBlockSize += nTxSize;
2797 nBlockSigOps += nTxSigOps;
2799 // Add transactions that depend on this one to the priority queue
2800 uint256 hash = tx.GetHash();
2801 if (mapDependers.count(hash))
2803 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2805 if (!porphan->setDependsOn.empty())
2807 porphan->setDependsOn.erase(hash);
2808 if (porphan->setDependsOn.empty())
2809 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2815 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2818 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
2819 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2820 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2821 pblock->nBits = GetNextWorkRequired(pindexPrev);
2824 return pblock.release();
2828 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
2830 // Update nExtraNonce
2831 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2832 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
2837 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
2838 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2842 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
2845 // Prebuild hash buffers
2852 uint256 hashPrevBlock;
2853 uint256 hashMerkleRoot;
2856 unsigned int nNonce;
2859 unsigned char pchPadding0[64];
2861 unsigned char pchPadding1[64];
2864 memset(&tmp, 0, sizeof(tmp));
2866 tmp.block.nVersion = pblock->nVersion;
2867 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
2868 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
2869 tmp.block.nTime = pblock->nTime;
2870 tmp.block.nBits = pblock->nBits;
2871 tmp.block.nNonce = pblock->nNonce;
2873 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2874 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2876 // Byte swap all the input buffer
2877 for (int i = 0; i < sizeof(tmp)/4; i++)
2878 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2880 // Precalc the first half of the first hash, which stays constant
2881 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
2883 memcpy(pdata, &tmp.block, 128);
2884 memcpy(phash1, &tmp.hash1, 64);
2888 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
2890 uint256 hash = pblock->GetHash();
2891 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2893 if (hash > hashTarget)
2897 printf("BitcoinMiner:\n");
2898 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2900 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2901 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2904 CRITICAL_BLOCK(cs_main)
2906 if (pblock->hashPrevBlock != hashBestChain)
2907 return error("BitcoinMiner : generated block is stale");
2909 // Remove key from key pool
2910 reservekey.KeepKey();
2912 // Track how many getdata requests this block gets
2913 CRITICAL_BLOCK(wallet.cs_mapRequestCount)
2914 wallet.mapRequestCount[pblock->GetHash()] = 0;
2916 // Process this block the same as if we had received it from another node
2917 if (!ProcessBlock(NULL, pblock))
2918 return error("BitcoinMiner : ProcessBlock, block not accepted");
2925 void static ThreadBitcoinMiner(void* parg);
2927 void static BitcoinMiner(CWallet *pwallet)
2929 printf("BitcoinMiner started\n");
2930 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2932 // Each thread has its own key and counter
2933 CReserveKey reservekey(pwallet);
2934 unsigned int nExtraNonce = 0;
2935 int64 nPrevTime = 0;
2937 while (fGenerateBitcoins)
2939 if (AffinityBugWorkaround(ThreadBitcoinMiner))
2943 while (vNodes.empty() || IsInitialBlockDownload())
2948 if (!fGenerateBitcoins)
2956 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2957 CBlockIndex* pindexPrev = pindexBest;
2959 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
2962 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
2964 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2968 // Prebuild hash buffers
2970 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
2971 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
2972 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
2974 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
2976 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
2977 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
2983 int64 nStart = GetTime();
2984 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2986 uint256& hash = *alignup<16>(hashbuf);
2989 unsigned int nHashesDone = 0;
2990 unsigned int nNonceFound;
2993 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
2994 (char*)&hash, nHashesDone);
2996 // Check if something found
2997 if (nNonceFound != -1)
2999 for (int i = 0; i < sizeof(hash)/4; i++)
3000 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3002 if (hash <= hashTarget)
3005 pblock->nNonce = ByteReverse(nNonceFound);
3006 assert(hash == pblock->GetHash());
3008 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3009 CheckWork(pblock.get(), *pwalletMain, reservekey);
3010 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3016 static int64 nHashCounter;
3017 if (nHPSTimerStart == 0)
3019 nHPSTimerStart = GetTimeMillis();
3023 nHashCounter += nHashesDone;
3024 if (GetTimeMillis() - nHPSTimerStart > 4000)
3026 static CCriticalSection cs;
3029 if (GetTimeMillis() - nHPSTimerStart > 4000)
3031 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3032 nHPSTimerStart = GetTimeMillis();
3034 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3035 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3036 static int64 nLogTime;
3037 if (GetTime() - nLogTime > 30 * 60)
3039 nLogTime = GetTime();
3040 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3041 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3047 // Check for stop or if block needs to be rebuilt
3050 if (!fGenerateBitcoins)
3052 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3056 if (nBlockNonce >= 0xffff0000)
3058 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3060 if (pindexPrev != pindexBest)
3063 // Update nTime every few seconds
3064 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3065 nBlockTime = ByteReverse(pblock->nTime);
3070 void static ThreadBitcoinMiner(void* parg)
3072 CWallet* pwallet = (CWallet*)parg;
3075 vnThreadsRunning[3]++;
3076 BitcoinMiner(pwallet);
3077 vnThreadsRunning[3]--;
3079 catch (std::exception& e) {
3080 vnThreadsRunning[3]--;
3081 PrintException(&e, "ThreadBitcoinMiner()");
3083 vnThreadsRunning[3]--;
3084 PrintException(NULL, "ThreadBitcoinMiner()");
3086 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3088 if (vnThreadsRunning[3] == 0)
3090 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3094 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3096 if (fGenerateBitcoins != fGenerate)
3098 fGenerateBitcoins = fGenerate;
3099 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3102 if (fGenerateBitcoins)
3104 int nProcessors = boost::thread::hardware_concurrency();
3105 printf("%d processors\n", nProcessors);
3106 if (nProcessors < 1)
3108 if (fLimitProcessors && nProcessors > nLimitProcessors)
3109 nProcessors = nLimitProcessors;
3110 int nAddThreads = nProcessors - vnThreadsRunning[3];
3111 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3112 for (int i = 0; i < nAddThreads; i++)
3114 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3115 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");