1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #include "checkpoints.h"
10 #include "cryptopp/sha.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
15 using namespace boost;
21 CCriticalSection cs_setpwalletRegistered;
22 set<CWallet*> setpwalletRegistered;
24 CCriticalSection cs_main;
26 static map<uint256, CTransaction> mapTransactions;
27 CCriticalSection cs_mapTransactions;
28 unsigned int nTransactionsUpdated = 0;
29 map<COutPoint, CInPoint> mapNextTx;
31 map<uint256, CBlockIndex*> mapBlockIndex;
32 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
33 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
34 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
35 CBlockIndex* pindexGenesisBlock = NULL;
37 CBigNum bnBestChainWork = 0;
38 CBigNum bnBestInvalidWork = 0;
39 uint256 hashBestChain = 0;
40 CBlockIndex* pindexBest = NULL;
41 int64 nTimeBestReceived = 0;
43 map<uint256, CBlock*> mapOrphanBlocks;
44 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
46 map<uint256, CDataStream*> mapOrphanTransactions;
47 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
54 int fGenerateBitcoins = false;
55 int64 nTransactionFee = 0;
56 int fLimitProcessors = false;
57 int nLimitProcessors = 1;
58 int fMinimizeToTray = true;
59 int fMinimizeOnClose = true;
72 //////////////////////////////////////////////////////////////////////////////
74 // dispatching functions
77 void RegisterWallet(CWallet* pwalletIn)
79 CRITICAL_BLOCK(cs_setpwalletRegistered)
81 setpwalletRegistered.insert(pwalletIn);
85 void UnregisterWallet(CWallet* pwalletIn)
87 CRITICAL_BLOCK(cs_setpwalletRegistered)
89 setpwalletRegistered.erase(pwalletIn);
93 bool static IsFromMe(CTransaction& tx)
95 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
96 if (pwallet->IsFromMe(tx))
101 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
103 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
104 if (pwallet->GetTransaction(hashTx,wtx))
109 void static EraseFromWallets(uint256 hash)
111 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
112 pwallet->EraseFromWallet(hash);
115 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
117 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
118 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
121 void static SetBestChain(const CBlockLocator& loc)
123 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
124 pwallet->SetBestChain(loc);
127 void static UpdatedTransaction(const uint256& hashTx)
129 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
130 pwallet->UpdatedTransaction(hashTx);
133 void static PrintWallets(const CBlock& block)
135 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
136 pwallet->PrintWallet(block);
139 void static Inventory(const uint256& hash)
141 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
142 pwallet->Inventory(hash);
145 void static ResendWalletTransactions()
147 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
148 pwallet->ResendWalletTransactions();
157 //////////////////////////////////////////////////////////////////////////////
159 // mapOrphanTransactions
162 void static AddOrphanTx(const CDataStream& vMsg)
165 CDataStream(vMsg) >> tx;
166 uint256 hash = tx.GetHash();
167 if (mapOrphanTransactions.count(hash))
169 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
170 BOOST_FOREACH(const CTxIn& txin, tx.vin)
171 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
174 void static EraseOrphanTx(uint256 hash)
176 if (!mapOrphanTransactions.count(hash))
178 const CDataStream* pvMsg = mapOrphanTransactions[hash];
180 CDataStream(*pvMsg) >> tx;
181 BOOST_FOREACH(const CTxIn& txin, tx.vin)
183 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
184 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
186 if ((*mi).second == pvMsg)
187 mapOrphanTransactionsByPrev.erase(mi++);
193 mapOrphanTransactions.erase(hash);
203 //////////////////////////////////////////////////////////////////////////////
205 // CTransaction and CTxIndex
208 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
211 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
213 if (!ReadFromDisk(txindexRet.pos))
215 if (prevout.n >= vout.size())
223 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
226 return ReadFromDisk(txdb, prevout, txindex);
229 bool CTransaction::ReadFromDisk(COutPoint prevout)
233 return ReadFromDisk(txdb, prevout, txindex);
238 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
250 // Load the block this tx is in
252 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
254 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
259 // Update the tx's hashBlock
260 hashBlock = pblock->GetHash();
262 // Locate the transaction
263 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
264 if (pblock->vtx[nIndex] == *(CTransaction*)this)
266 if (nIndex == pblock->vtx.size())
268 vMerkleBranch.clear();
270 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
274 // Fill in merkle branch
275 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
278 // Is the tx in a block that's in the main chain
279 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
280 if (mi == mapBlockIndex.end())
282 CBlockIndex* pindex = (*mi).second;
283 if (!pindex || !pindex->IsInMainChain())
286 return pindexBest->nHeight - pindex->nHeight + 1;
295 bool CTransaction::CheckTransaction() const
297 // Basic checks that don't depend on any context
299 return error("CTransaction::CheckTransaction() : vin empty");
301 return error("CTransaction::CheckTransaction() : vout empty");
303 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
304 return error("CTransaction::CheckTransaction() : size limits failed");
306 // Check for negative or overflow output values
308 BOOST_FOREACH(const CTxOut& txout, vout)
310 if (txout.nValue < 0)
311 return error("CTransaction::CheckTransaction() : txout.nValue negative");
312 if (txout.nValue > MAX_MONEY)
313 return error("CTransaction::CheckTransaction() : txout.nValue too high");
314 nValueOut += txout.nValue;
315 if (!MoneyRange(nValueOut))
316 return error("CTransaction::CheckTransaction() : txout total out of range");
319 // Check for duplicate inputs
320 set<COutPoint> vInOutPoints;
321 BOOST_FOREACH(const CTxIn& txin, vin)
323 if (vInOutPoints.count(txin.prevout))
325 vInOutPoints.insert(txin.prevout);
330 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
331 return error("CTransaction::CheckTransaction() : coinbase script size");
335 BOOST_FOREACH(const CTxIn& txin, vin)
336 if (txin.prevout.IsNull())
337 return error("CTransaction::CheckTransaction() : prevout is null");
343 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
346 *pfMissingInputs = false;
348 if (!CheckTransaction())
349 return error("AcceptToMemoryPool() : CheckTransaction failed");
351 // Coinbase is only valid in a block, not as a loose transaction
353 return error("AcceptToMemoryPool() : coinbase as individual tx");
355 // To help v0.1.5 clients who would see it as a negative number
356 if ((int64)nLockTime > INT_MAX)
357 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
360 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
361 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
362 // attacks disallow transactions with more than one SigOp per 34 bytes.
363 // 34 bytes because a TxOut is:
364 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
365 if (GetSigOpCount() > nSize / 34 || nSize < 100)
366 return error("AcceptToMemoryPool() : nonstandard transaction");
368 // Rather not work on nonstandard transactions (unless -testnet)
369 if (!fTestNet && !IsStandard())
370 return error("AcceptToMemoryPool() : nonstandard transaction type");
372 // Do we already have it?
373 uint256 hash = GetHash();
374 CRITICAL_BLOCK(cs_mapTransactions)
375 if (mapTransactions.count(hash))
378 if (txdb.ContainsTx(hash))
381 // Check for conflicts with in-memory transactions
382 CTransaction* ptxOld = NULL;
383 for (int i = 0; i < vin.size(); i++)
385 COutPoint outpoint = vin[i].prevout;
386 if (mapNextTx.count(outpoint))
388 // Disable replacement feature for now
391 // Allow replacing with a newer version of the same transaction
394 ptxOld = mapNextTx[outpoint].ptx;
395 if (ptxOld->IsFinal())
397 if (!IsNewerThan(*ptxOld))
399 for (int i = 0; i < vin.size(); i++)
401 COutPoint outpoint = vin[i].prevout;
402 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
411 // Check against previous transactions
412 map<uint256, CTxIndex> mapUnused;
414 bool fInvalid = false;
415 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, 0, fInvalid))
418 return error("AcceptToMemoryPool() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
419 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
422 // Don't accept it if it can't get into a block
423 if (nFees < GetMinFee(1000, true, true))
424 return error("AcceptToMemoryPool() : not enough fees");
426 // Continuously rate-limit free transactions
427 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
428 // be annoying or make other's transactions take longer to confirm.
429 if (nFees < MIN_RELAY_TX_FEE)
431 static CCriticalSection cs;
432 static double dFreeCount;
433 static int64 nLastTime;
434 int64 nNow = GetTime();
438 // Use an exponentially decaying ~10-minute window:
439 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
441 // -limitfreerelay unit is thousand-bytes-per-minute
442 // At default rate it would take over a month to fill 1GB
443 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
444 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
446 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
452 // Store transaction in memory
453 CRITICAL_BLOCK(cs_mapTransactions)
457 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
458 ptxOld->RemoveFromMemoryPool();
460 AddToMemoryPoolUnchecked();
463 ///// are we sure this is ok when loading transactions or restoring block txes
464 // If updated, erase old tx from wallet
466 EraseFromWallets(ptxOld->GetHash());
468 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
472 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
475 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
478 bool CTransaction::AddToMemoryPoolUnchecked()
480 // Add to memory pool without checking anything. Don't call this directly,
481 // call AcceptToMemoryPool to properly check the transaction first.
482 CRITICAL_BLOCK(cs_mapTransactions)
484 uint256 hash = GetHash();
485 mapTransactions[hash] = *this;
486 for (int i = 0; i < vin.size(); i++)
487 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
488 nTransactionsUpdated++;
494 bool CTransaction::RemoveFromMemoryPool()
496 // Remove transaction from memory pool
497 CRITICAL_BLOCK(cs_mapTransactions)
499 BOOST_FOREACH(const CTxIn& txin, vin)
500 mapNextTx.erase(txin.prevout);
501 mapTransactions.erase(GetHash());
502 nTransactionsUpdated++;
512 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
514 if (hashBlock == 0 || nIndex == -1)
517 // Find the block it claims to be in
518 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
519 if (mi == mapBlockIndex.end())
521 CBlockIndex* pindex = (*mi).second;
522 if (!pindex || !pindex->IsInMainChain())
525 // Make sure the merkle branch connects to this block
526 if (!fMerkleVerified)
528 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
530 fMerkleVerified = true;
533 nHeightRet = pindex->nHeight;
534 return pindexBest->nHeight - pindex->nHeight + 1;
538 int CMerkleTx::GetBlocksToMaturity() const
542 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
546 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
550 if (!IsInMainChain() && !ClientConnectInputs())
552 return CTransaction::AcceptToMemoryPool(txdb, false);
556 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
560 bool CMerkleTx::AcceptToMemoryPool()
563 return AcceptToMemoryPool(txdb);
568 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
570 CRITICAL_BLOCK(cs_mapTransactions)
572 // Add previous supporting transactions first
573 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
575 if (!tx.IsCoinBase())
577 uint256 hash = tx.GetHash();
578 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
579 tx.AcceptToMemoryPool(txdb, fCheckInputs);
582 return AcceptToMemoryPool(txdb, fCheckInputs);
587 bool CWalletTx::AcceptWalletTransaction()
590 return AcceptWalletTransaction(txdb);
593 int CTxIndex::GetDepthInMainChain() const
597 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
599 // Find the block in the index
600 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
601 if (mi == mapBlockIndex.end())
603 CBlockIndex* pindex = (*mi).second;
604 if (!pindex || !pindex->IsInMainChain())
606 return 1 + nBestHeight - pindex->nHeight;
618 //////////////////////////////////////////////////////////////////////////////
620 // CBlock and CBlockIndex
623 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
625 if (!fReadTransactions)
627 *this = pindex->GetBlockHeader();
630 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
632 if (GetHash() != pindex->GetBlockHash())
633 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
637 uint256 static GetOrphanRoot(const CBlock* pblock)
639 // Work back to the first block in the orphan chain
640 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
641 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
642 return pblock->GetHash();
645 int64 static GetBlockValue(int nHeight, int64 nFees)
647 int64 nSubsidy = 50 * COIN;
649 // Subsidy is cut in half every 4 years
650 nSubsidy >>= (nHeight / 210000);
652 return nSubsidy + nFees;
655 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
656 static const int64 nTargetSpacing = 10 * 60;
657 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
660 // minimum amount of work that could possibly be required nTime after
661 // minimum work required was nBase
663 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
665 // Testnet has min-difficulty blocks
666 // after nTargetSpacing*2 time between blocks:
667 if (fTestNet && nTime > nTargetSpacing*2)
668 return bnProofOfWorkLimit.GetCompact();
671 bnResult.SetCompact(nBase);
672 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
674 // Maximum 400% adjustment...
676 // ... in best-case exactly 4-times-normal target time
677 nTime -= nTargetTimespan*4;
679 if (bnResult > bnProofOfWorkLimit)
680 bnResult = bnProofOfWorkLimit;
681 return bnResult.GetCompact();
684 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
686 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
689 if (pindexLast == NULL)
690 return nProofOfWorkLimit;
692 // Only change once per interval
693 if ((pindexLast->nHeight+1) % nInterval != 0)
695 // Special rules for testnet after 15 Feb 2012:
696 if (fTestNet && pblock->nTime > 1329264000)
698 // If the new block's timestamp is more than 2* 10 minutes
699 // then allow mining of a min-difficulty block.
700 if (pblock->nTime - pindexLast->nTime > nTargetSpacing*2)
701 return nProofOfWorkLimit;
704 // Return the last non-special-min-difficulty-rules-block
705 const CBlockIndex* pindex = pindexLast;
706 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
707 pindex = pindex->pprev;
708 return pindex->nBits;
712 return pindexLast->nBits;
715 // Go back by what we want to be 14 days worth of blocks
716 const CBlockIndex* pindexFirst = pindexLast;
717 for (int i = 0; pindexFirst && i < nInterval-1; i++)
718 pindexFirst = pindexFirst->pprev;
721 // Limit adjustment step
722 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
723 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
724 if (nActualTimespan < nTargetTimespan/4)
725 nActualTimespan = nTargetTimespan/4;
726 if (nActualTimespan > nTargetTimespan*4)
727 nActualTimespan = nTargetTimespan*4;
731 bnNew.SetCompact(pindexLast->nBits);
732 bnNew *= nActualTimespan;
733 bnNew /= nTargetTimespan;
735 if (bnNew > bnProofOfWorkLimit)
736 bnNew = bnProofOfWorkLimit;
739 printf("GetNextWorkRequired RETARGET\n");
740 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
741 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
742 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
744 return bnNew.GetCompact();
747 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
750 bnTarget.SetCompact(nBits);
753 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
754 return error("CheckProofOfWork() : nBits below minimum work");
756 // Check proof of work matches claimed amount
757 if (hash > bnTarget.getuint256())
758 return error("CheckProofOfWork() : hash doesn't match nBits");
763 bool IsInitialBlockDownload()
765 if (pindexBest == NULL || nBestHeight < (Checkpoints::GetTotalBlocksEstimate()-nInitialBlockThreshold))
767 static int64 nLastUpdate;
768 static CBlockIndex* pindexLastBest;
769 if (pindexBest != pindexLastBest)
771 pindexLastBest = pindexBest;
772 nLastUpdate = GetTime();
774 return (GetTime() - nLastUpdate < 10 &&
775 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
778 void static InvalidChainFound(CBlockIndex* pindexNew)
780 if (pindexNew->bnChainWork > bnBestInvalidWork)
782 bnBestInvalidWork = pindexNew->bnChainWork;
783 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
786 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());
787 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
788 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
789 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
802 bool CTransaction::DisconnectInputs(CTxDB& txdb)
804 // Relinquish previous transactions' spent pointers
807 BOOST_FOREACH(const CTxIn& txin, vin)
809 COutPoint prevout = txin.prevout;
811 // Get prev txindex from disk
813 if (!txdb.ReadTxIndex(prevout.hash, txindex))
814 return error("DisconnectInputs() : ReadTxIndex failed");
816 if (prevout.n >= txindex.vSpent.size())
817 return error("DisconnectInputs() : prevout.n out of range");
819 // Mark outpoint as not spent
820 txindex.vSpent[prevout.n].SetNull();
823 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
824 return error("DisconnectInputs() : UpdateTxIndex failed");
828 // Remove transaction from index
829 if (!txdb.EraseTxIndex(*this))
830 return error("DisconnectInputs() : EraseTxPos failed");
836 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
837 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee,
840 // FetchInputs can return false either because we just haven't seen some inputs
841 // (in which case the transaction should be stored as an orphan)
842 // or because the transaction is malformed (in which case the transaction should
843 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
846 // Take over previous transactions' spent pointers
850 for (int i = 0; i < vin.size(); i++)
852 COutPoint prevout = vin[i].prevout;
857 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
859 // Get txindex from current proposed changes
860 txindex = mapTestPool[prevout.hash];
864 // Read txindex from txdb
865 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
867 if (!fFound && (fBlock || fMiner))
868 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());
872 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
874 // Get prev tx from single transactions in memory
875 CRITICAL_BLOCK(cs_mapTransactions)
877 if (!mapTransactions.count(prevout.hash))
878 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
879 txPrev = mapTransactions[prevout.hash];
882 txindex.vSpent.resize(txPrev.vout.size());
886 // Get prev tx from disk
887 if (!txPrev.ReadFromDisk(txindex.pos))
888 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
891 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
893 // Revisit this if/when transaction replacement is implemented and allows
896 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());
899 // If prev is coinbase, check that it's matured
900 if (txPrev.IsCoinBase())
901 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
902 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
903 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
906 if (!VerifySignature(txPrev, *this, i))
907 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
909 // Check for conflicts
910 if (!txindex.vSpent[prevout.n].IsNull())
911 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());
913 // Check for negative or overflow input values
914 nValueIn += txPrev.vout[prevout.n].nValue;
915 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
916 return error("ConnectInputs() : txin values out of range");
918 // Mark outpoints as spent
919 txindex.vSpent[prevout.n] = posThisTx;
922 if (fBlock || fMiner)
924 mapTestPool[prevout.hash] = txindex;
928 if (nValueIn < GetValueOut())
929 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
931 // Tally transaction fees
932 int64 nTxFee = nValueIn - GetValueOut();
934 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
935 if (nTxFee < nMinFee)
938 if (!MoneyRange(nFees))
939 return error("ConnectInputs() : nFees out of range");
944 // Add transaction to changes
945 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
949 // Add transaction to test pool
950 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
957 bool CTransaction::ClientConnectInputs()
962 // Take over previous transactions' spent pointers
963 CRITICAL_BLOCK(cs_mapTransactions)
966 for (int i = 0; i < vin.size(); i++)
968 // Get prev tx from single transactions in memory
969 COutPoint prevout = vin[i].prevout;
970 if (!mapTransactions.count(prevout.hash))
972 CTransaction& txPrev = mapTransactions[prevout.hash];
974 if (prevout.n >= txPrev.vout.size())
978 if (!VerifySignature(txPrev, *this, i))
979 return error("ConnectInputs() : VerifySignature failed");
981 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
982 ///// this has to go away now that posNext is gone
983 // // Check for conflicts
984 // if (!txPrev.vout[prevout.n].posNext.IsNull())
985 // return error("ConnectInputs() : prev tx already used");
987 // // Flag outpoints as used
988 // txPrev.vout[prevout.n].posNext = posThisTx;
990 nValueIn += txPrev.vout[prevout.n].nValue;
992 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
993 return error("ClientConnectInputs() : txin values out of range");
995 if (GetValueOut() > nValueIn)
1005 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1007 // Disconnect in reverse order
1008 for (int i = vtx.size()-1; i >= 0; i--)
1009 if (!vtx[i].DisconnectInputs(txdb))
1012 // Update block index on disk without changing it in memory.
1013 // The memory index structure will be changed after the db commits.
1016 CDiskBlockIndex blockindexPrev(pindex->pprev);
1017 blockindexPrev.hashNext = 0;
1018 if (!txdb.WriteBlockIndex(blockindexPrev))
1019 return error("DisconnectBlock() : WriteBlockIndex failed");
1025 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1027 // Check it again in case a previous version let a bad block in
1031 //// issue here: it doesn't know the version
1032 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1034 map<uint256, CTxIndex> mapQueuedChanges;
1036 BOOST_FOREACH(CTransaction& tx, vtx)
1038 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1039 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1042 if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false, 0, fInvalid))
1045 // Write queued txindex changes
1046 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1048 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1049 return error("ConnectBlock() : UpdateTxIndex failed");
1052 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1055 // Update block index on disk without changing it in memory.
1056 // The memory index structure will be changed after the db commits.
1059 CDiskBlockIndex blockindexPrev(pindex->pprev);
1060 blockindexPrev.hashNext = pindex->GetBlockHash();
1061 if (!txdb.WriteBlockIndex(blockindexPrev))
1062 return error("ConnectBlock() : WriteBlockIndex failed");
1065 // Watch for transactions paying to me
1066 BOOST_FOREACH(CTransaction& tx, vtx)
1067 SyncWithWallets(tx, this, true);
1072 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1074 printf("REORGANIZE\n");
1077 CBlockIndex* pfork = pindexBest;
1078 CBlockIndex* plonger = pindexNew;
1079 while (pfork != plonger)
1081 while (plonger->nHeight > pfork->nHeight)
1082 if (!(plonger = plonger->pprev))
1083 return error("Reorganize() : plonger->pprev is null");
1084 if (pfork == plonger)
1086 if (!(pfork = pfork->pprev))
1087 return error("Reorganize() : pfork->pprev is null");
1090 // List of what to disconnect
1091 vector<CBlockIndex*> vDisconnect;
1092 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1093 vDisconnect.push_back(pindex);
1095 // List of what to connect
1096 vector<CBlockIndex*> vConnect;
1097 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1098 vConnect.push_back(pindex);
1099 reverse(vConnect.begin(), vConnect.end());
1101 // Disconnect shorter branch
1102 vector<CTransaction> vResurrect;
1103 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1106 if (!block.ReadFromDisk(pindex))
1107 return error("Reorganize() : ReadFromDisk for disconnect failed");
1108 if (!block.DisconnectBlock(txdb, pindex))
1109 return error("Reorganize() : DisconnectBlock failed");
1111 // Queue memory transactions to resurrect
1112 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1113 if (!tx.IsCoinBase())
1114 vResurrect.push_back(tx);
1117 // Connect longer branch
1118 vector<CTransaction> vDelete;
1119 for (int i = 0; i < vConnect.size(); i++)
1121 CBlockIndex* pindex = vConnect[i];
1123 if (!block.ReadFromDisk(pindex))
1124 return error("Reorganize() : ReadFromDisk for connect failed");
1125 if (!block.ConnectBlock(txdb, pindex))
1129 return error("Reorganize() : ConnectBlock failed");
1132 // Queue memory transactions to delete
1133 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1134 vDelete.push_back(tx);
1136 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1137 return error("Reorganize() : WriteHashBestChain failed");
1139 // Make sure it's successfully written to disk before changing memory structure
1140 if (!txdb.TxnCommit())
1141 return error("Reorganize() : TxnCommit failed");
1143 // Disconnect shorter branch
1144 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1146 pindex->pprev->pnext = NULL;
1148 // Connect longer branch
1149 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1151 pindex->pprev->pnext = pindex;
1153 // Resurrect memory transactions that were in the disconnected branch
1154 BOOST_FOREACH(CTransaction& tx, vResurrect)
1155 tx.AcceptToMemoryPool(txdb, false);
1157 // Delete redundant memory transactions that are in the connected branch
1158 BOOST_FOREACH(CTransaction& tx, vDelete)
1159 tx.RemoveFromMemoryPool();
1165 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1167 uint256 hash = GetHash();
1170 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1172 txdb.WriteHashBestChain(hash);
1173 if (!txdb.TxnCommit())
1174 return error("SetBestChain() : TxnCommit failed");
1175 pindexGenesisBlock = pindexNew;
1177 else if (hashPrevBlock == hashBestChain)
1179 // Adding to current best branch
1180 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1183 InvalidChainFound(pindexNew);
1184 return error("SetBestChain() : ConnectBlock failed");
1186 if (!txdb.TxnCommit())
1187 return error("SetBestChain() : TxnCommit failed");
1189 // Add to current best branch
1190 pindexNew->pprev->pnext = pindexNew;
1192 // Delete redundant memory transactions
1193 BOOST_FOREACH(CTransaction& tx, vtx)
1194 tx.RemoveFromMemoryPool();
1199 if (!Reorganize(txdb, pindexNew))
1202 InvalidChainFound(pindexNew);
1203 return error("SetBestChain() : Reorganize failed");
1207 // Update best block in wallet (so we can detect restored wallets)
1208 if (!IsInitialBlockDownload())
1210 const CBlockLocator locator(pindexNew);
1211 ::SetBestChain(locator);
1215 hashBestChain = hash;
1216 pindexBest = pindexNew;
1217 nBestHeight = pindexBest->nHeight;
1218 bnBestChainWork = pindexNew->bnChainWork;
1219 nTimeBestReceived = GetTime();
1220 nTransactionsUpdated++;
1221 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1227 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1229 // Check for duplicate
1230 uint256 hash = GetHash();
1231 if (mapBlockIndex.count(hash))
1232 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1234 // Construct new block index object
1235 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1237 return error("AddToBlockIndex() : new CBlockIndex failed");
1238 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1239 pindexNew->phashBlock = &((*mi).first);
1240 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1241 if (miPrev != mapBlockIndex.end())
1243 pindexNew->pprev = (*miPrev).second;
1244 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1246 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1250 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1251 if (!txdb.TxnCommit())
1255 if (pindexNew->bnChainWork > bnBestChainWork)
1256 if (!SetBestChain(txdb, pindexNew))
1261 if (pindexNew == pindexBest)
1263 // Notify UI to display prev block's coinbase if it was ours
1264 static uint256 hashPrevBestCoinBase;
1265 UpdatedTransaction(hashPrevBestCoinBase);
1266 hashPrevBestCoinBase = vtx[0].GetHash();
1276 bool CBlock::CheckBlock() const
1278 // These are checks that are independent of context
1279 // that can be verified before saving an orphan block.
1282 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1283 return error("CheckBlock() : size limits failed");
1285 // Check proof of work matches claimed amount
1286 if (!CheckProofOfWork(GetHash(), nBits))
1287 return error("CheckBlock() : proof of work failed");
1290 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1291 return error("CheckBlock() : block timestamp too far in the future");
1293 // First transaction must be coinbase, the rest must not be
1294 if (vtx.empty() || !vtx[0].IsCoinBase())
1295 return error("CheckBlock() : first tx is not coinbase");
1296 for (int i = 1; i < vtx.size(); i++)
1297 if (vtx[i].IsCoinBase())
1298 return error("CheckBlock() : more than one coinbase");
1300 // Check transactions
1301 BOOST_FOREACH(const CTransaction& tx, vtx)
1302 if (!tx.CheckTransaction())
1303 return error("CheckBlock() : CheckTransaction failed");
1305 // Check that it's not full of nonstandard transactions
1306 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1307 return error("CheckBlock() : too many nonstandard transactions");
1310 if (hashMerkleRoot != BuildMerkleTree())
1311 return error("CheckBlock() : hashMerkleRoot mismatch");
1316 bool CBlock::AcceptBlock()
1318 // Check for duplicate
1319 uint256 hash = GetHash();
1320 if (mapBlockIndex.count(hash))
1321 return error("AcceptBlock() : block already in mapBlockIndex");
1323 // Get prev block index
1324 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1325 if (mi == mapBlockIndex.end())
1326 return error("AcceptBlock() : prev block not found");
1327 CBlockIndex* pindexPrev = (*mi).second;
1328 int nHeight = pindexPrev->nHeight+1;
1330 // Check proof of work
1331 if (nBits != GetNextWorkRequired(pindexPrev, this))
1332 return error("AcceptBlock() : incorrect proof of work");
1334 // Check timestamp against prev
1335 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1336 return error("AcceptBlock() : block's timestamp is too early");
1338 // Check that all transactions are finalized
1339 BOOST_FOREACH(const CTransaction& tx, vtx)
1340 if (!tx.IsFinal(nHeight, GetBlockTime()))
1341 return error("AcceptBlock() : contains a non-final transaction");
1343 // Check that the block chain matches the known block chain up to a checkpoint
1344 if (!Checkpoints::CheckBlock(nHeight, hash))
1345 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1347 // Write block to history file
1348 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1349 return error("AcceptBlock() : out of disk space");
1350 unsigned int nFile = -1;
1351 unsigned int nBlockPos = 0;
1352 if (!WriteToDisk(nFile, nBlockPos))
1353 return error("AcceptBlock() : WriteToDisk failed");
1354 if (!AddToBlockIndex(nFile, nBlockPos))
1355 return error("AcceptBlock() : AddToBlockIndex failed");
1357 // Relay inventory, but don't relay old inventory during initial block download
1358 if (hashBestChain == hash)
1359 CRITICAL_BLOCK(cs_vNodes)
1360 BOOST_FOREACH(CNode* pnode, vNodes)
1361 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1362 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1367 bool static ProcessBlock(CNode* pfrom, CBlock* pblock)
1369 // Check for duplicate
1370 uint256 hash = pblock->GetHash();
1371 if (mapBlockIndex.count(hash))
1372 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1373 if (mapOrphanBlocks.count(hash))
1374 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1376 // Preliminary checks
1377 if (!pblock->CheckBlock())
1378 return error("ProcessBlock() : CheckBlock FAILED");
1380 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1381 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1383 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1384 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1387 return error("ProcessBlock() : block with timestamp before last checkpoint");
1390 bnNewBlock.SetCompact(pblock->nBits);
1392 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1393 if (bnNewBlock > bnRequired)
1395 return error("ProcessBlock() : block with too little proof-of-work");
1400 // If don't already have its previous block, shunt it off to holding area until we get it
1401 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1403 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1404 CBlock* pblock2 = new CBlock(*pblock);
1405 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1406 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1408 // Ask this guy to fill in what we're missing
1410 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1415 if (!pblock->AcceptBlock())
1416 return error("ProcessBlock() : AcceptBlock FAILED");
1418 // Recursively process any orphan blocks that depended on this one
1419 vector<uint256> vWorkQueue;
1420 vWorkQueue.push_back(hash);
1421 for (int i = 0; i < vWorkQueue.size(); i++)
1423 uint256 hashPrev = vWorkQueue[i];
1424 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1425 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1428 CBlock* pblockOrphan = (*mi).second;
1429 if (pblockOrphan->AcceptBlock())
1430 vWorkQueue.push_back(pblockOrphan->GetHash());
1431 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1432 delete pblockOrphan;
1434 mapOrphanBlocksByPrev.erase(hashPrev);
1437 printf("ProcessBlock: ACCEPTED\n");
1448 bool CheckDiskSpace(uint64 nAdditionalBytes)
1450 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1452 // Check for 15MB because database could create another 10MB log file at any time
1453 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1456 string strMessage = _("Warning: Disk space is low ");
1457 strMiscWarning = strMessage;
1458 printf("*** %s\n", strMessage.c_str());
1459 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1460 CreateThread(Shutdown, NULL);
1466 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1470 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1473 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1475 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1484 static unsigned int nCurrentBlockFile = 1;
1486 FILE* AppendBlockFile(unsigned int& nFileRet)
1491 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1494 if (fseek(file, 0, SEEK_END) != 0)
1496 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1497 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1499 nFileRet = nCurrentBlockFile;
1503 nCurrentBlockFile++;
1507 bool LoadBlockIndex(bool fAllowNew)
1511 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1512 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1513 pchMessageStart[0] = 0xfa;
1514 pchMessageStart[1] = 0xbf;
1515 pchMessageStart[2] = 0xb5;
1516 pchMessageStart[3] = 0xda;
1523 if (!txdb.LoadBlockIndex())
1528 // Init with genesis block
1530 if (mapBlockIndex.empty())
1536 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1537 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1538 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1539 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1540 // vMerkleTree: 4a5e1e
1543 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1545 txNew.vin.resize(1);
1546 txNew.vout.resize(1);
1547 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1548 txNew.vout[0].nValue = 50 * COIN;
1549 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1551 block.vtx.push_back(txNew);
1552 block.hashPrevBlock = 0;
1553 block.hashMerkleRoot = block.BuildMerkleTree();
1555 block.nTime = 1231006505;
1556 block.nBits = 0x1d00ffff;
1557 block.nNonce = 2083236893;
1561 block.nTime = 1296688602;
1562 block.nBits = 0x1d07fff8;
1563 block.nNonce = 384568319;
1567 printf("%s\n", block.GetHash().ToString().c_str());
1568 printf("%s\n", hashGenesisBlock.ToString().c_str());
1569 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1570 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1572 assert(block.GetHash() == hashGenesisBlock);
1574 // Start new block file
1576 unsigned int nBlockPos;
1577 if (!block.WriteToDisk(nFile, nBlockPos))
1578 return error("LoadBlockIndex() : writing genesis block to disk failed");
1579 if (!block.AddToBlockIndex(nFile, nBlockPos))
1580 return error("LoadBlockIndex() : genesis block not accepted");
1588 void PrintBlockTree()
1590 // precompute tree structure
1591 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1592 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1594 CBlockIndex* pindex = (*mi).second;
1595 mapNext[pindex->pprev].push_back(pindex);
1597 //while (rand() % 3 == 0)
1598 // mapNext[pindex->pprev].push_back(pindex);
1601 vector<pair<int, CBlockIndex*> > vStack;
1602 vStack.push_back(make_pair(0, pindexGenesisBlock));
1605 while (!vStack.empty())
1607 int nCol = vStack.back().first;
1608 CBlockIndex* pindex = vStack.back().second;
1611 // print split or gap
1612 if (nCol > nPrevCol)
1614 for (int i = 0; i < nCol-1; i++)
1618 else if (nCol < nPrevCol)
1620 for (int i = 0; i < nCol; i++)
1627 for (int i = 0; i < nCol; i++)
1632 block.ReadFromDisk(pindex);
1633 printf("%d (%u,%u) %s %s tx %d",
1637 block.GetHash().ToString().substr(0,20).c_str(),
1638 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1641 PrintWallets(block);
1643 // put the main timechain first
1644 vector<CBlockIndex*>& vNext = mapNext[pindex];
1645 for (int i = 0; i < vNext.size(); i++)
1647 if (vNext[i]->pnext)
1649 swap(vNext[0], vNext[i]);
1655 for (int i = 0; i < vNext.size(); i++)
1656 vStack.push_back(make_pair(nCol+i, vNext[i]));
1669 //////////////////////////////////////////////////////////////////////////////
1674 map<uint256, CAlert> mapAlerts;
1675 CCriticalSection cs_mapAlerts;
1677 string GetWarnings(string strFor)
1680 string strStatusBar;
1682 if (GetBoolArg("-testsafemode"))
1685 // Misc warnings like out of disk space and clock is wrong
1686 if (strMiscWarning != "")
1689 strStatusBar = strMiscWarning;
1692 // Longer invalid proof-of-work chain
1693 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1696 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1700 CRITICAL_BLOCK(cs_mapAlerts)
1702 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1704 const CAlert& alert = item.second;
1705 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1707 nPriority = alert.nPriority;
1708 strStatusBar = alert.strStatusBar;
1713 if (strFor == "statusbar")
1714 return strStatusBar;
1715 else if (strFor == "rpc")
1717 assert(!"GetWarnings() : invalid parameter");
1721 bool CAlert::ProcessAlert()
1723 if (!CheckSignature())
1728 CRITICAL_BLOCK(cs_mapAlerts)
1730 // Cancel previous alerts
1731 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1733 const CAlert& alert = (*mi).second;
1736 printf("cancelling alert %d\n", alert.nID);
1737 mapAlerts.erase(mi++);
1739 else if (!alert.IsInEffect())
1741 printf("expiring alert %d\n", alert.nID);
1742 mapAlerts.erase(mi++);
1748 // Check if this alert has been cancelled
1749 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1751 const CAlert& alert = item.second;
1752 if (alert.Cancels(*this))
1754 printf("alert already cancelled by %d\n", alert.nID);
1760 mapAlerts.insert(make_pair(GetHash(), *this));
1763 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1775 //////////////////////////////////////////////////////////////////////////////
1781 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1785 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1786 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1788 // Don't know what it is, just say we already got one
1795 // The message start string is designed to be unlikely to occur in normal data.
1796 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1797 // a large 4-byte int at any alignment.
1798 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1801 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1803 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1804 RandAddSeedPerfmon();
1806 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1807 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1809 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1811 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1819 if (strCommand == "version")
1821 // Each connection can only send one version message
1822 if (pfrom->nVersion != 0)
1829 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1830 if (pfrom->nVersion == 10300)
1831 pfrom->nVersion = 300;
1832 if (pfrom->nVersion >= 106 && !vRecv.empty())
1833 vRecv >> addrFrom >> nNonce;
1834 if (pfrom->nVersion >= 106 && !vRecv.empty())
1835 vRecv >> pfrom->strSubVer;
1836 if (pfrom->nVersion >= 209 && !vRecv.empty())
1837 vRecv >> pfrom->nStartingHeight;
1839 if (pfrom->nVersion == 0)
1842 // Disconnect if we connected to ourself
1843 if (nNonce == nLocalHostNonce && nNonce > 1)
1845 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1846 pfrom->fDisconnect = true;
1850 // Be shy and don't send version until we hear
1851 if (pfrom->fInbound)
1852 pfrom->PushVersion();
1854 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1856 AddTimeData(pfrom->addr.ip, nTime);
1859 if (pfrom->nVersion >= 209)
1860 pfrom->PushMessage("verack");
1861 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1862 if (pfrom->nVersion < 209)
1863 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1865 if (!pfrom->fInbound)
1867 // Advertise our address
1868 if (addrLocalHost.IsRoutable() && !fUseProxy)
1870 CAddress addr(addrLocalHost);
1871 addr.nTime = GetAdjustedTime();
1872 pfrom->PushAddress(addr);
1875 // Get recent addresses
1876 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
1878 pfrom->PushMessage("getaddr");
1879 pfrom->fGetAddr = true;
1883 // Ask the first connected node for block updates
1884 static int nAskedForBlocks;
1885 if (!pfrom->fClient &&
1886 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
1887 (nAskedForBlocks < 1 || vNodes.size() <= 1))
1890 pfrom->PushGetBlocks(pindexBest, uint256(0));
1894 CRITICAL_BLOCK(cs_mapAlerts)
1895 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1896 item.second.RelayTo(pfrom);
1898 pfrom->fSuccessfullyConnected = true;
1900 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1904 else if (pfrom->nVersion == 0)
1906 // Must have a version message before anything else
1911 else if (strCommand == "verack")
1913 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1917 else if (strCommand == "addr")
1919 vector<CAddress> vAddr;
1922 // Don't want addr from older versions unless seeding
1923 if (pfrom->nVersion < 209)
1925 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
1927 if (vAddr.size() > 1000)
1928 return error("message addr size() = %d", vAddr.size());
1930 // Store the new addresses
1933 int64 nNow = GetAdjustedTime();
1934 int64 nSince = nNow - 10 * 60;
1935 BOOST_FOREACH(CAddress& addr, vAddr)
1939 // ignore IPv6 for now, since it isn't implemented anyway
1942 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1943 addr.nTime = nNow - 5 * 24 * 60 * 60;
1944 AddAddress(addr, 2 * 60 * 60, &addrDB);
1945 pfrom->AddAddressKnown(addr);
1946 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1948 // Relay to a limited number of other nodes
1949 CRITICAL_BLOCK(cs_vNodes)
1951 // Use deterministic randomness to send to the same nodes for 24 hours
1952 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
1953 static uint256 hashSalt;
1955 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1956 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
1957 hashRand = Hash(BEGIN(hashRand), END(hashRand));
1958 multimap<uint256, CNode*> mapMix;
1959 BOOST_FOREACH(CNode* pnode, vNodes)
1961 if (pnode->nVersion < 31402)
1963 unsigned int nPointer;
1964 memcpy(&nPointer, &pnode, sizeof(nPointer));
1965 uint256 hashKey = hashRand ^ nPointer;
1966 hashKey = Hash(BEGIN(hashKey), END(hashKey));
1967 mapMix.insert(make_pair(hashKey, pnode));
1969 int nRelayNodes = 2;
1970 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1971 ((*mi).second)->PushAddress(addr);
1975 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
1976 if (vAddr.size() < 1000)
1977 pfrom->fGetAddr = false;
1981 else if (strCommand == "inv")
1985 if (vInv.size() > 50000)
1986 return error("message inv size() = %d", vInv.size());
1989 BOOST_FOREACH(const CInv& inv, vInv)
1993 pfrom->AddInventoryKnown(inv);
1995 bool fAlreadyHave = AlreadyHave(txdb, inv);
1997 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2001 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2002 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2004 // Track requests for our stuff
2005 Inventory(inv.hash);
2010 else if (strCommand == "getdata")
2014 if (vInv.size() > 50000)
2015 return error("message getdata size() = %d", vInv.size());
2017 BOOST_FOREACH(const CInv& inv, vInv)
2021 printf("received getdata for: %s\n", inv.ToString().c_str());
2023 if (inv.type == MSG_BLOCK)
2025 // Send block from disk
2026 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2027 if (mi != mapBlockIndex.end())
2030 block.ReadFromDisk((*mi).second);
2031 pfrom->PushMessage("block", block);
2033 // Trigger them to send a getblocks request for the next batch of inventory
2034 if (inv.hash == pfrom->hashContinue)
2036 // Bypass PushInventory, this must send even if redundant,
2037 // and we want it right after the last block so they don't
2038 // wait for other stuff first.
2040 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2041 pfrom->PushMessage("inv", vInv);
2042 pfrom->hashContinue = 0;
2046 else if (inv.IsKnownType())
2048 // Send stream from relay memory
2049 CRITICAL_BLOCK(cs_mapRelay)
2051 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2052 if (mi != mapRelay.end())
2053 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2057 // Track requests for our stuff
2058 Inventory(inv.hash);
2063 else if (strCommand == "getblocks")
2065 CBlockLocator locator;
2067 vRecv >> locator >> hashStop;
2069 // Find the last block the caller has in the main chain
2070 CBlockIndex* pindex = locator.GetBlockIndex();
2072 // Send the rest of the chain
2074 pindex = pindex->pnext;
2075 int nLimit = 500 + locator.GetDistanceBack();
2076 unsigned int nBytes = 0;
2077 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2078 for (; pindex; pindex = pindex->pnext)
2080 if (pindex->GetBlockHash() == hashStop)
2082 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2085 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2087 block.ReadFromDisk(pindex, true);
2088 nBytes += block.GetSerializeSize(SER_NETWORK);
2089 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2091 // When this block is requested, we'll send an inv that'll make them
2092 // getblocks the next batch of inventory.
2093 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2094 pfrom->hashContinue = pindex->GetBlockHash();
2101 else if (strCommand == "getheaders")
2103 CBlockLocator locator;
2105 vRecv >> locator >> hashStop;
2107 CBlockIndex* pindex = NULL;
2108 if (locator.IsNull())
2110 // If locator is null, return the hashStop block
2111 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2112 if (mi == mapBlockIndex.end())
2114 pindex = (*mi).second;
2118 // Find the last block the caller has in the main chain
2119 pindex = locator.GetBlockIndex();
2121 pindex = pindex->pnext;
2124 vector<CBlock> vHeaders;
2125 int nLimit = 2000 + locator.GetDistanceBack();
2126 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2127 for (; pindex; pindex = pindex->pnext)
2129 vHeaders.push_back(pindex->GetBlockHeader());
2130 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2133 pfrom->PushMessage("headers", vHeaders);
2137 else if (strCommand == "tx")
2139 vector<uint256> vWorkQueue;
2140 CDataStream vMsg(vRecv);
2144 CInv inv(MSG_TX, tx.GetHash());
2145 pfrom->AddInventoryKnown(inv);
2147 bool fMissingInputs = false;
2148 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2150 SyncWithWallets(tx, NULL, true);
2151 RelayMessage(inv, vMsg);
2152 mapAlreadyAskedFor.erase(inv);
2153 vWorkQueue.push_back(inv.hash);
2155 // Recursively process any orphan transactions that depended on this one
2156 for (int i = 0; i < vWorkQueue.size(); i++)
2158 uint256 hashPrev = vWorkQueue[i];
2159 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2160 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2163 const CDataStream& vMsg = *((*mi).second);
2165 CDataStream(vMsg) >> tx;
2166 CInv inv(MSG_TX, tx.GetHash());
2168 if (tx.AcceptToMemoryPool(true))
2170 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2171 SyncWithWallets(tx, NULL, true);
2172 RelayMessage(inv, vMsg);
2173 mapAlreadyAskedFor.erase(inv);
2174 vWorkQueue.push_back(inv.hash);
2179 BOOST_FOREACH(uint256 hash, vWorkQueue)
2180 EraseOrphanTx(hash);
2182 else if (fMissingInputs)
2184 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2190 else if (strCommand == "block")
2195 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2198 CInv inv(MSG_BLOCK, block.GetHash());
2199 pfrom->AddInventoryKnown(inv);
2201 if (ProcessBlock(pfrom, &block))
2202 mapAlreadyAskedFor.erase(inv);
2206 else if (strCommand == "getaddr")
2208 // Nodes rebroadcast an addr every 24 hours
2209 pfrom->vAddrToSend.clear();
2210 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2211 CRITICAL_BLOCK(cs_mapAddresses)
2213 unsigned int nCount = 0;
2214 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2216 const CAddress& addr = item.second;
2217 if (addr.nTime > nSince)
2220 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2222 const CAddress& addr = item.second;
2223 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2224 pfrom->PushAddress(addr);
2230 else if (strCommand == "checkorder")
2235 if (!GetBoolArg("-allowreceivebyip"))
2237 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2244 /// we have a chance to check the order here
2246 // Keep giving the same key to the same ip until they use it
2247 if (!mapReuseKey.count(pfrom->addr.ip))
2248 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2250 // Send back approval of order and pubkey to use
2251 CScript scriptPubKey;
2252 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2253 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2257 else if (strCommand == "reply")
2262 CRequestTracker tracker;
2263 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2265 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2266 if (mi != pfrom->mapRequests.end())
2268 tracker = (*mi).second;
2269 pfrom->mapRequests.erase(mi);
2272 if (!tracker.IsNull())
2273 tracker.fn(tracker.param1, vRecv);
2277 else if (strCommand == "ping")
2282 else if (strCommand == "alert")
2287 if (alert.ProcessAlert())
2290 pfrom->setKnown.insert(alert.GetHash());
2291 CRITICAL_BLOCK(cs_vNodes)
2292 BOOST_FOREACH(CNode* pnode, vNodes)
2293 alert.RelayTo(pnode);
2300 // Ignore unknown commands for extensibility
2304 // Update the last seen time for this node's address
2305 if (pfrom->fNetworkNode)
2306 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2307 AddressCurrentlyConnected(pfrom->addr);
2313 bool ProcessMessages(CNode* pfrom)
2315 CDataStream& vRecv = pfrom->vRecv;
2319 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2323 // (4) message start
2332 // Scan for message start
2333 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2334 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2335 if (vRecv.end() - pstart < nHeaderSize)
2337 if (vRecv.size() > nHeaderSize)
2339 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2340 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2344 if (pstart - vRecv.begin() > 0)
2345 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2346 vRecv.erase(vRecv.begin(), pstart);
2349 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2354 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2357 string strCommand = hdr.GetCommand();
2360 unsigned int nMessageSize = hdr.nMessageSize;
2361 if (nMessageSize > MAX_SIZE)
2363 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2366 if (nMessageSize > vRecv.size())
2368 // Rewind and wait for rest of message
2369 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2374 if (vRecv.GetVersion() >= 209)
2376 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2377 unsigned int nChecksum = 0;
2378 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2379 if (nChecksum != hdr.nChecksum)
2381 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2382 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2387 // Copy message to its own buffer
2388 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2389 vRecv.ignore(nMessageSize);
2395 CRITICAL_BLOCK(cs_main)
2396 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2400 catch (std::ios_base::failure& e)
2402 if (strstr(e.what(), "end of data"))
2404 // Allow exceptions from underlength message on vRecv
2405 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());
2407 else if (strstr(e.what(), "size too large"))
2409 // Allow exceptions from overlong size
2410 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2414 PrintExceptionContinue(&e, "ProcessMessage()");
2417 catch (std::exception& e) {
2418 PrintExceptionContinue(&e, "ProcessMessage()");
2420 PrintExceptionContinue(NULL, "ProcessMessage()");
2424 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2432 bool SendMessages(CNode* pto, bool fSendTrickle)
2434 CRITICAL_BLOCK(cs_main)
2436 // Don't send anything until we get their version message
2437 if (pto->nVersion == 0)
2441 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2442 pto->PushMessage("ping");
2444 // Resend wallet transactions that haven't gotten in a block yet
2445 ResendWalletTransactions();
2447 // Address refresh broadcast
2448 static int64 nLastRebroadcast;
2449 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2451 nLastRebroadcast = GetTime();
2452 CRITICAL_BLOCK(cs_vNodes)
2454 BOOST_FOREACH(CNode* pnode, vNodes)
2456 // Periodically clear setAddrKnown to allow refresh broadcasts
2457 pnode->setAddrKnown.clear();
2459 // Rebroadcast our address
2460 if (addrLocalHost.IsRoutable() && !fUseProxy)
2462 CAddress addr(addrLocalHost);
2463 addr.nTime = GetAdjustedTime();
2464 pnode->PushAddress(addr);
2470 // Clear out old addresses periodically so it's not too much work at once
2471 static int64 nLastClear;
2472 if (nLastClear == 0)
2473 nLastClear = GetTime();
2474 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2476 nLastClear = GetTime();
2477 CRITICAL_BLOCK(cs_mapAddresses)
2480 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2481 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2482 mi != mapAddresses.end();)
2484 const CAddress& addr = (*mi).second;
2485 if (addr.nTime < nSince)
2487 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2489 addrdb.EraseAddress(addr);
2490 mapAddresses.erase(mi++);
2504 vector<CAddress> vAddr;
2505 vAddr.reserve(pto->vAddrToSend.size());
2506 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2508 // returns true if wasn't already contained in the set
2509 if (pto->setAddrKnown.insert(addr).second)
2511 vAddr.push_back(addr);
2512 // receiver rejects addr messages larger than 1000
2513 if (vAddr.size() >= 1000)
2515 pto->PushMessage("addr", vAddr);
2520 pto->vAddrToSend.clear();
2522 pto->PushMessage("addr", vAddr);
2527 // Message: inventory
2530 vector<CInv> vInvWait;
2531 CRITICAL_BLOCK(pto->cs_inventory)
2533 vInv.reserve(pto->vInventoryToSend.size());
2534 vInvWait.reserve(pto->vInventoryToSend.size());
2535 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2537 if (pto->setInventoryKnown.count(inv))
2540 // trickle out tx inv to protect privacy
2541 if (inv.type == MSG_TX && !fSendTrickle)
2543 // 1/4 of tx invs blast to all immediately
2544 static uint256 hashSalt;
2546 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2547 uint256 hashRand = inv.hash ^ hashSalt;
2548 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2549 bool fTrickleWait = ((hashRand & 3) != 0);
2551 // always trickle our own transactions
2555 if (GetTransaction(inv.hash, wtx))
2557 fTrickleWait = true;
2562 vInvWait.push_back(inv);
2567 // returns true if wasn't already contained in the set
2568 if (pto->setInventoryKnown.insert(inv).second)
2570 vInv.push_back(inv);
2571 if (vInv.size() >= 1000)
2573 pto->PushMessage("inv", vInv);
2578 pto->vInventoryToSend = vInvWait;
2581 pto->PushMessage("inv", vInv);
2587 vector<CInv> vGetData;
2588 int64 nNow = GetTime() * 1000000;
2590 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2592 const CInv& inv = (*pto->mapAskFor.begin()).second;
2593 if (!AlreadyHave(txdb, inv))
2595 printf("sending getdata: %s\n", inv.ToString().c_str());
2596 vGetData.push_back(inv);
2597 if (vGetData.size() >= 1000)
2599 pto->PushMessage("getdata", vGetData);
2603 mapAlreadyAskedFor[inv] = nNow;
2604 pto->mapAskFor.erase(pto->mapAskFor.begin());
2606 if (!vGetData.empty())
2607 pto->PushMessage("getdata", vGetData);
2626 //////////////////////////////////////////////////////////////////////////////
2631 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2633 unsigned char* pdata = (unsigned char*)pbuffer;
2634 unsigned int blocks = 1 + ((len + 8) / 64);
2635 unsigned char* pend = pdata + 64 * blocks;
2636 memset(pdata + len, 0, 64 * blocks - len);
2638 unsigned int bits = len * 8;
2639 pend[-1] = (bits >> 0) & 0xff;
2640 pend[-2] = (bits >> 8) & 0xff;
2641 pend[-3] = (bits >> 16) & 0xff;
2642 pend[-4] = (bits >> 24) & 0xff;
2646 using CryptoPP::ByteReverse;
2648 static const unsigned int pSHA256InitState[8] =
2649 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2651 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2653 memcpy(pstate, pinit, 32);
2654 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2658 // ScanHash scans nonces looking for a hash with at least some zero bits.
2659 // It operates on big endian data. Caller does the byte reversing.
2660 // All input buffers are 16-byte aligned. nNonce is usually preserved
2661 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2662 // the block is rebuilt and nNonce starts over at zero.
2664 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2666 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2670 // Hash pdata using pmidstate as the starting state into
2671 // preformatted buffer phash1, then hash phash1 into phash
2673 SHA256Transform(phash1, pdata, pmidstate);
2674 SHA256Transform(phash, phash1, pSHA256InitState);
2676 // Return the nonce if the hash has at least some zero bits,
2677 // caller will check if it has enough to reach the target
2678 if (((unsigned short*)phash)[14] == 0)
2681 // If nothing found after trying for a while, return -1
2682 if ((nNonce & 0xffff) == 0)
2684 nHashesDone = 0xffff+1;
2690 // Some explaining would be appreciated
2695 set<uint256> setDependsOn;
2698 COrphan(CTransaction* ptxIn)
2706 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2707 BOOST_FOREACH(uint256 hash, setDependsOn)
2708 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2713 CBlock* CreateNewBlock(CReserveKey& reservekey)
2715 CBlockIndex* pindexPrev = pindexBest;
2718 auto_ptr<CBlock> pblock(new CBlock());
2722 // Create coinbase tx
2724 txNew.vin.resize(1);
2725 txNew.vin[0].prevout.SetNull();
2726 txNew.vout.resize(1);
2727 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2729 // Add our coinbase tx as first transaction
2730 pblock->vtx.push_back(txNew);
2732 // Collect memory pool transactions into the block
2734 CRITICAL_BLOCK(cs_main)
2735 CRITICAL_BLOCK(cs_mapTransactions)
2739 // Priority order to process transactions
2740 list<COrphan> vOrphan; // list memory doesn't move
2741 map<uint256, vector<COrphan*> > mapDependers;
2742 multimap<double, CTransaction*> mapPriority;
2743 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2745 CTransaction& tx = (*mi).second;
2746 if (tx.IsCoinBase() || !tx.IsFinal())
2749 COrphan* porphan = NULL;
2750 double dPriority = 0;
2751 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2753 // Read prev transaction
2754 CTransaction txPrev;
2756 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2758 // Has to wait for dependencies
2761 // Use list for automatic deletion
2762 vOrphan.push_back(COrphan(&tx));
2763 porphan = &vOrphan.back();
2765 mapDependers[txin.prevout.hash].push_back(porphan);
2766 porphan->setDependsOn.insert(txin.prevout.hash);
2769 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2771 // Read block header
2772 int nConf = txindex.GetDepthInMainChain();
2774 dPriority += (double)nValueIn * nConf;
2776 if (fDebug && GetBoolArg("-printpriority"))
2777 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2780 // Priority is sum(valuein * age) / txsize
2781 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2784 porphan->dPriority = dPriority;
2786 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2788 if (fDebug && GetBoolArg("-printpriority"))
2790 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2797 // Collect transactions into block
2798 map<uint256, CTxIndex> mapTestPool;
2799 uint64 nBlockSize = 1000;
2800 int nBlockSigOps = 100;
2801 while (!mapPriority.empty())
2803 // Take highest priority transaction off priority queue
2804 double dPriority = -(*mapPriority.begin()).first;
2805 CTransaction& tx = *(*mapPriority.begin()).second;
2806 mapPriority.erase(mapPriority.begin());
2809 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2810 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2812 int nTxSigOps = tx.GetSigOpCount();
2813 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2816 // Transaction fee required depends on block size
2817 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2818 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
2820 // Connecting shouldn't fail due to dependency on other memory pool transactions
2821 // because we're already processing them in order of dependency
2822 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2824 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee, fInvalid))
2826 swap(mapTestPool, mapTestPoolTmp);
2829 pblock->vtx.push_back(tx);
2830 nBlockSize += nTxSize;
2831 nBlockSigOps += nTxSigOps;
2833 // Add transactions that depend on this one to the priority queue
2834 uint256 hash = tx.GetHash();
2835 if (mapDependers.count(hash))
2837 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2839 if (!porphan->setDependsOn.empty())
2841 porphan->setDependsOn.erase(hash);
2842 if (porphan->setDependsOn.empty())
2843 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2849 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2852 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
2853 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2854 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2855 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
2858 return pblock.release();
2862 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
2864 // Update nExtraNonce
2865 static uint256 hashPrevBlock;
2866 if (hashPrevBlock != pblock->hashPrevBlock)
2869 hashPrevBlock = pblock->hashPrevBlock;
2872 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
2873 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2877 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
2880 // Prebuild hash buffers
2887 uint256 hashPrevBlock;
2888 uint256 hashMerkleRoot;
2891 unsigned int nNonce;
2894 unsigned char pchPadding0[64];
2896 unsigned char pchPadding1[64];
2899 memset(&tmp, 0, sizeof(tmp));
2901 tmp.block.nVersion = pblock->nVersion;
2902 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
2903 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
2904 tmp.block.nTime = pblock->nTime;
2905 tmp.block.nBits = pblock->nBits;
2906 tmp.block.nNonce = pblock->nNonce;
2908 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2909 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2911 // Byte swap all the input buffer
2912 for (int i = 0; i < sizeof(tmp)/4; i++)
2913 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2915 // Precalc the first half of the first hash, which stays constant
2916 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
2918 memcpy(pdata, &tmp.block, 128);
2919 memcpy(phash1, &tmp.hash1, 64);
2923 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
2925 uint256 hash = pblock->GetHash();
2926 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2928 if (hash > hashTarget)
2932 printf("BitcoinMiner:\n");
2933 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2935 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2936 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2939 CRITICAL_BLOCK(cs_main)
2941 if (pblock->hashPrevBlock != hashBestChain)
2942 return error("BitcoinMiner : generated block is stale");
2944 // Remove key from key pool
2945 reservekey.KeepKey();
2947 // Track how many getdata requests this block gets
2948 CRITICAL_BLOCK(wallet.cs_wallet)
2949 wallet.mapRequestCount[pblock->GetHash()] = 0;
2951 // Process this block the same as if we had received it from another node
2952 if (!ProcessBlock(NULL, pblock))
2953 return error("BitcoinMiner : ProcessBlock, block not accepted");
2960 void static ThreadBitcoinMiner(void* parg);
2962 void static BitcoinMiner(CWallet *pwallet)
2964 printf("BitcoinMiner started\n");
2965 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2967 // Each thread has its own key and counter
2968 CReserveKey reservekey(pwallet);
2969 unsigned int nExtraNonce = 0;
2971 while (fGenerateBitcoins)
2973 if (AffinityBugWorkaround(ThreadBitcoinMiner))
2977 while (vNodes.empty() || IsInitialBlockDownload())
2982 if (!fGenerateBitcoins)
2990 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2991 CBlockIndex* pindexPrev = pindexBest;
2993 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
2996 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
2998 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3002 // Prebuild hash buffers
3004 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3005 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3006 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3008 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3010 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3011 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3017 int64 nStart = GetTime();
3018 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3020 uint256& hash = *alignup<16>(hashbuf);
3023 unsigned int nHashesDone = 0;
3024 unsigned int nNonceFound;
3027 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3028 (char*)&hash, nHashesDone);
3030 // Check if something found
3031 if (nNonceFound != -1)
3033 for (int i = 0; i < sizeof(hash)/4; i++)
3034 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3036 if (hash <= hashTarget)
3039 pblock->nNonce = ByteReverse(nNonceFound);
3040 assert(hash == pblock->GetHash());
3042 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3043 CheckWork(pblock.get(), *pwalletMain, reservekey);
3044 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3050 static int64 nHashCounter;
3051 if (nHPSTimerStart == 0)
3053 nHPSTimerStart = GetTimeMillis();
3057 nHashCounter += nHashesDone;
3058 if (GetTimeMillis() - nHPSTimerStart > 4000)
3060 static CCriticalSection cs;
3063 if (GetTimeMillis() - nHPSTimerStart > 4000)
3065 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3066 nHPSTimerStart = GetTimeMillis();
3068 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3069 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3070 static int64 nLogTime;
3071 if (GetTime() - nLogTime > 30 * 60)
3073 nLogTime = GetTime();
3074 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3075 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3081 // Check for stop or if block needs to be rebuilt
3084 if (!fGenerateBitcoins)
3086 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3090 if (nBlockNonce >= 0xffff0000)
3092 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3094 if (pindexPrev != pindexBest)
3097 // Update nTime every few seconds
3098 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3099 nBlockTime = ByteReverse(pblock->nTime);
3104 void static ThreadBitcoinMiner(void* parg)
3106 CWallet* pwallet = (CWallet*)parg;
3109 vnThreadsRunning[3]++;
3110 BitcoinMiner(pwallet);
3111 vnThreadsRunning[3]--;
3113 catch (std::exception& e) {
3114 vnThreadsRunning[3]--;
3115 PrintException(&e, "ThreadBitcoinMiner()");
3117 vnThreadsRunning[3]--;
3118 PrintException(NULL, "ThreadBitcoinMiner()");
3120 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3122 if (vnThreadsRunning[3] == 0)
3124 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3128 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3130 if (fGenerateBitcoins != fGenerate)
3132 fGenerateBitcoins = fGenerate;
3133 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3136 if (fGenerateBitcoins)
3138 int nProcessors = boost::thread::hardware_concurrency();
3139 printf("%d processors\n", nProcessors);
3140 if (nProcessors < 1)
3142 if (fLimitProcessors && nProcessors > nLimitProcessors)
3143 nProcessors = nLimitProcessors;
3144 int nAddThreads = nProcessors - vnThreadsRunning[3];
3145 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3146 for (int i = 0; i < nAddThreads; i++)
3148 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3149 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");