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 COPYING or http://www.opensource.org/licenses/mit-license.php.
26 class CRequestTracker;
29 static const int CLIENT_VERSION = 60008;
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 int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
37 static const int64 COIN = 100000000;
38 static const int64 CENT = 1000000;
39 static const int64 MIN_TX_FEE = 50000;
40 static const int64 MIN_RELAY_TX_FEE = 10000;
41 static const int64 MAX_MONEY = 21000000 * COIN;
42 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
43 static const int COINBASE_MATURITY = 100;
44 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
45 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
47 static const int fHaveUPnP = true;
49 static const int fHaveUPnP = false;
53 extern CScript COINBASE_FLAGS;
60 extern CCriticalSection cs_main;
61 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
62 extern uint256 hashGenesisBlock;
63 extern CBlockIndex* pindexGenesisBlock;
64 extern int nBestHeight;
65 extern CBigNum bnBestChainWork;
66 extern CBigNum bnBestInvalidWork;
67 extern uint256 hashBestChain;
68 extern CBlockIndex* pindexBest;
69 extern uint64 nPooledTx;
70 extern unsigned int nTransactionsUpdated;
71 extern uint64 nLastBlockTx;
72 extern uint64 nLastBlockSize;
73 extern const std::string strMessageMagic;
74 extern double dHashesPerSec;
75 extern int64 nHPSTimerStart;
76 extern int64 nTimeBestReceived;
77 extern CCriticalSection cs_setpwalletRegistered;
78 extern std::set<CWallet*> setpwalletRegistered;
81 extern int64 nTransactionFee;
91 void RegisterWallet(CWallet* pwalletIn);
92 void UnregisterWallet(CWallet* pwalletIn);
93 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
94 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
95 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
96 FILE* AppendBlockFile(unsigned int& nFileRet);
97 bool LoadBlockIndex(bool fAllowNew=true);
98 void PrintBlockTree();
99 bool ProcessMessages(CNode* pfrom);
100 bool SendMessages(CNode* pto, bool fSendTrickle);
101 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
102 CBlock* CreateNewBlock(CReserveKey& reservekey);
103 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
104 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
105 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
106 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
107 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
108 int GetNumBlocksOfPeers();
109 bool IsInitialBlockDownload();
110 std::string GetWarnings(std::string strFor);
123 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
125 /** Position on disk for a particular transaction. */
130 unsigned int nBlockPos;
138 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
141 nBlockPos = nBlockPosIn;
145 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
146 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
147 bool IsNull() const { return (nFile == -1); }
149 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
151 return (a.nFile == b.nFile &&
152 a.nBlockPos == b.nBlockPos &&
153 a.nTxPos == b.nTxPos);
156 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
161 std::string ToString() const
164 return strprintf("null");
166 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
171 printf("%s", ToString().c_str());
177 /** An inpoint - a combination of a transaction and an index n into its vin */
184 CInPoint() { SetNull(); }
185 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
186 void SetNull() { ptx = NULL; n = -1; }
187 bool IsNull() const { return (ptx == NULL && n == -1); }
192 /** An outpoint - a combination of a transaction hash and an index n into its vout */
199 COutPoint() { SetNull(); }
200 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
201 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
202 void SetNull() { hash = 0; n = -1; }
203 bool IsNull() const { return (hash == 0 && n == -1); }
205 friend bool operator<(const COutPoint& a, const COutPoint& b)
207 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
210 friend bool operator==(const COutPoint& a, const COutPoint& b)
212 return (a.hash == b.hash && a.n == b.n);
215 friend bool operator!=(const COutPoint& a, const COutPoint& b)
220 std::string ToString() const
222 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
227 printf("%s\n", ToString().c_str());
234 /** An input of a transaction. It contains the location of the previous
235 * transaction's output that it claims and a signature that matches the
236 * output's public key.
243 unsigned int nSequence;
247 nSequence = std::numeric_limits<unsigned int>::max();
250 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
253 scriptSig = scriptSigIn;
254 nSequence = nSequenceIn;
257 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
259 prevout = COutPoint(hashPrevTx, nOut);
260 scriptSig = scriptSigIn;
261 nSequence = nSequenceIn;
267 READWRITE(scriptSig);
268 READWRITE(nSequence);
273 return (nSequence == std::numeric_limits<unsigned int>::max());
276 friend bool operator==(const CTxIn& a, const CTxIn& b)
278 return (a.prevout == b.prevout &&
279 a.scriptSig == b.scriptSig &&
280 a.nSequence == b.nSequence);
283 friend bool operator!=(const CTxIn& a, const CTxIn& b)
288 std::string ToString() const
291 str += strprintf("CTxIn(");
292 str += prevout.ToString();
293 if (prevout.IsNull())
294 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
296 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
297 if (nSequence != std::numeric_limits<unsigned int>::max())
298 str += strprintf(", nSequence=%u", nSequence);
305 printf("%s\n", ToString().c_str());
312 /** An output of a transaction. It contains the public key that the next input
313 * must be able to sign with to claim it.
319 CScript scriptPubKey;
326 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
329 scriptPubKey = scriptPubKeyIn;
335 READWRITE(scriptPubKey);
341 scriptPubKey.clear();
346 return (nValue == -1);
349 uint256 GetHash() const
351 return SerializeHash(*this);
354 friend bool operator==(const CTxOut& a, const CTxOut& b)
356 return (a.nValue == b.nValue &&
357 a.scriptPubKey == b.scriptPubKey);
360 friend bool operator!=(const CTxOut& a, const CTxOut& b)
365 std::string ToString() const
367 if (scriptPubKey.size() < 6)
368 return "CTxOut(error)";
369 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
374 printf("%s\n", ToString().c_str());
388 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
390 /** The basic transaction that is broadcasted on the network and contained in
391 * blocks. A transaction can contain multiple inputs and outputs.
397 std::vector<CTxIn> vin;
398 std::vector<CTxOut> vout;
399 unsigned int nLockTime;
401 // Denial-of-service detection:
403 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
412 READWRITE(this->nVersion);
413 nVersion = this->nVersion;
416 READWRITE(nLockTime);
425 nDoS = 0; // Denial-of-service prevention
430 return (vin.empty() && vout.empty());
433 uint256 GetHash() const
435 return SerializeHash(*this);
438 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
440 // Time based nLockTime implemented in 0.1.6
443 if (nBlockHeight == 0)
444 nBlockHeight = nBestHeight;
446 nBlockTime = GetAdjustedTime();
447 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
449 BOOST_FOREACH(const CTxIn& txin, vin)
455 bool IsNewerThan(const CTransaction& old) const
457 if (vin.size() != old.vin.size())
459 for (unsigned int i = 0; i < vin.size(); i++)
460 if (vin[i].prevout != old.vin[i].prevout)
464 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
465 for (unsigned int i = 0; i < vin.size(); i++)
467 if (vin[i].nSequence != old.vin[i].nSequence)
469 if (vin[i].nSequence <= nLowest)
472 nLowest = vin[i].nSequence;
474 if (old.vin[i].nSequence < nLowest)
477 nLowest = old.vin[i].nSequence;
484 bool IsCoinBase() const
486 return (vin.size() == 1 && vin[0].prevout.IsNull());
489 /** Check for standard transaction types
490 @return True if all outputs (scriptPubKeys) use only standard transaction forms
492 bool IsStandard() const;
494 /** Check for standard transaction types
495 @param[in] mapInputs Map of previous transactions that have outputs we're spending
496 @return True if all inputs (scriptSigs) use only standard transaction forms
497 @see CTransaction::FetchInputs
499 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
501 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
502 @return number of sigops this transaction's outputs will produce when spent
503 @see CTransaction::FetchInputs
505 int GetLegacySigOpCount() const;
507 /** Count ECDSA signature operations in pay-to-script-hash inputs.
509 @param[in] mapInputs Map of previous transactions that have outputs we're spending
510 @return maximum number of sigops required to validate this transaction's inputs
511 @see CTransaction::FetchInputs
513 int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
515 /** Amount of bitcoins spent by this transaction.
516 @return sum of all outputs (note: does not include fees)
518 int64 GetValueOut() const
521 BOOST_FOREACH(const CTxOut& txout, vout)
523 nValueOut += txout.nValue;
524 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
525 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
530 /** Amount of bitcoins coming in to this transaction
531 Note that lightweight clients may not know anything besides the hash of previous transactions,
532 so may not be able to calculate this.
534 @param[in] mapInputs Map of previous transactions that have outputs we're spending
535 @return Sum of value of all inputs (scriptSigs)
536 @see CTransaction::FetchInputs
538 int64 GetValueIn(const MapPrevTx& mapInputs) const;
540 static bool AllowFree(double dPriority)
542 // Large (in bytes) low-priority (new, small-coin) transactions
544 return dPriority > COIN * 144 / 250;
547 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
549 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
550 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
552 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
553 unsigned int nNewBlockSize = nBlockSize + nBytes;
554 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
560 // Transactions under 10K are free
561 // (about 4500bc if made of 50bc inputs)
567 // Free transaction area
568 if (nNewBlockSize < 27000)
573 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
574 if (nMinFee < nBaseFee)
576 BOOST_FOREACH(const CTxOut& txout, vout)
577 if (txout.nValue < CENT)
581 // Raise the price as the block approaches full
582 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
584 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
586 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
589 if (!MoneyRange(nMinFee))
595 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
597 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
599 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
602 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
603 return error("CTransaction::ReadFromDisk() : fseek failed");
608 catch (std::exception &e) {
609 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
612 // Return file pointer
615 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
616 return error("CTransaction::ReadFromDisk() : second fseek failed");
617 *pfileRet = filein.release();
622 friend bool operator==(const CTransaction& a, const CTransaction& b)
624 return (a.nVersion == b.nVersion &&
627 a.nLockTime == b.nLockTime);
630 friend bool operator!=(const CTransaction& a, const CTransaction& b)
636 std::string ToString() const
639 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
640 GetHash().ToString().substr(0,10).c_str(),
645 for (unsigned int i = 0; i < vin.size(); i++)
646 str += " " + vin[i].ToString() + "\n";
647 for (unsigned int i = 0; i < vout.size(); i++)
648 str += " " + vout[i].ToString() + "\n";
654 printf("%s", ToString().c_str());
658 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
659 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
660 bool ReadFromDisk(COutPoint prevout);
661 bool DisconnectInputs(CTxDB& txdb);
663 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
665 @param[in] txdb Transaction database
666 @param[in] mapTestPool List of pending changes to the transaction index database
667 @param[in] fBlock True if being called to add a new best-block to the chain
668 @param[in] fMiner True if being called by CreateNewBlock
669 @param[out] inputsRet Pointers to this transaction's inputs
670 @param[out] fInvalid returns true if transaction is invalid
671 @return Returns true if all inputs are in txdb or mapTestPool
673 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
674 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
676 /** Sanity check previous transactions, then, if all checks succeed,
677 mark them as spent by this transaction.
679 @param[in] inputs Previous transactions (from FetchInputs)
680 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
681 @param[in] posThisTx Position of this transaction on disk
682 @param[in] pindexBlock
683 @param[in] fBlock true if called from ConnectBlock
684 @param[in] fMiner true if called from CreateNewBlock
685 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
686 @return Returns true if all checks succeed
688 bool ConnectInputs(MapPrevTx inputs,
689 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
690 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
691 bool ClientConnectInputs();
692 bool CheckTransaction() const;
693 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
694 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
697 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
698 bool AddToMemoryPoolUnchecked();
700 bool RemoveFromMemoryPool();
707 /** A transaction with a merkle branch linking it to the block chain. */
708 class CMerkleTx : public CTransaction
712 std::vector<uint256> vMerkleBranch;
716 mutable char fMerkleVerified;
724 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
733 fMerkleVerified = false;
739 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
740 nVersion = this->nVersion;
741 READWRITE(hashBlock);
742 READWRITE(vMerkleBranch);
747 int SetMerkleBranch(const CBlock* pblock=NULL);
748 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
749 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
750 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
751 int GetBlocksToMaturity() const;
752 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
753 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 void UpdateTime(const CBlockIndex* pindexPrev);
901 uint256 BuildMerkleTree() const
904 BOOST_FOREACH(const CTransaction& tx, vtx)
905 vMerkleTree.push_back(tx.GetHash());
907 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
909 for (int i = 0; i < nSize; i += 2)
911 int i2 = std::min(i+1, nSize-1);
912 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
913 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
917 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
920 std::vector<uint256> GetMerkleBranch(int nIndex) const
922 if (vMerkleTree.empty())
924 std::vector<uint256> vMerkleBranch;
926 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
928 int i = std::min(nIndex^1, nSize-1);
929 vMerkleBranch.push_back(vMerkleTree[j+i]);
933 return vMerkleBranch;
936 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
940 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
943 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
945 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
952 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
954 // Open history file to append
955 CAutoFile fileout = AppendBlockFile(nFileRet);
957 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
959 // Write index header
960 unsigned int nSize = fileout.GetSerializeSize(*this);
961 fileout << FLATDATA(pchMessageStart) << nSize;
964 long fileOutPos = ftell(fileout);
966 return error("CBlock::WriteToDisk() : ftell failed");
967 nBlockPosRet = fileOutPos;
970 // Flush stdio buffers and commit to disk before returning
972 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
975 _commit(_fileno(fileout));
977 fsync(fileno(fileout));
984 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
988 // Open history file to read
989 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
991 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
992 if (!fReadTransactions)
993 filein.nType |= SER_BLOCKHEADERONLY;
999 catch (std::exception &e) {
1000 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1004 if (!CheckProofOfWork(GetHash(), nBits))
1005 return error("CBlock::ReadFromDisk() : errors in block header");
1014 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1015 GetHash().ToString().substr(0,20).c_str(),
1017 hashPrevBlock.ToString().substr(0,20).c_str(),
1018 hashMerkleRoot.ToString().substr(0,10).c_str(),
1019 nTime, nBits, nNonce,
1021 for (unsigned int i = 0; i < vtx.size(); i++)
1026 printf(" vMerkleTree: ");
1027 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1028 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1033 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1034 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1035 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1036 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1037 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1038 bool CheckBlock() const;
1042 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
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());
1213 /** Used to marshal pointers into hashes for db storage. */
1214 class CDiskBlockIndex : public CBlockIndex
1226 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1228 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1229 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1234 if (!(nType & SER_GETHASH))
1235 READWRITE(nVersion);
1237 READWRITE(hashNext);
1239 READWRITE(nBlockPos);
1243 READWRITE(this->nVersion);
1244 READWRITE(hashPrev);
1245 READWRITE(hashMerkleRoot);
1251 uint256 GetBlockHash() const
1254 block.nVersion = nVersion;
1255 block.hashPrevBlock = hashPrev;
1256 block.hashMerkleRoot = hashMerkleRoot;
1257 block.nTime = nTime;
1258 block.nBits = nBits;
1259 block.nNonce = nNonce;
1260 return block.GetHash();
1264 std::string ToString() const
1266 std::string str = "CDiskBlockIndex(";
1267 str += CBlockIndex::ToString();
1268 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1269 GetBlockHash().ToString().c_str(),
1270 hashPrev.ToString().substr(0,20).c_str(),
1271 hashNext.ToString().substr(0,20).c_str());
1277 printf("%s\n", ToString().c_str());
1288 /** Describes a place in the block chain to another node such that if the
1289 * other node doesn't have the same branch, it can find a recent common trunk.
1290 * The further back it is, the further before the fork it may be.
1295 std::vector<uint256> vHave;
1302 explicit CBlockLocator(const CBlockIndex* pindex)
1307 explicit CBlockLocator(uint256 hashBlock)
1309 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1310 if (mi != mapBlockIndex.end())
1314 CBlockLocator(const std::vector<uint256>& vHaveIn)
1321 if (!(nType & SER_GETHASH))
1322 READWRITE(nVersion);
1333 return vHave.empty();
1336 void Set(const CBlockIndex* pindex)
1342 vHave.push_back(pindex->GetBlockHash());
1344 // Exponentially larger steps back
1345 for (int i = 0; pindex && i < nStep; i++)
1346 pindex = pindex->pprev;
1347 if (vHave.size() > 10)
1350 vHave.push_back(hashGenesisBlock);
1353 int GetDistanceBack()
1355 // Retrace how far back it was in the sender's branch
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())
1374 CBlockIndex* GetBlockIndex()
1376 // Find the first block the caller has in the main chain
1377 BOOST_FOREACH(const uint256& hash, vHave)
1379 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1380 if (mi != mapBlockIndex.end())
1382 CBlockIndex* pindex = (*mi).second;
1383 if (pindex->IsInMainChain())
1387 return pindexGenesisBlock;
1390 uint256 GetBlockHash()
1392 // Find the first block the caller has in the main chain
1393 BOOST_FOREACH(const uint256& hash, vHave)
1395 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1396 if (mi != mapBlockIndex.end())
1398 CBlockIndex* pindex = (*mi).second;
1399 if (pindex->IsInMainChain())
1403 return hashGenesisBlock;
1408 CBlockIndex* pindex = GetBlockIndex();
1411 return pindex->nHeight;
1423 /** Alerts are for notifying old versions if they become too obsolete and
1424 * need to upgrade. The message is displayed in the status bar.
1425 * Alert messages are broadcast as a vector of signed data. Unserializing may
1426 * not read the entire buffer if the alert is for a newer version, but older
1427 * versions can still relay the original data.
1429 class CUnsignedAlert
1433 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1437 std::set<int> setCancel;
1438 int nMinVer; // lowest version inclusive
1439 int nMaxVer; // highest version inclusive
1440 std::set<std::string> setSubVer; // empty matches all
1444 std::string strComment;
1445 std::string strStatusBar;
1446 std::string strReserved;
1450 READWRITE(this->nVersion);
1451 nVersion = this->nVersion;
1452 READWRITE(nRelayUntil);
1453 READWRITE(nExpiration);
1456 READWRITE(setCancel);
1459 READWRITE(setSubVer);
1460 READWRITE(nPriority);
1462 READWRITE(strComment);
1463 READWRITE(strStatusBar);
1464 READWRITE(strReserved);
1481 strStatusBar.clear();
1482 strReserved.clear();
1485 std::string ToString() const
1487 std::string strSetCancel;
1488 BOOST_FOREACH(int n, setCancel)
1489 strSetCancel += strprintf("%d ", n);
1490 std::string strSetSubVer;
1491 BOOST_FOREACH(std::string str, setSubVer)
1492 strSetSubVer += "\"" + str + "\" ";
1496 " nRelayUntil = %"PRI64d"\n"
1497 " nExpiration = %"PRI64d"\n"
1505 " strComment = \"%s\"\n"
1506 " strStatusBar = \"%s\"\n"
1513 strSetCancel.c_str(),
1516 strSetSubVer.c_str(),
1519 strStatusBar.c_str());
1524 printf("%s", ToString().c_str());
1528 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1529 class CAlert : public CUnsignedAlert
1532 std::vector<unsigned char> vchMsg;
1533 std::vector<unsigned char> vchSig;
1548 CUnsignedAlert::SetNull();
1555 return (nExpiration == 0);
1558 uint256 GetHash() const
1560 return SerializeHash(*this);
1563 bool IsInEffect() const
1565 return (GetAdjustedTime() < nExpiration);
1568 bool Cancels(const CAlert& alert) const
1571 return false; // this was a no-op before 31403
1572 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1575 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1577 // TODO: rework for client-version-embedded-in-strSubVer ?
1578 return (IsInEffect() &&
1579 nMinVer <= nVersion && nVersion <= nMaxVer &&
1580 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1583 bool AppliesToMe() const
1585 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1588 bool RelayTo(CNode* pnode) const
1592 // returns true if wasn't already contained in the set
1593 if (pnode->setKnown.insert(GetHash()).second)
1595 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1597 GetAdjustedTime() < nRelayUntil)
1599 pnode->PushMessage("alert", *this);
1606 bool CheckSignature()
1609 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1610 return error("CAlert::CheckSignature() : SetPubKey failed");
1611 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1612 return error("CAlert::CheckSignature() : verify signature failed");
1614 // Now unserialize the data
1615 CDataStream sMsg(vchMsg);
1616 sMsg >> *(CUnsignedAlert*)this;
1620 bool ProcessAlert();