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 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 int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
37 static const int64 MIN_TX_FEE = 50000;
38 static const int64 MIN_RELAY_TX_FEE = 10000;
39 static const int64 MAX_MONEY = 21000000 * COIN;
40 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
41 static const int COINBASE_MATURITY = 100;
42 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
43 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
45 static const int fHaveUPnP = true;
47 static const int fHaveUPnP = false;
51 extern CScript COINBASE_FLAGS;
58 extern CCriticalSection cs_main;
59 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
60 extern uint256 hashGenesisBlock;
61 extern CBlockIndex* pindexGenesisBlock;
62 extern int nBestHeight;
63 extern CBigNum bnBestChainWork;
64 extern CBigNum bnBestInvalidWork;
65 extern uint256 hashBestChain;
66 extern CBlockIndex* pindexBest;
67 extern uint64 nPooledTx;
68 extern unsigned int nTransactionsUpdated;
69 extern uint64 nLastBlockTx;
70 extern uint64 nLastBlockSize;
71 extern const std::string strMessageMagic;
72 extern double dHashesPerSec;
73 extern int64 nHPSTimerStart;
74 extern int64 nTimeBestReceived;
75 extern CCriticalSection cs_setpwalletRegistered;
76 extern std::set<CWallet*> setpwalletRegistered;
79 extern int64 nTransactionFee;
89 void RegisterWallet(CWallet* pwalletIn);
90 void UnregisterWallet(CWallet* pwalletIn);
91 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
92 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
93 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
94 FILE* AppendBlockFile(unsigned int& nFileRet);
95 bool LoadBlockIndex(bool fAllowNew=true);
96 void PrintBlockTree();
97 bool ProcessMessages(CNode* pfrom);
98 bool SendMessages(CNode* pto, bool fSendTrickle);
99 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
100 CBlock* CreateNewBlock(CReserveKey& reservekey);
101 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
102 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
103 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
104 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
105 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
106 int GetNumBlocksOfPeers();
107 bool IsInitialBlockDownload();
108 std::string GetWarnings(std::string strFor);
121 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
123 /** Position on disk for a particular transaction. */
128 unsigned int nBlockPos;
136 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
139 nBlockPos = nBlockPosIn;
143 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
144 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
145 bool IsNull() const { return (nFile == -1); }
147 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
149 return (a.nFile == b.nFile &&
150 a.nBlockPos == b.nBlockPos &&
151 a.nTxPos == b.nTxPos);
154 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
159 std::string ToString() const
164 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
169 printf("%s", ToString().c_str());
175 /** An inpoint - a combination of a transaction and an index n into its vin */
182 CInPoint() { SetNull(); }
183 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
184 void SetNull() { ptx = NULL; n = -1; }
185 bool IsNull() const { return (ptx == NULL && n == -1); }
190 /** An outpoint - a combination of a transaction hash and an index n into its vout */
197 COutPoint() { SetNull(); }
198 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
199 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
200 void SetNull() { hash = 0; n = -1; }
201 bool IsNull() const { return (hash == 0 && n == -1); }
203 friend bool operator<(const COutPoint& a, const COutPoint& b)
205 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
208 friend bool operator==(const COutPoint& a, const COutPoint& b)
210 return (a.hash == b.hash && a.n == b.n);
213 friend bool operator!=(const COutPoint& a, const COutPoint& b)
218 std::string ToString() const
220 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
225 printf("%s\n", ToString().c_str());
232 /** An input of a transaction. It contains the location of the previous
233 * transaction's output that it claims and a signature that matches the
234 * output's public key.
241 unsigned int nSequence;
245 nSequence = std::numeric_limits<unsigned int>::max();
248 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
251 scriptSig = scriptSigIn;
252 nSequence = nSequenceIn;
255 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
257 prevout = COutPoint(hashPrevTx, nOut);
258 scriptSig = scriptSigIn;
259 nSequence = nSequenceIn;
265 READWRITE(scriptSig);
266 READWRITE(nSequence);
271 return (nSequence == std::numeric_limits<unsigned int>::max());
274 friend bool operator==(const CTxIn& a, const CTxIn& b)
276 return (a.prevout == b.prevout &&
277 a.scriptSig == b.scriptSig &&
278 a.nSequence == b.nSequence);
281 friend bool operator!=(const CTxIn& a, const CTxIn& b)
286 std::string ToString() const
290 str += prevout.ToString();
291 if (prevout.IsNull())
292 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
294 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
295 if (nSequence != std::numeric_limits<unsigned int>::max())
296 str += strprintf(", nSequence=%u", nSequence);
303 printf("%s\n", ToString().c_str());
310 /** An output of a transaction. It contains the public key that the next input
311 * must be able to sign with to claim it.
317 CScript scriptPubKey;
324 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
327 scriptPubKey = scriptPubKeyIn;
333 READWRITE(scriptPubKey);
339 scriptPubKey.clear();
344 return (nValue == -1);
347 uint256 GetHash() const
349 return SerializeHash(*this);
352 friend bool operator==(const CTxOut& a, const CTxOut& b)
354 return (a.nValue == b.nValue &&
355 a.scriptPubKey == b.scriptPubKey);
358 friend bool operator!=(const CTxOut& a, const CTxOut& b)
363 std::string ToString() const
365 if (scriptPubKey.size() < 6)
366 return "CTxOut(error)";
367 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
372 printf("%s\n", ToString().c_str());
386 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
388 /** The basic transaction that is broadcasted on the network and contained in
389 * blocks. A transaction can contain multiple inputs and outputs.
395 std::vector<CTxIn> vin;
396 std::vector<CTxOut> vout;
397 unsigned int nLockTime;
399 // Denial-of-service detection:
401 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
410 READWRITE(this->nVersion);
411 nVersion = this->nVersion;
414 READWRITE(nLockTime);
423 nDoS = 0; // Denial-of-service prevention
428 return (vin.empty() && vout.empty());
431 uint256 GetHash() const
433 return SerializeHash(*this);
436 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
438 // Time based nLockTime implemented in 0.1.6
441 if (nBlockHeight == 0)
442 nBlockHeight = nBestHeight;
444 nBlockTime = GetAdjustedTime();
445 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
447 BOOST_FOREACH(const CTxIn& txin, vin)
453 bool IsNewerThan(const CTransaction& old) const
455 if (vin.size() != old.vin.size())
457 for (unsigned int i = 0; i < vin.size(); i++)
458 if (vin[i].prevout != old.vin[i].prevout)
462 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
463 for (unsigned int i = 0; i < vin.size(); i++)
465 if (vin[i].nSequence != old.vin[i].nSequence)
467 if (vin[i].nSequence <= nLowest)
470 nLowest = vin[i].nSequence;
472 if (old.vin[i].nSequence < nLowest)
475 nLowest = old.vin[i].nSequence;
482 bool IsCoinBase() const
484 return (vin.size() == 1 && vin[0].prevout.IsNull());
487 /** Check for standard transaction types
488 @return True if all outputs (scriptPubKeys) use only standard transaction forms
490 bool IsStandard() const;
492 /** Check for standard transaction types
493 @param[in] mapInputs Map of previous transactions that have outputs we're spending
494 @return True if all inputs (scriptSigs) use only standard transaction forms
495 @see CTransaction::FetchInputs
497 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
499 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
500 @return number of sigops this transaction's outputs will produce when spent
501 @see CTransaction::FetchInputs
503 int GetLegacySigOpCount() const;
505 /** Count ECDSA signature operations in pay-to-script-hash inputs.
507 @param[in] mapInputs Map of previous transactions that have outputs we're spending
508 @return maximum number of sigops required to validate this transaction's inputs
509 @see CTransaction::FetchInputs
511 int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
513 /** Amount of bitcoins spent by this transaction.
514 @return sum of all outputs (note: does not include fees)
516 int64 GetValueOut() const
519 BOOST_FOREACH(const CTxOut& txout, vout)
521 nValueOut += txout.nValue;
522 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
523 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
528 /** Amount of bitcoins coming in to this transaction
529 Note that lightweight clients may not know anything besides the hash of previous transactions,
530 so may not be able to calculate this.
532 @param[in] mapInputs Map of previous transactions that have outputs we're spending
533 @return Sum of value of all inputs (scriptSigs)
534 @see CTransaction::FetchInputs
536 int64 GetValueIn(const MapPrevTx& mapInputs) const;
538 static bool AllowFree(double dPriority)
540 // Large (in bytes) low-priority (new, small-coin) transactions
542 return dPriority > COIN * 144 / 250;
545 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
547 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
548 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
550 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
551 unsigned int nNewBlockSize = nBlockSize + nBytes;
552 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
558 // Transactions under 10K are free
559 // (about 4500bc if made of 50bc inputs)
565 // Free transaction area
566 if (nNewBlockSize < 27000)
571 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
572 if (nMinFee < nBaseFee)
574 BOOST_FOREACH(const CTxOut& txout, vout)
575 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 (unsigned int i = 0; i < vin.size(); i++)
638 str += " " + vin[i].ToString() + "\n";
639 for (unsigned 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] inputs Previous transactions (from FetchInputs)
672 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
673 @param[in] posThisTx Position 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);
688 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
689 bool AddToMemoryPoolUnchecked();
691 bool RemoveFromMemoryPool();
698 /** A transaction with a merkle branch linking it to the block chain. */
699 class CMerkleTx : public CTransaction
703 std::vector<uint256> vMerkleBranch;
707 mutable char fMerkleVerified;
715 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
724 fMerkleVerified = false;
730 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
731 nVersion = this->nVersion;
732 READWRITE(hashBlock);
733 READWRITE(vMerkleBranch);
738 int SetMerkleBranch(const CBlock* pblock=NULL);
739 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
740 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
741 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
742 int GetBlocksToMaturity() const;
743 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
744 bool AcceptToMemoryPool();
750 /** A txdb record that contains the disk location of a transaction and the
751 * locations of transactions that spend its outputs. vSpent is really only
752 * used as a flag, but having the location is very helpful for debugging.
758 std::vector<CDiskTxPos> vSpent;
765 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
768 vSpent.resize(nOutputs);
773 if (!(nType & SER_GETHASH))
790 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
792 return (a.pos == b.pos &&
793 a.vSpent == b.vSpent);
796 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
800 int GetDepthInMainChain() const;
808 /** Nodes collect new transactions into a block, hash them into a hash tree,
809 * and scan through nonce values to make the block's hash satisfy proof-of-work
810 * requirements. When they solve the proof-of-work, they broadcast the block
811 * to everyone and the block is added to the block chain. The first transaction
812 * in the block is a special one that creates a new coin owned by the creator
815 * Blocks are appended to blk0001.dat files on disk. Their location on disk
816 * is indexed by CBlockIndex objects in memory.
823 uint256 hashPrevBlock;
824 uint256 hashMerkleRoot;
830 std::vector<CTransaction> vtx;
833 mutable std::vector<uint256> vMerkleTree;
835 // Denial-of-service detection:
837 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
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();
879 uint256 GetHash() const
881 return Hash(BEGIN(nVersion), END(nNonce));
884 int64 GetBlockTime() const
889 void UpdateTime(const CBlockIndex* pindexPrev);
892 uint256 BuildMerkleTree() const
895 BOOST_FOREACH(const CTransaction& tx, vtx)
896 vMerkleTree.push_back(tx.GetHash());
898 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
900 for (int i = 0; i < nSize; i += 2)
902 int i2 = std::min(i+1, nSize-1);
903 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
904 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
908 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
911 std::vector<uint256> GetMerkleBranch(int nIndex) const
913 if (vMerkleTree.empty())
915 std::vector<uint256> vMerkleBranch;
917 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
919 int i = std::min(nIndex^1, nSize-1);
920 vMerkleBranch.push_back(vMerkleTree[j+i]);
924 return vMerkleBranch;
927 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
931 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
934 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
936 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
943 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
945 // Open history file to append
946 CAutoFile fileout = AppendBlockFile(nFileRet);
948 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
950 // Write index header
951 unsigned int nSize = fileout.GetSerializeSize(*this);
952 fileout << FLATDATA(pchMessageStart) << nSize;
955 nBlockPosRet = ftell(fileout);
956 if (nBlockPosRet == -1)
957 return error("CBlock::WriteToDisk() : ftell failed");
960 // Flush stdio buffers and commit to disk before returning
962 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
965 _commit(_fileno(fileout));
967 fsync(fileno(fileout));
974 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
978 // Open history file to read
979 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
981 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
982 if (!fReadTransactions)
983 filein.nType |= SER_BLOCKHEADERONLY;
989 if (!CheckProofOfWork(GetHash(), nBits))
990 return error("CBlock::ReadFromDisk() : errors in block header");
999 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1000 GetHash().ToString().substr(0,20).c_str(),
1002 hashPrevBlock.ToString().substr(0,20).c_str(),
1003 hashMerkleRoot.ToString().substr(0,10).c_str(),
1004 nTime, nBits, nNonce,
1006 for (unsigned int i = 0; i < vtx.size(); i++)
1011 printf(" vMerkleTree: ");
1012 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1013 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1018 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1019 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1020 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1021 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1022 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1023 bool CheckBlock() const;
1027 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1035 /** The block chain is a tree shaped structure starting with the
1036 * genesis block at the root, with each block potentially having multiple
1037 * candidates to be the next block. pprev and pnext link a path through the
1038 * main/longest chain. A blockindex may have multiple pprev pointing back
1039 * to it, but pnext will only point forward to the longest branch, or will
1040 * be null if the block is not part of the longest chain.
1045 const uint256* phashBlock;
1049 unsigned int nBlockPos;
1051 CBigNum bnChainWork;
1055 uint256 hashMerkleRoot;
1058 unsigned int nNonce;
1078 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1084 nBlockPos = nBlockPosIn;
1088 nVersion = block.nVersion;
1089 hashMerkleRoot = block.hashMerkleRoot;
1090 nTime = block.nTime;
1091 nBits = block.nBits;
1092 nNonce = block.nNonce;
1095 CBlock GetBlockHeader() const
1098 block.nVersion = nVersion;
1100 block.hashPrevBlock = pprev->GetBlockHash();
1101 block.hashMerkleRoot = hashMerkleRoot;
1102 block.nTime = nTime;
1103 block.nBits = nBits;
1104 block.nNonce = nNonce;
1108 uint256 GetBlockHash() const
1113 int64 GetBlockTime() const
1115 return (int64)nTime;
1118 CBigNum GetBlockWork() const
1121 bnTarget.SetCompact(nBits);
1124 return (CBigNum(1)<<256) / (bnTarget+1);
1127 bool IsInMainChain() const
1129 return (pnext || this == pindexBest);
1132 bool CheckIndex() const
1134 return CheckProofOfWork(GetBlockHash(), nBits);
1137 bool EraseBlockFromDisk()
1139 // Open history file
1140 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1144 // Overwrite with empty null block
1152 enum { nMedianTimeSpan=11 };
1154 int64 GetMedianTimePast() const
1156 int64 pmedian[nMedianTimeSpan];
1157 int64* pbegin = &pmedian[nMedianTimeSpan];
1158 int64* pend = &pmedian[nMedianTimeSpan];
1160 const CBlockIndex* pindex = this;
1161 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1162 *(--pbegin) = pindex->GetBlockTime();
1164 std::sort(pbegin, pend);
1165 return pbegin[(pend - pbegin)/2];
1168 int64 GetMedianTime() const
1170 const CBlockIndex* pindex = this;
1171 for (int i = 0; i < nMedianTimeSpan/2; i++)
1174 return GetBlockTime();
1175 pindex = pindex->pnext;
1177 return pindex->GetMedianTimePast();
1182 std::string ToString() const
1184 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1185 pprev, pnext, nFile, nBlockPos, nHeight,
1186 hashMerkleRoot.ToString().substr(0,10).c_str(),
1187 GetBlockHash().ToString().substr(0,20).c_str());
1192 printf("%s\n", ToString().c_str());
1198 /** Used to marshal pointers into hashes for db storage. */
1199 class CDiskBlockIndex : public CBlockIndex
1211 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1213 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1214 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1219 if (!(nType & SER_GETHASH))
1220 READWRITE(nVersion);
1222 READWRITE(hashNext);
1224 READWRITE(nBlockPos);
1228 READWRITE(this->nVersion);
1229 READWRITE(hashPrev);
1230 READWRITE(hashMerkleRoot);
1236 uint256 GetBlockHash() const
1239 block.nVersion = nVersion;
1240 block.hashPrevBlock = hashPrev;
1241 block.hashMerkleRoot = hashMerkleRoot;
1242 block.nTime = nTime;
1243 block.nBits = nBits;
1244 block.nNonce = nNonce;
1245 return block.GetHash();
1249 std::string ToString() const
1251 std::string str = "CDiskBlockIndex(";
1252 str += CBlockIndex::ToString();
1253 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1254 GetBlockHash().ToString().c_str(),
1255 hashPrev.ToString().substr(0,20).c_str(),
1256 hashNext.ToString().substr(0,20).c_str());
1262 printf("%s\n", ToString().c_str());
1273 /** Describes a place in the block chain to another node such that if the
1274 * other node doesn't have the same branch, it can find a recent common trunk.
1275 * The further back it is, the further before the fork it may be.
1280 std::vector<uint256> vHave;
1287 explicit CBlockLocator(const CBlockIndex* pindex)
1292 explicit CBlockLocator(uint256 hashBlock)
1294 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1295 if (mi != mapBlockIndex.end())
1299 CBlockLocator(const std::vector<uint256>& vHaveIn)
1306 if (!(nType & SER_GETHASH))
1307 READWRITE(nVersion);
1318 return vHave.empty();
1321 void Set(const CBlockIndex* pindex)
1327 vHave.push_back(pindex->GetBlockHash());
1329 // Exponentially larger steps back
1330 for (int i = 0; pindex && i < nStep; i++)
1331 pindex = pindex->pprev;
1332 if (vHave.size() > 10)
1335 vHave.push_back(hashGenesisBlock);
1338 int GetDistanceBack()
1340 // Retrace how far back it was in the sender's branch
1343 BOOST_FOREACH(const uint256& hash, vHave)
1345 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1346 if (mi != mapBlockIndex.end())
1348 CBlockIndex* pindex = (*mi).second;
1349 if (pindex->IsInMainChain())
1359 CBlockIndex* GetBlockIndex()
1361 // Find the first block the caller has in the main chain
1362 BOOST_FOREACH(const uint256& hash, vHave)
1364 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1365 if (mi != mapBlockIndex.end())
1367 CBlockIndex* pindex = (*mi).second;
1368 if (pindex->IsInMainChain())
1372 return pindexGenesisBlock;
1375 uint256 GetBlockHash()
1377 // Find the first block the caller has in the main chain
1378 BOOST_FOREACH(const uint256& hash, vHave)
1380 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1381 if (mi != mapBlockIndex.end())
1383 CBlockIndex* pindex = (*mi).second;
1384 if (pindex->IsInMainChain())
1388 return hashGenesisBlock;
1393 CBlockIndex* pindex = GetBlockIndex();
1396 return pindex->nHeight;
1408 /** Alerts are for notifying old versions if they become too obsolete and
1409 * need to upgrade. The message is displayed in the status bar.
1410 * Alert messages are broadcast as a vector of signed data. Unserializing may
1411 * not read the entire buffer if the alert is for a newer version, but older
1412 * versions can still relay the original data.
1414 class CUnsignedAlert
1418 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1422 std::set<int> setCancel;
1423 int nMinVer; // lowest version inclusive
1424 int nMaxVer; // highest version inclusive
1425 std::set<std::string> setSubVer; // empty matches all
1429 std::string strComment;
1430 std::string strStatusBar;
1431 std::string strReserved;
1435 READWRITE(this->nVersion);
1436 nVersion = this->nVersion;
1437 READWRITE(nRelayUntil);
1438 READWRITE(nExpiration);
1441 READWRITE(setCancel);
1444 READWRITE(setSubVer);
1445 READWRITE(nPriority);
1447 READWRITE(strComment);
1448 READWRITE(strStatusBar);
1449 READWRITE(strReserved);
1466 strStatusBar.clear();
1467 strReserved.clear();
1470 std::string ToString() const
1472 std::string strSetCancel;
1473 BOOST_FOREACH(int n, setCancel)
1474 strSetCancel += strprintf("%d ", n);
1475 std::string strSetSubVer;
1476 BOOST_FOREACH(std::string str, setSubVer)
1477 strSetSubVer += "\"" + str + "\" ";
1481 " nRelayUntil = %"PRI64d"\n"
1482 " nExpiration = %"PRI64d"\n"
1490 " strComment = \"%s\"\n"
1491 " strStatusBar = \"%s\"\n"
1498 strSetCancel.c_str(),
1501 strSetSubVer.c_str(),
1504 strStatusBar.c_str());
1509 printf("%s", ToString().c_str());
1513 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1514 class CAlert : public CUnsignedAlert
1517 std::vector<unsigned char> vchMsg;
1518 std::vector<unsigned char> vchSig;
1533 CUnsignedAlert::SetNull();
1540 return (nExpiration == 0);
1543 uint256 GetHash() const
1545 return SerializeHash(*this);
1548 bool IsInEffect() const
1550 return (GetAdjustedTime() < nExpiration);
1553 bool Cancels(const CAlert& alert) const
1556 return false; // this was a no-op before 31403
1557 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1560 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1562 // TODO: rework for client-version-embedded-in-strSubVer ?
1563 return (IsInEffect() &&
1564 nMinVer <= nVersion && nVersion <= nMaxVer &&
1565 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1568 bool AppliesToMe() const
1570 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
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();