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 = 60004;
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;
1035 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1044 // The block chain is a tree shaped structure starting with the
1045 // genesis block at the root, with each block potentially having multiple
1046 // candidates to be the next block. pprev and pnext link a path through the
1047 // main/longest chain. A blockindex may have multiple pprev pointing back
1048 // to it, but pnext will only point forward to the longest branch, or will
1049 // be null if the block is not part of the longest chain.
1054 const uint256* phashBlock;
1058 unsigned int nBlockPos;
1060 CBigNum bnChainWork;
1064 uint256 hashMerkleRoot;
1067 unsigned int nNonce;
1087 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1093 nBlockPos = nBlockPosIn;
1097 nVersion = block.nVersion;
1098 hashMerkleRoot = block.hashMerkleRoot;
1099 nTime = block.nTime;
1100 nBits = block.nBits;
1101 nNonce = block.nNonce;
1104 CBlock GetBlockHeader() const
1107 block.nVersion = nVersion;
1109 block.hashPrevBlock = pprev->GetBlockHash();
1110 block.hashMerkleRoot = hashMerkleRoot;
1111 block.nTime = nTime;
1112 block.nBits = nBits;
1113 block.nNonce = nNonce;
1117 uint256 GetBlockHash() const
1122 int64 GetBlockTime() const
1124 return (int64)nTime;
1127 CBigNum GetBlockWork() const
1130 bnTarget.SetCompact(nBits);
1133 return (CBigNum(1)<<256) / (bnTarget+1);
1136 bool IsInMainChain() const
1138 return (pnext || this == pindexBest);
1141 bool CheckIndex() const
1143 return CheckProofOfWork(GetBlockHash(), nBits);
1146 bool EraseBlockFromDisk()
1148 // Open history file
1149 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1153 // Overwrite with empty null block
1161 enum { nMedianTimeSpan=11 };
1163 int64 GetMedianTimePast() const
1165 int64 pmedian[nMedianTimeSpan];
1166 int64* pbegin = &pmedian[nMedianTimeSpan];
1167 int64* pend = &pmedian[nMedianTimeSpan];
1169 const CBlockIndex* pindex = this;
1170 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1171 *(--pbegin) = pindex->GetBlockTime();
1173 std::sort(pbegin, pend);
1174 return pbegin[(pend - pbegin)/2];
1177 int64 GetMedianTime() const
1179 const CBlockIndex* pindex = this;
1180 for (int i = 0; i < nMedianTimeSpan/2; i++)
1183 return GetBlockTime();
1184 pindex = pindex->pnext;
1186 return pindex->GetMedianTimePast();
1191 std::string ToString() const
1193 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1194 pprev, pnext, nFile, nBlockPos, nHeight,
1195 hashMerkleRoot.ToString().substr(0,10).c_str(),
1196 GetBlockHash().ToString().substr(0,20).c_str());
1201 printf("%s\n", ToString().c_str());
1208 // Used to marshal pointers into hashes for db storage.
1210 class CDiskBlockIndex : public CBlockIndex
1222 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1224 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1225 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1230 if (!(nType & SER_GETHASH))
1231 READWRITE(nVersion);
1233 READWRITE(hashNext);
1235 READWRITE(nBlockPos);
1239 READWRITE(this->nVersion);
1240 READWRITE(hashPrev);
1241 READWRITE(hashMerkleRoot);
1247 uint256 GetBlockHash() const
1250 block.nVersion = nVersion;
1251 block.hashPrevBlock = hashPrev;
1252 block.hashMerkleRoot = hashMerkleRoot;
1253 block.nTime = nTime;
1254 block.nBits = nBits;
1255 block.nNonce = nNonce;
1256 return block.GetHash();
1260 std::string ToString() const
1262 std::string str = "CDiskBlockIndex(";
1263 str += CBlockIndex::ToString();
1264 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1265 GetBlockHash().ToString().c_str(),
1266 hashPrev.ToString().substr(0,20).c_str(),
1267 hashNext.ToString().substr(0,20).c_str());
1273 printf("%s\n", ToString().c_str());
1285 // Describes a place in the block chain to another node such that if the
1286 // other node doesn't have the same branch, it can find a recent common trunk.
1287 // The further back it is, the further before the fork it may be.
1292 std::vector<uint256> vHave;
1299 explicit CBlockLocator(const CBlockIndex* pindex)
1304 explicit CBlockLocator(uint256 hashBlock)
1306 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1307 if (mi != mapBlockIndex.end())
1311 CBlockLocator(const std::vector<uint256>& vHaveIn)
1318 if (!(nType & SER_GETHASH))
1319 READWRITE(nVersion);
1330 return vHave.empty();
1333 void Set(const CBlockIndex* pindex)
1339 vHave.push_back(pindex->GetBlockHash());
1341 // Exponentially larger steps back
1342 for (int i = 0; pindex && i < nStep; i++)
1343 pindex = pindex->pprev;
1344 if (vHave.size() > 10)
1347 vHave.push_back(hashGenesisBlock);
1350 int GetDistanceBack()
1352 // Retrace how far back it was in the sender's branch
1355 BOOST_FOREACH(const uint256& hash, vHave)
1357 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1358 if (mi != mapBlockIndex.end())
1360 CBlockIndex* pindex = (*mi).second;
1361 if (pindex->IsInMainChain())
1371 CBlockIndex* GetBlockIndex()
1373 // Find the first block the caller has in the main chain
1374 BOOST_FOREACH(const uint256& hash, vHave)
1376 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1377 if (mi != mapBlockIndex.end())
1379 CBlockIndex* pindex = (*mi).second;
1380 if (pindex->IsInMainChain())
1384 return pindexGenesisBlock;
1387 uint256 GetBlockHash()
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 hashGenesisBlock;
1405 CBlockIndex* pindex = GetBlockIndex();
1408 return pindex->nHeight;
1421 // Alerts are for notifying old versions if they become too obsolete and
1422 // need to upgrade. The message is displayed in the status bar.
1423 // Alert messages are broadcast as a vector of signed data. Unserializing may
1424 // not read the entire buffer if the alert is for a newer version, but older
1425 // versions can still relay the original data.
1427 class CUnsignedAlert
1431 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1435 std::set<int> setCancel;
1436 int nMinVer; // lowest version inclusive
1437 int nMaxVer; // highest version inclusive
1438 std::set<std::string> setSubVer; // empty matches all
1442 std::string strComment;
1443 std::string strStatusBar;
1444 std::string strReserved;
1448 READWRITE(this->nVersion);
1449 nVersion = this->nVersion;
1450 READWRITE(nRelayUntil);
1451 READWRITE(nExpiration);
1454 READWRITE(setCancel);
1457 READWRITE(setSubVer);
1458 READWRITE(nPriority);
1460 READWRITE(strComment);
1461 READWRITE(strStatusBar);
1462 READWRITE(strReserved);
1479 strStatusBar.clear();
1480 strReserved.clear();
1483 std::string ToString() const
1485 std::string strSetCancel;
1486 BOOST_FOREACH(int n, setCancel)
1487 strSetCancel += strprintf("%d ", n);
1488 std::string strSetSubVer;
1489 BOOST_FOREACH(std::string str, setSubVer)
1490 strSetSubVer += "\"" + str + "\" ";
1494 " nRelayUntil = %"PRI64d"\n"
1495 " nExpiration = %"PRI64d"\n"
1503 " strComment = \"%s\"\n"
1504 " strStatusBar = \"%s\"\n"
1511 strSetCancel.c_str(),
1514 strSetSubVer.c_str(),
1517 strStatusBar.c_str());
1522 printf("%s", ToString().c_str());
1526 class CAlert : public CUnsignedAlert
1529 std::vector<unsigned char> vchMsg;
1530 std::vector<unsigned char> vchSig;
1545 CUnsignedAlert::SetNull();
1552 return (nExpiration == 0);
1555 uint256 GetHash() const
1557 return SerializeHash(*this);
1560 bool IsInEffect() const
1562 return (GetAdjustedTime() < nExpiration);
1565 bool Cancels(const CAlert& alert) const
1568 return false; // this was a no-op before 31403
1569 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1572 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1574 // TODO: rework for client-version-embedded-in-strSubVer ?
1575 return (IsInEffect() &&
1576 nMinVer <= nVersion && nVersion <= nMaxVer &&
1577 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1580 bool AppliesToMe() const
1582 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1585 bool RelayTo(CNode* pnode) const
1589 // returns true if wasn't already contained in the set
1590 if (pnode->setKnown.insert(GetHash()).second)
1592 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1594 GetAdjustedTime() < nRelayUntil)
1596 pnode->PushMessage("alert", *this);
1603 bool CheckSignature()
1606 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1607 return error("CAlert::CheckSignature() : SetPubKey failed");
1608 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1609 return error("CAlert::CheckSignature() : verify signature failed");
1611 // Now unserialize the data
1612 CDataStream sMsg(vchMsg);
1613 sMsg >> *(CUnsignedAlert*)this;
1617 bool ProcessAlert();