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;
52 // Put "/P2SH/" in the coinbase so everybody can tell when
53 // a majority of miners support it
54 static const char* pszP2SH = "/P2SH/";
55 static const CScript COINBASE_FLAGS = CScript() << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
62 extern CCriticalSection cs_main;
63 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
64 extern uint256 hashGenesisBlock;
65 extern CBlockIndex* pindexGenesisBlock;
66 extern int nBestHeight;
67 extern CBigNum bnBestChainWork;
68 extern CBigNum bnBestInvalidWork;
69 extern uint256 hashBestChain;
70 extern CBlockIndex* pindexBest;
71 extern uint64 nPooledTx;
72 extern unsigned int nTransactionsUpdated;
73 extern uint64 nLastBlockTx;
74 extern uint64 nLastBlockSize;
75 extern double dHashesPerSec;
76 extern int64 nHPSTimerStart;
77 extern int64 nTimeBestReceived;
78 extern CCriticalSection cs_setpwalletRegistered;
79 extern std::set<CWallet*> setpwalletRegistered;
82 extern int fGenerateBitcoins;
83 extern int64 nTransactionFee;
84 extern int fLimitProcessors;
85 extern int nLimitProcessors;
86 extern int fMinimizeToTray;
87 extern int fMinimizeOnClose;
98 void RegisterWallet(CWallet* pwalletIn);
99 void UnregisterWallet(CWallet* pwalletIn);
100 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
101 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
102 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
103 FILE* AppendBlockFile(unsigned int& nFileRet);
104 bool LoadBlockIndex(bool fAllowNew=true);
105 void PrintBlockTree();
106 bool ProcessMessages(CNode* pfrom);
107 bool SendMessages(CNode* pto, bool fSendTrickle);
108 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
109 CBlock* CreateNewBlock(CReserveKey& reservekey);
110 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
111 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
112 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
113 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
114 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
115 int GetNumBlocksOfPeers();
116 bool IsInitialBlockDownload();
117 std::string GetWarnings(std::string strFor);
130 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
133 bool WriteSetting(const std::string& strKey, const T& value)
136 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
138 std::string strWalletFile;
139 if (!GetWalletFile(pwallet, strWalletFile))
141 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
151 unsigned int nBlockPos;
159 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
162 nBlockPos = nBlockPosIn;
166 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
167 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
168 bool IsNull() const { return (nFile == -1); }
170 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
172 return (a.nFile == b.nFile &&
173 a.nBlockPos == b.nBlockPos &&
174 a.nTxPos == b.nTxPos);
177 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
182 std::string ToString() const
185 return strprintf("null");
187 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
192 printf("%s", ToString().c_str());
205 CInPoint() { SetNull(); }
206 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
207 void SetNull() { ptx = NULL; n = -1; }
208 bool IsNull() const { return (ptx == NULL && n == -1); }
220 COutPoint() { SetNull(); }
221 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
222 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
223 void SetNull() { hash = 0; n = -1; }
224 bool IsNull() const { return (hash == 0 && n == -1); }
226 friend bool operator<(const COutPoint& a, const COutPoint& b)
228 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
231 friend bool operator==(const COutPoint& a, const COutPoint& b)
233 return (a.hash == b.hash && a.n == b.n);
236 friend bool operator!=(const COutPoint& a, const COutPoint& b)
241 std::string ToString() const
243 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
248 printf("%s\n", ToString().c_str());
256 // An input of a transaction. It contains the location of the previous
257 // transaction's output that it claims and a signature that matches the
258 // output's public key.
265 unsigned int nSequence;
269 nSequence = std::numeric_limits<unsigned int>::max();
272 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
275 scriptSig = scriptSigIn;
276 nSequence = nSequenceIn;
279 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
281 prevout = COutPoint(hashPrevTx, nOut);
282 scriptSig = scriptSigIn;
283 nSequence = nSequenceIn;
289 READWRITE(scriptSig);
290 READWRITE(nSequence);
295 return (nSequence == std::numeric_limits<unsigned int>::max());
298 friend bool operator==(const CTxIn& a, const CTxIn& b)
300 return (a.prevout == b.prevout &&
301 a.scriptSig == b.scriptSig &&
302 a.nSequence == b.nSequence);
305 friend bool operator!=(const CTxIn& a, const CTxIn& b)
310 std::string ToString() const
313 str += strprintf("CTxIn(");
314 str += prevout.ToString();
315 if (prevout.IsNull())
316 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
318 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
319 if (nSequence != std::numeric_limits<unsigned int>::max())
320 str += strprintf(", nSequence=%u", nSequence);
327 printf("%s\n", ToString().c_str());
335 // An output of a transaction. It contains the public key that the next input
336 // must be able to sign with to claim it.
342 CScript scriptPubKey;
349 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
352 scriptPubKey = scriptPubKeyIn;
358 READWRITE(scriptPubKey);
364 scriptPubKey.clear();
369 return (nValue == -1);
372 uint256 GetHash() const
374 return SerializeHash(*this);
377 friend bool operator==(const CTxOut& a, const CTxOut& b)
379 return (a.nValue == b.nValue &&
380 a.scriptPubKey == b.scriptPubKey);
383 friend bool operator!=(const CTxOut& a, const CTxOut& b)
388 std::string ToString() const
390 if (scriptPubKey.size() < 6)
391 return "CTxOut(error)";
392 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
397 printf("%s\n", ToString().c_str());
411 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
414 // The basic transaction that is broadcasted on the network and contained in
415 // blocks. A transaction can contain multiple inputs and outputs.
421 std::vector<CTxIn> vin;
422 std::vector<CTxOut> vout;
423 unsigned int nLockTime;
425 // Denial-of-service detection:
427 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
436 READWRITE(this->nVersion);
437 nVersion = this->nVersion;
440 READWRITE(nLockTime);
449 nDoS = 0; // Denial-of-service prevention
454 return (vin.empty() && vout.empty());
457 uint256 GetHash() const
459 return SerializeHash(*this);
462 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
464 // Time based nLockTime implemented in 0.1.6
467 if (nBlockHeight == 0)
468 nBlockHeight = nBestHeight;
470 nBlockTime = GetAdjustedTime();
471 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
473 BOOST_FOREACH(const CTxIn& txin, vin)
479 bool IsNewerThan(const CTransaction& old) const
481 if (vin.size() != old.vin.size())
483 for (int i = 0; i < vin.size(); i++)
484 if (vin[i].prevout != old.vin[i].prevout)
488 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
489 for (int i = 0; i < vin.size(); i++)
491 if (vin[i].nSequence != old.vin[i].nSequence)
493 if (vin[i].nSequence <= nLowest)
496 nLowest = vin[i].nSequence;
498 if (old.vin[i].nSequence < nLowest)
501 nLowest = old.vin[i].nSequence;
508 bool IsCoinBase() const
510 return (vin.size() == 1 && vin[0].prevout.IsNull());
513 /** Check for standard transaction types
514 @return True if all outputs (scriptPubKeys) use only standard transaction forms
516 bool IsStandard() const;
518 /** Check for standard transaction types
519 @param[in] mapInputs Map of previous transactions that have outputs we're spending
520 @return True if all inputs (scriptSigs) use only standard transaction forms
521 @see CTransaction::FetchInputs
523 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
525 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
526 @return number of sigops this transaction's outputs will produce when spent
527 @see CTransaction::FetchInputs
529 int GetLegacySigOpCount() const;
531 /** Count ECDSA signature operations the new (0.6-and-later) way
532 This is a better measure of how expensive it is to process this transaction.
534 @param[in] mapInputs Map of previous transactions that have outputs we're spending
535 @return maximum number of sigops required to validate this transaction's inputs
536 @see CTransaction::FetchInputs
538 int GetSigOpCount(const MapPrevTx& mapInputs) const;
540 /** Amount of bitcoins spent by this transaction.
541 @return sum of all outputs (note: does not include fees)
543 int64 GetValueOut() const
546 BOOST_FOREACH(const CTxOut& txout, vout)
548 nValueOut += txout.nValue;
549 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
550 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
555 /** Amount of bitcoins coming in to this transaction
556 Note that lightweight clients may not know anything besides the hash of previous transactions,
557 so may not be able to calculate this.
559 @param[in] mapInputs Map of previous transactions that have outputs we're spending
560 @return Sum of value of all inputs (scriptSigs)
561 @see CTransaction::FetchInputs
563 int64 GetValueIn(const MapPrevTx& mapInputs) const;
565 static bool AllowFree(double dPriority)
567 // Large (in bytes) low-priority (new, small-coin) transactions
569 return dPriority > COIN * 144 / 250;
572 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
574 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
575 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
577 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
578 unsigned int nNewBlockSize = nBlockSize + nBytes;
579 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
585 // Transactions under 10K are free
586 // (about 4500bc if made of 50bc inputs)
592 // Free transaction area
593 if (nNewBlockSize < 27000)
598 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
599 if (nMinFee < nBaseFee)
600 BOOST_FOREACH(const CTxOut& txout, vout)
601 if (txout.nValue < CENT)
604 // Raise the price as the block approaches full
605 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
607 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
609 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
612 if (!MoneyRange(nMinFee))
618 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
620 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
622 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
625 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
626 return error("CTransaction::ReadFromDisk() : fseek failed");
629 // Return file pointer
632 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
633 return error("CTransaction::ReadFromDisk() : second fseek failed");
634 *pfileRet = filein.release();
639 friend bool operator==(const CTransaction& a, const CTransaction& b)
641 return (a.nVersion == b.nVersion &&
644 a.nLockTime == b.nLockTime);
647 friend bool operator!=(const CTransaction& a, const CTransaction& b)
653 std::string ToString() const
656 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
657 GetHash().ToString().substr(0,10).c_str(),
662 for (int i = 0; i < vin.size(); i++)
663 str += " " + vin[i].ToString() + "\n";
664 for (int i = 0; i < vout.size(); i++)
665 str += " " + vout[i].ToString() + "\n";
671 printf("%s", ToString().c_str());
675 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
676 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
677 bool ReadFromDisk(COutPoint prevout);
678 bool DisconnectInputs(CTxDB& txdb);
680 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
682 @param[in] txdb Transaction database
683 @param[in] mapTestPool List of pending changes to the transaction index database
684 @param[in] fBlock True if being called to add a new best-block to the chain
685 @param[in] fMiner True if being called by CreateNewBlock
686 @param[out] inputsRet Pointers to this transaction's inputs
687 @return Returns true if all inputs are in txdb or mapTestPool
689 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
690 bool fBlock, bool fMiner, MapPrevTx& inputsRet);
692 /** Sanity check previous transactions, then, if all checks succeed,
693 mark them as spent by this transaction.
695 @param[in] inputs Previous transactions (from FetchInputs)
696 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
697 @param[in] posThisTx Position of this transaction on disk
698 @param[in] pindexBlock
699 @param[in] fBlock true if called from ConnectBlock
700 @param[in] fMiner true if called from CreateNewBlock
701 @return Returns true if all checks succeed
703 bool ConnectInputs(MapPrevTx inputs,
704 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
705 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner);
706 bool ClientConnectInputs();
707 bool CheckTransaction() const;
708 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
709 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
712 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
713 bool AddToMemoryPoolUnchecked();
715 bool RemoveFromMemoryPool();
723 // A transaction with a merkle branch linking it to the block chain
725 class CMerkleTx : public CTransaction
729 std::vector<uint256> vMerkleBranch;
733 mutable char fMerkleVerified;
741 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
750 fMerkleVerified = false;
756 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
757 nVersion = this->nVersion;
758 READWRITE(hashBlock);
759 READWRITE(vMerkleBranch);
764 int SetMerkleBranch(const CBlock* pblock=NULL);
765 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
766 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
767 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
768 int GetBlocksToMaturity() const;
769 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
770 bool AcceptToMemoryPool();
777 // A txdb record that contains the disk location of a transaction and the
778 // locations of transactions that spend its outputs. vSpent is really only
779 // used as a flag, but having the location is very helpful for debugging.
785 std::vector<CDiskTxPos> vSpent;
792 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
795 vSpent.resize(nOutputs);
800 if (!(nType & SER_GETHASH))
817 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
819 return (a.pos == b.pos &&
820 a.vSpent == b.vSpent);
823 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
827 int GetDepthInMainChain() const;
836 // Nodes collect new transactions into a block, hash them into a hash tree,
837 // and scan through nonce values to make the block's hash satisfy proof-of-work
838 // requirements. When they solve the proof-of-work, they broadcast the block
839 // to everyone and the block is added to the block chain. The first transaction
840 // in the block is a special one that creates a new coin owned by the creator
843 // Blocks are appended to blk0001.dat files on disk. Their location on disk
844 // is indexed by CBlockIndex objects in memory.
851 uint256 hashPrevBlock;
852 uint256 hashMerkleRoot;
858 std::vector<CTransaction> vtx;
861 mutable std::vector<uint256> vMerkleTree;
863 // Denial-of-service detection:
865 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
874 READWRITE(this->nVersion);
875 nVersion = this->nVersion;
876 READWRITE(hashPrevBlock);
877 READWRITE(hashMerkleRoot);
882 // ConnectBlock depends on vtx being last so it can calculate offset
883 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
886 const_cast<CBlock*>(this)->vtx.clear();
907 uint256 GetHash() const
909 return Hash(BEGIN(nVersion), END(nNonce));
912 int64 GetBlockTime() const
919 uint256 BuildMerkleTree() const
922 BOOST_FOREACH(const CTransaction& tx, vtx)
923 vMerkleTree.push_back(tx.GetHash());
925 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
927 for (int i = 0; i < nSize; i += 2)
929 int i2 = std::min(i+1, nSize-1);
930 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
931 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
935 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
938 std::vector<uint256> GetMerkleBranch(int nIndex) const
940 if (vMerkleTree.empty())
942 std::vector<uint256> vMerkleBranch;
944 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
946 int i = std::min(nIndex^1, nSize-1);
947 vMerkleBranch.push_back(vMerkleTree[j+i]);
951 return vMerkleBranch;
954 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
958 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
961 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
963 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
970 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
972 // Open history file to append
973 CAutoFile fileout = AppendBlockFile(nFileRet);
975 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
977 // Write index header
978 unsigned int nSize = fileout.GetSerializeSize(*this);
979 fileout << FLATDATA(pchMessageStart) << nSize;
982 nBlockPosRet = ftell(fileout);
983 if (nBlockPosRet == -1)
984 return error("CBlock::WriteToDisk() : ftell failed");
987 // Flush stdio buffers and commit to disk before returning
989 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
992 _commit(_fileno(fileout));
994 fsync(fileno(fileout));
1001 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1005 // Open history file to read
1006 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1008 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1009 if (!fReadTransactions)
1010 filein.nType |= SER_BLOCKHEADERONLY;
1016 if (!CheckProofOfWork(GetHash(), nBits))
1017 return error("CBlock::ReadFromDisk() : errors in block header");
1026 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1027 GetHash().ToString().substr(0,20).c_str(),
1029 hashPrevBlock.ToString().substr(0,20).c_str(),
1030 hashMerkleRoot.ToString().substr(0,10).c_str(),
1031 nTime, nBits, nNonce,
1033 for (int i = 0; i < vtx.size(); i++)
1038 printf(" vMerkleTree: ");
1039 for (int i = 0; i < vMerkleTree.size(); i++)
1040 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1045 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1046 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1047 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1048 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1049 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1050 bool CheckBlock() const;
1060 // The block chain is a tree shaped structure starting with the
1061 // genesis block at the root, with each block potentially having multiple
1062 // candidates to be the next block. pprev and pnext link a path through the
1063 // main/longest chain. A blockindex may have multiple pprev pointing back
1064 // to it, but pnext will only point forward to the longest branch, or will
1065 // be null if the block is not part of the longest chain.
1070 const uint256* phashBlock;
1074 unsigned int nBlockPos;
1076 CBigNum bnChainWork;
1080 uint256 hashMerkleRoot;
1083 unsigned int nNonce;
1103 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1109 nBlockPos = nBlockPosIn;
1113 nVersion = block.nVersion;
1114 hashMerkleRoot = block.hashMerkleRoot;
1115 nTime = block.nTime;
1116 nBits = block.nBits;
1117 nNonce = block.nNonce;
1120 CBlock GetBlockHeader() const
1123 block.nVersion = nVersion;
1125 block.hashPrevBlock = pprev->GetBlockHash();
1126 block.hashMerkleRoot = hashMerkleRoot;
1127 block.nTime = nTime;
1128 block.nBits = nBits;
1129 block.nNonce = nNonce;
1133 uint256 GetBlockHash() const
1138 int64 GetBlockTime() const
1140 return (int64)nTime;
1143 CBigNum GetBlockWork() const
1146 bnTarget.SetCompact(nBits);
1149 return (CBigNum(1)<<256) / (bnTarget+1);
1152 bool IsInMainChain() const
1154 return (pnext || this == pindexBest);
1157 bool CheckIndex() const
1159 return CheckProofOfWork(GetBlockHash(), nBits);
1162 bool EraseBlockFromDisk()
1164 // Open history file
1165 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1169 // Overwrite with empty null block
1177 enum { nMedianTimeSpan=11 };
1179 int64 GetMedianTimePast() const
1181 int64 pmedian[nMedianTimeSpan];
1182 int64* pbegin = &pmedian[nMedianTimeSpan];
1183 int64* pend = &pmedian[nMedianTimeSpan];
1185 const CBlockIndex* pindex = this;
1186 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1187 *(--pbegin) = pindex->GetBlockTime();
1189 std::sort(pbegin, pend);
1190 return pbegin[(pend - pbegin)/2];
1193 int64 GetMedianTime() const
1195 const CBlockIndex* pindex = this;
1196 for (int i = 0; i < nMedianTimeSpan/2; i++)
1199 return GetBlockTime();
1200 pindex = pindex->pnext;
1202 return pindex->GetMedianTimePast();
1207 std::string ToString() const
1209 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1210 pprev, pnext, nFile, nBlockPos, nHeight,
1211 hashMerkleRoot.ToString().substr(0,10).c_str(),
1212 GetBlockHash().ToString().substr(0,20).c_str());
1217 printf("%s\n", ToString().c_str());
1224 // Used to marshal pointers into hashes for db storage.
1226 class CDiskBlockIndex : public CBlockIndex
1238 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1240 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1241 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1246 if (!(nType & SER_GETHASH))
1247 READWRITE(nVersion);
1249 READWRITE(hashNext);
1251 READWRITE(nBlockPos);
1255 READWRITE(this->nVersion);
1256 READWRITE(hashPrev);
1257 READWRITE(hashMerkleRoot);
1263 uint256 GetBlockHash() const
1266 block.nVersion = nVersion;
1267 block.hashPrevBlock = hashPrev;
1268 block.hashMerkleRoot = hashMerkleRoot;
1269 block.nTime = nTime;
1270 block.nBits = nBits;
1271 block.nNonce = nNonce;
1272 return block.GetHash();
1276 std::string ToString() const
1278 std::string str = "CDiskBlockIndex(";
1279 str += CBlockIndex::ToString();
1280 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1281 GetBlockHash().ToString().c_str(),
1282 hashPrev.ToString().substr(0,20).c_str(),
1283 hashNext.ToString().substr(0,20).c_str());
1289 printf("%s\n", ToString().c_str());
1301 // Describes a place in the block chain to another node such that if the
1302 // other node doesn't have the same branch, it can find a recent common trunk.
1303 // The further back it is, the further before the fork it may be.
1308 std::vector<uint256> vHave;
1315 explicit CBlockLocator(const CBlockIndex* pindex)
1320 explicit CBlockLocator(uint256 hashBlock)
1322 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1323 if (mi != mapBlockIndex.end())
1327 CBlockLocator(const std::vector<uint256>& vHaveIn)
1334 if (!(nType & SER_GETHASH))
1335 READWRITE(nVersion);
1346 return vHave.empty();
1349 void Set(const CBlockIndex* pindex)
1355 vHave.push_back(pindex->GetBlockHash());
1357 // Exponentially larger steps back
1358 for (int i = 0; pindex && i < nStep; i++)
1359 pindex = pindex->pprev;
1360 if (vHave.size() > 10)
1363 vHave.push_back(hashGenesisBlock);
1366 int GetDistanceBack()
1368 // Retrace how far back it was in the sender's branch
1371 BOOST_FOREACH(const uint256& hash, vHave)
1373 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1374 if (mi != mapBlockIndex.end())
1376 CBlockIndex* pindex = (*mi).second;
1377 if (pindex->IsInMainChain())
1387 CBlockIndex* GetBlockIndex()
1389 // Find the first block the caller has in the main chain
1390 BOOST_FOREACH(const uint256& hash, vHave)
1392 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1393 if (mi != mapBlockIndex.end())
1395 CBlockIndex* pindex = (*mi).second;
1396 if (pindex->IsInMainChain())
1400 return pindexGenesisBlock;
1403 uint256 GetBlockHash()
1405 // Find the first block the caller has in the main chain
1406 BOOST_FOREACH(const uint256& hash, vHave)
1408 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1409 if (mi != mapBlockIndex.end())
1411 CBlockIndex* pindex = (*mi).second;
1412 if (pindex->IsInMainChain())
1416 return hashGenesisBlock;
1421 CBlockIndex* pindex = GetBlockIndex();
1424 return pindex->nHeight;
1437 // Alerts are for notifying old versions if they become too obsolete and
1438 // need to upgrade. The message is displayed in the status bar.
1439 // Alert messages are broadcast as a vector of signed data. Unserializing may
1440 // not read the entire buffer if the alert is for a newer version, but older
1441 // versions can still relay the original data.
1443 class CUnsignedAlert
1447 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1451 std::set<int> setCancel;
1452 int nMinVer; // lowest version inclusive
1453 int nMaxVer; // highest version inclusive
1454 std::set<std::string> setSubVer; // empty matches all
1458 std::string strComment;
1459 std::string strStatusBar;
1460 std::string strReserved;
1464 READWRITE(this->nVersion);
1465 nVersion = this->nVersion;
1466 READWRITE(nRelayUntil);
1467 READWRITE(nExpiration);
1470 READWRITE(setCancel);
1473 READWRITE(setSubVer);
1474 READWRITE(nPriority);
1476 READWRITE(strComment);
1477 READWRITE(strStatusBar);
1478 READWRITE(strReserved);
1495 strStatusBar.clear();
1496 strReserved.clear();
1499 std::string ToString() const
1501 std::string strSetCancel;
1502 BOOST_FOREACH(int n, setCancel)
1503 strSetCancel += strprintf("%d ", n);
1504 std::string strSetSubVer;
1505 BOOST_FOREACH(std::string str, setSubVer)
1506 strSetSubVer += "\"" + str + "\" ";
1510 " nRelayUntil = %"PRI64d"\n"
1511 " nExpiration = %"PRI64d"\n"
1519 " strComment = \"%s\"\n"
1520 " strStatusBar = \"%s\"\n"
1527 strSetCancel.c_str(),
1530 strSetSubVer.c_str(),
1533 strStatusBar.c_str());
1538 printf("%s", ToString().c_str());
1542 class CAlert : public CUnsignedAlert
1545 std::vector<unsigned char> vchMsg;
1546 std::vector<unsigned char> vchSig;
1561 CUnsignedAlert::SetNull();
1568 return (nExpiration == 0);
1571 uint256 GetHash() const
1573 return SerializeHash(*this);
1576 bool IsInEffect() const
1578 return (GetAdjustedTime() < nExpiration);
1581 bool Cancels(const CAlert& alert) const
1584 return false; // this was a no-op before 31403
1585 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1588 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1590 // TODO: rework for client-version-embedded-in-strSubVer ?
1591 return (IsInEffect() &&
1592 nMinVer <= nVersion && nVersion <= nMaxVer &&
1593 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1596 bool AppliesToMe() const
1598 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1601 bool RelayTo(CNode* pnode) const
1605 // returns true if wasn't already contained in the set
1606 if (pnode->setKnown.insert(GetHash()).second)
1608 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1610 GetAdjustedTime() < nRelayUntil)
1612 pnode->PushMessage("alert", *this);
1619 bool CheckSignature()
1622 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1623 return error("CAlert::CheckSignature() : SetPubKey failed");
1624 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1625 return error("CAlert::CheckSignature() : verify signature failed");
1627 // Now unserialize the data
1628 CDataStream sMsg(vchMsg);
1629 sMsg >> *(CUnsignedAlert*)this;
1633 bool ProcessAlert();