1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 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 = 60000;
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 extern CScript COINBASE_FLAGS;
59 extern CCriticalSection cs_main;
60 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
61 extern uint256 hashGenesisBlock;
62 extern CBlockIndex* pindexGenesisBlock;
63 extern int nBestHeight;
64 extern CBigNum bnBestChainWork;
65 extern CBigNum bnBestInvalidWork;
66 extern uint256 hashBestChain;
67 extern CBlockIndex* pindexBest;
68 extern uint64 nPooledTx;
69 extern unsigned int nTransactionsUpdated;
70 extern uint64 nLastBlockTx;
71 extern uint64 nLastBlockSize;
72 extern const std::string strMessageMagic;
73 extern double dHashesPerSec;
74 extern int64 nHPSTimerStart;
75 extern int64 nTimeBestReceived;
76 extern CCriticalSection cs_setpwalletRegistered;
77 extern std::set<CWallet*> setpwalletRegistered;
80 extern int64 nTransactionFee;
90 void RegisterWallet(CWallet* pwalletIn);
91 void UnregisterWallet(CWallet* pwalletIn);
92 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
93 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
94 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
95 FILE* AppendBlockFile(unsigned int& nFileRet);
96 bool LoadBlockIndex(bool fAllowNew=true);
97 void PrintBlockTree();
98 bool ProcessMessages(CNode* pfrom);
99 bool SendMessages(CNode* pto, bool fSendTrickle);
100 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
101 CBlock* CreateNewBlock(CReserveKey& reservekey);
102 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
103 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
104 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
105 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
106 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
107 int GetNumBlocksOfPeers();
108 bool IsInitialBlockDownload();
109 std::string GetWarnings(std::string strFor);
122 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
129 unsigned int nBlockPos;
137 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
140 nBlockPos = nBlockPosIn;
144 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
145 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
146 bool IsNull() const { return (nFile == -1); }
148 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
150 return (a.nFile == b.nFile &&
151 a.nBlockPos == b.nBlockPos &&
152 a.nTxPos == b.nTxPos);
155 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
160 std::string ToString() const
163 return strprintf("null");
165 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
170 printf("%s", ToString().c_str());
183 CInPoint() { SetNull(); }
184 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
185 void SetNull() { ptx = NULL; n = -1; }
186 bool IsNull() const { return (ptx == NULL && n == -1); }
198 COutPoint() { SetNull(); }
199 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
200 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
201 void SetNull() { hash = 0; n = -1; }
202 bool IsNull() const { return (hash == 0 && n == -1); }
204 friend bool operator<(const COutPoint& a, const COutPoint& b)
206 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
209 friend bool operator==(const COutPoint& a, const COutPoint& b)
211 return (a.hash == b.hash && a.n == b.n);
214 friend bool operator!=(const COutPoint& a, const COutPoint& b)
219 std::string ToString() const
221 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
226 printf("%s\n", ToString().c_str());
234 // An input of a transaction. It contains the location of the previous
235 // transaction's output that it claims and a signature that matches the
236 // output's public key.
243 unsigned int nSequence;
247 nSequence = std::numeric_limits<unsigned int>::max();
250 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
253 scriptSig = scriptSigIn;
254 nSequence = nSequenceIn;
257 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
259 prevout = COutPoint(hashPrevTx, nOut);
260 scriptSig = scriptSigIn;
261 nSequence = nSequenceIn;
267 READWRITE(scriptSig);
268 READWRITE(nSequence);
273 return (nSequence == std::numeric_limits<unsigned int>::max());
276 friend bool operator==(const CTxIn& a, const CTxIn& b)
278 return (a.prevout == b.prevout &&
279 a.scriptSig == b.scriptSig &&
280 a.nSequence == b.nSequence);
283 friend bool operator!=(const CTxIn& a, const CTxIn& b)
288 std::string ToString() const
291 str += strprintf("CTxIn(");
292 str += prevout.ToString();
293 if (prevout.IsNull())
294 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
296 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
297 if (nSequence != std::numeric_limits<unsigned int>::max())
298 str += strprintf(", nSequence=%u", nSequence);
305 printf("%s\n", ToString().c_str());
313 // An output of a transaction. It contains the public key that the next input
314 // must be able to sign with to claim it.
320 CScript scriptPubKey;
327 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
330 scriptPubKey = scriptPubKeyIn;
336 READWRITE(scriptPubKey);
342 scriptPubKey.clear();
347 return (nValue == -1);
350 uint256 GetHash() const
352 return SerializeHash(*this);
355 friend bool operator==(const CTxOut& a, const CTxOut& b)
357 return (a.nValue == b.nValue &&
358 a.scriptPubKey == b.scriptPubKey);
361 friend bool operator!=(const CTxOut& a, const CTxOut& b)
366 std::string ToString() const
368 if (scriptPubKey.size() < 6)
369 return "CTxOut(error)";
370 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
375 printf("%s\n", ToString().c_str());
389 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
392 // The basic transaction that is broadcasted on the network and contained in
393 // blocks. A transaction can contain multiple inputs and outputs.
399 std::vector<CTxIn> vin;
400 std::vector<CTxOut> vout;
401 unsigned int nLockTime;
403 // Denial-of-service detection:
405 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
414 READWRITE(this->nVersion);
415 nVersion = this->nVersion;
418 READWRITE(nLockTime);
427 nDoS = 0; // Denial-of-service prevention
432 return (vin.empty() && vout.empty());
435 uint256 GetHash() const
437 return SerializeHash(*this);
440 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
442 // Time based nLockTime implemented in 0.1.6
445 if (nBlockHeight == 0)
446 nBlockHeight = nBestHeight;
448 nBlockTime = GetAdjustedTime();
449 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
451 BOOST_FOREACH(const CTxIn& txin, vin)
457 bool IsNewerThan(const CTransaction& old) const
459 if (vin.size() != old.vin.size())
461 for (int i = 0; i < vin.size(); i++)
462 if (vin[i].prevout != old.vin[i].prevout)
466 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
467 for (int i = 0; i < vin.size(); i++)
469 if (vin[i].nSequence != old.vin[i].nSequence)
471 if (vin[i].nSequence <= nLowest)
474 nLowest = vin[i].nSequence;
476 if (old.vin[i].nSequence < nLowest)
479 nLowest = old.vin[i].nSequence;
486 bool IsCoinBase() const
488 return (vin.size() == 1 && vin[0].prevout.IsNull());
491 /** Check for standard transaction types
492 @return True if all outputs (scriptPubKeys) use only standard transaction forms
494 bool IsStandard() const;
496 /** Check for standard transaction types
497 @param[in] mapInputs Map of previous transactions that have outputs we're spending
498 @return True if all inputs (scriptSigs) use only standard transaction forms
499 @see CTransaction::FetchInputs
501 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
503 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
504 @return number of sigops this transaction's outputs will produce when spent
505 @see CTransaction::FetchInputs
507 int GetLegacySigOpCount() const;
509 /** Count ECDSA signature operations in pay-to-script-hash inputs.
511 @param[in] mapInputs Map of previous transactions that have outputs we're spending
512 @return maximum number of sigops required to validate this transaction's inputs
513 @see CTransaction::FetchInputs
515 int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
517 /** Amount of bitcoins spent by this transaction.
518 @return sum of all outputs (note: does not include fees)
520 int64 GetValueOut() const
523 BOOST_FOREACH(const CTxOut& txout, vout)
525 nValueOut += txout.nValue;
526 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
527 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
532 /** Amount of bitcoins coming in to this transaction
533 Note that lightweight clients may not know anything besides the hash of previous transactions,
534 so may not be able to calculate this.
536 @param[in] mapInputs Map of previous transactions that have outputs we're spending
537 @return Sum of value of all inputs (scriptSigs)
538 @see CTransaction::FetchInputs
540 int64 GetValueIn(const MapPrevTx& mapInputs) const;
542 static bool AllowFree(double dPriority)
544 // Large (in bytes) low-priority (new, small-coin) transactions
546 return dPriority > COIN * 144 / 250;
549 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
551 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
552 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
554 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
555 unsigned int nNewBlockSize = nBlockSize + nBytes;
556 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
562 // Transactions under 10K are free
563 // (about 4500bc if made of 50bc inputs)
569 // Free transaction area
570 if (nNewBlockSize < 27000)
575 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
576 if (nMinFee < nBaseFee)
577 BOOST_FOREACH(const CTxOut& txout, vout)
578 if (txout.nValue < CENT)
581 // Raise the price as the block approaches full
582 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
584 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
586 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
589 if (!MoneyRange(nMinFee))
595 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
597 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
599 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
602 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
603 return error("CTransaction::ReadFromDisk() : fseek failed");
606 // Return file pointer
609 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
610 return error("CTransaction::ReadFromDisk() : second fseek failed");
611 *pfileRet = filein.release();
616 friend bool operator==(const CTransaction& a, const CTransaction& b)
618 return (a.nVersion == b.nVersion &&
621 a.nLockTime == b.nLockTime);
624 friend bool operator!=(const CTransaction& a, const CTransaction& b)
630 std::string ToString() const
633 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
634 GetHash().ToString().substr(0,10).c_str(),
639 for (int i = 0; i < vin.size(); i++)
640 str += " " + vin[i].ToString() + "\n";
641 for (int i = 0; i < vout.size(); i++)
642 str += " " + vout[i].ToString() + "\n";
648 printf("%s", ToString().c_str());
652 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
653 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
654 bool ReadFromDisk(COutPoint prevout);
655 bool DisconnectInputs(CTxDB& txdb);
657 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
659 @param[in] txdb Transaction database
660 @param[in] mapTestPool List of pending changes to the transaction index database
661 @param[in] fBlock True if being called to add a new best-block to the chain
662 @param[in] fMiner True if being called by CreateNewBlock
663 @param[out] inputsRet Pointers to this transaction's inputs
664 @param[out] fInvalid returns true if transaction is invalid
665 @return Returns true if all inputs are in txdb or mapTestPool
667 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
668 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
670 /** Sanity check previous transactions, then, if all checks succeed,
671 mark them as spent by this transaction.
673 @param[in] inputs Previous transactions (from FetchInputs)
674 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
675 @param[in] posThisTx Position of this transaction on disk
676 @param[in] pindexBlock
677 @param[in] fBlock true if called from ConnectBlock
678 @param[in] fMiner true if called from CreateNewBlock
679 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
680 @return Returns true if all checks succeed
682 bool ConnectInputs(MapPrevTx inputs,
683 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
684 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
685 bool ClientConnectInputs();
686 bool CheckTransaction() const;
687 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
688 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
691 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
692 bool AddToMemoryPoolUnchecked();
694 bool RemoveFromMemoryPool();
702 // A transaction with a merkle branch linking it to the block chain
704 class CMerkleTx : public CTransaction
708 std::vector<uint256> vMerkleBranch;
712 mutable char fMerkleVerified;
720 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
729 fMerkleVerified = false;
735 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
736 nVersion = this->nVersion;
737 READWRITE(hashBlock);
738 READWRITE(vMerkleBranch);
743 int SetMerkleBranch(const CBlock* pblock=NULL);
744 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
745 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
746 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
747 int GetBlocksToMaturity() const;
748 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
749 bool AcceptToMemoryPool();
756 // A txdb record that contains the disk location of a transaction and the
757 // locations of transactions that spend its outputs. vSpent is really only
758 // used as a flag, but having the location is very helpful for debugging.
764 std::vector<CDiskTxPos> vSpent;
771 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
774 vSpent.resize(nOutputs);
779 if (!(nType & SER_GETHASH))
796 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
798 return (a.pos == b.pos &&
799 a.vSpent == b.vSpent);
802 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
806 int GetDepthInMainChain() const;
815 // Nodes collect new transactions into a block, hash them into a hash tree,
816 // and scan through nonce values to make the block's hash satisfy proof-of-work
817 // requirements. When they solve the proof-of-work, they broadcast the block
818 // to everyone and the block is added to the block chain. The first transaction
819 // in the block is a special one that creates a new coin owned by the creator
822 // Blocks are appended to blk0001.dat files on disk. Their location on disk
823 // is indexed by CBlockIndex objects in memory.
830 uint256 hashPrevBlock;
831 uint256 hashMerkleRoot;
837 std::vector<CTransaction> vtx;
840 mutable std::vector<uint256> vMerkleTree;
842 // Denial-of-service detection:
844 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
853 READWRITE(this->nVersion);
854 nVersion = this->nVersion;
855 READWRITE(hashPrevBlock);
856 READWRITE(hashMerkleRoot);
861 // ConnectBlock depends on vtx being last so it can calculate offset
862 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
865 const_cast<CBlock*>(this)->vtx.clear();
886 uint256 GetHash() const
888 return Hash(BEGIN(nVersion), END(nNonce));
891 int64 GetBlockTime() const
896 void UpdateTime(const CBlockIndex* pindexPrev);
899 uint256 BuildMerkleTree() const
902 BOOST_FOREACH(const CTransaction& tx, vtx)
903 vMerkleTree.push_back(tx.GetHash());
905 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
907 for (int i = 0; i < nSize; i += 2)
909 int i2 = std::min(i+1, nSize-1);
910 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
911 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
915 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
918 std::vector<uint256> GetMerkleBranch(int nIndex) const
920 if (vMerkleTree.empty())
922 std::vector<uint256> vMerkleBranch;
924 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
926 int i = std::min(nIndex^1, nSize-1);
927 vMerkleBranch.push_back(vMerkleTree[j+i]);
931 return vMerkleBranch;
934 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
938 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
941 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
943 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
950 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
952 // Open history file to append
953 CAutoFile fileout = AppendBlockFile(nFileRet);
955 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
957 // Write index header
958 unsigned int nSize = fileout.GetSerializeSize(*this);
959 fileout << FLATDATA(pchMessageStart) << nSize;
962 nBlockPosRet = ftell(fileout);
963 if (nBlockPosRet == -1)
964 return error("CBlock::WriteToDisk() : ftell failed");
967 // Flush stdio buffers and commit to disk before returning
969 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
972 _commit(_fileno(fileout));
974 fsync(fileno(fileout));
981 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
985 // Open history file to read
986 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
988 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
989 if (!fReadTransactions)
990 filein.nType |= SER_BLOCKHEADERONLY;
996 if (!CheckProofOfWork(GetHash(), nBits))
997 return error("CBlock::ReadFromDisk() : errors in block header");
1006 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1007 GetHash().ToString().substr(0,20).c_str(),
1009 hashPrevBlock.ToString().substr(0,20).c_str(),
1010 hashMerkleRoot.ToString().substr(0,10).c_str(),
1011 nTime, nBits, nNonce,
1013 for (int i = 0; i < vtx.size(); i++)
1018 printf(" vMerkleTree: ");
1019 for (int i = 0; i < vMerkleTree.size(); i++)
1020 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1025 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1026 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1027 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1028 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1029 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1030 bool CheckBlock() const;
1040 // The block chain is a tree shaped structure starting with the
1041 // genesis block at the root, with each block potentially having multiple
1042 // candidates to be the next block. pprev and pnext link a path through the
1043 // main/longest chain. A blockindex may have multiple pprev pointing back
1044 // to it, but pnext will only point forward to the longest branch, or will
1045 // be null if the block is not part of the longest chain.
1050 const uint256* phashBlock;
1054 unsigned int nBlockPos;
1056 CBigNum bnChainWork;
1060 uint256 hashMerkleRoot;
1063 unsigned int nNonce;
1083 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1089 nBlockPos = nBlockPosIn;
1093 nVersion = block.nVersion;
1094 hashMerkleRoot = block.hashMerkleRoot;
1095 nTime = block.nTime;
1096 nBits = block.nBits;
1097 nNonce = block.nNonce;
1100 CBlock GetBlockHeader() const
1103 block.nVersion = nVersion;
1105 block.hashPrevBlock = pprev->GetBlockHash();
1106 block.hashMerkleRoot = hashMerkleRoot;
1107 block.nTime = nTime;
1108 block.nBits = nBits;
1109 block.nNonce = nNonce;
1113 uint256 GetBlockHash() const
1118 int64 GetBlockTime() const
1120 return (int64)nTime;
1123 CBigNum GetBlockWork() const
1126 bnTarget.SetCompact(nBits);
1129 return (CBigNum(1)<<256) / (bnTarget+1);
1132 bool IsInMainChain() const
1134 return (pnext || this == pindexBest);
1137 bool CheckIndex() const
1139 return CheckProofOfWork(GetBlockHash(), nBits);
1142 bool EraseBlockFromDisk()
1144 // Open history file
1145 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1149 // Overwrite with empty null block
1157 enum { nMedianTimeSpan=11 };
1159 int64 GetMedianTimePast() const
1161 int64 pmedian[nMedianTimeSpan];
1162 int64* pbegin = &pmedian[nMedianTimeSpan];
1163 int64* pend = &pmedian[nMedianTimeSpan];
1165 const CBlockIndex* pindex = this;
1166 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1167 *(--pbegin) = pindex->GetBlockTime();
1169 std::sort(pbegin, pend);
1170 return pbegin[(pend - pbegin)/2];
1173 int64 GetMedianTime() const
1175 const CBlockIndex* pindex = this;
1176 for (int i = 0; i < nMedianTimeSpan/2; i++)
1179 return GetBlockTime();
1180 pindex = pindex->pnext;
1182 return pindex->GetMedianTimePast();
1187 std::string ToString() const
1189 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1190 pprev, pnext, nFile, nBlockPos, nHeight,
1191 hashMerkleRoot.ToString().substr(0,10).c_str(),
1192 GetBlockHash().ToString().substr(0,20).c_str());
1197 printf("%s\n", ToString().c_str());
1204 // Used to marshal pointers into hashes for db storage.
1206 class CDiskBlockIndex : public CBlockIndex
1218 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1220 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1221 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1226 if (!(nType & SER_GETHASH))
1227 READWRITE(nVersion);
1229 READWRITE(hashNext);
1231 READWRITE(nBlockPos);
1235 READWRITE(this->nVersion);
1236 READWRITE(hashPrev);
1237 READWRITE(hashMerkleRoot);
1243 uint256 GetBlockHash() const
1246 block.nVersion = nVersion;
1247 block.hashPrevBlock = hashPrev;
1248 block.hashMerkleRoot = hashMerkleRoot;
1249 block.nTime = nTime;
1250 block.nBits = nBits;
1251 block.nNonce = nNonce;
1252 return block.GetHash();
1256 std::string ToString() const
1258 std::string str = "CDiskBlockIndex(";
1259 str += CBlockIndex::ToString();
1260 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1261 GetBlockHash().ToString().c_str(),
1262 hashPrev.ToString().substr(0,20).c_str(),
1263 hashNext.ToString().substr(0,20).c_str());
1269 printf("%s\n", ToString().c_str());
1281 // Describes a place in the block chain to another node such that if the
1282 // other node doesn't have the same branch, it can find a recent common trunk.
1283 // The further back it is, the further before the fork it may be.
1288 std::vector<uint256> vHave;
1295 explicit CBlockLocator(const CBlockIndex* pindex)
1300 explicit CBlockLocator(uint256 hashBlock)
1302 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1303 if (mi != mapBlockIndex.end())
1307 CBlockLocator(const std::vector<uint256>& vHaveIn)
1314 if (!(nType & SER_GETHASH))
1315 READWRITE(nVersion);
1326 return vHave.empty();
1329 void Set(const CBlockIndex* pindex)
1335 vHave.push_back(pindex->GetBlockHash());
1337 // Exponentially larger steps back
1338 for (int i = 0; pindex && i < nStep; i++)
1339 pindex = pindex->pprev;
1340 if (vHave.size() > 10)
1343 vHave.push_back(hashGenesisBlock);
1346 int GetDistanceBack()
1348 // Retrace how far back it was in the sender's branch
1351 BOOST_FOREACH(const uint256& hash, vHave)
1353 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1354 if (mi != mapBlockIndex.end())
1356 CBlockIndex* pindex = (*mi).second;
1357 if (pindex->IsInMainChain())
1367 CBlockIndex* GetBlockIndex()
1369 // Find the first block the caller has in the main chain
1370 BOOST_FOREACH(const uint256& hash, vHave)
1372 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1373 if (mi != mapBlockIndex.end())
1375 CBlockIndex* pindex = (*mi).second;
1376 if (pindex->IsInMainChain())
1380 return pindexGenesisBlock;
1383 uint256 GetBlockHash()
1385 // Find the first block the caller has in the main chain
1386 BOOST_FOREACH(const uint256& hash, vHave)
1388 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1389 if (mi != mapBlockIndex.end())
1391 CBlockIndex* pindex = (*mi).second;
1392 if (pindex->IsInMainChain())
1396 return hashGenesisBlock;
1401 CBlockIndex* pindex = GetBlockIndex();
1404 return pindex->nHeight;
1417 // Alerts are for notifying old versions if they become too obsolete and
1418 // need to upgrade. The message is displayed in the status bar.
1419 // Alert messages are broadcast as a vector of signed data. Unserializing may
1420 // not read the entire buffer if the alert is for a newer version, but older
1421 // versions can still relay the original data.
1423 class CUnsignedAlert
1427 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1431 std::set<int> setCancel;
1432 int nMinVer; // lowest version inclusive
1433 int nMaxVer; // highest version inclusive
1434 std::set<std::string> setSubVer; // empty matches all
1438 std::string strComment;
1439 std::string strStatusBar;
1440 std::string strReserved;
1444 READWRITE(this->nVersion);
1445 nVersion = this->nVersion;
1446 READWRITE(nRelayUntil);
1447 READWRITE(nExpiration);
1450 READWRITE(setCancel);
1453 READWRITE(setSubVer);
1454 READWRITE(nPriority);
1456 READWRITE(strComment);
1457 READWRITE(strStatusBar);
1458 READWRITE(strReserved);
1475 strStatusBar.clear();
1476 strReserved.clear();
1479 std::string ToString() const
1481 std::string strSetCancel;
1482 BOOST_FOREACH(int n, setCancel)
1483 strSetCancel += strprintf("%d ", n);
1484 std::string strSetSubVer;
1485 BOOST_FOREACH(std::string str, setSubVer)
1486 strSetSubVer += "\"" + str + "\" ";
1490 " nRelayUntil = %"PRI64d"\n"
1491 " nExpiration = %"PRI64d"\n"
1499 " strComment = \"%s\"\n"
1500 " strStatusBar = \"%s\"\n"
1507 strSetCancel.c_str(),
1510 strSetSubVer.c_str(),
1513 strStatusBar.c_str());
1518 printf("%s", ToString().c_str());
1522 class CAlert : public CUnsignedAlert
1525 std::vector<unsigned char> vchMsg;
1526 std::vector<unsigned char> vchSig;
1541 CUnsignedAlert::SetNull();
1548 return (nExpiration == 0);
1551 uint256 GetHash() const
1553 return SerializeHash(*this);
1556 bool IsInEffect() const
1558 return (GetAdjustedTime() < nExpiration);
1561 bool Cancels(const CAlert& alert) const
1564 return false; // this was a no-op before 31403
1565 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1568 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1570 // TODO: rework for client-version-embedded-in-strSubVer ?
1571 return (IsInEffect() &&
1572 nMinVer <= nVersion && nVersion <= nMaxVer &&
1573 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1576 bool AppliesToMe() const
1578 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1581 bool RelayTo(CNode* pnode) const
1585 // returns true if wasn't already contained in the set
1586 if (pnode->setKnown.insert(GetHash()).second)
1588 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1590 GetAdjustedTime() < nRelayUntil)
1592 pnode->PushMessage("alert", *this);
1599 bool CheckSignature()
1602 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1603 return error("CAlert::CheckSignature() : SetPubKey failed");
1604 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1605 return error("CAlert::CheckSignature() : verify signature failed");
1607 // Now unserialize the data
1608 CDataStream sMsg(vchMsg);
1609 sMsg >> *(CUnsignedAlert*)this;
1613 bool ProcessAlert();