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;
29 static const int CLIENT_VERSION = 60000;
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);
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());
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); }
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());
235 // An input of a transaction. It contains the location of the previous
236 // transaction's output that it claims and a signature that matches the
237 // output's public key.
244 unsigned int nSequence;
248 nSequence = std::numeric_limits<unsigned int>::max();
251 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
254 scriptSig = scriptSigIn;
255 nSequence = nSequenceIn;
258 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
260 prevout = COutPoint(hashPrevTx, nOut);
261 scriptSig = scriptSigIn;
262 nSequence = nSequenceIn;
268 READWRITE(scriptSig);
269 READWRITE(nSequence);
274 return (nSequence == std::numeric_limits<unsigned int>::max());
277 friend bool operator==(const CTxIn& a, const CTxIn& b)
279 return (a.prevout == b.prevout &&
280 a.scriptSig == b.scriptSig &&
281 a.nSequence == b.nSequence);
284 friend bool operator!=(const CTxIn& a, const CTxIn& b)
289 std::string ToString() const
292 str += strprintf("CTxIn(");
293 str += prevout.ToString();
294 if (prevout.IsNull())
295 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
297 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
298 if (nSequence != std::numeric_limits<unsigned int>::max())
299 str += strprintf(", nSequence=%u", nSequence);
306 printf("%s\n", ToString().c_str());
314 // An output of a transaction. It contains the public key that the next input
315 // must be able to sign with to claim it.
321 CScript scriptPubKey;
328 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
331 scriptPubKey = scriptPubKeyIn;
337 READWRITE(scriptPubKey);
343 scriptPubKey.clear();
348 return (nValue == -1);
351 uint256 GetHash() const
353 return SerializeHash(*this);
356 friend bool operator==(const CTxOut& a, const CTxOut& b)
358 return (a.nValue == b.nValue &&
359 a.scriptPubKey == b.scriptPubKey);
362 friend bool operator!=(const CTxOut& a, const CTxOut& b)
367 std::string ToString() const
369 if (scriptPubKey.size() < 6)
370 return "CTxOut(error)";
371 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
376 printf("%s\n", ToString().c_str());
390 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
393 // The basic transaction that is broadcasted on the network and contained in
394 // blocks. A transaction can contain multiple inputs and outputs.
400 std::vector<CTxIn> vin;
401 std::vector<CTxOut> vout;
402 unsigned int nLockTime;
404 // Denial-of-service detection:
406 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
415 READWRITE(this->nVersion);
416 nVersion = this->nVersion;
419 READWRITE(nLockTime);
428 nDoS = 0; // Denial-of-service prevention
433 return (vin.empty() && vout.empty());
436 uint256 GetHash() const
438 return SerializeHash(*this);
441 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
443 // Time based nLockTime implemented in 0.1.6
446 if (nBlockHeight == 0)
447 nBlockHeight = nBestHeight;
449 nBlockTime = GetAdjustedTime();
450 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
452 BOOST_FOREACH(const CTxIn& txin, vin)
458 bool IsNewerThan(const CTransaction& old) const
460 if (vin.size() != old.vin.size())
462 for (int i = 0; i < vin.size(); i++)
463 if (vin[i].prevout != old.vin[i].prevout)
467 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
468 for (int i = 0; i < vin.size(); i++)
470 if (vin[i].nSequence != old.vin[i].nSequence)
472 if (vin[i].nSequence <= nLowest)
475 nLowest = vin[i].nSequence;
477 if (old.vin[i].nSequence < nLowest)
480 nLowest = old.vin[i].nSequence;
487 bool IsCoinBase() const
489 return (vin.size() == 1 && vin[0].prevout.IsNull());
492 /** Check for standard transaction types
493 @return True if all outputs (scriptPubKeys) use only standard transaction forms
495 bool IsStandard() const;
497 /** Check for standard transaction types
498 @param[in] mapInputs Map of previous transactions that have outputs we're spending
499 @return True if all inputs (scriptSigs) use only standard transaction forms
500 @see CTransaction::FetchInputs
502 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
504 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
505 @return number of sigops this transaction's outputs will produce when spent
506 @see CTransaction::FetchInputs
508 int GetLegacySigOpCount() const;
510 /** Count ECDSA signature operations in pay-to-script-hash inputs.
512 @param[in] mapInputs Map of previous transactions that have outputs we're spending
513 @return maximum number of sigops required to validate this transaction's inputs
514 @see CTransaction::FetchInputs
516 int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
518 /** Amount of bitcoins spent by this transaction.
519 @return sum of all outputs (note: does not include fees)
521 int64 GetValueOut() const
524 BOOST_FOREACH(const CTxOut& txout, vout)
526 nValueOut += txout.nValue;
527 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
528 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
533 /** Amount of bitcoins coming in to this transaction
534 Note that lightweight clients may not know anything besides the hash of previous transactions,
535 so may not be able to calculate this.
537 @param[in] mapInputs Map of previous transactions that have outputs we're spending
538 @return Sum of value of all inputs (scriptSigs)
539 @see CTransaction::FetchInputs
541 int64 GetValueIn(const MapPrevTx& mapInputs) const;
543 static bool AllowFree(double dPriority)
545 // Large (in bytes) low-priority (new, small-coin) transactions
547 return dPriority > COIN * 144 / 250;
550 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
552 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
553 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
555 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
556 unsigned int nNewBlockSize = nBlockSize + nBytes;
557 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
563 // Transactions under 10K are free
564 // (about 4500bc if made of 50bc inputs)
570 // Free transaction area
571 if (nNewBlockSize < 27000)
576 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
577 if (nMinFee < nBaseFee)
578 BOOST_FOREACH(const CTxOut& txout, vout)
579 if (txout.nValue < CENT)
582 // Raise the price as the block approaches full
583 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
585 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
587 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
590 if (!MoneyRange(nMinFee))
596 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
598 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
600 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
603 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
604 return error("CTransaction::ReadFromDisk() : fseek failed");
607 // Return file pointer
610 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
611 return error("CTransaction::ReadFromDisk() : second fseek failed");
612 *pfileRet = filein.release();
617 friend bool operator==(const CTransaction& a, const CTransaction& b)
619 return (a.nVersion == b.nVersion &&
622 a.nLockTime == b.nLockTime);
625 friend bool operator!=(const CTransaction& a, const CTransaction& b)
631 std::string ToString() const
634 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
635 GetHash().ToString().substr(0,10).c_str(),
640 for (int i = 0; i < vin.size(); i++)
641 str += " " + vin[i].ToString() + "\n";
642 for (int i = 0; i < vout.size(); i++)
643 str += " " + vout[i].ToString() + "\n";
649 printf("%s", ToString().c_str());
653 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
654 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
655 bool ReadFromDisk(COutPoint prevout);
656 bool DisconnectInputs(CTxDB& txdb);
658 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
660 @param[in] txdb Transaction database
661 @param[in] mapTestPool List of pending changes to the transaction index database
662 @param[in] fBlock True if being called to add a new best-block to the chain
663 @param[in] fMiner True if being called by CreateNewBlock
664 @param[out] inputsRet Pointers to this transaction's inputs
665 @param[out] fInvalid returns true if transaction is invalid
666 @return Returns true if all inputs are in txdb or mapTestPool
668 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
669 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
671 /** Sanity check previous transactions, then, if all checks succeed,
672 mark them as spent by this transaction.
674 @param[in] inputs Previous transactions (from FetchInputs)
675 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
676 @param[in] posThisTx Position of this transaction on disk
677 @param[in] pindexBlock
678 @param[in] fBlock true if called from ConnectBlock
679 @param[in] fMiner true if called from CreateNewBlock
680 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
681 @return Returns true if all checks succeed
683 bool ConnectInputs(MapPrevTx inputs,
684 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
685 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
686 bool ClientConnectInputs();
687 bool CheckTransaction() const;
688 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
689 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
692 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
693 bool AddToMemoryPoolUnchecked();
695 bool RemoveFromMemoryPool();
703 // A transaction with a merkle branch linking it to the block chain
705 class CMerkleTx : public CTransaction
709 std::vector<uint256> vMerkleBranch;
713 mutable char fMerkleVerified;
721 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
730 fMerkleVerified = false;
736 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
737 nVersion = this->nVersion;
738 READWRITE(hashBlock);
739 READWRITE(vMerkleBranch);
744 int SetMerkleBranch(const CBlock* pblock=NULL);
745 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
746 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
747 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
748 int GetBlocksToMaturity() const;
749 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
750 bool AcceptToMemoryPool();
757 // A txdb record that contains the disk location of a transaction and the
758 // locations of transactions that spend its outputs. vSpent is really only
759 // used as a flag, but having the location is very helpful for debugging.
765 std::vector<CDiskTxPos> vSpent;
772 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
775 vSpent.resize(nOutputs);
780 if (!(nType & SER_GETHASH))
797 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
799 return (a.pos == b.pos &&
800 a.vSpent == b.vSpent);
803 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
807 int GetDepthInMainChain() const;
816 // Nodes collect new transactions into a block, hash them into a hash tree,
817 // and scan through nonce values to make the block's hash satisfy proof-of-work
818 // requirements. When they solve the proof-of-work, they broadcast the block
819 // to everyone and the block is added to the block chain. The first transaction
820 // in the block is a special one that creates a new coin owned by the creator
823 // Blocks are appended to blk0001.dat files on disk. Their location on disk
824 // is indexed by CBlockIndex objects in memory.
831 uint256 hashPrevBlock;
832 uint256 hashMerkleRoot;
838 std::vector<CTransaction> vtx;
841 mutable std::vector<uint256> vMerkleTree;
843 // Denial-of-service detection:
845 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
854 READWRITE(this->nVersion);
855 nVersion = this->nVersion;
856 READWRITE(hashPrevBlock);
857 READWRITE(hashMerkleRoot);
862 // ConnectBlock depends on vtx being last so it can calculate offset
863 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
866 const_cast<CBlock*>(this)->vtx.clear();
887 uint256 GetHash() const
889 return Hash(BEGIN(nVersion), END(nNonce));
892 int64 GetBlockTime() const
897 void UpdateTime(const CBlockIndex* pindexPrev);
900 uint256 BuildMerkleTree() const
903 BOOST_FOREACH(const CTransaction& tx, vtx)
904 vMerkleTree.push_back(tx.GetHash());
906 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
908 for (int i = 0; i < nSize; i += 2)
910 int i2 = std::min(i+1, nSize-1);
911 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
912 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
916 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
919 std::vector<uint256> GetMerkleBranch(int nIndex) const
921 if (vMerkleTree.empty())
923 std::vector<uint256> vMerkleBranch;
925 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
927 int i = std::min(nIndex^1, nSize-1);
928 vMerkleBranch.push_back(vMerkleTree[j+i]);
932 return vMerkleBranch;
935 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
939 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
942 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
944 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
951 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
953 // Open history file to append
954 CAutoFile fileout = AppendBlockFile(nFileRet);
956 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
958 // Write index header
959 unsigned int nSize = fileout.GetSerializeSize(*this);
960 fileout << FLATDATA(pchMessageStart) << nSize;
963 nBlockPosRet = ftell(fileout);
964 if (nBlockPosRet == -1)
965 return error("CBlock::WriteToDisk() : ftell failed");
968 // Flush stdio buffers and commit to disk before returning
970 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
973 _commit(_fileno(fileout));
975 fsync(fileno(fileout));
982 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
986 // Open history file to read
987 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
989 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
990 if (!fReadTransactions)
991 filein.nType |= SER_BLOCKHEADERONLY;
997 if (!CheckProofOfWork(GetHash(), nBits))
998 return error("CBlock::ReadFromDisk() : errors in block header");
1007 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1008 GetHash().ToString().substr(0,20).c_str(),
1010 hashPrevBlock.ToString().substr(0,20).c_str(),
1011 hashMerkleRoot.ToString().substr(0,10).c_str(),
1012 nTime, nBits, nNonce,
1014 for (int i = 0; i < vtx.size(); i++)
1019 printf(" vMerkleTree: ");
1020 for (int i = 0; i < vMerkleTree.size(); i++)
1021 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1026 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1027 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1028 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1029 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1030 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1031 bool CheckBlock() const;
1041 // The block chain is a tree shaped structure starting with the
1042 // genesis block at the root, with each block potentially having multiple
1043 // candidates to be the next block. pprev and pnext link a path through the
1044 // main/longest chain. A blockindex may have multiple pprev pointing back
1045 // to it, but pnext will only point forward to the longest branch, or will
1046 // be null if the block is not part of the longest chain.
1051 const uint256* phashBlock;
1055 unsigned int nBlockPos;
1057 CBigNum bnChainWork;
1061 uint256 hashMerkleRoot;
1064 unsigned int nNonce;
1084 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1090 nBlockPos = nBlockPosIn;
1094 nVersion = block.nVersion;
1095 hashMerkleRoot = block.hashMerkleRoot;
1096 nTime = block.nTime;
1097 nBits = block.nBits;
1098 nNonce = block.nNonce;
1101 CBlock GetBlockHeader() const
1104 block.nVersion = nVersion;
1106 block.hashPrevBlock = pprev->GetBlockHash();
1107 block.hashMerkleRoot = hashMerkleRoot;
1108 block.nTime = nTime;
1109 block.nBits = nBits;
1110 block.nNonce = nNonce;
1114 uint256 GetBlockHash() const
1119 int64 GetBlockTime() const
1121 return (int64)nTime;
1124 CBigNum GetBlockWork() const
1127 bnTarget.SetCompact(nBits);
1130 return (CBigNum(1)<<256) / (bnTarget+1);
1133 bool IsInMainChain() const
1135 return (pnext || this == pindexBest);
1138 bool CheckIndex() const
1140 return CheckProofOfWork(GetBlockHash(), nBits);
1143 bool EraseBlockFromDisk()
1145 // Open history file
1146 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1150 // Overwrite with empty null block
1158 enum { nMedianTimeSpan=11 };
1160 int64 GetMedianTimePast() const
1162 int64 pmedian[nMedianTimeSpan];
1163 int64* pbegin = &pmedian[nMedianTimeSpan];
1164 int64* pend = &pmedian[nMedianTimeSpan];
1166 const CBlockIndex* pindex = this;
1167 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1168 *(--pbegin) = pindex->GetBlockTime();
1170 std::sort(pbegin, pend);
1171 return pbegin[(pend - pbegin)/2];
1174 int64 GetMedianTime() const
1176 const CBlockIndex* pindex = this;
1177 for (int i = 0; i < nMedianTimeSpan/2; i++)
1180 return GetBlockTime();
1181 pindex = pindex->pnext;
1183 return pindex->GetMedianTimePast();
1188 std::string ToString() const
1190 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1191 pprev, pnext, nFile, nBlockPos, nHeight,
1192 hashMerkleRoot.ToString().substr(0,10).c_str(),
1193 GetBlockHash().ToString().substr(0,20).c_str());
1198 printf("%s\n", ToString().c_str());
1205 // Used to marshal pointers into hashes for db storage.
1207 class CDiskBlockIndex : public CBlockIndex
1219 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1221 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1222 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1227 if (!(nType & SER_GETHASH))
1228 READWRITE(nVersion);
1230 READWRITE(hashNext);
1232 READWRITE(nBlockPos);
1236 READWRITE(this->nVersion);
1237 READWRITE(hashPrev);
1238 READWRITE(hashMerkleRoot);
1244 uint256 GetBlockHash() const
1247 block.nVersion = nVersion;
1248 block.hashPrevBlock = hashPrev;
1249 block.hashMerkleRoot = hashMerkleRoot;
1250 block.nTime = nTime;
1251 block.nBits = nBits;
1252 block.nNonce = nNonce;
1253 return block.GetHash();
1257 std::string ToString() const
1259 std::string str = "CDiskBlockIndex(";
1260 str += CBlockIndex::ToString();
1261 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1262 GetBlockHash().ToString().c_str(),
1263 hashPrev.ToString().substr(0,20).c_str(),
1264 hashNext.ToString().substr(0,20).c_str());
1270 printf("%s\n", ToString().c_str());
1282 // Describes a place in the block chain to another node such that if the
1283 // other node doesn't have the same branch, it can find a recent common trunk.
1284 // The further back it is, the further before the fork it may be.
1289 std::vector<uint256> vHave;
1296 explicit CBlockLocator(const CBlockIndex* pindex)
1301 explicit CBlockLocator(uint256 hashBlock)
1303 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1304 if (mi != mapBlockIndex.end())
1308 CBlockLocator(const std::vector<uint256>& vHaveIn)
1315 if (!(nType & SER_GETHASH))
1316 READWRITE(nVersion);
1327 return vHave.empty();
1330 void Set(const CBlockIndex* pindex)
1336 vHave.push_back(pindex->GetBlockHash());
1338 // Exponentially larger steps back
1339 for (int i = 0; pindex && i < nStep; i++)
1340 pindex = pindex->pprev;
1341 if (vHave.size() > 10)
1344 vHave.push_back(hashGenesisBlock);
1347 int GetDistanceBack()
1349 // Retrace how far back it was in the sender's branch
1352 BOOST_FOREACH(const uint256& hash, vHave)
1354 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1355 if (mi != mapBlockIndex.end())
1357 CBlockIndex* pindex = (*mi).second;
1358 if (pindex->IsInMainChain())
1368 CBlockIndex* GetBlockIndex()
1370 // Find the first block the caller has in the main chain
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())
1381 return pindexGenesisBlock;
1384 uint256 GetBlockHash()
1386 // Find the first block the caller has in the main chain
1387 BOOST_FOREACH(const uint256& hash, vHave)
1389 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1390 if (mi != mapBlockIndex.end())
1392 CBlockIndex* pindex = (*mi).second;
1393 if (pindex->IsInMainChain())
1397 return hashGenesisBlock;
1402 CBlockIndex* pindex = GetBlockIndex();
1405 return pindex->nHeight;
1418 // Alerts are for notifying old versions if they become too obsolete and
1419 // need to upgrade. The message is displayed in the status bar.
1420 // Alert messages are broadcast as a vector of signed data. Unserializing may
1421 // not read the entire buffer if the alert is for a newer version, but older
1422 // versions can still relay the original data.
1424 class CUnsignedAlert
1428 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1432 std::set<int> setCancel;
1433 int nMinVer; // lowest version inclusive
1434 int nMaxVer; // highest version inclusive
1435 std::set<std::string> setSubVer; // empty matches all
1439 std::string strComment;
1440 std::string strStatusBar;
1441 std::string strReserved;
1445 READWRITE(this->nVersion);
1446 nVersion = this->nVersion;
1447 READWRITE(nRelayUntil);
1448 READWRITE(nExpiration);
1451 READWRITE(setCancel);
1454 READWRITE(setSubVer);
1455 READWRITE(nPriority);
1457 READWRITE(strComment);
1458 READWRITE(strStatusBar);
1459 READWRITE(strReserved);
1476 strStatusBar.clear();
1477 strReserved.clear();
1480 std::string ToString() const
1482 std::string strSetCancel;
1483 BOOST_FOREACH(int n, setCancel)
1484 strSetCancel += strprintf("%d ", n);
1485 std::string strSetSubVer;
1486 BOOST_FOREACH(std::string str, setSubVer)
1487 strSetSubVer += "\"" + str + "\" ";
1491 " nRelayUntil = %"PRI64d"\n"
1492 " nExpiration = %"PRI64d"\n"
1500 " strComment = \"%s\"\n"
1501 " strStatusBar = \"%s\"\n"
1508 strSetCancel.c_str(),
1511 strSetSubVer.c_str(),
1514 strStatusBar.c_str());
1519 printf("%s", ToString().c_str());
1523 class CAlert : public CUnsignedAlert
1526 std::vector<unsigned char> vchMsg;
1527 std::vector<unsigned char> vchSig;
1542 CUnsignedAlert::SetNull();
1549 return (nExpiration == 0);
1552 uint256 GetHash() const
1554 return SerializeHash(*this);
1557 bool IsInEffect() const
1559 return (GetAdjustedTime() < nExpiration);
1562 bool Cancels(const CAlert& alert) const
1565 return false; // this was a no-op before 31403
1566 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1569 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1571 // TODO: rework for client-version-embedded-in-strSubVer ?
1572 return (IsInEffect() &&
1573 nMinVer <= nVersion && nVersion <= nMaxVer &&
1574 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1577 bool AppliesToMe() const
1579 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1582 bool RelayTo(CNode* pnode) const
1586 // returns true if wasn't already contained in the set
1587 if (pnode->setKnown.insert(GetHash()).second)
1589 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1591 GetAdjustedTime() < nRelayUntil)
1593 pnode->PushMessage("alert", *this);
1600 bool CheckSignature()
1603 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1604 return error("CAlert::CheckSignature() : SetPubKey failed");
1605 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1606 return error("CAlert::CheckSignature() : verify signature failed");
1608 // Now unserialize the data
1609 CDataStream sMsg(vchMsg);
1610 sMsg >> *(CUnsignedAlert*)this;
1614 bool ProcessAlert();