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.
15 #include <io.h> /* for _commit */
30 class CRequestTracker;
33 static const int CLIENT_VERSION = 60099;
34 static const bool VERSION_IS_BETA = true;
35 extern const std::string CLIENT_NAME;
37 static const unsigned int MAX_BLOCK_SIZE = 1000000;
38 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
39 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
40 static const int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
41 static const int64 COIN = 100000000;
42 static const int64 CENT = 1000000;
43 static const int64 MIN_TX_FEE = 50000;
44 static const int64 MIN_RELAY_TX_FEE = 10000;
45 static const int64 MAX_MONEY = 21000000 * COIN;
46 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
47 static const int COINBASE_MATURITY = 100;
48 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
49 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
51 static const int fHaveUPnP = true;
53 static const int fHaveUPnP = false;
57 extern CScript COINBASE_FLAGS;
64 extern CCriticalSection cs_main;
65 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
66 extern uint256 hashGenesisBlock;
67 extern CBlockIndex* pindexGenesisBlock;
68 extern int nBestHeight;
69 extern CBigNum bnBestChainWork;
70 extern CBigNum bnBestInvalidWork;
71 extern uint256 hashBestChain;
72 extern CBlockIndex* pindexBest;
73 extern uint64 nPooledTx;
74 extern unsigned int nTransactionsUpdated;
75 extern uint64 nLastBlockTx;
76 extern uint64 nLastBlockSize;
77 extern const std::string strMessageMagic;
78 extern double dHashesPerSec;
79 extern int64 nHPSTimerStart;
80 extern int64 nTimeBestReceived;
81 extern CCriticalSection cs_setpwalletRegistered;
82 extern std::set<CWallet*> setpwalletRegistered;
85 extern int64 nTransactionFee;
95 void RegisterWallet(CWallet* pwalletIn);
96 void UnregisterWallet(CWallet* pwalletIn);
97 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
98 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
99 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
100 FILE* AppendBlockFile(unsigned int& nFileRet);
101 bool LoadBlockIndex(bool fAllowNew=true);
102 void PrintBlockTree();
103 bool ProcessMessages(CNode* pfrom);
104 bool SendMessages(CNode* pto, bool fSendTrickle);
105 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
106 CBlock* CreateNewBlock(CReserveKey& reservekey);
107 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
108 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
109 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
110 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
111 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
112 int GetNumBlocksOfPeers();
113 bool IsInitialBlockDownload();
114 std::string GetWarnings(std::string strFor);
127 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
129 /** Position on disk for a particular transaction. */
134 unsigned int nBlockPos;
142 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
145 nBlockPos = nBlockPosIn;
149 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
150 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
151 bool IsNull() const { return (nFile == -1); }
153 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
155 return (a.nFile == b.nFile &&
156 a.nBlockPos == b.nBlockPos &&
157 a.nTxPos == b.nTxPos);
160 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
165 std::string ToString() const
170 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
175 printf("%s", ToString().c_str());
181 /** An inpoint - a combination of a transaction and an index n into its vin */
188 CInPoint() { SetNull(); }
189 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
190 void SetNull() { ptx = NULL; n = -1; }
191 bool IsNull() const { return (ptx == NULL && n == -1); }
196 /** An outpoint - a combination of a transaction hash and an index n into its vout */
203 COutPoint() { SetNull(); }
204 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
205 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
206 void SetNull() { hash = 0; n = -1; }
207 bool IsNull() const { return (hash == 0 && n == -1); }
209 friend bool operator<(const COutPoint& a, const COutPoint& b)
211 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
214 friend bool operator==(const COutPoint& a, const COutPoint& b)
216 return (a.hash == b.hash && a.n == b.n);
219 friend bool operator!=(const COutPoint& a, const COutPoint& b)
224 std::string ToString() const
226 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
231 printf("%s\n", ToString().c_str());
238 /** An input of a transaction. It contains the location of the previous
239 * transaction's output that it claims and a signature that matches the
240 * output's public key.
247 unsigned int nSequence;
251 nSequence = std::numeric_limits<unsigned int>::max();
254 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
257 scriptSig = scriptSigIn;
258 nSequence = nSequenceIn;
261 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
263 prevout = COutPoint(hashPrevTx, nOut);
264 scriptSig = scriptSigIn;
265 nSequence = nSequenceIn;
271 READWRITE(scriptSig);
272 READWRITE(nSequence);
277 return (nSequence == std::numeric_limits<unsigned int>::max());
280 friend bool operator==(const CTxIn& a, const CTxIn& b)
282 return (a.prevout == b.prevout &&
283 a.scriptSig == b.scriptSig &&
284 a.nSequence == b.nSequence);
287 friend bool operator!=(const CTxIn& a, const CTxIn& b)
292 std::string ToString() const
296 str += prevout.ToString();
297 if (prevout.IsNull())
298 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
300 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
301 if (nSequence != std::numeric_limits<unsigned int>::max())
302 str += strprintf(", nSequence=%u", nSequence);
309 printf("%s\n", ToString().c_str());
316 /** An output of a transaction. It contains the public key that the next input
317 * must be able to sign with to claim it.
323 CScript scriptPubKey;
330 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
333 scriptPubKey = scriptPubKeyIn;
339 READWRITE(scriptPubKey);
345 scriptPubKey.clear();
350 return (nValue == -1);
353 uint256 GetHash() const
355 return SerializeHash(*this);
358 friend bool operator==(const CTxOut& a, const CTxOut& b)
360 return (a.nValue == b.nValue &&
361 a.scriptPubKey == b.scriptPubKey);
364 friend bool operator!=(const CTxOut& a, const CTxOut& b)
369 std::string ToString() const
371 if (scriptPubKey.size() < 6)
372 return "CTxOut(error)";
373 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
378 printf("%s\n", ToString().c_str());
392 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
394 /** The basic transaction that is broadcasted on the network and contained in
395 * blocks. A transaction can contain multiple inputs and outputs.
401 std::vector<CTxIn> vin;
402 std::vector<CTxOut> vout;
403 unsigned int nLockTime;
405 // Denial-of-service detection:
407 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
416 READWRITE(this->nVersion);
417 nVersion = this->nVersion;
420 READWRITE(nLockTime);
429 nDoS = 0; // Denial-of-service prevention
434 return (vin.empty() && vout.empty());
437 uint256 GetHash() const
439 return SerializeHash(*this);
442 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
444 // Time based nLockTime implemented in 0.1.6
447 if (nBlockHeight == 0)
448 nBlockHeight = nBestHeight;
450 nBlockTime = GetAdjustedTime();
451 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
453 BOOST_FOREACH(const CTxIn& txin, vin)
459 bool IsNewerThan(const CTransaction& old) const
461 if (vin.size() != old.vin.size())
463 for (int i = 0; i < vin.size(); i++)
464 if (vin[i].prevout != old.vin[i].prevout)
468 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
469 for (int i = 0; i < vin.size(); i++)
471 if (vin[i].nSequence != old.vin[i].nSequence)
473 if (vin[i].nSequence <= nLowest)
476 nLowest = vin[i].nSequence;
478 if (old.vin[i].nSequence < nLowest)
481 nLowest = old.vin[i].nSequence;
488 bool IsCoinBase() const
490 return (vin.size() == 1 && vin[0].prevout.IsNull());
493 /** Check for standard transaction types
494 @return True if all outputs (scriptPubKeys) use only standard transaction forms
496 bool IsStandard() const;
498 /** Check for standard transaction types
499 @param[in] mapInputs Map of previous transactions that have outputs we're spending
500 @return True if all inputs (scriptSigs) use only standard transaction forms
501 @see CTransaction::FetchInputs
503 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
505 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
506 @return number of sigops this transaction's outputs will produce when spent
507 @see CTransaction::FetchInputs
509 int GetLegacySigOpCount() const;
511 /** Count ECDSA signature operations in pay-to-script-hash inputs.
513 @param[in] mapInputs Map of previous transactions that have outputs we're spending
514 @return maximum number of sigops required to validate this transaction's inputs
515 @see CTransaction::FetchInputs
517 int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
519 /** Amount of bitcoins spent by this transaction.
520 @return sum of all outputs (note: does not include fees)
522 int64 GetValueOut() const
525 BOOST_FOREACH(const CTxOut& txout, vout)
527 nValueOut += txout.nValue;
528 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
529 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
534 /** Amount of bitcoins coming in to this transaction
535 Note that lightweight clients may not know anything besides the hash of previous transactions,
536 so may not be able to calculate this.
538 @param[in] mapInputs Map of previous transactions that have outputs we're spending
539 @return Sum of value of all inputs (scriptSigs)
540 @see CTransaction::FetchInputs
542 int64 GetValueIn(const MapPrevTx& mapInputs) const;
544 static bool AllowFree(double dPriority)
546 // Large (in bytes) low-priority (new, small-coin) transactions
548 return dPriority > COIN * 144 / 250;
551 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
553 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
554 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
556 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
557 unsigned int nNewBlockSize = nBlockSize + nBytes;
558 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
564 // Transactions under 10K are free
565 // (about 4500bc if made of 50bc inputs)
571 // Free transaction area
572 if (nNewBlockSize < 27000)
577 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
578 if (nMinFee < nBaseFee)
579 BOOST_FOREACH(const CTxOut& txout, vout)
580 if (txout.nValue < CENT)
583 // Raise the price as the block approaches full
584 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
586 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
588 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
591 if (!MoneyRange(nMinFee))
597 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
599 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
601 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
604 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
605 return error("CTransaction::ReadFromDisk() : fseek failed");
608 // Return file pointer
611 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
612 return error("CTransaction::ReadFromDisk() : second fseek failed");
613 *pfileRet = filein.release();
618 friend bool operator==(const CTransaction& a, const CTransaction& b)
620 return (a.nVersion == b.nVersion &&
623 a.nLockTime == b.nLockTime);
626 friend bool operator!=(const CTransaction& a, const CTransaction& b)
632 std::string ToString() const
635 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
636 GetHash().ToString().substr(0,10).c_str(),
641 for (int i = 0; i < vin.size(); i++)
642 str += " " + vin[i].ToString() + "\n";
643 for (int i = 0; i < vout.size(); i++)
644 str += " " + vout[i].ToString() + "\n";
650 printf("%s", ToString().c_str());
654 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
655 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
656 bool ReadFromDisk(COutPoint prevout);
657 bool DisconnectInputs(CTxDB& txdb);
659 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
661 @param[in] txdb Transaction database
662 @param[in] mapTestPool List of pending changes to the transaction index database
663 @param[in] fBlock True if being called to add a new best-block to the chain
664 @param[in] fMiner True if being called by CreateNewBlock
665 @param[out] inputsRet Pointers to this transaction's inputs
666 @param[out] fInvalid returns true if transaction is invalid
667 @return Returns true if all inputs are in txdb or mapTestPool
669 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
670 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
672 /** Sanity check previous transactions, then, if all checks succeed,
673 mark them as spent by this transaction.
675 @param[in] inputs Previous transactions (from FetchInputs)
676 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
677 @param[in] posThisTx Position of this transaction on disk
678 @param[in] pindexBlock
679 @param[in] fBlock true if called from ConnectBlock
680 @param[in] fMiner true if called from CreateNewBlock
681 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
682 @return Returns true if all checks succeed
684 bool ConnectInputs(MapPrevTx inputs,
685 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
686 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
687 bool ClientConnectInputs();
688 bool CheckTransaction() const;
689 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
690 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
693 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
694 bool AddToMemoryPoolUnchecked();
696 bool RemoveFromMemoryPool();
703 /** 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();
755 /** A txdb record that contains the disk location of a transaction and the
756 * locations of transactions that spend its outputs. vSpent is really only
757 * used as a flag, but having the location is very helpful for debugging.
763 std::vector<CDiskTxPos> vSpent;
770 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
773 vSpent.resize(nOutputs);
778 if (!(nType & SER_GETHASH))
795 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
797 return (a.pos == b.pos &&
798 a.vSpent == b.vSpent);
801 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
805 int GetDepthInMainChain() const;
813 /** Nodes collect new transactions into a block, hash them into a hash tree,
814 * and scan through nonce values to make the block's hash satisfy proof-of-work
815 * requirements. When they solve the proof-of-work, they broadcast the block
816 * to everyone and the block is added to the block chain. The first transaction
817 * in the block is a special one that creates a new coin owned by the creator
820 * Blocks are appended to blk0001.dat files on disk. Their location on disk
821 * is indexed by CBlockIndex objects in memory.
828 uint256 hashPrevBlock;
829 uint256 hashMerkleRoot;
835 std::vector<CTransaction> vtx;
838 mutable std::vector<uint256> vMerkleTree;
840 // Denial-of-service detection:
842 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
851 READWRITE(this->nVersion);
852 nVersion = this->nVersion;
853 READWRITE(hashPrevBlock);
854 READWRITE(hashMerkleRoot);
859 // ConnectBlock depends on vtx being last so it can calculate offset
860 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
863 const_cast<CBlock*>(this)->vtx.clear();
884 uint256 GetHash() const
886 return Hash(BEGIN(nVersion), END(nNonce));
889 int64 GetBlockTime() const
894 void UpdateTime(const CBlockIndex* pindexPrev);
897 uint256 BuildMerkleTree() const
900 BOOST_FOREACH(const CTransaction& tx, vtx)
901 vMerkleTree.push_back(tx.GetHash());
903 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
905 for (int i = 0; i < nSize; i += 2)
907 int i2 = std::min(i+1, nSize-1);
908 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
909 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
913 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
916 std::vector<uint256> GetMerkleBranch(int nIndex) const
918 if (vMerkleTree.empty())
920 std::vector<uint256> vMerkleBranch;
922 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
924 int i = std::min(nIndex^1, nSize-1);
925 vMerkleBranch.push_back(vMerkleTree[j+i]);
929 return vMerkleBranch;
932 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
936 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
939 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
941 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
948 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
950 // Open history file to append
951 CAutoFile fileout = AppendBlockFile(nFileRet);
953 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
955 // Write index header
956 unsigned int nSize = fileout.GetSerializeSize(*this);
957 fileout << FLATDATA(pchMessageStart) << nSize;
960 nBlockPosRet = ftell(fileout);
961 if (nBlockPosRet == -1)
962 return error("CBlock::WriteToDisk() : ftell failed");
965 // Flush stdio buffers and commit to disk before returning
967 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
970 _commit(_fileno(fileout));
972 fsync(fileno(fileout));
979 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
983 // Open history file to read
984 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
986 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
987 if (!fReadTransactions)
988 filein.nType |= SER_BLOCKHEADERONLY;
994 if (!CheckProofOfWork(GetHash(), nBits))
995 return error("CBlock::ReadFromDisk() : errors in block header");
1004 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1005 GetHash().ToString().substr(0,20).c_str(),
1007 hashPrevBlock.ToString().substr(0,20).c_str(),
1008 hashMerkleRoot.ToString().substr(0,10).c_str(),
1009 nTime, nBits, nNonce,
1011 for (int i = 0; i < vtx.size(); i++)
1016 printf(" vMerkleTree: ");
1017 for (int i = 0; i < vMerkleTree.size(); i++)
1018 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1023 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1024 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1025 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1026 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1027 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1028 bool CheckBlock() const;
1032 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
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());
1203 /** Used to marshal pointers into hashes for db storage. */
1204 class CDiskBlockIndex : public CBlockIndex
1216 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1218 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1219 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1224 if (!(nType & SER_GETHASH))
1225 READWRITE(nVersion);
1227 READWRITE(hashNext);
1229 READWRITE(nBlockPos);
1233 READWRITE(this->nVersion);
1234 READWRITE(hashPrev);
1235 READWRITE(hashMerkleRoot);
1241 uint256 GetBlockHash() const
1244 block.nVersion = nVersion;
1245 block.hashPrevBlock = hashPrev;
1246 block.hashMerkleRoot = hashMerkleRoot;
1247 block.nTime = nTime;
1248 block.nBits = nBits;
1249 block.nNonce = nNonce;
1250 return block.GetHash();
1254 std::string ToString() const
1256 std::string str = "CDiskBlockIndex(";
1257 str += CBlockIndex::ToString();
1258 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1259 GetBlockHash().ToString().c_str(),
1260 hashPrev.ToString().substr(0,20).c_str(),
1261 hashNext.ToString().substr(0,20).c_str());
1267 printf("%s\n", ToString().c_str());
1278 /** Describes a place in the block chain to another node such that if the
1279 * other node doesn't have the same branch, it can find a recent common trunk.
1280 * The further back it is, the further before the fork it may be.
1285 std::vector<uint256> vHave;
1292 explicit CBlockLocator(const CBlockIndex* pindex)
1297 explicit CBlockLocator(uint256 hashBlock)
1299 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1300 if (mi != mapBlockIndex.end())
1304 CBlockLocator(const std::vector<uint256>& vHaveIn)
1311 if (!(nType & SER_GETHASH))
1312 READWRITE(nVersion);
1323 return vHave.empty();
1326 void Set(const CBlockIndex* pindex)
1332 vHave.push_back(pindex->GetBlockHash());
1334 // Exponentially larger steps back
1335 for (int i = 0; pindex && i < nStep; i++)
1336 pindex = pindex->pprev;
1337 if (vHave.size() > 10)
1340 vHave.push_back(hashGenesisBlock);
1343 int GetDistanceBack()
1345 // Retrace how far back it was in the sender's branch
1348 BOOST_FOREACH(const uint256& hash, vHave)
1350 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1351 if (mi != mapBlockIndex.end())
1353 CBlockIndex* pindex = (*mi).second;
1354 if (pindex->IsInMainChain())
1364 CBlockIndex* GetBlockIndex()
1366 // Find the first block the caller has in the main chain
1367 BOOST_FOREACH(const uint256& hash, vHave)
1369 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1370 if (mi != mapBlockIndex.end())
1372 CBlockIndex* pindex = (*mi).second;
1373 if (pindex->IsInMainChain())
1377 return pindexGenesisBlock;
1380 uint256 GetBlockHash()
1382 // Find the first block the caller has in the main chain
1383 BOOST_FOREACH(const uint256& hash, vHave)
1385 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1386 if (mi != mapBlockIndex.end())
1388 CBlockIndex* pindex = (*mi).second;
1389 if (pindex->IsInMainChain())
1393 return hashGenesisBlock;
1398 CBlockIndex* pindex = GetBlockIndex();
1401 return pindex->nHeight;
1413 /** Alerts are for notifying old versions if they become too obsolete and
1414 * need to upgrade. The message is displayed in the status bar.
1415 * Alert messages are broadcast as a vector of signed data. Unserializing may
1416 * not read the entire buffer if the alert is for a newer version, but older
1417 * versions can still relay the original data.
1419 class CUnsignedAlert
1423 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1427 std::set<int> setCancel;
1428 int nMinVer; // lowest version inclusive
1429 int nMaxVer; // highest version inclusive
1430 std::set<std::string> setSubVer; // empty matches all
1434 std::string strComment;
1435 std::string strStatusBar;
1436 std::string strReserved;
1440 READWRITE(this->nVersion);
1441 nVersion = this->nVersion;
1442 READWRITE(nRelayUntil);
1443 READWRITE(nExpiration);
1446 READWRITE(setCancel);
1449 READWRITE(setSubVer);
1450 READWRITE(nPriority);
1452 READWRITE(strComment);
1453 READWRITE(strStatusBar);
1454 READWRITE(strReserved);
1471 strStatusBar.clear();
1472 strReserved.clear();
1475 std::string ToString() const
1477 std::string strSetCancel;
1478 BOOST_FOREACH(int n, setCancel)
1479 strSetCancel += strprintf("%d ", n);
1480 std::string strSetSubVer;
1481 BOOST_FOREACH(std::string str, setSubVer)
1482 strSetSubVer += "\"" + str + "\" ";
1486 " nRelayUntil = %"PRI64d"\n"
1487 " nExpiration = %"PRI64d"\n"
1495 " strComment = \"%s\"\n"
1496 " strStatusBar = \"%s\"\n"
1503 strSetCancel.c_str(),
1506 strSetSubVer.c_str(),
1509 strStatusBar.c_str());
1514 printf("%s", ToString().c_str());
1518 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1519 class CAlert : public CUnsignedAlert
1522 std::vector<unsigned char> vchMsg;
1523 std::vector<unsigned char> vchSig;
1538 CUnsignedAlert::SetNull();
1545 return (nExpiration == 0);
1548 uint256 GetHash() const
1550 return SerializeHash(*this);
1553 bool IsInEffect() const
1555 return (GetAdjustedTime() < nExpiration);
1558 bool Cancels(const CAlert& alert) const
1561 return false; // this was a no-op before 31403
1562 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1565 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1567 // TODO: rework for client-version-embedded-in-strSubVer ?
1568 return (IsInEffect() &&
1569 nMinVer <= nVersion && nVersion <= nMaxVer &&
1570 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1573 bool AppliesToMe() const
1575 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1578 bool RelayTo(CNode* pnode) const
1582 // returns true if wasn't already contained in the set
1583 if (pnode->setKnown.insert(GetHash()).second)
1585 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1587 GetAdjustedTime() < nRelayUntil)
1589 pnode->PushMessage("alert", *this);
1596 bool CheckSignature()
1599 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1600 return error("CAlert::CheckSignature() : SetPubKey failed");
1601 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1602 return error("CAlert::CheckSignature() : verify signature failed");
1604 // Now unserialize the data
1605 CDataStream sMsg(vchMsg);
1606 sMsg >> *(CUnsignedAlert*)this;
1610 bool ProcessAlert();