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 */
28 class CRequestTracker;
31 static const unsigned int MAX_BLOCK_SIZE = 1000000;
32 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
33 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
34 static const int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
35 static const int64 MIN_TX_FEE = 50000;
36 static const int64 MIN_RELAY_TX_FEE = 10000;
37 static const int64 MAX_MONEY = 21000000 * COIN;
38 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
39 static const int COINBASE_MATURITY = 100;
40 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
41 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
43 static const int fHaveUPnP = true;
45 static const int fHaveUPnP = false;
49 extern CScript COINBASE_FLAGS;
56 extern CCriticalSection cs_main;
57 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
58 extern uint256 hashGenesisBlock;
59 extern CBlockIndex* pindexGenesisBlock;
60 extern int nBestHeight;
61 extern CBigNum bnBestChainWork;
62 extern CBigNum bnBestInvalidWork;
63 extern uint256 hashBestChain;
64 extern CBlockIndex* pindexBest;
65 extern uint64 nPooledTx;
66 extern unsigned int nTransactionsUpdated;
67 extern uint64 nLastBlockTx;
68 extern uint64 nLastBlockSize;
69 extern const std::string strMessageMagic;
70 extern double dHashesPerSec;
71 extern int64 nHPSTimerStart;
72 extern int64 nTimeBestReceived;
73 extern CCriticalSection cs_setpwalletRegistered;
74 extern std::set<CWallet*> setpwalletRegistered;
77 extern int64 nTransactionFee;
87 void RegisterWallet(CWallet* pwalletIn);
88 void UnregisterWallet(CWallet* pwalletIn);
89 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
90 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
91 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
92 FILE* AppendBlockFile(unsigned int& nFileRet);
93 bool LoadBlockIndex(bool fAllowNew=true);
94 void PrintBlockTree();
95 bool ProcessMessages(CNode* pfrom);
96 bool SendMessages(CNode* pto, bool fSendTrickle);
97 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
98 CBlock* CreateNewBlock(CReserveKey& reservekey);
99 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
100 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
101 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
102 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
103 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
104 int GetNumBlocksOfPeers();
105 bool IsInitialBlockDownload();
106 std::string GetWarnings(std::string strFor);
119 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
121 /** Position on disk for a particular transaction. */
126 unsigned int nBlockPos;
134 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
137 nBlockPos = nBlockPosIn;
141 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
142 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
143 bool IsNull() const { return (nFile == -1); }
145 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
147 return (a.nFile == b.nFile &&
148 a.nBlockPos == b.nBlockPos &&
149 a.nTxPos == b.nTxPos);
152 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
157 std::string ToString() const
162 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
167 printf("%s", ToString().c_str());
173 /** An inpoint - a combination of a transaction and an index n into its vin */
180 CInPoint() { SetNull(); }
181 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
182 void SetNull() { ptx = NULL; n = -1; }
183 bool IsNull() const { return (ptx == NULL && n == -1); }
188 /** An outpoint - a combination of a transaction hash and an index n into its vout */
195 COutPoint() { SetNull(); }
196 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
197 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
198 void SetNull() { hash = 0; n = -1; }
199 bool IsNull() const { return (hash == 0 && n == -1); }
201 friend bool operator<(const COutPoint& a, const COutPoint& b)
203 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
206 friend bool operator==(const COutPoint& a, const COutPoint& b)
208 return (a.hash == b.hash && a.n == b.n);
211 friend bool operator!=(const COutPoint& a, const COutPoint& b)
216 std::string ToString() const
218 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
223 printf("%s\n", ToString().c_str());
230 /** An input of a transaction. It contains the location of the previous
231 * transaction's output that it claims and a signature that matches the
232 * output's public key.
239 unsigned int nSequence;
243 nSequence = std::numeric_limits<unsigned int>::max();
246 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
249 scriptSig = scriptSigIn;
250 nSequence = nSequenceIn;
253 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
255 prevout = COutPoint(hashPrevTx, nOut);
256 scriptSig = scriptSigIn;
257 nSequence = nSequenceIn;
263 READWRITE(scriptSig);
264 READWRITE(nSequence);
269 return (nSequence == std::numeric_limits<unsigned int>::max());
272 friend bool operator==(const CTxIn& a, const CTxIn& b)
274 return (a.prevout == b.prevout &&
275 a.scriptSig == b.scriptSig &&
276 a.nSequence == b.nSequence);
279 friend bool operator!=(const CTxIn& a, const CTxIn& b)
284 std::string ToString() const
288 str += prevout.ToString();
289 if (prevout.IsNull())
290 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
292 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
293 if (nSequence != std::numeric_limits<unsigned int>::max())
294 str += strprintf(", nSequence=%u", nSequence);
301 printf("%s\n", ToString().c_str());
308 /** An output of a transaction. It contains the public key that the next input
309 * must be able to sign with to claim it.
315 CScript scriptPubKey;
322 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
325 scriptPubKey = scriptPubKeyIn;
331 READWRITE(scriptPubKey);
337 scriptPubKey.clear();
342 return (nValue == -1);
345 uint256 GetHash() const
347 return SerializeHash(*this);
350 friend bool operator==(const CTxOut& a, const CTxOut& b)
352 return (a.nValue == b.nValue &&
353 a.scriptPubKey == b.scriptPubKey);
356 friend bool operator!=(const CTxOut& a, const CTxOut& b)
361 std::string ToString() const
363 if (scriptPubKey.size() < 6)
364 return "CTxOut(error)";
365 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
370 printf("%s\n", ToString().c_str());
384 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
386 /** The basic transaction that is broadcasted on the network and contained in
387 * blocks. A transaction can contain multiple inputs and outputs.
393 std::vector<CTxIn> vin;
394 std::vector<CTxOut> vout;
395 unsigned int nLockTime;
397 // Denial-of-service detection:
399 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
408 READWRITE(this->nVersion);
409 nVersion = this->nVersion;
412 READWRITE(nLockTime);
421 nDoS = 0; // Denial-of-service prevention
426 return (vin.empty() && vout.empty());
429 uint256 GetHash() const
431 return SerializeHash(*this);
434 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
436 // Time based nLockTime implemented in 0.1.6
439 if (nBlockHeight == 0)
440 nBlockHeight = nBestHeight;
442 nBlockTime = GetAdjustedTime();
443 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
445 BOOST_FOREACH(const CTxIn& txin, vin)
451 bool IsNewerThan(const CTransaction& old) const
453 if (vin.size() != old.vin.size())
455 for (unsigned int i = 0; i < vin.size(); i++)
456 if (vin[i].prevout != old.vin[i].prevout)
460 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
461 for (unsigned int i = 0; i < vin.size(); i++)
463 if (vin[i].nSequence != old.vin[i].nSequence)
465 if (vin[i].nSequence <= nLowest)
468 nLowest = vin[i].nSequence;
470 if (old.vin[i].nSequence < nLowest)
473 nLowest = old.vin[i].nSequence;
480 bool IsCoinBase() const
482 return (vin.size() == 1 && vin[0].prevout.IsNull());
485 /** Check for standard transaction types
486 @return True if all outputs (scriptPubKeys) use only standard transaction forms
488 bool IsStandard() const;
490 /** Check for standard transaction types
491 @param[in] mapInputs Map of previous transactions that have outputs we're spending
492 @return True if all inputs (scriptSigs) use only standard transaction forms
493 @see CTransaction::FetchInputs
495 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
497 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
498 @return number of sigops this transaction's outputs will produce when spent
499 @see CTransaction::FetchInputs
501 int GetLegacySigOpCount() const;
503 /** Count ECDSA signature operations in pay-to-script-hash inputs.
505 @param[in] mapInputs Map of previous transactions that have outputs we're spending
506 @return maximum number of sigops required to validate this transaction's inputs
507 @see CTransaction::FetchInputs
509 int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
511 /** Amount of bitcoins spent by this transaction.
512 @return sum of all outputs (note: does not include fees)
514 int64 GetValueOut() const
517 BOOST_FOREACH(const CTxOut& txout, vout)
519 nValueOut += txout.nValue;
520 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
521 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
526 /** Amount of bitcoins coming in to this transaction
527 Note that lightweight clients may not know anything besides the hash of previous transactions,
528 so may not be able to calculate this.
530 @param[in] mapInputs Map of previous transactions that have outputs we're spending
531 @return Sum of value of all inputs (scriptSigs)
532 @see CTransaction::FetchInputs
534 int64 GetValueIn(const MapPrevTx& mapInputs) const;
536 static bool AllowFree(double dPriority)
538 // Large (in bytes) low-priority (new, small-coin) transactions
540 return dPriority > COIN * 144 / 250;
543 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
545 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
546 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
548 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
549 unsigned int nNewBlockSize = nBlockSize + nBytes;
550 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
556 // Transactions under 10K are free
557 // (about 4500bc if made of 50bc inputs)
563 // Free transaction area
564 if (nNewBlockSize < 27000)
569 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
570 if (nMinFee < nBaseFee)
572 BOOST_FOREACH(const CTxOut& txout, vout)
573 if (txout.nValue < CENT)
577 // Raise the price as the block approaches full
578 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
580 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
582 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
585 if (!MoneyRange(nMinFee))
591 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
593 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
595 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
598 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
599 return error("CTransaction::ReadFromDisk() : fseek failed");
602 // Return file pointer
605 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
606 return error("CTransaction::ReadFromDisk() : second fseek failed");
607 *pfileRet = filein.release();
612 friend bool operator==(const CTransaction& a, const CTransaction& b)
614 return (a.nVersion == b.nVersion &&
617 a.nLockTime == b.nLockTime);
620 friend bool operator!=(const CTransaction& a, const CTransaction& b)
626 std::string ToString() const
629 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
630 GetHash().ToString().substr(0,10).c_str(),
635 for (unsigned int i = 0; i < vin.size(); i++)
636 str += " " + vin[i].ToString() + "\n";
637 for (unsigned int i = 0; i < vout.size(); i++)
638 str += " " + vout[i].ToString() + "\n";
644 printf("%s", ToString().c_str());
648 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
649 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
650 bool ReadFromDisk(COutPoint prevout);
651 bool DisconnectInputs(CTxDB& txdb);
653 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
655 @param[in] txdb Transaction database
656 @param[in] mapTestPool List of pending changes to the transaction index database
657 @param[in] fBlock True if being called to add a new best-block to the chain
658 @param[in] fMiner True if being called by CreateNewBlock
659 @param[out] inputsRet Pointers to this transaction's inputs
660 @param[out] fInvalid returns true if transaction is invalid
661 @return Returns true if all inputs are in txdb or mapTestPool
663 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
664 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
666 /** Sanity check previous transactions, then, if all checks succeed,
667 mark them as spent by this transaction.
669 @param[in] inputs Previous transactions (from FetchInputs)
670 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
671 @param[in] posThisTx Position of this transaction on disk
672 @param[in] pindexBlock
673 @param[in] fBlock true if called from ConnectBlock
674 @param[in] fMiner true if called from CreateNewBlock
675 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
676 @return Returns true if all checks succeed
678 bool ConnectInputs(MapPrevTx inputs,
679 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
680 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
681 bool ClientConnectInputs();
682 bool CheckTransaction() const;
683 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
686 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
687 bool AddToMemoryPoolUnchecked();
689 bool RemoveFromMemoryPool();
696 /** A transaction with a merkle branch linking it to the block chain. */
697 class CMerkleTx : public CTransaction
701 std::vector<uint256> vMerkleBranch;
705 mutable char fMerkleVerified;
713 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
722 fMerkleVerified = false;
728 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
729 nVersion = this->nVersion;
730 READWRITE(hashBlock);
731 READWRITE(vMerkleBranch);
736 int SetMerkleBranch(const CBlock* pblock=NULL);
737 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
738 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
739 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
740 int GetBlocksToMaturity() const;
741 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
742 bool AcceptToMemoryPool();
748 /** A txdb record that contains the disk location of a transaction and the
749 * locations of transactions that spend its outputs. vSpent is really only
750 * used as a flag, but having the location is very helpful for debugging.
756 std::vector<CDiskTxPos> vSpent;
763 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
766 vSpent.resize(nOutputs);
771 if (!(nType & SER_GETHASH))
788 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
790 return (a.pos == b.pos &&
791 a.vSpent == b.vSpent);
794 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
798 int GetDepthInMainChain() const;
806 /** Nodes collect new transactions into a block, hash them into a hash tree,
807 * and scan through nonce values to make the block's hash satisfy proof-of-work
808 * requirements. When they solve the proof-of-work, they broadcast the block
809 * to everyone and the block is added to the block chain. The first transaction
810 * in the block is a special one that creates a new coin owned by the creator
813 * Blocks are appended to blk0001.dat files on disk. Their location on disk
814 * is indexed by CBlockIndex objects in memory.
821 uint256 hashPrevBlock;
822 uint256 hashMerkleRoot;
828 std::vector<CTransaction> vtx;
831 mutable std::vector<uint256> vMerkleTree;
833 // Denial-of-service detection:
835 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
844 READWRITE(this->nVersion);
845 nVersion = this->nVersion;
846 READWRITE(hashPrevBlock);
847 READWRITE(hashMerkleRoot);
852 // ConnectBlock depends on vtx being last so it can calculate offset
853 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
856 const_cast<CBlock*>(this)->vtx.clear();
877 uint256 GetHash() const
879 return Hash(BEGIN(nVersion), END(nNonce));
882 int64 GetBlockTime() const
887 void UpdateTime(const CBlockIndex* pindexPrev);
890 uint256 BuildMerkleTree() const
893 BOOST_FOREACH(const CTransaction& tx, vtx)
894 vMerkleTree.push_back(tx.GetHash());
896 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
898 for (int i = 0; i < nSize; i += 2)
900 int i2 = std::min(i+1, nSize-1);
901 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
902 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
906 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
909 std::vector<uint256> GetMerkleBranch(int nIndex) const
911 if (vMerkleTree.empty())
913 std::vector<uint256> vMerkleBranch;
915 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
917 int i = std::min(nIndex^1, nSize-1);
918 vMerkleBranch.push_back(vMerkleTree[j+i]);
922 return vMerkleBranch;
925 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
929 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
932 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
934 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
941 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
943 // Open history file to append
944 CAutoFile fileout = AppendBlockFile(nFileRet);
946 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
948 // Write index header
949 unsigned int nSize = fileout.GetSerializeSize(*this);
950 fileout << FLATDATA(pchMessageStart) << nSize;
953 nBlockPosRet = ftell(fileout);
954 if (nBlockPosRet == -1)
955 return error("CBlock::WriteToDisk() : ftell failed");
958 // Flush stdio buffers and commit to disk before returning
960 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
963 _commit(_fileno(fileout));
965 fsync(fileno(fileout));
972 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
976 // Open history file to read
977 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
979 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
980 if (!fReadTransactions)
981 filein.nType |= SER_BLOCKHEADERONLY;
987 if (!CheckProofOfWork(GetHash(), nBits))
988 return error("CBlock::ReadFromDisk() : errors in block header");
997 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
998 GetHash().ToString().substr(0,20).c_str(),
1000 hashPrevBlock.ToString().substr(0,20).c_str(),
1001 hashMerkleRoot.ToString().substr(0,10).c_str(),
1002 nTime, nBits, nNonce,
1004 for (unsigned int i = 0; i < vtx.size(); i++)
1009 printf(" vMerkleTree: ");
1010 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1011 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1016 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1017 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1018 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1019 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1020 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1021 bool CheckBlock() const;
1025 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1033 /** The block chain is a tree shaped structure starting with the
1034 * genesis block at the root, with each block potentially having multiple
1035 * candidates to be the next block. pprev and pnext link a path through the
1036 * main/longest chain. A blockindex may have multiple pprev pointing back
1037 * to it, but pnext will only point forward to the longest branch, or will
1038 * be null if the block is not part of the longest chain.
1043 const uint256* phashBlock;
1047 unsigned int nBlockPos;
1049 CBigNum bnChainWork;
1053 uint256 hashMerkleRoot;
1056 unsigned int nNonce;
1076 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1082 nBlockPos = nBlockPosIn;
1086 nVersion = block.nVersion;
1087 hashMerkleRoot = block.hashMerkleRoot;
1088 nTime = block.nTime;
1089 nBits = block.nBits;
1090 nNonce = block.nNonce;
1093 CBlock GetBlockHeader() const
1096 block.nVersion = nVersion;
1098 block.hashPrevBlock = pprev->GetBlockHash();
1099 block.hashMerkleRoot = hashMerkleRoot;
1100 block.nTime = nTime;
1101 block.nBits = nBits;
1102 block.nNonce = nNonce;
1106 uint256 GetBlockHash() const
1111 int64 GetBlockTime() const
1113 return (int64)nTime;
1116 CBigNum GetBlockWork() const
1119 bnTarget.SetCompact(nBits);
1122 return (CBigNum(1)<<256) / (bnTarget+1);
1125 bool IsInMainChain() const
1127 return (pnext || this == pindexBest);
1130 bool CheckIndex() const
1132 return CheckProofOfWork(GetBlockHash(), nBits);
1135 bool EraseBlockFromDisk()
1137 // Open history file
1138 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1142 // Overwrite with empty null block
1150 enum { nMedianTimeSpan=11 };
1152 int64 GetMedianTimePast() const
1154 int64 pmedian[nMedianTimeSpan];
1155 int64* pbegin = &pmedian[nMedianTimeSpan];
1156 int64* pend = &pmedian[nMedianTimeSpan];
1158 const CBlockIndex* pindex = this;
1159 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1160 *(--pbegin) = pindex->GetBlockTime();
1162 std::sort(pbegin, pend);
1163 return pbegin[(pend - pbegin)/2];
1166 int64 GetMedianTime() const
1168 const CBlockIndex* pindex = this;
1169 for (int i = 0; i < nMedianTimeSpan/2; i++)
1172 return GetBlockTime();
1173 pindex = pindex->pnext;
1175 return pindex->GetMedianTimePast();
1180 std::string ToString() const
1182 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1183 pprev, pnext, nFile, nBlockPos, nHeight,
1184 hashMerkleRoot.ToString().substr(0,10).c_str(),
1185 GetBlockHash().ToString().substr(0,20).c_str());
1190 printf("%s\n", ToString().c_str());
1196 /** Used to marshal pointers into hashes for db storage. */
1197 class CDiskBlockIndex : public CBlockIndex
1209 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1211 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1212 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1217 if (!(nType & SER_GETHASH))
1218 READWRITE(nVersion);
1220 READWRITE(hashNext);
1222 READWRITE(nBlockPos);
1226 READWRITE(this->nVersion);
1227 READWRITE(hashPrev);
1228 READWRITE(hashMerkleRoot);
1234 uint256 GetBlockHash() const
1237 block.nVersion = nVersion;
1238 block.hashPrevBlock = hashPrev;
1239 block.hashMerkleRoot = hashMerkleRoot;
1240 block.nTime = nTime;
1241 block.nBits = nBits;
1242 block.nNonce = nNonce;
1243 return block.GetHash();
1247 std::string ToString() const
1249 std::string str = "CDiskBlockIndex(";
1250 str += CBlockIndex::ToString();
1251 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1252 GetBlockHash().ToString().c_str(),
1253 hashPrev.ToString().substr(0,20).c_str(),
1254 hashNext.ToString().substr(0,20).c_str());
1260 printf("%s\n", ToString().c_str());
1271 /** Describes a place in the block chain to another node such that if the
1272 * other node doesn't have the same branch, it can find a recent common trunk.
1273 * The further back it is, the further before the fork it may be.
1278 std::vector<uint256> vHave;
1285 explicit CBlockLocator(const CBlockIndex* pindex)
1290 explicit CBlockLocator(uint256 hashBlock)
1292 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1293 if (mi != mapBlockIndex.end())
1297 CBlockLocator(const std::vector<uint256>& vHaveIn)
1304 if (!(nType & SER_GETHASH))
1305 READWRITE(nVersion);
1316 return vHave.empty();
1319 void Set(const CBlockIndex* pindex)
1325 vHave.push_back(pindex->GetBlockHash());
1327 // Exponentially larger steps back
1328 for (int i = 0; pindex && i < nStep; i++)
1329 pindex = pindex->pprev;
1330 if (vHave.size() > 10)
1333 vHave.push_back(hashGenesisBlock);
1336 int GetDistanceBack()
1338 // Retrace how far back it was in the sender's branch
1341 BOOST_FOREACH(const uint256& hash, vHave)
1343 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1344 if (mi != mapBlockIndex.end())
1346 CBlockIndex* pindex = (*mi).second;
1347 if (pindex->IsInMainChain())
1357 CBlockIndex* GetBlockIndex()
1359 // Find the first block the caller has in the main chain
1360 BOOST_FOREACH(const uint256& hash, vHave)
1362 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1363 if (mi != mapBlockIndex.end())
1365 CBlockIndex* pindex = (*mi).second;
1366 if (pindex->IsInMainChain())
1370 return pindexGenesisBlock;
1373 uint256 GetBlockHash()
1375 // Find the first block the caller has in the main chain
1376 BOOST_FOREACH(const uint256& hash, vHave)
1378 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1379 if (mi != mapBlockIndex.end())
1381 CBlockIndex* pindex = (*mi).second;
1382 if (pindex->IsInMainChain())
1386 return hashGenesisBlock;
1391 CBlockIndex* pindex = GetBlockIndex();
1394 return pindex->nHeight;
1406 /** Alerts are for notifying old versions if they become too obsolete and
1407 * need to upgrade. The message is displayed in the status bar.
1408 * Alert messages are broadcast as a vector of signed data. Unserializing may
1409 * not read the entire buffer if the alert is for a newer version, but older
1410 * versions can still relay the original data.
1412 class CUnsignedAlert
1416 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1420 std::set<int> setCancel;
1421 int nMinVer; // lowest version inclusive
1422 int nMaxVer; // highest version inclusive
1423 std::set<std::string> setSubVer; // empty matches all
1427 std::string strComment;
1428 std::string strStatusBar;
1429 std::string strReserved;
1433 READWRITE(this->nVersion);
1434 nVersion = this->nVersion;
1435 READWRITE(nRelayUntil);
1436 READWRITE(nExpiration);
1439 READWRITE(setCancel);
1442 READWRITE(setSubVer);
1443 READWRITE(nPriority);
1445 READWRITE(strComment);
1446 READWRITE(strStatusBar);
1447 READWRITE(strReserved);
1464 strStatusBar.clear();
1465 strReserved.clear();
1468 std::string ToString() const
1470 std::string strSetCancel;
1471 BOOST_FOREACH(int n, setCancel)
1472 strSetCancel += strprintf("%d ", n);
1473 std::string strSetSubVer;
1474 BOOST_FOREACH(std::string str, setSubVer)
1475 strSetSubVer += "\"" + str + "\" ";
1479 " nRelayUntil = %"PRI64d"\n"
1480 " nExpiration = %"PRI64d"\n"
1488 " strComment = \"%s\"\n"
1489 " strStatusBar = \"%s\"\n"
1496 strSetCancel.c_str(),
1499 strSetSubVer.c_str(),
1502 strStatusBar.c_str());
1507 printf("%s", ToString().c_str());
1511 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1512 class CAlert : public CUnsignedAlert
1515 std::vector<unsigned char> vchMsg;
1516 std::vector<unsigned char> vchSig;
1531 CUnsignedAlert::SetNull();
1538 return (nExpiration == 0);
1541 uint256 GetHash() const
1543 return SerializeHash(*this);
1546 bool IsInEffect() const
1548 return (GetAdjustedTime() < nExpiration);
1551 bool Cancels(const CAlert& alert) const
1554 return false; // this was a no-op before 31403
1555 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1558 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1560 // TODO: rework for client-version-embedded-in-strSubVer ?
1561 return (IsInEffect() &&
1562 nMinVer <= nVersion && nVersion <= nMaxVer &&
1563 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1566 bool AppliesToMe() const
1568 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1571 bool RelayTo(CNode* pnode) const
1575 // returns true if wasn't already contained in the set
1576 if (pnode->setKnown.insert(GetHash()).second)
1578 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1580 GetAdjustedTime() < nRelayUntil)
1582 pnode->PushMessage("alert", *this);
1589 bool CheckSignature()
1592 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1593 return error("CAlert::CheckSignature() : SetPubKey failed");
1594 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1595 return error("CAlert::CheckSignature() : verify signature failed");
1597 // Now unserialize the data
1598 CDataStream sMsg(vchMsg);
1599 sMsg >> *(CUnsignedAlert*)this;
1603 bool ProcessAlert();