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.
13 #include <io.h> /* for _commit */
26 class CRequestTracker;
29 static const unsigned int MAX_BLOCK_SIZE = 1000000;
30 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
31 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
32 static const int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
33 static const int64 MIN_TX_FEE = 50000;
34 static const int64 MIN_RELAY_TX_FEE = 10000;
35 static const int64 MAX_MONEY = 21000000 * COIN;
36 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
37 static const int COINBASE_MATURITY = 100;
38 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
39 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
41 static const int fHaveUPnP = true;
43 static const int fHaveUPnP = false;
47 extern CScript COINBASE_FLAGS;
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 uint64 nPooledTx;
64 extern unsigned int nTransactionsUpdated;
65 extern uint64 nLastBlockTx;
66 extern uint64 nLastBlockSize;
67 extern const std::string strMessageMagic;
68 extern double dHashesPerSec;
69 extern int64 nHPSTimerStart;
70 extern int64 nTimeBestReceived;
71 extern CCriticalSection cs_setpwalletRegistered;
72 extern std::set<CWallet*> setpwalletRegistered;
75 extern int64 nTransactionFee;
85 void RegisterWallet(CWallet* pwalletIn);
86 void UnregisterWallet(CWallet* pwalletIn);
87 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
88 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
89 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
90 FILE* AppendBlockFile(unsigned int& nFileRet);
91 bool LoadBlockIndex(bool fAllowNew=true);
92 void PrintBlockTree();
93 bool ProcessMessages(CNode* pfrom);
94 bool SendMessages(CNode* pto, bool fSendTrickle);
95 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
96 CBlock* CreateNewBlock(CReserveKey& reservekey);
97 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
98 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
99 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
100 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
101 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
102 int GetNumBlocksOfPeers();
103 bool IsInitialBlockDownload();
104 std::string GetWarnings(std::string strFor);
117 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
119 /** Position on disk for a particular transaction. */
124 unsigned int nBlockPos;
132 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
135 nBlockPos = nBlockPosIn;
139 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
140 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
141 bool IsNull() const { return (nFile == -1); }
143 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
145 return (a.nFile == b.nFile &&
146 a.nBlockPos == b.nBlockPos &&
147 a.nTxPos == b.nTxPos);
150 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
155 std::string ToString() const
160 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
165 printf("%s", ToString().c_str());
171 /** An inpoint - a combination of a transaction and an index n into its vin */
178 CInPoint() { SetNull(); }
179 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
180 void SetNull() { ptx = NULL; n = -1; }
181 bool IsNull() const { return (ptx == NULL && n == -1); }
186 /** An outpoint - a combination of a transaction hash and an index n into its vout */
193 COutPoint() { SetNull(); }
194 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
195 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
196 void SetNull() { hash = 0; n = -1; }
197 bool IsNull() const { return (hash == 0 && n == -1); }
199 friend bool operator<(const COutPoint& a, const COutPoint& b)
201 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
204 friend bool operator==(const COutPoint& a, const COutPoint& b)
206 return (a.hash == b.hash && a.n == b.n);
209 friend bool operator!=(const COutPoint& a, const COutPoint& b)
214 std::string ToString() const
216 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
221 printf("%s\n", ToString().c_str());
228 /** An input of a transaction. It contains the location of the previous
229 * transaction's output that it claims and a signature that matches the
230 * output's public key.
237 unsigned int nSequence;
241 nSequence = std::numeric_limits<unsigned int>::max();
244 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
247 scriptSig = scriptSigIn;
248 nSequence = nSequenceIn;
251 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
253 prevout = COutPoint(hashPrevTx, nOut);
254 scriptSig = scriptSigIn;
255 nSequence = nSequenceIn;
261 READWRITE(scriptSig);
262 READWRITE(nSequence);
267 return (nSequence == std::numeric_limits<unsigned int>::max());
270 friend bool operator==(const CTxIn& a, const CTxIn& b)
272 return (a.prevout == b.prevout &&
273 a.scriptSig == b.scriptSig &&
274 a.nSequence == b.nSequence);
277 friend bool operator!=(const CTxIn& a, const CTxIn& b)
282 std::string ToString() const
286 str += prevout.ToString();
287 if (prevout.IsNull())
288 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
290 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
291 if (nSequence != std::numeric_limits<unsigned int>::max())
292 str += strprintf(", nSequence=%u", nSequence);
299 printf("%s\n", ToString().c_str());
306 /** An output of a transaction. It contains the public key that the next input
307 * must be able to sign with to claim it.
313 CScript scriptPubKey;
320 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
323 scriptPubKey = scriptPubKeyIn;
329 READWRITE(scriptPubKey);
335 scriptPubKey.clear();
340 return (nValue == -1);
343 uint256 GetHash() const
345 return SerializeHash(*this);
348 friend bool operator==(const CTxOut& a, const CTxOut& b)
350 return (a.nValue == b.nValue &&
351 a.scriptPubKey == b.scriptPubKey);
354 friend bool operator!=(const CTxOut& a, const CTxOut& b)
359 std::string ToString() const
361 if (scriptPubKey.size() < 6)
362 return "CTxOut(error)";
363 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
368 printf("%s\n", ToString().c_str());
382 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
384 /** The basic transaction that is broadcasted on the network and contained in
385 * blocks. A transaction can contain multiple inputs and outputs.
391 std::vector<CTxIn> vin;
392 std::vector<CTxOut> vout;
393 unsigned int nLockTime;
395 // Denial-of-service detection:
397 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
406 READWRITE(this->nVersion);
407 nVersion = this->nVersion;
410 READWRITE(nLockTime);
419 nDoS = 0; // Denial-of-service prevention
424 return (vin.empty() && vout.empty());
427 uint256 GetHash() const
429 return SerializeHash(*this);
432 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
434 // Time based nLockTime implemented in 0.1.6
437 if (nBlockHeight == 0)
438 nBlockHeight = nBestHeight;
440 nBlockTime = GetAdjustedTime();
441 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
443 BOOST_FOREACH(const CTxIn& txin, vin)
449 bool IsNewerThan(const CTransaction& old) const
451 if (vin.size() != old.vin.size())
453 for (unsigned int i = 0; i < vin.size(); i++)
454 if (vin[i].prevout != old.vin[i].prevout)
458 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
459 for (unsigned int i = 0; i < vin.size(); i++)
461 if (vin[i].nSequence != old.vin[i].nSequence)
463 if (vin[i].nSequence <= nLowest)
466 nLowest = vin[i].nSequence;
468 if (old.vin[i].nSequence < nLowest)
471 nLowest = old.vin[i].nSequence;
478 bool IsCoinBase() const
480 return (vin.size() == 1 && vin[0].prevout.IsNull());
483 /** Check for standard transaction types
484 @return True if all outputs (scriptPubKeys) use only standard transaction forms
486 bool IsStandard() const;
488 /** Check for standard transaction types
489 @param[in] mapInputs Map of previous transactions that have outputs we're spending
490 @return True if all inputs (scriptSigs) use only standard transaction forms
491 @see CTransaction::FetchInputs
493 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
495 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
496 @return number of sigops this transaction's outputs will produce when spent
497 @see CTransaction::FetchInputs
499 int GetLegacySigOpCount() const;
501 /** Count ECDSA signature operations in pay-to-script-hash inputs.
503 @param[in] mapInputs Map of previous transactions that have outputs we're spending
504 @return maximum number of sigops required to validate this transaction's inputs
505 @see CTransaction::FetchInputs
507 int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
509 /** Amount of bitcoins spent by this transaction.
510 @return sum of all outputs (note: does not include fees)
512 int64 GetValueOut() const
515 BOOST_FOREACH(const CTxOut& txout, vout)
517 nValueOut += txout.nValue;
518 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
519 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
524 /** Amount of bitcoins coming in to this transaction
525 Note that lightweight clients may not know anything besides the hash of previous transactions,
526 so may not be able to calculate this.
528 @param[in] mapInputs Map of previous transactions that have outputs we're spending
529 @return Sum of value of all inputs (scriptSigs)
530 @see CTransaction::FetchInputs
532 int64 GetValueIn(const MapPrevTx& mapInputs) const;
534 static bool AllowFree(double dPriority)
536 // Large (in bytes) low-priority (new, small-coin) transactions
538 return dPriority > COIN * 144 / 250;
541 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
543 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
544 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
546 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
547 unsigned int nNewBlockSize = nBlockSize + nBytes;
548 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
554 // Transactions under 10K are free
555 // (about 4500bc if made of 50bc inputs)
561 // Free transaction area
562 if (nNewBlockSize < 27000)
567 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
568 if (nMinFee < nBaseFee)
570 BOOST_FOREACH(const CTxOut& txout, vout)
571 if (txout.nValue < CENT)
575 // Raise the price as the block approaches full
576 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
578 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
580 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
583 if (!MoneyRange(nMinFee))
589 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
591 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
593 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
596 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
597 return error("CTransaction::ReadFromDisk() : fseek failed");
600 // Return file pointer
603 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
604 return error("CTransaction::ReadFromDisk() : second fseek failed");
605 *pfileRet = filein.release();
610 friend bool operator==(const CTransaction& a, const CTransaction& b)
612 return (a.nVersion == b.nVersion &&
615 a.nLockTime == b.nLockTime);
618 friend bool operator!=(const CTransaction& a, const CTransaction& b)
624 std::string ToString() const
627 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
628 GetHash().ToString().substr(0,10).c_str(),
633 for (unsigned int i = 0; i < vin.size(); i++)
634 str += " " + vin[i].ToString() + "\n";
635 for (unsigned int i = 0; i < vout.size(); i++)
636 str += " " + vout[i].ToString() + "\n";
642 printf("%s", ToString().c_str());
646 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
647 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
648 bool ReadFromDisk(COutPoint prevout);
649 bool DisconnectInputs(CTxDB& txdb);
651 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
653 @param[in] txdb Transaction database
654 @param[in] mapTestPool List of pending changes to the transaction index database
655 @param[in] fBlock True if being called to add a new best-block to the chain
656 @param[in] fMiner True if being called by CreateNewBlock
657 @param[out] inputsRet Pointers to this transaction's inputs
658 @param[out] fInvalid returns true if transaction is invalid
659 @return Returns true if all inputs are in txdb or mapTestPool
661 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
662 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
664 /** Sanity check previous transactions, then, if all checks succeed,
665 mark them as spent by this transaction.
667 @param[in] inputs Previous transactions (from FetchInputs)
668 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
669 @param[in] posThisTx Position of this transaction on disk
670 @param[in] pindexBlock
671 @param[in] fBlock true if called from ConnectBlock
672 @param[in] fMiner true if called from CreateNewBlock
673 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
674 @return Returns true if all checks succeed
676 bool ConnectInputs(MapPrevTx inputs,
677 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
678 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
679 bool ClientConnectInputs();
680 bool CheckTransaction() const;
681 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
684 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
685 bool AddToMemoryPoolUnchecked();
687 bool RemoveFromMemoryPool();
694 /** A transaction with a merkle branch linking it to the block chain. */
695 class CMerkleTx : public CTransaction
699 std::vector<uint256> vMerkleBranch;
703 mutable char fMerkleVerified;
711 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
720 fMerkleVerified = false;
726 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
727 nVersion = this->nVersion;
728 READWRITE(hashBlock);
729 READWRITE(vMerkleBranch);
734 int SetMerkleBranch(const CBlock* pblock=NULL);
735 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
736 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
737 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
738 int GetBlocksToMaturity() const;
739 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
740 bool AcceptToMemoryPool();
746 /** A txdb record that contains the disk location of a transaction and the
747 * locations of transactions that spend its outputs. vSpent is really only
748 * used as a flag, but having the location is very helpful for debugging.
754 std::vector<CDiskTxPos> vSpent;
761 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
764 vSpent.resize(nOutputs);
769 if (!(nType & SER_GETHASH))
786 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
788 return (a.pos == b.pos &&
789 a.vSpent == b.vSpent);
792 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
796 int GetDepthInMainChain() const;
804 /** Nodes collect new transactions into a block, hash them into a hash tree,
805 * and scan through nonce values to make the block's hash satisfy proof-of-work
806 * requirements. When they solve the proof-of-work, they broadcast the block
807 * to everyone and the block is added to the block chain. The first transaction
808 * in the block is a special one that creates a new coin owned by the creator
811 * Blocks are appended to blk0001.dat files on disk. Their location on disk
812 * is indexed by CBlockIndex objects in memory.
819 uint256 hashPrevBlock;
820 uint256 hashMerkleRoot;
826 std::vector<CTransaction> vtx;
829 mutable std::vector<uint256> vMerkleTree;
831 // Denial-of-service detection:
833 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
842 READWRITE(this->nVersion);
843 nVersion = this->nVersion;
844 READWRITE(hashPrevBlock);
845 READWRITE(hashMerkleRoot);
850 // ConnectBlock depends on vtx being last so it can calculate offset
851 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
854 const_cast<CBlock*>(this)->vtx.clear();
875 uint256 GetHash() const
877 return Hash(BEGIN(nVersion), END(nNonce));
880 int64 GetBlockTime() const
885 void UpdateTime(const CBlockIndex* pindexPrev);
888 uint256 BuildMerkleTree() const
891 BOOST_FOREACH(const CTransaction& tx, vtx)
892 vMerkleTree.push_back(tx.GetHash());
894 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
896 for (int i = 0; i < nSize; i += 2)
898 int i2 = std::min(i+1, nSize-1);
899 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
900 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
904 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
907 std::vector<uint256> GetMerkleBranch(int nIndex) const
909 if (vMerkleTree.empty())
911 std::vector<uint256> vMerkleBranch;
913 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
915 int i = std::min(nIndex^1, nSize-1);
916 vMerkleBranch.push_back(vMerkleTree[j+i]);
920 return vMerkleBranch;
923 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
927 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
930 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
932 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
939 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
941 // Open history file to append
942 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
944 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
946 // Write index header
947 unsigned int nSize = fileout.GetSerializeSize(*this);
948 fileout << FLATDATA(pchMessageStart) << nSize;
951 nBlockPosRet = ftell(fileout);
952 if (nBlockPosRet == -1)
953 return error("CBlock::WriteToDisk() : ftell failed");
956 // Flush stdio buffers and commit to disk before returning
958 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
961 _commit(_fileno(fileout));
963 fsync(fileno(fileout));
970 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
974 // Open history file to read
975 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
977 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
978 if (!fReadTransactions)
979 filein.nType |= SER_BLOCKHEADERONLY;
985 if (!CheckProofOfWork(GetHash(), nBits))
986 return error("CBlock::ReadFromDisk() : errors in block header");
995 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
996 GetHash().ToString().substr(0,20).c_str(),
998 hashPrevBlock.ToString().substr(0,20).c_str(),
999 hashMerkleRoot.ToString().substr(0,10).c_str(),
1000 nTime, nBits, nNonce,
1002 for (unsigned int i = 0; i < vtx.size(); i++)
1007 printf(" vMerkleTree: ");
1008 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1009 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1014 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1015 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1016 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1017 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1018 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1019 bool CheckBlock() const;
1023 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1031 /** The block chain is a tree shaped structure starting with the
1032 * genesis block at the root, with each block potentially having multiple
1033 * candidates to be the next block. pprev and pnext link a path through the
1034 * main/longest chain. A blockindex may have multiple pprev pointing back
1035 * to it, but pnext will only point forward to the longest branch, or will
1036 * be null if the block is not part of the longest chain.
1041 const uint256* phashBlock;
1045 unsigned int nBlockPos;
1047 CBigNum bnChainWork;
1051 uint256 hashMerkleRoot;
1054 unsigned int nNonce;
1074 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1080 nBlockPos = nBlockPosIn;
1084 nVersion = block.nVersion;
1085 hashMerkleRoot = block.hashMerkleRoot;
1086 nTime = block.nTime;
1087 nBits = block.nBits;
1088 nNonce = block.nNonce;
1091 CBlock GetBlockHeader() const
1094 block.nVersion = nVersion;
1096 block.hashPrevBlock = pprev->GetBlockHash();
1097 block.hashMerkleRoot = hashMerkleRoot;
1098 block.nTime = nTime;
1099 block.nBits = nBits;
1100 block.nNonce = nNonce;
1104 uint256 GetBlockHash() const
1109 int64 GetBlockTime() const
1111 return (int64)nTime;
1114 CBigNum GetBlockWork() const
1117 bnTarget.SetCompact(nBits);
1120 return (CBigNum(1)<<256) / (bnTarget+1);
1123 bool IsInMainChain() const
1125 return (pnext || this == pindexBest);
1128 bool CheckIndex() const
1130 return CheckProofOfWork(GetBlockHash(), nBits);
1133 bool EraseBlockFromDisk()
1135 // Open history file
1136 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1140 // Overwrite with empty null block
1148 enum { nMedianTimeSpan=11 };
1150 int64 GetMedianTimePast() const
1152 int64 pmedian[nMedianTimeSpan];
1153 int64* pbegin = &pmedian[nMedianTimeSpan];
1154 int64* pend = &pmedian[nMedianTimeSpan];
1156 const CBlockIndex* pindex = this;
1157 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1158 *(--pbegin) = pindex->GetBlockTime();
1160 std::sort(pbegin, pend);
1161 return pbegin[(pend - pbegin)/2];
1164 int64 GetMedianTime() const
1166 const CBlockIndex* pindex = this;
1167 for (int i = 0; i < nMedianTimeSpan/2; i++)
1170 return GetBlockTime();
1171 pindex = pindex->pnext;
1173 return pindex->GetMedianTimePast();
1178 std::string ToString() const
1180 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1181 pprev, pnext, nFile, nBlockPos, nHeight,
1182 hashMerkleRoot.ToString().substr(0,10).c_str(),
1183 GetBlockHash().ToString().substr(0,20).c_str());
1188 printf("%s\n", ToString().c_str());
1194 /** Used to marshal pointers into hashes for db storage. */
1195 class CDiskBlockIndex : public CBlockIndex
1207 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1209 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1210 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1215 if (!(nType & SER_GETHASH))
1216 READWRITE(nVersion);
1218 READWRITE(hashNext);
1220 READWRITE(nBlockPos);
1224 READWRITE(this->nVersion);
1225 READWRITE(hashPrev);
1226 READWRITE(hashMerkleRoot);
1232 uint256 GetBlockHash() const
1235 block.nVersion = nVersion;
1236 block.hashPrevBlock = hashPrev;
1237 block.hashMerkleRoot = hashMerkleRoot;
1238 block.nTime = nTime;
1239 block.nBits = nBits;
1240 block.nNonce = nNonce;
1241 return block.GetHash();
1245 std::string ToString() const
1247 std::string str = "CDiskBlockIndex(";
1248 str += CBlockIndex::ToString();
1249 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1250 GetBlockHash().ToString().c_str(),
1251 hashPrev.ToString().substr(0,20).c_str(),
1252 hashNext.ToString().substr(0,20).c_str());
1258 printf("%s\n", ToString().c_str());
1269 /** Describes a place in the block chain to another node such that if the
1270 * other node doesn't have the same branch, it can find a recent common trunk.
1271 * The further back it is, the further before the fork it may be.
1276 std::vector<uint256> vHave;
1283 explicit CBlockLocator(const CBlockIndex* pindex)
1288 explicit CBlockLocator(uint256 hashBlock)
1290 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1291 if (mi != mapBlockIndex.end())
1295 CBlockLocator(const std::vector<uint256>& vHaveIn)
1302 if (!(nType & SER_GETHASH))
1303 READWRITE(nVersion);
1314 return vHave.empty();
1317 void Set(const CBlockIndex* pindex)
1323 vHave.push_back(pindex->GetBlockHash());
1325 // Exponentially larger steps back
1326 for (int i = 0; pindex && i < nStep; i++)
1327 pindex = pindex->pprev;
1328 if (vHave.size() > 10)
1331 vHave.push_back(hashGenesisBlock);
1334 int GetDistanceBack()
1336 // Retrace how far back it was in the sender's branch
1339 BOOST_FOREACH(const uint256& hash, vHave)
1341 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1342 if (mi != mapBlockIndex.end())
1344 CBlockIndex* pindex = (*mi).second;
1345 if (pindex->IsInMainChain())
1355 CBlockIndex* GetBlockIndex()
1357 // Find the first block the caller has in the main chain
1358 BOOST_FOREACH(const uint256& hash, vHave)
1360 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1361 if (mi != mapBlockIndex.end())
1363 CBlockIndex* pindex = (*mi).second;
1364 if (pindex->IsInMainChain())
1368 return pindexGenesisBlock;
1371 uint256 GetBlockHash()
1373 // Find the first block the caller has in the main chain
1374 BOOST_FOREACH(const uint256& hash, vHave)
1376 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1377 if (mi != mapBlockIndex.end())
1379 CBlockIndex* pindex = (*mi).second;
1380 if (pindex->IsInMainChain())
1384 return hashGenesisBlock;
1389 CBlockIndex* pindex = GetBlockIndex();
1392 return pindex->nHeight;
1404 /** Alerts are for notifying old versions if they become too obsolete and
1405 * need to upgrade. The message is displayed in the status bar.
1406 * Alert messages are broadcast as a vector of signed data. Unserializing may
1407 * not read the entire buffer if the alert is for a newer version, but older
1408 * versions can still relay the original data.
1410 class CUnsignedAlert
1414 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1418 std::set<int> setCancel;
1419 int nMinVer; // lowest version inclusive
1420 int nMaxVer; // highest version inclusive
1421 std::set<std::string> setSubVer; // empty matches all
1425 std::string strComment;
1426 std::string strStatusBar;
1427 std::string strReserved;
1431 READWRITE(this->nVersion);
1432 nVersion = this->nVersion;
1433 READWRITE(nRelayUntil);
1434 READWRITE(nExpiration);
1437 READWRITE(setCancel);
1440 READWRITE(setSubVer);
1441 READWRITE(nPriority);
1443 READWRITE(strComment);
1444 READWRITE(strStatusBar);
1445 READWRITE(strReserved);
1462 strStatusBar.clear();
1463 strReserved.clear();
1466 std::string ToString() const
1468 std::string strSetCancel;
1469 BOOST_FOREACH(int n, setCancel)
1470 strSetCancel += strprintf("%d ", n);
1471 std::string strSetSubVer;
1472 BOOST_FOREACH(std::string str, setSubVer)
1473 strSetSubVer += "\"" + str + "\" ";
1477 " nRelayUntil = %"PRI64d"\n"
1478 " nExpiration = %"PRI64d"\n"
1486 " strComment = \"%s\"\n"
1487 " strStatusBar = \"%s\"\n"
1494 strSetCancel.c_str(),
1497 strSetSubVer.c_str(),
1500 strStatusBar.c_str());
1505 printf("%s", ToString().c_str());
1509 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1510 class CAlert : public CUnsignedAlert
1513 std::vector<unsigned char> vchMsg;
1514 std::vector<unsigned char> vchSig;
1529 CUnsignedAlert::SetNull();
1536 return (nExpiration == 0);
1539 uint256 GetHash() const
1541 return SerializeHash(*this);
1544 bool IsInEffect() const
1546 return (GetAdjustedTime() < nExpiration);
1549 bool Cancels(const CAlert& alert) const
1552 return false; // this was a no-op before 31403
1553 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1556 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1558 // TODO: rework for client-version-embedded-in-strSubVer ?
1559 return (IsInEffect() &&
1560 nMinVer <= nVersion && nVersion <= nMaxVer &&
1561 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1564 bool AppliesToMe() const
1566 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1569 bool RelayTo(CNode* pnode) const
1573 // returns true if wasn't already contained in the set
1574 if (pnode->setKnown.insert(GetHash()).second)
1576 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1578 GetAdjustedTime() < nRelayUntil)
1580 pnode->PushMessage("alert", *this);
1587 bool CheckSignature()
1590 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1591 return error("CAlert::CheckSignature() : SetPubKey failed");
1592 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1593 return error("CAlert::CheckSignature() : verify signature failed");
1595 // Now unserialize the data
1596 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1597 sMsg >> *(CUnsignedAlert*)this;
1601 bool ProcessAlert();