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;
30 static const unsigned int MAX_BLOCK_SIZE = 1000000;
31 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
32 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
33 static const int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
34 static const int64 COIN = 100000000;
35 static const int64 CENT = 1000000;
36 static const int64 MIN_TX_FEE = 50000;
37 static const int64 MIN_RELAY_TX_FEE = 10000;
38 static const int64 MAX_MONEY = 21000000 * COIN;
39 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
40 static const int COINBASE_MATURITY = 100;
41 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
42 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
44 static const int fHaveUPnP = true;
46 static const int fHaveUPnP = false;
54 extern CCriticalSection cs_main;
55 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
56 extern uint256 hashGenesisBlock;
57 extern CBlockIndex* pindexGenesisBlock;
58 extern int nBestHeight;
59 extern CBigNum bnBestChainWork;
60 extern CBigNum bnBestInvalidWork;
61 extern uint256 hashBestChain;
62 extern CBlockIndex* pindexBest;
63 extern unsigned int nTransactionsUpdated;
64 extern double dHashesPerSec;
65 extern int64 nHPSTimerStart;
66 extern int64 nTimeBestReceived;
67 extern CCriticalSection cs_setpwalletRegistered;
68 extern std::set<CWallet*> setpwalletRegistered;
71 extern int fGenerateBitcoins;
72 extern int64 nTransactionFee;
73 extern int fLimitProcessors;
74 extern int nLimitProcessors;
75 extern int fMinimizeToTray;
76 extern int fMinimizeOnClose;
87 void RegisterWallet(CWallet* pwalletIn);
88 void UnregisterWallet(CWallet* pwalletIn);
89 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
90 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
91 FILE* AppendBlockFile(unsigned int& nFileRet);
92 bool LoadBlockIndex(bool fAllowNew=true);
93 void PrintBlockTree();
94 bool ProcessMessages(CNode* pfrom);
95 bool SendMessages(CNode* pto, bool fSendTrickle);
96 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
97 CBlock* CreateNewBlock(CReserveKey& reservekey);
98 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
99 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
100 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
101 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
102 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
103 bool IsInitialBlockDownload();
104 std::string GetWarnings(std::string strFor);
117 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
120 bool WriteSetting(const std::string& strKey, const T& value)
123 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
125 std::string strWalletFile;
126 if (!GetWalletFile(pwallet, strWalletFile))
128 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
138 unsigned int nBlockPos;
146 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
149 nBlockPos = nBlockPosIn;
153 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
154 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
155 bool IsNull() const { return (nFile == -1); }
157 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
159 return (a.nFile == b.nFile &&
160 a.nBlockPos == b.nBlockPos &&
161 a.nTxPos == b.nTxPos);
164 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
169 std::string ToString() const
172 return strprintf("null");
174 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
179 printf("%s", ToString().c_str());
192 CInPoint() { SetNull(); }
193 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
194 void SetNull() { ptx = NULL; n = -1; }
195 bool IsNull() const { return (ptx == NULL && n == -1); }
207 COutPoint() { SetNull(); }
208 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
209 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
210 void SetNull() { hash = 0; n = -1; }
211 bool IsNull() const { return (hash == 0 && n == -1); }
213 friend bool operator<(const COutPoint& a, const COutPoint& b)
215 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
218 friend bool operator==(const COutPoint& a, const COutPoint& b)
220 return (a.hash == b.hash && a.n == b.n);
223 friend bool operator!=(const COutPoint& a, const COutPoint& b)
228 std::string ToString() const
230 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
235 printf("%s\n", ToString().c_str());
243 // An input of a transaction. It contains the location of the previous
244 // transaction's output that it claims and a signature that matches the
245 // output's public key.
252 unsigned int nSequence;
256 nSequence = UINT_MAX;
259 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
262 scriptSig = scriptSigIn;
263 nSequence = nSequenceIn;
266 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
268 prevout = COutPoint(hashPrevTx, nOut);
269 scriptSig = scriptSigIn;
270 nSequence = nSequenceIn;
276 READWRITE(scriptSig);
277 READWRITE(nSequence);
282 return (nSequence == UINT_MAX);
285 friend bool operator==(const CTxIn& a, const CTxIn& b)
287 return (a.prevout == b.prevout &&
288 a.scriptSig == b.scriptSig &&
289 a.nSequence == b.nSequence);
292 friend bool operator!=(const CTxIn& a, const CTxIn& b)
297 std::string ToString() const
300 str += strprintf("CTxIn(");
301 str += prevout.ToString();
302 if (prevout.IsNull())
303 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
305 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
306 if (nSequence != UINT_MAX)
307 str += strprintf(", nSequence=%u", nSequence);
314 printf("%s\n", ToString().c_str());
322 // An output of a transaction. It contains the public key that the next input
323 // must be able to sign with to claim it.
329 CScript scriptPubKey;
336 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
339 scriptPubKey = scriptPubKeyIn;
345 READWRITE(scriptPubKey);
351 scriptPubKey.clear();
356 return (nValue == -1);
359 uint256 GetHash() const
361 return SerializeHash(*this);
364 friend bool operator==(const CTxOut& a, const CTxOut& b)
366 return (a.nValue == b.nValue &&
367 a.scriptPubKey == b.scriptPubKey);
370 friend bool operator!=(const CTxOut& a, const CTxOut& b)
375 std::string ToString() const
377 if (scriptPubKey.size() < 6)
378 return "CTxOut(error)";
379 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
384 printf("%s\n", ToString().c_str());
389 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
393 // The basic transaction that is broadcasted on the network and contained in
394 // blocks. A transaction can contain multiple inputs and outputs.
400 std::vector<CTxIn> vin;
401 std::vector<CTxOut> vout;
402 unsigned int nLockTime;
412 READWRITE(this->nVersion);
413 nVersion = this->nVersion;
416 READWRITE(nLockTime);
429 return (vin.empty() && vout.empty());
432 uint256 GetHash() const
434 return SerializeHash(*this);
437 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
439 // Time based nLockTime implemented in 0.1.6
442 if (nBlockHeight == 0)
443 nBlockHeight = nBestHeight;
445 nBlockTime = GetAdjustedTime();
446 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
448 BOOST_FOREACH(const CTxIn& txin, vin)
454 bool IsNewerThan(const CTransaction& old) const
456 if (vin.size() != old.vin.size())
458 for (int i = 0; i < vin.size(); i++)
459 if (vin[i].prevout != old.vin[i].prevout)
463 unsigned int nLowest = UINT_MAX;
464 for (int i = 0; i < vin.size(); i++)
466 if (vin[i].nSequence != old.vin[i].nSequence)
468 if (vin[i].nSequence <= nLowest)
471 nLowest = vin[i].nSequence;
473 if (old.vin[i].nSequence < nLowest)
476 nLowest = old.vin[i].nSequence;
483 bool IsCoinBase() const
485 return (vin.size() == 1 && vin[0].prevout.IsNull());
488 int GetSigOpCount() const
491 BOOST_FOREACH(const CTxIn& txin, vin)
492 n += txin.scriptSig.GetSigOpCount();
493 BOOST_FOREACH(const CTxOut& txout, vout)
494 n += txout.scriptPubKey.GetSigOpCount();
498 /** Count ECDSA signature operations in pay-to-script-hash inputs.
499 This is a better measure of how expensive it is to process this transaction.
501 @param[in] mapInputsMap of previous transactions that have outputs we're spending
502 @return maximum number of sigops required to validate this transaction's inputs
503 @see CTransaction::FetchInputs
505 int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
507 bool IsStandard() const
509 BOOST_FOREACH(const CTxIn& txin, vin)
510 if (!txin.scriptSig.IsPushOnly())
511 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
512 BOOST_FOREACH(const CTxOut& txout, vout)
513 if (!::IsStandard(txout.scriptPubKey))
514 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
518 int64 GetValueOut() const
521 BOOST_FOREACH(const CTxOut& txout, vout)
523 nValueOut += txout.nValue;
524 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
525 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
530 /** Amount of bitcoins coming in to this transaction
531 Note that lightweight clients may not know anything besides the hash of previous transactions,
532 so may not be able to calculate this.
534 @param[in] mapInputsMap of previous transactions that have outputs we're spending
535 @returnSum of value of all inputs (scriptSigs)
536 @see CTransaction::FetchInputs
538 int64 GetValueIn(const MapPrevTx& mapInputs) const;
540 static bool AllowFree(double dPriority)
542 // Large (in bytes) low-priority (new, small-coin) transactions
544 return dPriority > COIN * 144 / 250;
547 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
549 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
550 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
552 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
553 unsigned int nNewBlockSize = nBlockSize + nBytes;
554 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
560 // Transactions under 10K are free
561 // (about 4500bc if made of 50bc inputs)
567 // Free transaction area
568 if (nNewBlockSize < 27000)
573 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
574 if (nMinFee < nBaseFee)
575 BOOST_FOREACH(const CTxOut& txout, vout)
576 if (txout.nValue < CENT)
579 // Raise the price as the block approaches full
580 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
582 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
584 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
587 if (!MoneyRange(nMinFee))
593 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
595 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
597 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
600 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
601 return error("CTransaction::ReadFromDisk() : fseek failed");
604 // Return file pointer
607 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
608 return error("CTransaction::ReadFromDisk() : second fseek failed");
609 *pfileRet = filein.release();
614 friend bool operator==(const CTransaction& a, const CTransaction& b)
616 return (a.nVersion == b.nVersion &&
619 a.nLockTime == b.nLockTime);
622 friend bool operator!=(const CTransaction& a, const CTransaction& b)
628 std::string ToString() const
631 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
632 GetHash().ToString().substr(0,10).c_str(),
637 for (int i = 0; i < vin.size(); i++)
638 str += " " + vin[i].ToString() + "\n";
639 for (int i = 0; i < vout.size(); i++)
640 str += " " + vout[i].ToString() + "\n";
646 printf("%s", ToString().c_str());
650 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
651 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
652 bool ReadFromDisk(COutPoint prevout);
653 bool DisconnectInputs(CTxDB& txdb);
655 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
657 @param[in] txdb Transaction database
658 @param[in] mapTestPool List of pending changes to the transaction index database
659 @param[in] fBlock True if being called to add a new best-block to the chain
660 @param[in] fMiner True if being called by CreateNewBlock
661 @param[out] inputsRet Pointers to this transaction's inputs
662 @param[out] fInvalid returns true if transaction is invalid
663 @return Returns true if all inputs are in txdb or mapTestPool
665 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
666 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
668 /** Sanity check previous transactions, then, if all checks succeed,
669 mark them as spent by this transaction.
671 @param[in] inputsPrevious transactions (from FetchInputs)
672 @param[out] mapTestPoolKeeps track of inputs that need to be updated on disk
673 @param[in] posThisTxPosition of this transaction on disk
674 @param[in] pindexBlock
675 @param[in] fBlock true if called from ConnectBlock
676 @param[in] fMiner true if called from CreateNewBlock
677 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
678 @return Returns true if all checks succeed
680 bool ConnectInputs(MapPrevTx inputs,
681 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
682 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
683 bool ClientConnectInputs();
684 bool CheckTransaction() const;
685 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
686 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
688 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
689 bool AddToMemoryPoolUnchecked();
691 bool RemoveFromMemoryPool();
699 // A transaction with a merkle branch linking it to the block chain
701 class CMerkleTx : public CTransaction
705 std::vector<uint256> vMerkleBranch;
709 mutable char fMerkleVerified;
717 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
726 fMerkleVerified = false;
732 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
733 nVersion = this->nVersion;
734 READWRITE(hashBlock);
735 READWRITE(vMerkleBranch);
740 int SetMerkleBranch(const CBlock* pblock=NULL);
741 int GetDepthInMainChain(int& nHeightRet) const;
742 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
743 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
744 int GetBlocksToMaturity() const;
745 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
746 bool AcceptToMemoryPool();
753 // A txdb record that contains the disk location of a transaction and the
754 // locations of transactions that spend its outputs. vSpent is really only
755 // used as a flag, but having the location is very helpful for debugging.
761 std::vector<CDiskTxPos> vSpent;
768 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
771 vSpent.resize(nOutputs);
776 if (!(nType & SER_GETHASH))
793 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
795 return (a.pos == b.pos &&
796 a.vSpent == b.vSpent);
799 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
803 int GetDepthInMainChain() const;
811 // Nodes collect new transactions into a block, hash them into a hash tree,
812 // and scan through nonce values to make the block's hash satisfy proof-of-work
813 // requirements. When they solve the proof-of-work, they broadcast the block
814 // to everyone and the block is added to the block chain. The first transaction
815 // in the block is a special one that creates a new coin owned by the creator
818 // Blocks are appended to blk0001.dat files on disk. Their location on disk
819 // is indexed by CBlockIndex objects in memory.
826 uint256 hashPrevBlock;
827 uint256 hashMerkleRoot;
833 std::vector<CTransaction> vtx;
836 mutable std::vector<uint256> vMerkleTree;
846 READWRITE(this->nVersion);
847 nVersion = this->nVersion;
848 READWRITE(hashPrevBlock);
849 READWRITE(hashMerkleRoot);
854 // ConnectBlock depends on vtx being last so it can calculate offset
855 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
858 const_cast<CBlock*>(this)->vtx.clear();
878 uint256 GetHash() const
880 return Hash(BEGIN(nVersion), END(nNonce));
883 int64 GetBlockTime() const
888 int GetSigOpCount() const
891 BOOST_FOREACH(const CTransaction& tx, vtx)
892 n += tx.GetSigOpCount();
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;
1038 // The block chain is a tree shaped structure starting with the
1039 // genesis block at the root, with each block potentially having multiple
1040 // candidates to be the next block. pprev and pnext link a path through the
1041 // main/longest chain. A blockindex may have multiple pprev pointing back
1042 // to it, but pnext will only point forward to the longest branch, or will
1043 // be null if the block is not part of the longest chain.
1048 const uint256* phashBlock;
1052 unsigned int nBlockPos;
1054 CBigNum bnChainWork;
1058 uint256 hashMerkleRoot;
1061 unsigned int nNonce;
1081 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1087 nBlockPos = nBlockPosIn;
1091 nVersion = block.nVersion;
1092 hashMerkleRoot = block.hashMerkleRoot;
1093 nTime = block.nTime;
1094 nBits = block.nBits;
1095 nNonce = block.nNonce;
1098 CBlock GetBlockHeader() const
1101 block.nVersion = nVersion;
1103 block.hashPrevBlock = pprev->GetBlockHash();
1104 block.hashMerkleRoot = hashMerkleRoot;
1105 block.nTime = nTime;
1106 block.nBits = nBits;
1107 block.nNonce = nNonce;
1111 uint256 GetBlockHash() const
1116 int64 GetBlockTime() const
1118 return (int64)nTime;
1121 CBigNum GetBlockWork() const
1124 bnTarget.SetCompact(nBits);
1127 return (CBigNum(1)<<256) / (bnTarget+1);
1130 bool IsInMainChain() const
1132 return (pnext || this == pindexBest);
1135 bool CheckIndex() const
1137 return CheckProofOfWork(GetBlockHash(), nBits);
1140 bool EraseBlockFromDisk()
1142 // Open history file
1143 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1147 // Overwrite with empty null block
1155 enum { nMedianTimeSpan=11 };
1157 int64 GetMedianTimePast() const
1159 int64 pmedian[nMedianTimeSpan];
1160 int64* pbegin = &pmedian[nMedianTimeSpan];
1161 int64* pend = &pmedian[nMedianTimeSpan];
1163 const CBlockIndex* pindex = this;
1164 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1165 *(--pbegin) = pindex->GetBlockTime();
1167 std::sort(pbegin, pend);
1168 return pbegin[(pend - pbegin)/2];
1171 int64 GetMedianTime() const
1173 const CBlockIndex* pindex = this;
1174 for (int i = 0; i < nMedianTimeSpan/2; i++)
1177 return GetBlockTime();
1178 pindex = pindex->pnext;
1180 return pindex->GetMedianTimePast();
1185 std::string ToString() const
1187 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1188 pprev, pnext, nFile, nBlockPos, nHeight,
1189 hashMerkleRoot.ToString().substr(0,10).c_str(),
1190 GetBlockHash().ToString().substr(0,20).c_str());
1195 printf("%s\n", ToString().c_str());
1202 // 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());
1279 // Describes a place in the block chain to another node such that if the
1280 // other node doesn't have the same branch, it can find a recent common trunk.
1281 // The further back it is, the further before the fork it may be.
1286 std::vector<uint256> vHave;
1293 explicit CBlockLocator(const CBlockIndex* pindex)
1298 explicit CBlockLocator(uint256 hashBlock)
1300 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1301 if (mi != mapBlockIndex.end())
1307 if (!(nType & SER_GETHASH))
1308 READWRITE(nVersion);
1319 return vHave.empty();
1322 void Set(const CBlockIndex* pindex)
1328 vHave.push_back(pindex->GetBlockHash());
1330 // Exponentially larger steps back
1331 for (int i = 0; pindex && i < nStep; i++)
1332 pindex = pindex->pprev;
1333 if (vHave.size() > 10)
1336 vHave.push_back(hashGenesisBlock);
1339 int GetDistanceBack()
1341 // Retrace how far back it was in the sender's branch
1344 BOOST_FOREACH(const uint256& hash, vHave)
1346 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1347 if (mi != mapBlockIndex.end())
1349 CBlockIndex* pindex = (*mi).second;
1350 if (pindex->IsInMainChain())
1360 CBlockIndex* GetBlockIndex()
1362 // Find the first block the caller has in the main chain
1363 BOOST_FOREACH(const uint256& hash, vHave)
1365 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1366 if (mi != mapBlockIndex.end())
1368 CBlockIndex* pindex = (*mi).second;
1369 if (pindex->IsInMainChain())
1373 return pindexGenesisBlock;
1376 uint256 GetBlockHash()
1378 // Find the first block the caller has in the main chain
1379 BOOST_FOREACH(const uint256& hash, vHave)
1381 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1382 if (mi != mapBlockIndex.end())
1384 CBlockIndex* pindex = (*mi).second;
1385 if (pindex->IsInMainChain())
1389 return hashGenesisBlock;
1394 CBlockIndex* pindex = GetBlockIndex();
1397 return pindex->nHeight;
1410 // Alerts are for notifying old versions if they become too obsolete and
1411 // need to upgrade. The message is displayed in the status bar.
1412 // Alert messages are broadcast as a vector of signed data. Unserializing may
1413 // not read the entire buffer if the alert is for a newer version, but older
1414 // versions can still relay the original data.
1416 class CUnsignedAlert
1420 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1424 std::set<int> setCancel;
1425 int nMinVer; // lowest version inclusive
1426 int nMaxVer; // highest version inclusive
1427 std::set<std::string> setSubVer; // empty matches all
1431 std::string strComment;
1432 std::string strStatusBar;
1433 std::string strReserved;
1437 READWRITE(this->nVersion);
1438 nVersion = this->nVersion;
1439 READWRITE(nRelayUntil);
1440 READWRITE(nExpiration);
1443 READWRITE(setCancel);
1446 READWRITE(setSubVer);
1447 READWRITE(nPriority);
1449 READWRITE(strComment);
1450 READWRITE(strStatusBar);
1451 READWRITE(strReserved);
1468 strStatusBar.clear();
1469 strReserved.clear();
1472 std::string ToString() const
1474 std::string strSetCancel;
1475 BOOST_FOREACH(int n, setCancel)
1476 strSetCancel += strprintf("%d ", n);
1477 std::string strSetSubVer;
1478 BOOST_FOREACH(std::string str, setSubVer)
1479 strSetSubVer += "\"" + str + "\" ";
1483 " nRelayUntil = %"PRI64d"\n"
1484 " nExpiration = %"PRI64d"\n"
1492 " strComment = \"%s\"\n"
1493 " strStatusBar = \"%s\"\n"
1500 strSetCancel.c_str(),
1503 strSetSubVer.c_str(),
1506 strStatusBar.c_str());
1511 printf("%s", ToString().c_str());
1515 class CAlert : public CUnsignedAlert
1518 std::vector<unsigned char> vchMsg;
1519 std::vector<unsigned char> vchSig;
1534 CUnsignedAlert::SetNull();
1541 return (nExpiration == 0);
1544 uint256 GetHash() const
1546 return SerializeHash(*this);
1549 bool IsInEffect() const
1551 return (GetAdjustedTime() < nExpiration);
1554 bool Cancels(const CAlert& alert) const
1557 return false; // this was a no-op before 31403
1558 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1561 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1563 return (IsInEffect() &&
1564 nMinVer <= nVersion && nVersion <= nMaxVer &&
1565 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1568 bool AppliesToMe() const
1570 return AppliesTo(VERSION, ::pszSubVer);
1573 bool RelayTo(CNode* pnode) const
1577 // returns true if wasn't already contained in the set
1578 if (pnode->setKnown.insert(GetHash()).second)
1580 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1582 GetAdjustedTime() < nRelayUntil)
1584 pnode->PushMessage("alert", *this);
1591 bool CheckSignature()
1594 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1595 return error("CAlert::CheckSignature() : SetPubKey failed");
1596 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1597 return error("CAlert::CheckSignature() : verify signature failed");
1599 // Now unserialize the data
1600 CDataStream sMsg(vchMsg);
1601 sMsg >> *(CUnsignedAlert*)this;
1605 bool ProcessAlert();