1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 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;
29 static const int CLIENT_VERSION = 59900;
30 static const bool VERSION_IS_BETA = true;
31 extern const std::string CLIENT_NAME;
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 int64 COIN = 100000000;
37 static const int64 CENT = 1000000;
38 static const int64 MIN_TX_FEE = 50000;
39 static const int64 MIN_RELAY_TX_FEE = 10000;
40 static const int64 MAX_MONEY = 21000000 * COIN;
41 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
42 static const int COINBASE_MATURITY = 100;
43 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
44 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
46 static const int fHaveUPnP = true;
48 static const int fHaveUPnP = false;
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 double dHashesPerSec;
70 extern int64 nHPSTimerStart;
71 extern int64 nTimeBestReceived;
72 extern CCriticalSection cs_setpwalletRegistered;
73 extern std::set<CWallet*> setpwalletRegistered;
76 extern int fGenerateBitcoins;
77 extern int64 nTransactionFee;
78 extern int fLimitProcessors;
79 extern int nLimitProcessors;
80 extern int fMinimizeToTray;
81 extern int fMinimizeOnClose;
92 void RegisterWallet(CWallet* pwalletIn);
93 void UnregisterWallet(CWallet* pwalletIn);
94 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
95 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
96 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
97 FILE* AppendBlockFile(unsigned int& nFileRet);
98 bool LoadBlockIndex(bool fAllowNew=true);
99 void PrintBlockTree();
100 bool ProcessMessages(CNode* pfrom);
101 bool SendMessages(CNode* pto, bool fSendTrickle);
102 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
103 CBlock* CreateNewBlock(CReserveKey& reservekey);
104 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
105 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
106 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
107 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
108 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
109 int GetNumBlocksOfPeers();
110 bool IsInitialBlockDownload();
111 std::string GetWarnings(std::string strFor);
124 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
127 bool WriteSetting(const std::string& strKey, const T& value)
130 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
132 std::string strWalletFile;
133 if (!GetWalletFile(pwallet, strWalletFile))
135 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
145 unsigned int nBlockPos;
153 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
156 nBlockPos = nBlockPosIn;
160 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
161 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
162 bool IsNull() const { return (nFile == -1); }
164 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
166 return (a.nFile == b.nFile &&
167 a.nBlockPos == b.nBlockPos &&
168 a.nTxPos == b.nTxPos);
171 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
176 std::string ToString() const
179 return strprintf("null");
181 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
186 printf("%s", ToString().c_str());
199 CInPoint() { SetNull(); }
200 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
201 void SetNull() { ptx = NULL; n = -1; }
202 bool IsNull() const { return (ptx == NULL && n == -1); }
214 COutPoint() { SetNull(); }
215 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
216 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
217 void SetNull() { hash = 0; n = -1; }
218 bool IsNull() const { return (hash == 0 && n == -1); }
220 friend bool operator<(const COutPoint& a, const COutPoint& b)
222 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
225 friend bool operator==(const COutPoint& a, const COutPoint& b)
227 return (a.hash == b.hash && a.n == b.n);
230 friend bool operator!=(const COutPoint& a, const COutPoint& b)
235 std::string ToString() const
237 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
242 printf("%s\n", ToString().c_str());
250 // An input of a transaction. It contains the location of the previous
251 // transaction's output that it claims and a signature that matches the
252 // output's public key.
259 unsigned int nSequence;
263 nSequence = std::numeric_limits<unsigned int>::max();
266 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
269 scriptSig = scriptSigIn;
270 nSequence = nSequenceIn;
273 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
275 prevout = COutPoint(hashPrevTx, nOut);
276 scriptSig = scriptSigIn;
277 nSequence = nSequenceIn;
283 READWRITE(scriptSig);
284 READWRITE(nSequence);
289 return (nSequence == std::numeric_limits<unsigned int>::max());
292 friend bool operator==(const CTxIn& a, const CTxIn& b)
294 return (a.prevout == b.prevout &&
295 a.scriptSig == b.scriptSig &&
296 a.nSequence == b.nSequence);
299 friend bool operator!=(const CTxIn& a, const CTxIn& b)
304 std::string ToString() const
307 str += strprintf("CTxIn(");
308 str += prevout.ToString();
309 if (prevout.IsNull())
310 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
312 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
313 if (nSequence != std::numeric_limits<unsigned int>::max())
314 str += strprintf(", nSequence=%u", nSequence);
321 printf("%s\n", ToString().c_str());
329 // An output of a transaction. It contains the public key that the next input
330 // must be able to sign with to claim it.
336 CScript scriptPubKey;
343 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
346 scriptPubKey = scriptPubKeyIn;
352 READWRITE(scriptPubKey);
358 scriptPubKey.clear();
363 return (nValue == -1);
366 uint256 GetHash() const
368 return SerializeHash(*this);
371 friend bool operator==(const CTxOut& a, const CTxOut& b)
373 return (a.nValue == b.nValue &&
374 a.scriptPubKey == b.scriptPubKey);
377 friend bool operator!=(const CTxOut& a, const CTxOut& b)
382 std::string ToString() const
384 if (scriptPubKey.size() < 6)
385 return "CTxOut(error)";
386 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
391 printf("%s\n", ToString().c_str());
405 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
408 // The basic transaction that is broadcasted on the network and contained in
409 // blocks. A transaction can contain multiple inputs and outputs.
415 std::vector<CTxIn> vin;
416 std::vector<CTxOut> vout;
417 unsigned int nLockTime;
419 // Denial-of-service detection:
421 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
430 READWRITE(this->nVersion);
431 nVersion = this->nVersion;
434 READWRITE(nLockTime);
443 nDoS = 0; // Denial-of-service prevention
448 return (vin.empty() && vout.empty());
451 uint256 GetHash() const
453 return SerializeHash(*this);
456 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
458 // Time based nLockTime implemented in 0.1.6
461 if (nBlockHeight == 0)
462 nBlockHeight = nBestHeight;
464 nBlockTime = GetAdjustedTime();
465 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
467 BOOST_FOREACH(const CTxIn& txin, vin)
473 bool IsNewerThan(const CTransaction& old) const
475 if (vin.size() != old.vin.size())
477 for (int i = 0; i < vin.size(); i++)
478 if (vin[i].prevout != old.vin[i].prevout)
482 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
483 for (int i = 0; i < vin.size(); i++)
485 if (vin[i].nSequence != old.vin[i].nSequence)
487 if (vin[i].nSequence <= nLowest)
490 nLowest = vin[i].nSequence;
492 if (old.vin[i].nSequence < nLowest)
495 nLowest = old.vin[i].nSequence;
502 bool IsCoinBase() const
504 return (vin.size() == 1 && vin[0].prevout.IsNull());
507 /** Check for standard transaction types
508 @return True if all outputs (scriptPubKeys) use only standard transaction forms
510 bool IsStandard() const;
512 /** Check for standard transaction types
513 @param[in] mapInputs Map of previous transactions that have outputs we're spending
514 @return True if all inputs (scriptSigs) use only standard transaction forms
515 @see CTransaction::FetchInputs
517 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
519 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
520 @return number of sigops this transaction's outputs will produce when spent
521 @see CTransaction::FetchInputs
523 int GetLegacySigOpCount() const;
525 /** Count ECDSA signature operations the new (0.6-and-later) way
526 This is a better measure of how expensive it is to process this transaction.
528 @param[in] mapInputs Map of previous transactions that have outputs we're spending
529 @return maximum number of sigops required to validate this transaction's inputs
530 @see CTransaction::FetchInputs
532 int GetSigOpCount(const MapPrevTx& mapInputs) const;
534 /** Amount of bitcoins spent by this transaction.
535 @return sum of all outputs (note: does not include fees)
537 int64 GetValueOut() const
540 BOOST_FOREACH(const CTxOut& txout, vout)
542 nValueOut += txout.nValue;
543 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
544 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
549 /** Amount of bitcoins coming in to this transaction
550 Note that lightweight clients may not know anything besides the hash of previous transactions,
551 so may not be able to calculate this.
553 @param[in] mapInputs Map of previous transactions that have outputs we're spending
554 @return Sum of value of all inputs (scriptSigs)
555 @see CTransaction::FetchInputs
557 int64 GetValueIn(const MapPrevTx& mapInputs) const;
559 static bool AllowFree(double dPriority)
561 // Large (in bytes) low-priority (new, small-coin) transactions
563 return dPriority > COIN * 144 / 250;
566 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
568 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
569 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
571 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
572 unsigned int nNewBlockSize = nBlockSize + nBytes;
573 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
579 // Transactions under 10K are free
580 // (about 4500bc if made of 50bc inputs)
586 // Free transaction area
587 if (nNewBlockSize < 27000)
592 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
593 if (nMinFee < nBaseFee)
594 BOOST_FOREACH(const CTxOut& txout, vout)
595 if (txout.nValue < CENT)
598 // Raise the price as the block approaches full
599 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
601 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
603 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
606 if (!MoneyRange(nMinFee))
612 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
614 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
616 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
619 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
620 return error("CTransaction::ReadFromDisk() : fseek failed");
623 // Return file pointer
626 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
627 return error("CTransaction::ReadFromDisk() : second fseek failed");
628 *pfileRet = filein.release();
633 friend bool operator==(const CTransaction& a, const CTransaction& b)
635 return (a.nVersion == b.nVersion &&
638 a.nLockTime == b.nLockTime);
641 friend bool operator!=(const CTransaction& a, const CTransaction& b)
647 std::string ToString() const
650 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
651 GetHash().ToString().substr(0,10).c_str(),
656 for (int i = 0; i < vin.size(); i++)
657 str += " " + vin[i].ToString() + "\n";
658 for (int i = 0; i < vout.size(); i++)
659 str += " " + vout[i].ToString() + "\n";
665 printf("%s", ToString().c_str());
669 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
670 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
671 bool ReadFromDisk(COutPoint prevout);
672 bool DisconnectInputs(CTxDB& txdb);
674 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
676 @param[in] txdb Transaction database
677 @param[in] mapTestPool List of pending changes to the transaction index database
678 @param[in] fBlock True if being called to add a new best-block to the chain
679 @param[in] fMiner True if being called by CreateNewBlock
680 @param[out] inputsRet Pointers to this transaction's inputs
681 @return Returns true if all inputs are in txdb or mapTestPool
683 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
684 bool fBlock, bool fMiner, MapPrevTx& inputsRet);
686 /** Sanity check previous transactions, then, if all checks succeed,
687 mark them as spent by this transaction.
689 @param[in] inputs Previous transactions (from FetchInputs)
690 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
691 @param[in] posThisTx Position of this transaction on disk
692 @param[in] pindexBlock
693 @param[in] fBlock true if called from ConnectBlock
694 @param[in] fMiner true if called from CreateNewBlock
695 @return Returns true if all checks succeed
697 bool ConnectInputs(MapPrevTx inputs,
698 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
699 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner);
700 bool ClientConnectInputs();
701 bool CheckTransaction() const;
702 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
703 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
706 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
707 bool AddToMemoryPoolUnchecked();
709 bool RemoveFromMemoryPool();
717 // A transaction with a merkle branch linking it to the block chain
719 class CMerkleTx : public CTransaction
723 std::vector<uint256> vMerkleBranch;
727 mutable char fMerkleVerified;
735 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
744 fMerkleVerified = false;
750 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
751 nVersion = this->nVersion;
752 READWRITE(hashBlock);
753 READWRITE(vMerkleBranch);
758 int SetMerkleBranch(const CBlock* pblock=NULL);
759 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
760 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
761 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
762 int GetBlocksToMaturity() const;
763 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
764 bool AcceptToMemoryPool();
771 // A txdb record that contains the disk location of a transaction and the
772 // locations of transactions that spend its outputs. vSpent is really only
773 // used as a flag, but having the location is very helpful for debugging.
779 std::vector<CDiskTxPos> vSpent;
786 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
789 vSpent.resize(nOutputs);
794 if (!(nType & SER_GETHASH))
811 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
813 return (a.pos == b.pos &&
814 a.vSpent == b.vSpent);
817 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
821 int GetDepthInMainChain() const;
830 // Nodes collect new transactions into a block, hash them into a hash tree,
831 // and scan through nonce values to make the block's hash satisfy proof-of-work
832 // requirements. When they solve the proof-of-work, they broadcast the block
833 // to everyone and the block is added to the block chain. The first transaction
834 // in the block is a special one that creates a new coin owned by the creator
837 // Blocks are appended to blk0001.dat files on disk. Their location on disk
838 // is indexed by CBlockIndex objects in memory.
845 uint256 hashPrevBlock;
846 uint256 hashMerkleRoot;
852 std::vector<CTransaction> vtx;
855 mutable std::vector<uint256> vMerkleTree;
857 // Denial-of-service detection:
859 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
868 READWRITE(this->nVersion);
869 nVersion = this->nVersion;
870 READWRITE(hashPrevBlock);
871 READWRITE(hashMerkleRoot);
876 // ConnectBlock depends on vtx being last so it can calculate offset
877 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
880 const_cast<CBlock*>(this)->vtx.clear();
901 uint256 GetHash() const
903 return Hash(BEGIN(nVersion), END(nNonce));
906 int64 GetBlockTime() const
913 uint256 BuildMerkleTree() const
916 BOOST_FOREACH(const CTransaction& tx, vtx)
917 vMerkleTree.push_back(tx.GetHash());
919 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
921 for (int i = 0; i < nSize; i += 2)
923 int i2 = std::min(i+1, nSize-1);
924 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
925 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
929 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
932 std::vector<uint256> GetMerkleBranch(int nIndex) const
934 if (vMerkleTree.empty())
936 std::vector<uint256> vMerkleBranch;
938 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
940 int i = std::min(nIndex^1, nSize-1);
941 vMerkleBranch.push_back(vMerkleTree[j+i]);
945 return vMerkleBranch;
948 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
952 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
955 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
957 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
964 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
966 // Open history file to append
967 CAutoFile fileout = AppendBlockFile(nFileRet);
969 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
971 // Write index header
972 unsigned int nSize = fileout.GetSerializeSize(*this);
973 fileout << FLATDATA(pchMessageStart) << nSize;
976 nBlockPosRet = ftell(fileout);
977 if (nBlockPosRet == -1)
978 return error("CBlock::WriteToDisk() : ftell failed");
981 // Flush stdio buffers and commit to disk before returning
983 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
986 _commit(_fileno(fileout));
988 fsync(fileno(fileout));
995 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
999 // Open history file to read
1000 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1002 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1003 if (!fReadTransactions)
1004 filein.nType |= SER_BLOCKHEADERONLY;
1010 if (!CheckProofOfWork(GetHash(), nBits))
1011 return error("CBlock::ReadFromDisk() : errors in block header");
1020 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1021 GetHash().ToString().substr(0,20).c_str(),
1023 hashPrevBlock.ToString().substr(0,20).c_str(),
1024 hashMerkleRoot.ToString().substr(0,10).c_str(),
1025 nTime, nBits, nNonce,
1027 for (int i = 0; i < vtx.size(); i++)
1032 printf(" vMerkleTree: ");
1033 for (int i = 0; i < vMerkleTree.size(); i++)
1034 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1039 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1040 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1041 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1042 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1043 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1044 bool CheckBlock() const;
1054 // The block chain is a tree shaped structure starting with the
1055 // genesis block at the root, with each block potentially having multiple
1056 // candidates to be the next block. pprev and pnext link a path through the
1057 // main/longest chain. A blockindex may have multiple pprev pointing back
1058 // to it, but pnext will only point forward to the longest branch, or will
1059 // be null if the block is not part of the longest chain.
1064 const uint256* phashBlock;
1068 unsigned int nBlockPos;
1070 CBigNum bnChainWork;
1074 uint256 hashMerkleRoot;
1077 unsigned int nNonce;
1097 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1103 nBlockPos = nBlockPosIn;
1107 nVersion = block.nVersion;
1108 hashMerkleRoot = block.hashMerkleRoot;
1109 nTime = block.nTime;
1110 nBits = block.nBits;
1111 nNonce = block.nNonce;
1114 CBlock GetBlockHeader() const
1117 block.nVersion = nVersion;
1119 block.hashPrevBlock = pprev->GetBlockHash();
1120 block.hashMerkleRoot = hashMerkleRoot;
1121 block.nTime = nTime;
1122 block.nBits = nBits;
1123 block.nNonce = nNonce;
1127 uint256 GetBlockHash() const
1132 int64 GetBlockTime() const
1134 return (int64)nTime;
1137 CBigNum GetBlockWork() const
1140 bnTarget.SetCompact(nBits);
1143 return (CBigNum(1)<<256) / (bnTarget+1);
1146 bool IsInMainChain() const
1148 return (pnext || this == pindexBest);
1151 bool CheckIndex() const
1153 return CheckProofOfWork(GetBlockHash(), nBits);
1156 bool EraseBlockFromDisk()
1158 // Open history file
1159 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1163 // Overwrite with empty null block
1171 enum { nMedianTimeSpan=11 };
1173 int64 GetMedianTimePast() const
1175 int64 pmedian[nMedianTimeSpan];
1176 int64* pbegin = &pmedian[nMedianTimeSpan];
1177 int64* pend = &pmedian[nMedianTimeSpan];
1179 const CBlockIndex* pindex = this;
1180 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1181 *(--pbegin) = pindex->GetBlockTime();
1183 std::sort(pbegin, pend);
1184 return pbegin[(pend - pbegin)/2];
1187 int64 GetMedianTime() const
1189 const CBlockIndex* pindex = this;
1190 for (int i = 0; i < nMedianTimeSpan/2; i++)
1193 return GetBlockTime();
1194 pindex = pindex->pnext;
1196 return pindex->GetMedianTimePast();
1201 std::string ToString() const
1203 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1204 pprev, pnext, nFile, nBlockPos, nHeight,
1205 hashMerkleRoot.ToString().substr(0,10).c_str(),
1206 GetBlockHash().ToString().substr(0,20).c_str());
1211 printf("%s\n", ToString().c_str());
1218 // Used to marshal pointers into hashes for db storage.
1220 class CDiskBlockIndex : public CBlockIndex
1232 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1234 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1235 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1240 if (!(nType & SER_GETHASH))
1241 READWRITE(nVersion);
1243 READWRITE(hashNext);
1245 READWRITE(nBlockPos);
1249 READWRITE(this->nVersion);
1250 READWRITE(hashPrev);
1251 READWRITE(hashMerkleRoot);
1257 uint256 GetBlockHash() const
1260 block.nVersion = nVersion;
1261 block.hashPrevBlock = hashPrev;
1262 block.hashMerkleRoot = hashMerkleRoot;
1263 block.nTime = nTime;
1264 block.nBits = nBits;
1265 block.nNonce = nNonce;
1266 return block.GetHash();
1270 std::string ToString() const
1272 std::string str = "CDiskBlockIndex(";
1273 str += CBlockIndex::ToString();
1274 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1275 GetBlockHash().ToString().c_str(),
1276 hashPrev.ToString().substr(0,20).c_str(),
1277 hashNext.ToString().substr(0,20).c_str());
1283 printf("%s\n", ToString().c_str());
1295 // Describes a place in the block chain to another node such that if the
1296 // other node doesn't have the same branch, it can find a recent common trunk.
1297 // The further back it is, the further before the fork it may be.
1302 std::vector<uint256> vHave;
1309 explicit CBlockLocator(const CBlockIndex* pindex)
1314 explicit CBlockLocator(uint256 hashBlock)
1316 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1317 if (mi != mapBlockIndex.end())
1321 CBlockLocator(const std::vector<uint256>& vHaveIn)
1328 if (!(nType & SER_GETHASH))
1329 READWRITE(nVersion);
1340 return vHave.empty();
1343 void Set(const CBlockIndex* pindex)
1349 vHave.push_back(pindex->GetBlockHash());
1351 // Exponentially larger steps back
1352 for (int i = 0; pindex && i < nStep; i++)
1353 pindex = pindex->pprev;
1354 if (vHave.size() > 10)
1357 vHave.push_back(hashGenesisBlock);
1360 int GetDistanceBack()
1362 // Retrace how far back it was in the sender's branch
1365 BOOST_FOREACH(const uint256& hash, vHave)
1367 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1368 if (mi != mapBlockIndex.end())
1370 CBlockIndex* pindex = (*mi).second;
1371 if (pindex->IsInMainChain())
1381 CBlockIndex* GetBlockIndex()
1383 // Find the first block the caller has in the main chain
1384 BOOST_FOREACH(const uint256& hash, vHave)
1386 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1387 if (mi != mapBlockIndex.end())
1389 CBlockIndex* pindex = (*mi).second;
1390 if (pindex->IsInMainChain())
1394 return pindexGenesisBlock;
1397 uint256 GetBlockHash()
1399 // Find the first block the caller has in the main chain
1400 BOOST_FOREACH(const uint256& hash, vHave)
1402 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1403 if (mi != mapBlockIndex.end())
1405 CBlockIndex* pindex = (*mi).second;
1406 if (pindex->IsInMainChain())
1410 return hashGenesisBlock;
1415 CBlockIndex* pindex = GetBlockIndex();
1418 return pindex->nHeight;
1431 // Alerts are for notifying old versions if they become too obsolete and
1432 // need to upgrade. The message is displayed in the status bar.
1433 // Alert messages are broadcast as a vector of signed data. Unserializing may
1434 // not read the entire buffer if the alert is for a newer version, but older
1435 // versions can still relay the original data.
1437 class CUnsignedAlert
1441 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1445 std::set<int> setCancel;
1446 int nMinVer; // lowest version inclusive
1447 int nMaxVer; // highest version inclusive
1448 std::set<std::string> setSubVer; // empty matches all
1452 std::string strComment;
1453 std::string strStatusBar;
1454 std::string strReserved;
1458 READWRITE(this->nVersion);
1459 nVersion = this->nVersion;
1460 READWRITE(nRelayUntil);
1461 READWRITE(nExpiration);
1464 READWRITE(setCancel);
1467 READWRITE(setSubVer);
1468 READWRITE(nPriority);
1470 READWRITE(strComment);
1471 READWRITE(strStatusBar);
1472 READWRITE(strReserved);
1489 strStatusBar.clear();
1490 strReserved.clear();
1493 std::string ToString() const
1495 std::string strSetCancel;
1496 BOOST_FOREACH(int n, setCancel)
1497 strSetCancel += strprintf("%d ", n);
1498 std::string strSetSubVer;
1499 BOOST_FOREACH(std::string str, setSubVer)
1500 strSetSubVer += "\"" + str + "\" ";
1504 " nRelayUntil = %"PRI64d"\n"
1505 " nExpiration = %"PRI64d"\n"
1513 " strComment = \"%s\"\n"
1514 " strStatusBar = \"%s\"\n"
1521 strSetCancel.c_str(),
1524 strSetSubVer.c_str(),
1527 strStatusBar.c_str());
1532 printf("%s", ToString().c_str());
1536 class CAlert : public CUnsignedAlert
1539 std::vector<unsigned char> vchMsg;
1540 std::vector<unsigned char> vchSig;
1555 CUnsignedAlert::SetNull();
1562 return (nExpiration == 0);
1565 uint256 GetHash() const
1567 return SerializeHash(*this);
1570 bool IsInEffect() const
1572 return (GetAdjustedTime() < nExpiration);
1575 bool Cancels(const CAlert& alert) const
1578 return false; // this was a no-op before 31403
1579 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1582 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1584 // TODO: rework for client-version-embedded-in-strSubVer ?
1585 return (IsInEffect() &&
1586 nMinVer <= nVersion && nVersion <= nMaxVer &&
1587 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1590 bool AppliesToMe() const
1592 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1595 bool RelayTo(CNode* pnode) const
1599 // returns true if wasn't already contained in the set
1600 if (pnode->setKnown.insert(GetHash()).second)
1602 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1604 GetAdjustedTime() < nRelayUntil)
1606 pnode->PushMessage("alert", *this);
1613 bool CheckSignature()
1616 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1617 return error("CAlert::CheckSignature() : SetPubKey failed");
1618 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1619 return error("CAlert::CheckSignature() : verify signature failed");
1621 // Now unserialize the data
1622 CDataStream sMsg(vchMsg);
1623 sMsg >> *(CUnsignedAlert*)this;
1627 bool ProcessAlert();