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.
13 #include <io.h> /* for _commit */
26 class CRequestTracker;
29 static const unsigned int MAX_BLOCK_SIZE = 1000000;
30 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
31 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
32 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
33 static const int64 MIN_TX_FEE = 50000;
34 static const int64 MIN_RELAY_TX_FEE = 10000;
35 static const int64 MAX_MONEY = 21000000 * COIN;
36 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
37 static const int COINBASE_MATURITY = 100;
38 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
39 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
41 static const int fHaveUPnP = true;
43 static const int fHaveUPnP = false;
47 extern CScript COINBASE_FLAGS;
54 extern CCriticalSection cs_main;
55 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
56 extern uint256 hashGenesisBlock;
57 extern CBlockIndex* pindexGenesisBlock;
58 extern int nBestHeight;
59 extern CBigNum bnBestChainWork;
60 extern CBigNum bnBestInvalidWork;
61 extern uint256 hashBestChain;
62 extern CBlockIndex* pindexBest;
63 extern unsigned int nTransactionsUpdated;
64 extern uint64 nLastBlockTx;
65 extern uint64 nLastBlockSize;
66 extern const std::string strMessageMagic;
67 extern double dHashesPerSec;
68 extern int64 nHPSTimerStart;
69 extern int64 nTimeBestReceived;
70 extern CCriticalSection cs_setpwalletRegistered;
71 extern std::set<CWallet*> setpwalletRegistered;
74 extern int64 nTransactionFee;
84 void RegisterWallet(CWallet* pwalletIn);
85 void UnregisterWallet(CWallet* pwalletIn);
86 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
87 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
88 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
89 FILE* AppendBlockFile(unsigned int& nFileRet);
90 bool LoadBlockIndex(bool fAllowNew=true);
91 void PrintBlockTree();
92 bool ProcessMessages(CNode* pfrom);
93 bool SendMessages(CNode* pto, bool fSendTrickle);
94 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
95 CBlock* CreateNewBlock(CReserveKey& reservekey);
96 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
97 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
98 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
99 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
100 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
101 int GetNumBlocksOfPeers();
102 bool IsInitialBlockDownload();
103 std::string GetWarnings(std::string strFor);
116 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
118 /** Position on disk for a particular transaction. */
123 unsigned int nBlockPos;
131 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
134 nBlockPos = nBlockPosIn;
138 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
139 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
140 bool IsNull() const { return (nFile == -1); }
142 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
144 return (a.nFile == b.nFile &&
145 a.nBlockPos == b.nBlockPos &&
146 a.nTxPos == b.nTxPos);
149 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
154 std::string ToString() const
159 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
164 printf("%s", ToString().c_str());
170 /** An inpoint - a combination of a transaction and an index n into its vin */
177 CInPoint() { SetNull(); }
178 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
179 void SetNull() { ptx = NULL; n = -1; }
180 bool IsNull() const { return (ptx == NULL && n == -1); }
185 /** An outpoint - a combination of a transaction hash and an index n into its vout */
192 COutPoint() { SetNull(); }
193 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
194 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
195 void SetNull() { hash = 0; n = -1; }
196 bool IsNull() const { return (hash == 0 && n == -1); }
198 friend bool operator<(const COutPoint& a, const COutPoint& b)
200 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
203 friend bool operator==(const COutPoint& a, const COutPoint& b)
205 return (a.hash == b.hash && a.n == b.n);
208 friend bool operator!=(const COutPoint& a, const COutPoint& b)
213 std::string ToString() const
215 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
220 printf("%s\n", ToString().c_str());
227 /** An input of a transaction. It contains the location of the previous
228 * transaction's output that it claims and a signature that matches the
229 * output's public key.
236 unsigned int nSequence;
240 nSequence = std::numeric_limits<unsigned int>::max();
243 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
246 scriptSig = scriptSigIn;
247 nSequence = nSequenceIn;
250 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
252 prevout = COutPoint(hashPrevTx, nOut);
253 scriptSig = scriptSigIn;
254 nSequence = nSequenceIn;
260 READWRITE(scriptSig);
261 READWRITE(nSequence);
266 return (nSequence == std::numeric_limits<unsigned int>::max());
269 friend bool operator==(const CTxIn& a, const CTxIn& b)
271 return (a.prevout == b.prevout &&
272 a.scriptSig == b.scriptSig &&
273 a.nSequence == b.nSequence);
276 friend bool operator!=(const CTxIn& a, const CTxIn& b)
281 std::string ToString() const
285 str += prevout.ToString();
286 if (prevout.IsNull())
287 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
289 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
290 if (nSequence != std::numeric_limits<unsigned int>::max())
291 str += strprintf(", nSequence=%u", nSequence);
298 printf("%s\n", ToString().c_str());
305 /** An output of a transaction. It contains the public key that the next input
306 * must be able to sign with to claim it.
312 CScript scriptPubKey;
319 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
322 scriptPubKey = scriptPubKeyIn;
328 READWRITE(scriptPubKey);
334 scriptPubKey.clear();
339 return (nValue == -1);
342 uint256 GetHash() const
344 return SerializeHash(*this);
347 friend bool operator==(const CTxOut& a, const CTxOut& b)
349 return (a.nValue == b.nValue &&
350 a.scriptPubKey == b.scriptPubKey);
353 friend bool operator!=(const CTxOut& a, const CTxOut& b)
358 std::string ToString() const
360 if (scriptPubKey.size() < 6)
361 return "CTxOut(error)";
362 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
367 printf("%s\n", ToString().c_str());
381 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
383 /** The basic transaction that is broadcasted on the network and contained in
384 * blocks. A transaction can contain multiple inputs and outputs.
390 std::vector<CTxIn> vin;
391 std::vector<CTxOut> vout;
392 unsigned int nLockTime;
394 // Denial-of-service detection:
396 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
405 READWRITE(this->nVersion);
406 nVersion = this->nVersion;
409 READWRITE(nLockTime);
418 nDoS = 0; // Denial-of-service prevention
423 return (vin.empty() && vout.empty());
426 uint256 GetHash() const
428 return SerializeHash(*this);
431 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
433 // Time based nLockTime implemented in 0.1.6
436 if (nBlockHeight == 0)
437 nBlockHeight = nBestHeight;
439 nBlockTime = GetAdjustedTime();
440 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
442 BOOST_FOREACH(const CTxIn& txin, vin)
448 bool IsNewerThan(const CTransaction& old) const
450 if (vin.size() != old.vin.size())
452 for (unsigned int i = 0; i < vin.size(); i++)
453 if (vin[i].prevout != old.vin[i].prevout)
457 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
458 for (unsigned int i = 0; i < vin.size(); i++)
460 if (vin[i].nSequence != old.vin[i].nSequence)
462 if (vin[i].nSequence <= nLowest)
465 nLowest = vin[i].nSequence;
467 if (old.vin[i].nSequence < nLowest)
470 nLowest = old.vin[i].nSequence;
477 bool IsCoinBase() const
479 return (vin.size() == 1 && vin[0].prevout.IsNull());
482 /** Check for standard transaction types
483 @return True if all outputs (scriptPubKeys) use only standard transaction forms
485 bool IsStandard() const;
487 /** Check for standard transaction types
488 @param[in] mapInputs Map of previous transactions that have outputs we're spending
489 @return True if all inputs (scriptSigs) use only standard transaction forms
490 @see CTransaction::FetchInputs
492 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
494 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
495 @return number of sigops this transaction's outputs will produce when spent
496 @see CTransaction::FetchInputs
498 unsigned int GetLegacySigOpCount() const;
500 /** Count ECDSA signature operations in pay-to-script-hash inputs.
502 @param[in] mapInputs Map of previous transactions that have outputs we're spending
503 @return maximum number of sigops required to validate this transaction's inputs
504 @see CTransaction::FetchInputs
506 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
508 /** Amount of bitcoins spent by this transaction.
509 @return sum of all outputs (note: does not include fees)
511 int64 GetValueOut() const
514 BOOST_FOREACH(const CTxOut& txout, vout)
516 nValueOut += txout.nValue;
517 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
518 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
523 /** Amount of bitcoins coming in to this transaction
524 Note that lightweight clients may not know anything besides the hash of previous transactions,
525 so may not be able to calculate this.
527 @param[in] mapInputs Map of previous transactions that have outputs we're spending
528 @return Sum of value of all inputs (scriptSigs)
529 @see CTransaction::FetchInputs
531 int64 GetValueIn(const MapPrevTx& mapInputs) const;
533 static bool AllowFree(double dPriority)
535 // Large (in bytes) low-priority (new, small-coin) transactions
537 return dPriority > COIN * 144 / 250;
540 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
542 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
543 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
545 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
546 unsigned int nNewBlockSize = nBlockSize + nBytes;
547 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
553 // Transactions under 10K are free
554 // (about 4500bc if made of 50bc inputs)
560 // Free transaction area
561 if (nNewBlockSize < 27000)
566 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
567 if (nMinFee < nBaseFee)
569 BOOST_FOREACH(const CTxOut& txout, vout)
570 if (txout.nValue < CENT)
574 // Raise the price as the block approaches full
575 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
577 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
579 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
582 if (!MoneyRange(nMinFee))
588 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
590 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
592 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
595 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
596 return error("CTransaction::ReadFromDisk() : fseek failed");
599 // Return file pointer
602 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
603 return error("CTransaction::ReadFromDisk() : second fseek failed");
604 *pfileRet = filein.release();
609 friend bool operator==(const CTransaction& a, const CTransaction& b)
611 return (a.nVersion == b.nVersion &&
614 a.nLockTime == b.nLockTime);
617 friend bool operator!=(const CTransaction& a, const CTransaction& b)
623 std::string ToString() const
626 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
627 GetHash().ToString().substr(0,10).c_str(),
632 for (unsigned int i = 0; i < vin.size(); i++)
633 str += " " + vin[i].ToString() + "\n";
634 for (unsigned int i = 0; i < vout.size(); i++)
635 str += " " + vout[i].ToString() + "\n";
641 printf("%s", ToString().c_str());
645 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
646 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
647 bool ReadFromDisk(COutPoint prevout);
648 bool DisconnectInputs(CTxDB& txdb);
650 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
652 @param[in] txdb Transaction database
653 @param[in] mapTestPool List of pending changes to the transaction index database
654 @param[in] fBlock True if being called to add a new best-block to the chain
655 @param[in] fMiner True if being called by CreateNewBlock
656 @param[out] inputsRet Pointers to this transaction's inputs
657 @param[out] fInvalid returns true if transaction is invalid
658 @return Returns true if all inputs are in txdb or mapTestPool
660 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
661 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
663 /** Sanity check previous transactions, then, if all checks succeed,
664 mark them as spent by this transaction.
666 @param[in] inputs Previous transactions (from FetchInputs)
667 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
668 @param[in] posThisTx Position of this transaction on disk
669 @param[in] pindexBlock
670 @param[in] fBlock true if called from ConnectBlock
671 @param[in] fMiner true if called from CreateNewBlock
672 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
673 @return Returns true if all checks succeed
675 bool ConnectInputs(MapPrevTx inputs,
676 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
677 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
678 bool ClientConnectInputs();
679 bool CheckTransaction() const;
680 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
683 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
690 /** A transaction with a merkle branch linking it to the block chain. */
691 class CMerkleTx : public CTransaction
695 std::vector<uint256> vMerkleBranch;
699 mutable bool fMerkleVerified;
707 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
716 fMerkleVerified = false;
722 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
723 nVersion = this->nVersion;
724 READWRITE(hashBlock);
725 READWRITE(vMerkleBranch);
730 int SetMerkleBranch(const CBlock* pblock=NULL);
731 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
732 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
733 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
734 int GetBlocksToMaturity() const;
735 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
736 bool AcceptToMemoryPool();
742 /** A txdb record that contains the disk location of a transaction and the
743 * locations of transactions that spend its outputs. vSpent is really only
744 * used as a flag, but having the location is very helpful for debugging.
750 std::vector<CDiskTxPos> vSpent;
757 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
760 vSpent.resize(nOutputs);
765 if (!(nType & SER_GETHASH))
782 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
784 return (a.pos == b.pos &&
785 a.vSpent == b.vSpent);
788 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
792 int GetDepthInMainChain() const;
800 /** Nodes collect new transactions into a block, hash them into a hash tree,
801 * and scan through nonce values to make the block's hash satisfy proof-of-work
802 * requirements. When they solve the proof-of-work, they broadcast the block
803 * to everyone and the block is added to the block chain. The first transaction
804 * in the block is a special one that creates a new coin owned by the creator
807 * Blocks are appended to blk0001.dat files on disk. Their location on disk
808 * is indexed by CBlockIndex objects in memory.
815 uint256 hashPrevBlock;
816 uint256 hashMerkleRoot;
822 std::vector<CTransaction> vtx;
825 mutable std::vector<uint256> vMerkleTree;
827 // Denial-of-service detection:
829 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
838 READWRITE(this->nVersion);
839 nVersion = this->nVersion;
840 READWRITE(hashPrevBlock);
841 READWRITE(hashMerkleRoot);
846 // ConnectBlock depends on vtx being last so it can calculate offset
847 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
850 const_cast<CBlock*>(this)->vtx.clear();
871 uint256 GetHash() const
873 return Hash(BEGIN(nVersion), END(nNonce));
876 int64 GetBlockTime() const
881 void UpdateTime(const CBlockIndex* pindexPrev);
884 uint256 BuildMerkleTree() const
887 BOOST_FOREACH(const CTransaction& tx, vtx)
888 vMerkleTree.push_back(tx.GetHash());
890 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
892 for (int i = 0; i < nSize; i += 2)
894 int i2 = std::min(i+1, nSize-1);
895 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
896 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
900 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
903 std::vector<uint256> GetMerkleBranch(int nIndex) const
905 if (vMerkleTree.empty())
907 std::vector<uint256> vMerkleBranch;
909 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
911 int i = std::min(nIndex^1, nSize-1);
912 vMerkleBranch.push_back(vMerkleTree[j+i]);
916 return vMerkleBranch;
919 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
923 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
926 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
928 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
935 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
937 // Open history file to append
938 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
940 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
942 // Write index header
943 unsigned int nSize = fileout.GetSerializeSize(*this);
944 fileout << FLATDATA(pchMessageStart) << nSize;
947 nBlockPosRet = ftell(fileout);
948 if (nBlockPosRet == -1)
949 return error("CBlock::WriteToDisk() : ftell failed");
952 // Flush stdio buffers and commit to disk before returning
954 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
957 _commit(_fileno(fileout));
959 fsync(fileno(fileout));
966 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
970 // Open history file to read
971 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
973 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
974 if (!fReadTransactions)
975 filein.nType |= SER_BLOCKHEADERONLY;
981 if (!CheckProofOfWork(GetHash(), nBits))
982 return error("CBlock::ReadFromDisk() : errors in block header");
991 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
992 GetHash().ToString().substr(0,20).c_str(),
994 hashPrevBlock.ToString().substr(0,20).c_str(),
995 hashMerkleRoot.ToString().substr(0,10).c_str(),
996 nTime, nBits, nNonce,
998 for (unsigned int i = 0; i < vtx.size(); i++)
1003 printf(" vMerkleTree: ");
1004 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1005 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1010 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1011 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1012 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1013 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1014 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1015 bool CheckBlock() const;
1019 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1027 /** The block chain is a tree shaped structure starting with the
1028 * genesis block at the root, with each block potentially having multiple
1029 * candidates to be the next block. pprev and pnext link a path through the
1030 * main/longest chain. A blockindex may have multiple pprev pointing back
1031 * to it, but pnext will only point forward to the longest branch, or will
1032 * be null if the block is not part of the longest chain.
1037 const uint256* phashBlock;
1041 unsigned int nBlockPos;
1043 CBigNum bnChainWork;
1047 uint256 hashMerkleRoot;
1050 unsigned int nNonce;
1070 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1076 nBlockPos = nBlockPosIn;
1080 nVersion = block.nVersion;
1081 hashMerkleRoot = block.hashMerkleRoot;
1082 nTime = block.nTime;
1083 nBits = block.nBits;
1084 nNonce = block.nNonce;
1087 CBlock GetBlockHeader() const
1090 block.nVersion = nVersion;
1092 block.hashPrevBlock = pprev->GetBlockHash();
1093 block.hashMerkleRoot = hashMerkleRoot;
1094 block.nTime = nTime;
1095 block.nBits = nBits;
1096 block.nNonce = nNonce;
1100 uint256 GetBlockHash() const
1105 int64 GetBlockTime() const
1107 return (int64)nTime;
1110 CBigNum GetBlockWork() const
1113 bnTarget.SetCompact(nBits);
1116 return (CBigNum(1)<<256) / (bnTarget+1);
1119 bool IsInMainChain() const
1121 return (pnext || this == pindexBest);
1124 bool CheckIndex() const
1126 return CheckProofOfWork(GetBlockHash(), nBits);
1129 bool EraseBlockFromDisk()
1131 // Open history file
1132 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1136 // Overwrite with empty null block
1144 enum { nMedianTimeSpan=11 };
1146 int64 GetMedianTimePast() const
1148 int64 pmedian[nMedianTimeSpan];
1149 int64* pbegin = &pmedian[nMedianTimeSpan];
1150 int64* pend = &pmedian[nMedianTimeSpan];
1152 const CBlockIndex* pindex = this;
1153 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1154 *(--pbegin) = pindex->GetBlockTime();
1156 std::sort(pbegin, pend);
1157 return pbegin[(pend - pbegin)/2];
1160 int64 GetMedianTime() const
1162 const CBlockIndex* pindex = this;
1163 for (int i = 0; i < nMedianTimeSpan/2; i++)
1166 return GetBlockTime();
1167 pindex = pindex->pnext;
1169 return pindex->GetMedianTimePast();
1174 std::string ToString() const
1176 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1177 pprev, pnext, nFile, nBlockPos, nHeight,
1178 hashMerkleRoot.ToString().substr(0,10).c_str(),
1179 GetBlockHash().ToString().substr(0,20).c_str());
1184 printf("%s\n", ToString().c_str());
1190 /** Used to marshal pointers into hashes for db storage. */
1191 class CDiskBlockIndex : public CBlockIndex
1203 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1205 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1206 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1211 if (!(nType & SER_GETHASH))
1212 READWRITE(nVersion);
1214 READWRITE(hashNext);
1216 READWRITE(nBlockPos);
1220 READWRITE(this->nVersion);
1221 READWRITE(hashPrev);
1222 READWRITE(hashMerkleRoot);
1228 uint256 GetBlockHash() const
1231 block.nVersion = nVersion;
1232 block.hashPrevBlock = hashPrev;
1233 block.hashMerkleRoot = hashMerkleRoot;
1234 block.nTime = nTime;
1235 block.nBits = nBits;
1236 block.nNonce = nNonce;
1237 return block.GetHash();
1241 std::string ToString() const
1243 std::string str = "CDiskBlockIndex(";
1244 str += CBlockIndex::ToString();
1245 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1246 GetBlockHash().ToString().c_str(),
1247 hashPrev.ToString().substr(0,20).c_str(),
1248 hashNext.ToString().substr(0,20).c_str());
1254 printf("%s\n", ToString().c_str());
1265 /** Describes a place in the block chain to another node such that if the
1266 * other node doesn't have the same branch, it can find a recent common trunk.
1267 * The further back it is, the further before the fork it may be.
1272 std::vector<uint256> vHave;
1279 explicit CBlockLocator(const CBlockIndex* pindex)
1284 explicit CBlockLocator(uint256 hashBlock)
1286 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1287 if (mi != mapBlockIndex.end())
1291 CBlockLocator(const std::vector<uint256>& vHaveIn)
1298 if (!(nType & SER_GETHASH))
1299 READWRITE(nVersion);
1310 return vHave.empty();
1313 void Set(const CBlockIndex* pindex)
1319 vHave.push_back(pindex->GetBlockHash());
1321 // Exponentially larger steps back
1322 for (int i = 0; pindex && i < nStep; i++)
1323 pindex = pindex->pprev;
1324 if (vHave.size() > 10)
1327 vHave.push_back(hashGenesisBlock);
1330 int GetDistanceBack()
1332 // Retrace how far back it was in the sender's branch
1335 BOOST_FOREACH(const uint256& hash, vHave)
1337 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1338 if (mi != mapBlockIndex.end())
1340 CBlockIndex* pindex = (*mi).second;
1341 if (pindex->IsInMainChain())
1351 CBlockIndex* GetBlockIndex()
1353 // Find the first block the caller has in the main chain
1354 BOOST_FOREACH(const uint256& hash, vHave)
1356 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1357 if (mi != mapBlockIndex.end())
1359 CBlockIndex* pindex = (*mi).second;
1360 if (pindex->IsInMainChain())
1364 return pindexGenesisBlock;
1367 uint256 GetBlockHash()
1369 // Find the first block the caller has in the main chain
1370 BOOST_FOREACH(const uint256& hash, vHave)
1372 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1373 if (mi != mapBlockIndex.end())
1375 CBlockIndex* pindex = (*mi).second;
1376 if (pindex->IsInMainChain())
1380 return hashGenesisBlock;
1385 CBlockIndex* pindex = GetBlockIndex();
1388 return pindex->nHeight;
1400 /** Alerts are for notifying old versions if they become too obsolete and
1401 * need to upgrade. The message is displayed in the status bar.
1402 * Alert messages are broadcast as a vector of signed data. Unserializing may
1403 * not read the entire buffer if the alert is for a newer version, but older
1404 * versions can still relay the original data.
1406 class CUnsignedAlert
1410 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1414 std::set<int> setCancel;
1415 int nMinVer; // lowest version inclusive
1416 int nMaxVer; // highest version inclusive
1417 std::set<std::string> setSubVer; // empty matches all
1421 std::string strComment;
1422 std::string strStatusBar;
1423 std::string strReserved;
1427 READWRITE(this->nVersion);
1428 nVersion = this->nVersion;
1429 READWRITE(nRelayUntil);
1430 READWRITE(nExpiration);
1433 READWRITE(setCancel);
1436 READWRITE(setSubVer);
1437 READWRITE(nPriority);
1439 READWRITE(strComment);
1440 READWRITE(strStatusBar);
1441 READWRITE(strReserved);
1458 strStatusBar.clear();
1459 strReserved.clear();
1462 std::string ToString() const
1464 std::string strSetCancel;
1465 BOOST_FOREACH(int n, setCancel)
1466 strSetCancel += strprintf("%d ", n);
1467 std::string strSetSubVer;
1468 BOOST_FOREACH(std::string str, setSubVer)
1469 strSetSubVer += "\"" + str + "\" ";
1473 " nRelayUntil = %"PRI64d"\n"
1474 " nExpiration = %"PRI64d"\n"
1482 " strComment = \"%s\"\n"
1483 " strStatusBar = \"%s\"\n"
1490 strSetCancel.c_str(),
1493 strSetSubVer.c_str(),
1496 strStatusBar.c_str());
1501 printf("%s", ToString().c_str());
1505 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1506 class CAlert : public CUnsignedAlert
1509 std::vector<unsigned char> vchMsg;
1510 std::vector<unsigned char> vchSig;
1525 CUnsignedAlert::SetNull();
1532 return (nExpiration == 0);
1535 uint256 GetHash() const
1537 return SerializeHash(*this);
1540 bool IsInEffect() const
1542 return (GetAdjustedTime() < nExpiration);
1545 bool Cancels(const CAlert& alert) const
1548 return false; // this was a no-op before 31403
1549 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1552 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1554 // TODO: rework for client-version-embedded-in-strSubVer ?
1555 return (IsInEffect() &&
1556 nMinVer <= nVersion && nVersion <= nMaxVer &&
1557 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1560 bool AppliesToMe() const
1562 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1565 bool RelayTo(CNode* pnode) const
1569 // returns true if wasn't already contained in the set
1570 if (pnode->setKnown.insert(GetHash()).second)
1572 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1574 GetAdjustedTime() < nRelayUntil)
1576 pnode->PushMessage("alert", *this);
1583 bool CheckSignature()
1586 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1587 return error("CAlert::CheckSignature() : SetPubKey failed");
1588 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1589 return error("CAlert::CheckSignature() : verify signature failed");
1591 // Now unserialize the data
1592 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1593 sMsg >> *(CUnsignedAlert*)this;
1597 bool ProcessAlert();
1603 mutable CCriticalSection cs;
1604 std::map<uint256, CTransaction> mapTx;
1605 std::map<COutPoint, CInPoint> mapNextTx;
1607 bool accept(CTxDB& txdb, CTransaction &tx,
1608 bool fCheckInputs, bool* pfMissingInputs);
1609 bool addUnchecked(CTransaction &tx);
1610 bool remove(CTransaction &tx);
1612 unsigned long size()
1615 return mapTx.size();
1618 bool exists(uint256 hash)
1620 return (mapTx.count(hash) != 0);
1623 CTransaction& lookup(uint256 hash)
1629 extern CTxMemPool mempool;