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.
26 class CRequestTracker;
29 static const int CLIENT_VERSION = 59900;
30 static const bool VERSION_IS_BETA = true;
31 extern const std::string CLIENT_NAME;
33 static const unsigned int MAX_BLOCK_SIZE = 1000000;
34 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
35 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
36 static const int64 COIN = 100000000;
37 static const int64 CENT = 1000000;
38 static const int64 MIN_TX_FEE = 50000;
39 static const int64 MIN_RELAY_TX_FEE = 10000;
40 static const int64 MAX_MONEY = 21000000 * COIN;
41 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
42 static const int COINBASE_MATURITY = 100;
43 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
44 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
46 static const int fHaveUPnP = true;
48 static const int fHaveUPnP = false;
52 // Put "/P2SH/" in the coinbase so everybody can tell when
53 // a majority of miners support it
54 static const char* pszP2SH = "/P2SH/";
55 static const CScript COINBASE_FLAGS = CScript() << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
62 extern CCriticalSection cs_main;
63 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
64 extern uint256 hashGenesisBlock;
65 extern CBlockIndex* pindexGenesisBlock;
66 extern int nBestHeight;
67 extern CBigNum bnBestChainWork;
68 extern CBigNum bnBestInvalidWork;
69 extern uint256 hashBestChain;
70 extern CBlockIndex* pindexBest;
71 extern uint64 nPooledTx;
72 extern unsigned int nTransactionsUpdated;
73 extern uint64 nLastBlockTx;
74 extern uint64 nLastBlockSize;
75 extern const std::string strMessageMagic;
76 extern double dHashesPerSec;
77 extern int64 nHPSTimerStart;
78 extern int64 nTimeBestReceived;
79 extern CCriticalSection cs_setpwalletRegistered;
80 extern std::set<CWallet*> setpwalletRegistered;
83 extern int fGenerateBitcoins;
84 extern int64 nTransactionFee;
85 extern int fLimitProcessors;
86 extern int nLimitProcessors;
87 extern int fMinimizeToTray;
88 extern int fMinimizeOnClose;
99 void RegisterWallet(CWallet* pwalletIn);
100 void UnregisterWallet(CWallet* pwalletIn);
101 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
102 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
103 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
104 FILE* AppendBlockFile(unsigned int& nFileRet);
105 bool LoadBlockIndex(bool fAllowNew=true);
106 void PrintBlockTree();
107 bool ProcessMessages(CNode* pfrom);
108 bool SendMessages(CNode* pto, bool fSendTrickle);
109 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
110 CBlock* CreateNewBlock(CReserveKey& reservekey);
111 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
112 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
113 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
114 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
115 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
116 int GetNumBlocksOfPeers();
117 bool IsInitialBlockDownload();
118 std::string GetWarnings(std::string strFor);
131 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
134 bool WriteSetting(const std::string& strKey, const T& value)
137 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
139 std::string strWalletFile;
140 if (!GetWalletFile(pwallet, strWalletFile))
142 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
152 unsigned int nBlockPos;
160 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
163 nBlockPos = nBlockPosIn;
167 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
168 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
169 bool IsNull() const { return (nFile == -1); }
171 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
173 return (a.nFile == b.nFile &&
174 a.nBlockPos == b.nBlockPos &&
175 a.nTxPos == b.nTxPos);
178 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
183 std::string ToString() const
186 return strprintf("null");
188 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
193 printf("%s", ToString().c_str());
206 CInPoint() { SetNull(); }
207 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
208 void SetNull() { ptx = NULL; n = -1; }
209 bool IsNull() const { return (ptx == NULL && n == -1); }
221 COutPoint() { SetNull(); }
222 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
223 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
224 void SetNull() { hash = 0; n = -1; }
225 bool IsNull() const { return (hash == 0 && n == -1); }
227 friend bool operator<(const COutPoint& a, const COutPoint& b)
229 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
232 friend bool operator==(const COutPoint& a, const COutPoint& b)
234 return (a.hash == b.hash && a.n == b.n);
237 friend bool operator!=(const COutPoint& a, const COutPoint& b)
242 std::string ToString() const
244 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
249 printf("%s\n", ToString().c_str());
257 // An input of a transaction. It contains the location of the previous
258 // transaction's output that it claims and a signature that matches the
259 // output's public key.
266 unsigned int nSequence;
270 nSequence = std::numeric_limits<unsigned int>::max();
273 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
276 scriptSig = scriptSigIn;
277 nSequence = nSequenceIn;
280 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
282 prevout = COutPoint(hashPrevTx, nOut);
283 scriptSig = scriptSigIn;
284 nSequence = nSequenceIn;
290 READWRITE(scriptSig);
291 READWRITE(nSequence);
296 return (nSequence == std::numeric_limits<unsigned int>::max());
299 friend bool operator==(const CTxIn& a, const CTxIn& b)
301 return (a.prevout == b.prevout &&
302 a.scriptSig == b.scriptSig &&
303 a.nSequence == b.nSequence);
306 friend bool operator!=(const CTxIn& a, const CTxIn& b)
311 std::string ToString() const
314 str += strprintf("CTxIn(");
315 str += prevout.ToString();
316 if (prevout.IsNull())
317 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
319 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
320 if (nSequence != std::numeric_limits<unsigned int>::max())
321 str += strprintf(", nSequence=%u", nSequence);
328 printf("%s\n", ToString().c_str());
336 // An output of a transaction. It contains the public key that the next input
337 // must be able to sign with to claim it.
343 CScript scriptPubKey;
350 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
353 scriptPubKey = scriptPubKeyIn;
359 READWRITE(scriptPubKey);
365 scriptPubKey.clear();
370 return (nValue == -1);
373 uint256 GetHash() const
375 return SerializeHash(*this);
378 friend bool operator==(const CTxOut& a, const CTxOut& b)
380 return (a.nValue == b.nValue &&
381 a.scriptPubKey == b.scriptPubKey);
384 friend bool operator!=(const CTxOut& a, const CTxOut& b)
389 std::string ToString() const
391 if (scriptPubKey.size() < 6)
392 return "CTxOut(error)";
393 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
398 printf("%s\n", ToString().c_str());
412 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
415 // The basic transaction that is broadcasted on the network and contained in
416 // blocks. A transaction can contain multiple inputs and outputs.
422 std::vector<CTxIn> vin;
423 std::vector<CTxOut> vout;
424 unsigned int nLockTime;
426 // Denial-of-service detection:
428 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
437 READWRITE(this->nVersion);
438 nVersion = this->nVersion;
441 READWRITE(nLockTime);
450 nDoS = 0; // Denial-of-service prevention
455 return (vin.empty() && vout.empty());
458 uint256 GetHash() const
460 return SerializeHash(*this);
463 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
465 // Time based nLockTime implemented in 0.1.6
468 if (nBlockHeight == 0)
469 nBlockHeight = nBestHeight;
471 nBlockTime = GetAdjustedTime();
472 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
474 BOOST_FOREACH(const CTxIn& txin, vin)
480 bool IsNewerThan(const CTransaction& old) const
482 if (vin.size() != old.vin.size())
484 for (int i = 0; i < vin.size(); i++)
485 if (vin[i].prevout != old.vin[i].prevout)
489 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
490 for (int i = 0; i < vin.size(); i++)
492 if (vin[i].nSequence != old.vin[i].nSequence)
494 if (vin[i].nSequence <= nLowest)
497 nLowest = vin[i].nSequence;
499 if (old.vin[i].nSequence < nLowest)
502 nLowest = old.vin[i].nSequence;
509 bool IsCoinBase() const
511 return (vin.size() == 1 && vin[0].prevout.IsNull());
514 /** Check for standard transaction types
515 @return True if all outputs (scriptPubKeys) use only standard transaction forms
517 bool IsStandard() const;
519 /** Check for standard transaction types
520 @param[in] mapInputs Map of previous transactions that have outputs we're spending
521 @return True if all inputs (scriptSigs) use only standard transaction forms
522 @see CTransaction::FetchInputs
524 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
526 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
527 @return number of sigops this transaction's outputs will produce when spent
528 @see CTransaction::FetchInputs
530 int GetLegacySigOpCount() const;
532 /** Count ECDSA signature operations in pay-to-script-hash inputs.
534 @param[in] mapInputs Map of previous transactions that have outputs we're spending
535 @return maximum number of sigops required to validate this transaction's inputs
536 @see CTransaction::FetchInputs
538 int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
540 /** Amount of bitcoins spent by this transaction.
541 @return sum of all outputs (note: does not include fees)
543 int64 GetValueOut() const
546 BOOST_FOREACH(const CTxOut& txout, vout)
548 nValueOut += txout.nValue;
549 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
550 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
555 /** Amount of bitcoins coming in to this transaction
556 Note that lightweight clients may not know anything besides the hash of previous transactions,
557 so may not be able to calculate this.
559 @param[in] mapInputs Map of previous transactions that have outputs we're spending
560 @return Sum of value of all inputs (scriptSigs)
561 @see CTransaction::FetchInputs
563 int64 GetValueIn(const MapPrevTx& mapInputs) const;
565 static bool AllowFree(double dPriority)
567 // Large (in bytes) low-priority (new, small-coin) transactions
569 return dPriority > COIN * 144 / 250;
572 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
574 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
575 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
577 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
578 unsigned int nNewBlockSize = nBlockSize + nBytes;
579 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
585 // Transactions under 10K are free
586 // (about 4500bc if made of 50bc inputs)
592 // Free transaction area
593 if (nNewBlockSize < 27000)
598 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
599 if (nMinFee < nBaseFee)
600 BOOST_FOREACH(const CTxOut& txout, vout)
601 if (txout.nValue < CENT)
604 // Raise the price as the block approaches full
605 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
607 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
609 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
612 if (!MoneyRange(nMinFee))
618 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
620 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
622 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
625 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
626 return error("CTransaction::ReadFromDisk() : fseek failed");
629 // Return file pointer
632 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
633 return error("CTransaction::ReadFromDisk() : second fseek failed");
634 *pfileRet = filein.release();
639 friend bool operator==(const CTransaction& a, const CTransaction& b)
641 return (a.nVersion == b.nVersion &&
644 a.nLockTime == b.nLockTime);
647 friend bool operator!=(const CTransaction& a, const CTransaction& b)
653 std::string ToString() const
656 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
657 GetHash().ToString().substr(0,10).c_str(),
662 for (int i = 0; i < vin.size(); i++)
663 str += " " + vin[i].ToString() + "\n";
664 for (int i = 0; i < vout.size(); i++)
665 str += " " + vout[i].ToString() + "\n";
671 printf("%s", ToString().c_str());
675 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
676 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
677 bool ReadFromDisk(COutPoint prevout);
678 bool DisconnectInputs(CTxDB& txdb);
680 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
682 @param[in] txdb Transaction database
683 @param[in] mapTestPool List of pending changes to the transaction index database
684 @param[in] fBlock True if being called to add a new best-block to the chain
685 @param[in] fMiner True if being called by CreateNewBlock
686 @param[out] inputsRet Pointers to this transaction's inputs
687 @param[out] fInvalid returns true if transaction is invalid
688 @return Returns true if all inputs are in txdb or mapTestPool
690 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
691 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
693 /** Sanity check previous transactions, then, if all checks succeed,
694 mark them as spent by this transaction.
696 @param[in] inputs Previous transactions (from FetchInputs)
697 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
698 @param[in] posThisTx Position of this transaction on disk
699 @param[in] pindexBlock
700 @param[in] fBlock true if called from ConnectBlock
701 @param[in] fMiner true if called from CreateNewBlock
702 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
703 @return Returns true if all checks succeed
705 bool ConnectInputs(MapPrevTx inputs,
706 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
707 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
708 bool ClientConnectInputs();
709 bool CheckTransaction() const;
710 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
711 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
714 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
715 bool AddToMemoryPoolUnchecked();
717 bool RemoveFromMemoryPool();
725 // A transaction with a merkle branch linking it to the block chain
727 class CMerkleTx : public CTransaction
731 std::vector<uint256> vMerkleBranch;
735 mutable char fMerkleVerified;
743 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
752 fMerkleVerified = false;
758 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
759 nVersion = this->nVersion;
760 READWRITE(hashBlock);
761 READWRITE(vMerkleBranch);
766 int SetMerkleBranch(const CBlock* pblock=NULL);
767 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
768 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
769 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
770 int GetBlocksToMaturity() const;
771 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
772 bool AcceptToMemoryPool();
779 // A txdb record that contains the disk location of a transaction and the
780 // locations of transactions that spend its outputs. vSpent is really only
781 // used as a flag, but having the location is very helpful for debugging.
787 std::vector<CDiskTxPos> vSpent;
794 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
797 vSpent.resize(nOutputs);
802 if (!(nType & SER_GETHASH))
819 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
821 return (a.pos == b.pos &&
822 a.vSpent == b.vSpent);
825 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
829 int GetDepthInMainChain() const;
838 // Nodes collect new transactions into a block, hash them into a hash tree,
839 // and scan through nonce values to make the block's hash satisfy proof-of-work
840 // requirements. When they solve the proof-of-work, they broadcast the block
841 // to everyone and the block is added to the block chain. The first transaction
842 // in the block is a special one that creates a new coin owned by the creator
845 // Blocks are appended to blk0001.dat files on disk. Their location on disk
846 // is indexed by CBlockIndex objects in memory.
853 uint256 hashPrevBlock;
854 uint256 hashMerkleRoot;
860 std::vector<CTransaction> vtx;
863 mutable std::vector<uint256> vMerkleTree;
865 // Denial-of-service detection:
867 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
876 READWRITE(this->nVersion);
877 nVersion = this->nVersion;
878 READWRITE(hashPrevBlock);
879 READWRITE(hashMerkleRoot);
884 // ConnectBlock depends on vtx being last so it can calculate offset
885 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
888 const_cast<CBlock*>(this)->vtx.clear();
909 uint256 GetHash() const
911 return Hash(BEGIN(nVersion), END(nNonce));
914 int64 GetBlockTime() const
921 uint256 BuildMerkleTree() const
924 BOOST_FOREACH(const CTransaction& tx, vtx)
925 vMerkleTree.push_back(tx.GetHash());
927 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
929 for (int i = 0; i < nSize; i += 2)
931 int i2 = std::min(i+1, nSize-1);
932 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
933 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
937 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
940 std::vector<uint256> GetMerkleBranch(int nIndex) const
942 if (vMerkleTree.empty())
944 std::vector<uint256> vMerkleBranch;
946 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
948 int i = std::min(nIndex^1, nSize-1);
949 vMerkleBranch.push_back(vMerkleTree[j+i]);
953 return vMerkleBranch;
956 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
960 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
963 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
965 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
972 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
974 // Open history file to append
975 CAutoFile fileout = AppendBlockFile(nFileRet);
977 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
979 // Write index header
980 unsigned int nSize = fileout.GetSerializeSize(*this);
981 fileout << FLATDATA(pchMessageStart) << nSize;
984 nBlockPosRet = ftell(fileout);
985 if (nBlockPosRet == -1)
986 return error("CBlock::WriteToDisk() : ftell failed");
989 // Flush stdio buffers and commit to disk before returning
991 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
994 _commit(_fileno(fileout));
996 fsync(fileno(fileout));
1003 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1007 // Open history file to read
1008 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1010 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1011 if (!fReadTransactions)
1012 filein.nType |= SER_BLOCKHEADERONLY;
1018 if (!CheckProofOfWork(GetHash(), nBits))
1019 return error("CBlock::ReadFromDisk() : errors in block header");
1028 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1029 GetHash().ToString().substr(0,20).c_str(),
1031 hashPrevBlock.ToString().substr(0,20).c_str(),
1032 hashMerkleRoot.ToString().substr(0,10).c_str(),
1033 nTime, nBits, nNonce,
1035 for (int i = 0; i < vtx.size(); i++)
1040 printf(" vMerkleTree: ");
1041 for (int i = 0; i < vMerkleTree.size(); i++)
1042 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1047 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1048 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1049 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1050 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1051 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1052 bool CheckBlock() const;
1062 // The block chain is a tree shaped structure starting with the
1063 // genesis block at the root, with each block potentially having multiple
1064 // candidates to be the next block. pprev and pnext link a path through the
1065 // main/longest chain. A blockindex may have multiple pprev pointing back
1066 // to it, but pnext will only point forward to the longest branch, or will
1067 // be null if the block is not part of the longest chain.
1072 const uint256* phashBlock;
1076 unsigned int nBlockPos;
1078 CBigNum bnChainWork;
1082 uint256 hashMerkleRoot;
1085 unsigned int nNonce;
1105 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1111 nBlockPos = nBlockPosIn;
1115 nVersion = block.nVersion;
1116 hashMerkleRoot = block.hashMerkleRoot;
1117 nTime = block.nTime;
1118 nBits = block.nBits;
1119 nNonce = block.nNonce;
1122 CBlock GetBlockHeader() const
1125 block.nVersion = nVersion;
1127 block.hashPrevBlock = pprev->GetBlockHash();
1128 block.hashMerkleRoot = hashMerkleRoot;
1129 block.nTime = nTime;
1130 block.nBits = nBits;
1131 block.nNonce = nNonce;
1135 uint256 GetBlockHash() const
1140 int64 GetBlockTime() const
1142 return (int64)nTime;
1145 CBigNum GetBlockWork() const
1148 bnTarget.SetCompact(nBits);
1151 return (CBigNum(1)<<256) / (bnTarget+1);
1154 bool IsInMainChain() const
1156 return (pnext || this == pindexBest);
1159 bool CheckIndex() const
1161 return CheckProofOfWork(GetBlockHash(), nBits);
1164 bool EraseBlockFromDisk()
1166 // Open history file
1167 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1171 // Overwrite with empty null block
1179 enum { nMedianTimeSpan=11 };
1181 int64 GetMedianTimePast() const
1183 int64 pmedian[nMedianTimeSpan];
1184 int64* pbegin = &pmedian[nMedianTimeSpan];
1185 int64* pend = &pmedian[nMedianTimeSpan];
1187 const CBlockIndex* pindex = this;
1188 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1189 *(--pbegin) = pindex->GetBlockTime();
1191 std::sort(pbegin, pend);
1192 return pbegin[(pend - pbegin)/2];
1195 int64 GetMedianTime() const
1197 const CBlockIndex* pindex = this;
1198 for (int i = 0; i < nMedianTimeSpan/2; i++)
1201 return GetBlockTime();
1202 pindex = pindex->pnext;
1204 return pindex->GetMedianTimePast();
1209 std::string ToString() const
1211 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1212 pprev, pnext, nFile, nBlockPos, nHeight,
1213 hashMerkleRoot.ToString().substr(0,10).c_str(),
1214 GetBlockHash().ToString().substr(0,20).c_str());
1219 printf("%s\n", ToString().c_str());
1226 // Used to marshal pointers into hashes for db storage.
1228 class CDiskBlockIndex : public CBlockIndex
1240 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1242 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1243 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1248 if (!(nType & SER_GETHASH))
1249 READWRITE(nVersion);
1251 READWRITE(hashNext);
1253 READWRITE(nBlockPos);
1257 READWRITE(this->nVersion);
1258 READWRITE(hashPrev);
1259 READWRITE(hashMerkleRoot);
1265 uint256 GetBlockHash() const
1268 block.nVersion = nVersion;
1269 block.hashPrevBlock = hashPrev;
1270 block.hashMerkleRoot = hashMerkleRoot;
1271 block.nTime = nTime;
1272 block.nBits = nBits;
1273 block.nNonce = nNonce;
1274 return block.GetHash();
1278 std::string ToString() const
1280 std::string str = "CDiskBlockIndex(";
1281 str += CBlockIndex::ToString();
1282 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1283 GetBlockHash().ToString().c_str(),
1284 hashPrev.ToString().substr(0,20).c_str(),
1285 hashNext.ToString().substr(0,20).c_str());
1291 printf("%s\n", ToString().c_str());
1303 // Describes a place in the block chain to another node such that if the
1304 // other node doesn't have the same branch, it can find a recent common trunk.
1305 // The further back it is, the further before the fork it may be.
1310 std::vector<uint256> vHave;
1317 explicit CBlockLocator(const CBlockIndex* pindex)
1322 explicit CBlockLocator(uint256 hashBlock)
1324 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1325 if (mi != mapBlockIndex.end())
1329 CBlockLocator(const std::vector<uint256>& vHaveIn)
1336 if (!(nType & SER_GETHASH))
1337 READWRITE(nVersion);
1348 return vHave.empty();
1351 void Set(const CBlockIndex* pindex)
1357 vHave.push_back(pindex->GetBlockHash());
1359 // Exponentially larger steps back
1360 for (int i = 0; pindex && i < nStep; i++)
1361 pindex = pindex->pprev;
1362 if (vHave.size() > 10)
1365 vHave.push_back(hashGenesisBlock);
1368 int GetDistanceBack()
1370 // Retrace how far back it was in the sender's branch
1373 BOOST_FOREACH(const uint256& hash, vHave)
1375 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1376 if (mi != mapBlockIndex.end())
1378 CBlockIndex* pindex = (*mi).second;
1379 if (pindex->IsInMainChain())
1389 CBlockIndex* GetBlockIndex()
1391 // Find the first block the caller has in the main chain
1392 BOOST_FOREACH(const uint256& hash, vHave)
1394 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1395 if (mi != mapBlockIndex.end())
1397 CBlockIndex* pindex = (*mi).second;
1398 if (pindex->IsInMainChain())
1402 return pindexGenesisBlock;
1405 uint256 GetBlockHash()
1407 // Find the first block the caller has in the main chain
1408 BOOST_FOREACH(const uint256& hash, vHave)
1410 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1411 if (mi != mapBlockIndex.end())
1413 CBlockIndex* pindex = (*mi).second;
1414 if (pindex->IsInMainChain())
1418 return hashGenesisBlock;
1423 CBlockIndex* pindex = GetBlockIndex();
1426 return pindex->nHeight;
1439 // Alerts are for notifying old versions if they become too obsolete and
1440 // need to upgrade. The message is displayed in the status bar.
1441 // Alert messages are broadcast as a vector of signed data. Unserializing may
1442 // not read the entire buffer if the alert is for a newer version, but older
1443 // versions can still relay the original data.
1445 class CUnsignedAlert
1449 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1453 std::set<int> setCancel;
1454 int nMinVer; // lowest version inclusive
1455 int nMaxVer; // highest version inclusive
1456 std::set<std::string> setSubVer; // empty matches all
1460 std::string strComment;
1461 std::string strStatusBar;
1462 std::string strReserved;
1466 READWRITE(this->nVersion);
1467 nVersion = this->nVersion;
1468 READWRITE(nRelayUntil);
1469 READWRITE(nExpiration);
1472 READWRITE(setCancel);
1475 READWRITE(setSubVer);
1476 READWRITE(nPriority);
1478 READWRITE(strComment);
1479 READWRITE(strStatusBar);
1480 READWRITE(strReserved);
1497 strStatusBar.clear();
1498 strReserved.clear();
1501 std::string ToString() const
1503 std::string strSetCancel;
1504 BOOST_FOREACH(int n, setCancel)
1505 strSetCancel += strprintf("%d ", n);
1506 std::string strSetSubVer;
1507 BOOST_FOREACH(std::string str, setSubVer)
1508 strSetSubVer += "\"" + str + "\" ";
1512 " nRelayUntil = %"PRI64d"\n"
1513 " nExpiration = %"PRI64d"\n"
1521 " strComment = \"%s\"\n"
1522 " strStatusBar = \"%s\"\n"
1529 strSetCancel.c_str(),
1532 strSetSubVer.c_str(),
1535 strStatusBar.c_str());
1540 printf("%s", ToString().c_str());
1544 class CAlert : public CUnsignedAlert
1547 std::vector<unsigned char> vchMsg;
1548 std::vector<unsigned char> vchSig;
1563 CUnsignedAlert::SetNull();
1570 return (nExpiration == 0);
1573 uint256 GetHash() const
1575 return SerializeHash(*this);
1578 bool IsInEffect() const
1580 return (GetAdjustedTime() < nExpiration);
1583 bool Cancels(const CAlert& alert) const
1586 return false; // this was a no-op before 31403
1587 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1590 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1592 // TODO: rework for client-version-embedded-in-strSubVer ?
1593 return (IsInEffect() &&
1594 nMinVer <= nVersion && nVersion <= nMaxVer &&
1595 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1598 bool AppliesToMe() const
1600 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1603 bool RelayTo(CNode* pnode) const
1607 // returns true if wasn't already contained in the set
1608 if (pnode->setKnown.insert(GetHash()).second)
1610 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1612 GetAdjustedTime() < nRelayUntil)
1614 pnode->PushMessage("alert", *this);
1621 bool CheckSignature()
1624 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1625 return error("CAlert::CheckSignature() : SetPubKey failed");
1626 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1627 return error("CAlert::CheckSignature() : verify signature failed");
1629 // Now unserialize the data
1630 CDataStream sMsg(vchMsg);
1631 sMsg >> *(CUnsignedAlert*)this;
1635 bool ProcessAlert();