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 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);
122 bool WriteSetting(const std::string& strKey, const T& value)
125 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
127 std::string strWalletFile;
128 if (!GetWalletFile(pwallet, strWalletFile))
130 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
140 unsigned int nBlockPos;
148 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
151 nBlockPos = nBlockPosIn;
155 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
156 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
157 bool IsNull() const { return (nFile == -1); }
159 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
161 return (a.nFile == b.nFile &&
162 a.nBlockPos == b.nBlockPos &&
163 a.nTxPos == b.nTxPos);
166 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
171 std::string ToString() const
174 return strprintf("null");
176 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
181 printf("%s", ToString().c_str());
194 CInPoint() { SetNull(); }
195 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
196 void SetNull() { ptx = NULL; n = -1; }
197 bool IsNull() const { return (ptx == NULL && n == -1); }
209 COutPoint() { SetNull(); }
210 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
211 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
212 void SetNull() { hash = 0; n = -1; }
213 bool IsNull() const { return (hash == 0 && n == -1); }
215 friend bool operator<(const COutPoint& a, const COutPoint& b)
217 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
220 friend bool operator==(const COutPoint& a, const COutPoint& b)
222 return (a.hash == b.hash && a.n == b.n);
225 friend bool operator!=(const COutPoint& a, const COutPoint& b)
230 std::string ToString() const
232 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
237 printf("%s\n", ToString().c_str());
245 // An input of a transaction. It contains the location of the previous
246 // transaction's output that it claims and a signature that matches the
247 // output's public key.
254 unsigned int nSequence;
258 nSequence = UINT_MAX;
261 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
264 scriptSig = scriptSigIn;
265 nSequence = nSequenceIn;
268 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
270 prevout = COutPoint(hashPrevTx, nOut);
271 scriptSig = scriptSigIn;
272 nSequence = nSequenceIn;
278 READWRITE(scriptSig);
279 READWRITE(nSequence);
284 return (nSequence == UINT_MAX);
287 friend bool operator==(const CTxIn& a, const CTxIn& b)
289 return (a.prevout == b.prevout &&
290 a.scriptSig == b.scriptSig &&
291 a.nSequence == b.nSequence);
294 friend bool operator!=(const CTxIn& a, const CTxIn& b)
299 std::string ToString() const
302 str += strprintf("CTxIn(");
303 str += prevout.ToString();
304 if (prevout.IsNull())
305 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
307 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
308 if (nSequence != UINT_MAX)
309 str += strprintf(", nSequence=%u", nSequence);
316 printf("%s\n", ToString().c_str());
324 // An output of a transaction. It contains the public key that the next input
325 // must be able to sign with to claim it.
331 CScript scriptPubKey;
338 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
341 scriptPubKey = scriptPubKeyIn;
347 READWRITE(scriptPubKey);
353 scriptPubKey.clear();
358 return (nValue == -1);
361 uint256 GetHash() const
363 return SerializeHash(*this);
366 friend bool operator==(const CTxOut& a, const CTxOut& b)
368 return (a.nValue == b.nValue &&
369 a.scriptPubKey == b.scriptPubKey);
372 friend bool operator!=(const CTxOut& a, const CTxOut& b)
377 std::string ToString() const
379 if (scriptPubKey.size() < 6)
380 return "CTxOut(error)";
381 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
386 printf("%s\n", ToString().c_str());
391 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
395 // The basic transaction that is broadcasted on the network and contained in
396 // blocks. A transaction can contain multiple inputs and outputs.
402 std::vector<CTxIn> vin;
403 std::vector<CTxOut> vout;
404 unsigned int nLockTime;
406 // Denial-of-service detection:
408 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
417 READWRITE(this->nVersion);
418 nVersion = this->nVersion;
421 READWRITE(nLockTime);
430 nDoS = 0; // Denial-of-service prevention
435 return (vin.empty() && vout.empty());
438 uint256 GetHash() const
440 return SerializeHash(*this);
443 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
445 // Time based nLockTime implemented in 0.1.6
448 if (nBlockHeight == 0)
449 nBlockHeight = nBestHeight;
451 nBlockTime = GetAdjustedTime();
452 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
454 BOOST_FOREACH(const CTxIn& txin, vin)
460 bool IsNewerThan(const CTransaction& old) const
462 if (vin.size() != old.vin.size())
464 for (int i = 0; i < vin.size(); i++)
465 if (vin[i].prevout != old.vin[i].prevout)
469 unsigned int nLowest = UINT_MAX;
470 for (int i = 0; i < vin.size(); i++)
472 if (vin[i].nSequence != old.vin[i].nSequence)
474 if (vin[i].nSequence <= nLowest)
477 nLowest = vin[i].nSequence;
479 if (old.vin[i].nSequence < nLowest)
482 nLowest = old.vin[i].nSequence;
489 bool IsCoinBase() const
491 return (vin.size() == 1 && vin[0].prevout.IsNull());
494 int GetSigOpCount() const
497 BOOST_FOREACH(const CTxIn& txin, vin)
498 n += txin.scriptSig.GetSigOpCount();
499 BOOST_FOREACH(const CTxOut& txout, vout)
500 n += txout.scriptPubKey.GetSigOpCount();
504 /** Count ECDSA signature operations in pay-to-script-hash inputs.
505 This is a better measure of how expensive it is to process this transaction.
507 @param[in] mapInputsMap 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 bool IsStandard() const
515 BOOST_FOREACH(const CTxIn& txin, vin)
516 if (!txin.scriptSig.IsPushOnly())
517 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
518 BOOST_FOREACH(const CTxOut& txout, vout)
519 if (!::IsStandard(txout.scriptPubKey))
520 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
524 int64 GetValueOut() const
527 BOOST_FOREACH(const CTxOut& txout, vout)
529 nValueOut += txout.nValue;
530 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
531 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
536 /** Amount of bitcoins coming in to this transaction
537 Note that lightweight clients may not know anything besides the hash of previous transactions,
538 so may not be able to calculate this.
540 @param[in] mapInputsMap of previous transactions that have outputs we're spending
541 @returnSum of value of all inputs (scriptSigs)
542 @see CTransaction::FetchInputs
544 int64 GetValueIn(const MapPrevTx& mapInputs) const;
546 static bool AllowFree(double dPriority)
548 // Large (in bytes) low-priority (new, small-coin) transactions
550 return dPriority > COIN * 144 / 250;
553 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
555 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
556 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
558 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
559 unsigned int nNewBlockSize = nBlockSize + nBytes;
560 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
566 // Transactions under 10K are free
567 // (about 4500bc if made of 50bc inputs)
573 // Free transaction area
574 if (nNewBlockSize < 27000)
579 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
580 if (nMinFee < nBaseFee)
581 BOOST_FOREACH(const CTxOut& txout, vout)
582 if (txout.nValue < CENT)
585 // Raise the price as the block approaches full
586 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
588 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
590 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
593 if (!MoneyRange(nMinFee))
599 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
601 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
603 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
606 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
607 return error("CTransaction::ReadFromDisk() : fseek failed");
610 // Return file pointer
613 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
614 return error("CTransaction::ReadFromDisk() : second fseek failed");
615 *pfileRet = filein.release();
620 friend bool operator==(const CTransaction& a, const CTransaction& b)
622 return (a.nVersion == b.nVersion &&
625 a.nLockTime == b.nLockTime);
628 friend bool operator!=(const CTransaction& a, const CTransaction& b)
634 std::string ToString() const
637 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
638 GetHash().ToString().substr(0,10).c_str(),
643 for (int i = 0; i < vin.size(); i++)
644 str += " " + vin[i].ToString() + "\n";
645 for (int i = 0; i < vout.size(); i++)
646 str += " " + vout[i].ToString() + "\n";
652 printf("%s", ToString().c_str());
656 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
657 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
658 bool ReadFromDisk(COutPoint prevout);
659 bool DisconnectInputs(CTxDB& txdb);
661 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
663 @param[in] txdb Transaction database
664 @param[in] mapTestPool List of pending changes to the transaction index database
665 @param[in] fBlock True if being called to add a new best-block to the chain
666 @param[in] fMiner True if being called by CreateNewBlock
667 @param[out] inputsRet Pointers to this transaction's inputs
668 @param[out] fInvalid returns true if transaction is invalid
669 @return Returns true if all inputs are in txdb or mapTestPool
671 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
672 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
674 /** Sanity check previous transactions, then, if all checks succeed,
675 mark them as spent by this transaction.
677 @param[in] inputsPrevious transactions (from FetchInputs)
678 @param[out] mapTestPoolKeeps track of inputs that need to be updated on disk
679 @param[in] posThisTxPosition of this transaction on disk
680 @param[in] pindexBlock
681 @param[in] fBlock true if called from ConnectBlock
682 @param[in] fMiner true if called from CreateNewBlock
683 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
684 @return Returns true if all checks succeed
686 bool ConnectInputs(MapPrevTx inputs,
687 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
688 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
689 bool ClientConnectInputs();
690 bool CheckTransaction() const;
691 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
692 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
694 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
695 bool AddToMemoryPoolUnchecked();
697 bool RemoveFromMemoryPool();
705 // A transaction with a merkle branch linking it to the block chain
707 class CMerkleTx : public CTransaction
711 std::vector<uint256> vMerkleBranch;
715 mutable char fMerkleVerified;
723 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
732 fMerkleVerified = false;
738 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
739 nVersion = this->nVersion;
740 READWRITE(hashBlock);
741 READWRITE(vMerkleBranch);
746 int SetMerkleBranch(const CBlock* pblock=NULL);
747 int GetDepthInMainChain(int& nHeightRet) const;
748 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
749 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
750 int GetBlocksToMaturity() const;
751 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
752 bool AcceptToMemoryPool();
759 // A txdb record that contains the disk location of a transaction and the
760 // locations of transactions that spend its outputs. vSpent is really only
761 // used as a flag, but having the location is very helpful for debugging.
767 std::vector<CDiskTxPos> vSpent;
774 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
777 vSpent.resize(nOutputs);
782 if (!(nType & SER_GETHASH))
799 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
801 return (a.pos == b.pos &&
802 a.vSpent == b.vSpent);
805 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
809 int GetDepthInMainChain() const;
817 // Nodes collect new transactions into a block, hash them into a hash tree,
818 // and scan through nonce values to make the block's hash satisfy proof-of-work
819 // requirements. When they solve the proof-of-work, they broadcast the block
820 // to everyone and the block is added to the block chain. The first transaction
821 // in the block is a special one that creates a new coin owned by the creator
824 // Blocks are appended to blk0001.dat files on disk. Their location on disk
825 // is indexed by CBlockIndex objects in memory.
832 uint256 hashPrevBlock;
833 uint256 hashMerkleRoot;
839 std::vector<CTransaction> vtx;
842 mutable std::vector<uint256> vMerkleTree;
844 // Denial-of-service detection:
846 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
855 READWRITE(this->nVersion);
856 nVersion = this->nVersion;
857 READWRITE(hashPrevBlock);
858 READWRITE(hashMerkleRoot);
863 // ConnectBlock depends on vtx being last so it can calculate offset
864 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
867 const_cast<CBlock*>(this)->vtx.clear();
888 uint256 GetHash() const
890 return Hash(BEGIN(nVersion), END(nNonce));
893 int64 GetBlockTime() const
898 int GetSigOpCount() const
901 BOOST_FOREACH(const CTransaction& tx, vtx)
902 n += tx.GetSigOpCount();
906 void UpdateTime(const CBlockIndex* pindexPrev);
909 uint256 BuildMerkleTree() const
912 BOOST_FOREACH(const CTransaction& tx, vtx)
913 vMerkleTree.push_back(tx.GetHash());
915 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
917 for (int i = 0; i < nSize; i += 2)
919 int i2 = std::min(i+1, nSize-1);
920 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
921 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
925 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
928 std::vector<uint256> GetMerkleBranch(int nIndex) const
930 if (vMerkleTree.empty())
932 std::vector<uint256> vMerkleBranch;
934 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
936 int i = std::min(nIndex^1, nSize-1);
937 vMerkleBranch.push_back(vMerkleTree[j+i]);
941 return vMerkleBranch;
944 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
948 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
951 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
953 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
960 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
962 // Open history file to append
963 CAutoFile fileout = AppendBlockFile(nFileRet);
965 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
967 // Write index header
968 unsigned int nSize = fileout.GetSerializeSize(*this);
969 fileout << FLATDATA(pchMessageStart) << nSize;
972 nBlockPosRet = ftell(fileout);
973 if (nBlockPosRet == -1)
974 return error("CBlock::WriteToDisk() : ftell failed");
977 // Flush stdio buffers and commit to disk before returning
979 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
982 _commit(_fileno(fileout));
984 fsync(fileno(fileout));
991 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
995 // Open history file to read
996 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
998 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
999 if (!fReadTransactions)
1000 filein.nType |= SER_BLOCKHEADERONLY;
1006 if (!CheckProofOfWork(GetHash(), nBits))
1007 return error("CBlock::ReadFromDisk() : errors in block header");
1016 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1017 GetHash().ToString().substr(0,20).c_str(),
1019 hashPrevBlock.ToString().substr(0,20).c_str(),
1020 hashMerkleRoot.ToString().substr(0,10).c_str(),
1021 nTime, nBits, nNonce,
1023 for (int i = 0; i < vtx.size(); i++)
1028 printf(" vMerkleTree: ");
1029 for (int i = 0; i < vMerkleTree.size(); i++)
1030 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1035 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1036 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1037 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1038 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1039 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1040 bool CheckBlock() const;
1050 // The block chain is a tree shaped structure starting with the
1051 // genesis block at the root, with each block potentially having multiple
1052 // candidates to be the next block. pprev and pnext link a path through the
1053 // main/longest chain. A blockindex may have multiple pprev pointing back
1054 // to it, but pnext will only point forward to the longest branch, or will
1055 // be null if the block is not part of the longest chain.
1060 const uint256* phashBlock;
1064 unsigned int nBlockPos;
1066 CBigNum bnChainWork;
1070 uint256 hashMerkleRoot;
1073 unsigned int nNonce;
1093 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1099 nBlockPos = nBlockPosIn;
1103 nVersion = block.nVersion;
1104 hashMerkleRoot = block.hashMerkleRoot;
1105 nTime = block.nTime;
1106 nBits = block.nBits;
1107 nNonce = block.nNonce;
1110 CBlock GetBlockHeader() const
1113 block.nVersion = nVersion;
1115 block.hashPrevBlock = pprev->GetBlockHash();
1116 block.hashMerkleRoot = hashMerkleRoot;
1117 block.nTime = nTime;
1118 block.nBits = nBits;
1119 block.nNonce = nNonce;
1123 uint256 GetBlockHash() const
1128 int64 GetBlockTime() const
1130 return (int64)nTime;
1133 CBigNum GetBlockWork() const
1136 bnTarget.SetCompact(nBits);
1139 return (CBigNum(1)<<256) / (bnTarget+1);
1142 bool IsInMainChain() const
1144 return (pnext || this == pindexBest);
1147 bool CheckIndex() const
1149 return CheckProofOfWork(GetBlockHash(), nBits);
1152 bool EraseBlockFromDisk()
1154 // Open history file
1155 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1159 // Overwrite with empty null block
1167 enum { nMedianTimeSpan=11 };
1169 int64 GetMedianTimePast() const
1171 int64 pmedian[nMedianTimeSpan];
1172 int64* pbegin = &pmedian[nMedianTimeSpan];
1173 int64* pend = &pmedian[nMedianTimeSpan];
1175 const CBlockIndex* pindex = this;
1176 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1177 *(--pbegin) = pindex->GetBlockTime();
1179 std::sort(pbegin, pend);
1180 return pbegin[(pend - pbegin)/2];
1183 int64 GetMedianTime() const
1185 const CBlockIndex* pindex = this;
1186 for (int i = 0; i < nMedianTimeSpan/2; i++)
1189 return GetBlockTime();
1190 pindex = pindex->pnext;
1192 return pindex->GetMedianTimePast();
1197 std::string ToString() const
1199 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1200 pprev, pnext, nFile, nBlockPos, nHeight,
1201 hashMerkleRoot.ToString().substr(0,10).c_str(),
1202 GetBlockHash().ToString().substr(0,20).c_str());
1207 printf("%s\n", ToString().c_str());
1214 // Used to marshal pointers into hashes for db storage.
1216 class CDiskBlockIndex : public CBlockIndex
1228 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1230 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1231 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1236 if (!(nType & SER_GETHASH))
1237 READWRITE(nVersion);
1239 READWRITE(hashNext);
1241 READWRITE(nBlockPos);
1245 READWRITE(this->nVersion);
1246 READWRITE(hashPrev);
1247 READWRITE(hashMerkleRoot);
1253 uint256 GetBlockHash() const
1256 block.nVersion = nVersion;
1257 block.hashPrevBlock = hashPrev;
1258 block.hashMerkleRoot = hashMerkleRoot;
1259 block.nTime = nTime;
1260 block.nBits = nBits;
1261 block.nNonce = nNonce;
1262 return block.GetHash();
1266 std::string ToString() const
1268 std::string str = "CDiskBlockIndex(";
1269 str += CBlockIndex::ToString();
1270 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1271 GetBlockHash().ToString().c_str(),
1272 hashPrev.ToString().substr(0,20).c_str(),
1273 hashNext.ToString().substr(0,20).c_str());
1279 printf("%s\n", ToString().c_str());
1291 // Describes a place in the block chain to another node such that if the
1292 // other node doesn't have the same branch, it can find a recent common trunk.
1293 // The further back it is, the further before the fork it may be.
1298 std::vector<uint256> vHave;
1305 explicit CBlockLocator(const CBlockIndex* pindex)
1310 explicit CBlockLocator(uint256 hashBlock)
1312 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1313 if (mi != mapBlockIndex.end())
1319 if (!(nType & SER_GETHASH))
1320 READWRITE(nVersion);
1331 return vHave.empty();
1334 void Set(const CBlockIndex* pindex)
1340 vHave.push_back(pindex->GetBlockHash());
1342 // Exponentially larger steps back
1343 for (int i = 0; pindex && i < nStep; i++)
1344 pindex = pindex->pprev;
1345 if (vHave.size() > 10)
1348 vHave.push_back(hashGenesisBlock);
1351 int GetDistanceBack()
1353 // Retrace how far back it was in the sender's branch
1356 BOOST_FOREACH(const uint256& hash, vHave)
1358 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1359 if (mi != mapBlockIndex.end())
1361 CBlockIndex* pindex = (*mi).second;
1362 if (pindex->IsInMainChain())
1372 CBlockIndex* GetBlockIndex()
1374 // Find the first block the caller has in the main chain
1375 BOOST_FOREACH(const uint256& hash, vHave)
1377 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1378 if (mi != mapBlockIndex.end())
1380 CBlockIndex* pindex = (*mi).second;
1381 if (pindex->IsInMainChain())
1385 return pindexGenesisBlock;
1388 uint256 GetBlockHash()
1390 // Find the first block the caller has in the main chain
1391 BOOST_FOREACH(const uint256& hash, vHave)
1393 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1394 if (mi != mapBlockIndex.end())
1396 CBlockIndex* pindex = (*mi).second;
1397 if (pindex->IsInMainChain())
1401 return hashGenesisBlock;
1406 CBlockIndex* pindex = GetBlockIndex();
1409 return pindex->nHeight;
1422 // Alerts are for notifying old versions if they become too obsolete and
1423 // need to upgrade. The message is displayed in the status bar.
1424 // Alert messages are broadcast as a vector of signed data. Unserializing may
1425 // not read the entire buffer if the alert is for a newer version, but older
1426 // versions can still relay the original data.
1428 class CUnsignedAlert
1432 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1436 std::set<int> setCancel;
1437 int nMinVer; // lowest version inclusive
1438 int nMaxVer; // highest version inclusive
1439 std::set<std::string> setSubVer; // empty matches all
1443 std::string strComment;
1444 std::string strStatusBar;
1445 std::string strReserved;
1449 READWRITE(this->nVersion);
1450 nVersion = this->nVersion;
1451 READWRITE(nRelayUntil);
1452 READWRITE(nExpiration);
1455 READWRITE(setCancel);
1458 READWRITE(setSubVer);
1459 READWRITE(nPriority);
1461 READWRITE(strComment);
1462 READWRITE(strStatusBar);
1463 READWRITE(strReserved);
1480 strStatusBar.clear();
1481 strReserved.clear();
1484 std::string ToString() const
1486 std::string strSetCancel;
1487 BOOST_FOREACH(int n, setCancel)
1488 strSetCancel += strprintf("%d ", n);
1489 std::string strSetSubVer;
1490 BOOST_FOREACH(std::string str, setSubVer)
1491 strSetSubVer += "\"" + str + "\" ";
1495 " nRelayUntil = %"PRI64d"\n"
1496 " nExpiration = %"PRI64d"\n"
1504 " strComment = \"%s\"\n"
1505 " strStatusBar = \"%s\"\n"
1512 strSetCancel.c_str(),
1515 strSetSubVer.c_str(),
1518 strStatusBar.c_str());
1523 printf("%s", ToString().c_str());
1527 class CAlert : public CUnsignedAlert
1530 std::vector<unsigned char> vchMsg;
1531 std::vector<unsigned char> vchSig;
1546 CUnsignedAlert::SetNull();
1553 return (nExpiration == 0);
1556 uint256 GetHash() const
1558 return SerializeHash(*this);
1561 bool IsInEffect() const
1563 return (GetAdjustedTime() < nExpiration);
1566 bool Cancels(const CAlert& alert) const
1569 return false; // this was a no-op before 31403
1570 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1573 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1575 return (IsInEffect() &&
1576 nMinVer <= nVersion && nVersion <= nMaxVer &&
1577 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1580 bool AppliesToMe() const
1582 return AppliesTo(VERSION, ::pszSubVer);
1585 bool RelayTo(CNode* pnode) const
1589 // returns true if wasn't already contained in the set
1590 if (pnode->setKnown.insert(GetHash()).second)
1592 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1594 GetAdjustedTime() < nRelayUntil)
1596 pnode->PushMessage("alert", *this);
1603 bool CheckSignature()
1606 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1607 return error("CAlert::CheckSignature() : SetPubKey failed");
1608 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1609 return error("CAlert::CheckSignature() : verify signature failed");
1611 // Now unserialize the data
1612 CDataStream sMsg(vchMsg);
1613 sMsg >> *(CUnsignedAlert*)this;
1617 bool ProcessAlert();