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.
16 #include <io.h> /* for _commit */
31 class CRequestTracker;
34 static const unsigned int MAX_BLOCK_SIZE = 1000000;
35 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
36 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
37 static const int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
38 static const int64 COIN = 100000000;
39 static const int64 CENT = 1000000;
40 static const int64 MIN_TX_FEE = 50000;
41 static const int64 MIN_RELAY_TX_FEE = 10000;
42 static const int64 MAX_MONEY = 21000000 * COIN;
43 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
44 static const int COINBASE_MATURITY = 100;
45 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
46 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
48 static const int fHaveUPnP = true;
50 static const int fHaveUPnP = false;
54 extern CScript COINBASE_FLAGS;
61 extern CCriticalSection cs_main;
62 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
63 extern uint256 hashGenesisBlock;
64 extern CBlockIndex* pindexGenesisBlock;
65 extern int nBestHeight;
66 extern CBigNum bnBestChainWork;
67 extern CBigNum bnBestInvalidWork;
68 extern uint256 hashBestChain;
69 extern CBlockIndex* pindexBest;
70 extern uint64 nPooledTx;
71 extern unsigned int nTransactionsUpdated;
72 extern uint64 nLastBlockTx;
73 extern uint64 nLastBlockSize;
74 extern const std::string strMessageMagic;
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 int64 nTransactionFee;
92 void RegisterWallet(CWallet* pwalletIn);
93 void UnregisterWallet(CWallet* pwalletIn);
94 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
95 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
96 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
97 FILE* AppendBlockFile(unsigned int& nFileRet);
98 bool LoadBlockIndex(bool fAllowNew=true);
99 void PrintBlockTree();
100 bool ProcessMessages(CNode* pfrom);
101 bool SendMessages(CNode* pto, bool fSendTrickle);
102 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
103 CBlock* CreateNewBlock(CReserveKey& reservekey);
104 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
105 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
106 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
107 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
108 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
109 int GetNumBlocksOfPeers();
110 bool IsInitialBlockDownload();
111 std::string GetWarnings(std::string strFor);
124 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
126 /** Position on disk for a particular transaction. */
131 unsigned int nBlockPos;
139 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
142 nBlockPos = nBlockPosIn;
146 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
147 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
148 bool IsNull() const { return (nFile == -1); }
150 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
152 return (a.nFile == b.nFile &&
153 a.nBlockPos == b.nBlockPos &&
154 a.nTxPos == b.nTxPos);
157 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
162 std::string ToString() const
167 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
172 printf("%s", ToString().c_str());
178 /** An inpoint - a combination of a transaction and an index n into its vin */
185 CInPoint() { SetNull(); }
186 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
187 void SetNull() { ptx = NULL; n = -1; }
188 bool IsNull() const { return (ptx == NULL && n == -1); }
193 /** An outpoint - a combination of a transaction hash and an index n into its vout */
200 COutPoint() { SetNull(); }
201 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
202 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
203 void SetNull() { hash = 0; n = -1; }
204 bool IsNull() const { return (hash == 0 && n == -1); }
206 friend bool operator<(const COutPoint& a, const COutPoint& b)
208 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
211 friend bool operator==(const COutPoint& a, const COutPoint& b)
213 return (a.hash == b.hash && a.n == b.n);
216 friend bool operator!=(const COutPoint& a, const COutPoint& b)
221 std::string ToString() const
223 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
228 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
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());
313 /** An output of a transaction. It contains the public key that the next input
314 * must be able to sign with to claim it.
320 CScript scriptPubKey;
327 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
330 scriptPubKey = scriptPubKeyIn;
336 READWRITE(scriptPubKey);
342 scriptPubKey.clear();
347 return (nValue == -1);
350 uint256 GetHash() const
352 return SerializeHash(*this);
355 friend bool operator==(const CTxOut& a, const CTxOut& b)
357 return (a.nValue == b.nValue &&
358 a.scriptPubKey == b.scriptPubKey);
361 friend bool operator!=(const CTxOut& a, const CTxOut& b)
366 std::string ToString() const
368 if (scriptPubKey.size() < 6)
369 return "CTxOut(error)";
370 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
375 printf("%s\n", ToString().c_str());
389 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
391 /** The basic transaction that is broadcasted on the network and contained in
392 * blocks. A transaction can contain multiple inputs and outputs.
398 std::vector<CTxIn> vin;
399 std::vector<CTxOut> vout;
400 unsigned int nLockTime;
402 // Denial-of-service detection:
404 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
413 READWRITE(this->nVersion);
414 nVersion = this->nVersion;
417 READWRITE(nLockTime);
426 nDoS = 0; // Denial-of-service prevention
431 return (vin.empty() && vout.empty());
434 uint256 GetHash() const
436 return SerializeHash(*this);
439 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
441 // Time based nLockTime implemented in 0.1.6
444 if (nBlockHeight == 0)
445 nBlockHeight = nBestHeight;
447 nBlockTime = GetAdjustedTime();
448 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
450 BOOST_FOREACH(const CTxIn& txin, vin)
456 bool IsNewerThan(const CTransaction& old) const
458 if (vin.size() != old.vin.size())
460 for (int i = 0; i < vin.size(); i++)
461 if (vin[i].prevout != old.vin[i].prevout)
465 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
466 for (int i = 0; i < vin.size(); i++)
468 if (vin[i].nSequence != old.vin[i].nSequence)
470 if (vin[i].nSequence <= nLowest)
473 nLowest = vin[i].nSequence;
475 if (old.vin[i].nSequence < nLowest)
478 nLowest = old.vin[i].nSequence;
485 bool IsCoinBase() const
487 return (vin.size() == 1 && vin[0].prevout.IsNull());
490 /** Check for standard transaction types
491 @return True if all outputs (scriptPubKeys) use only standard transaction forms
493 bool IsStandard() const;
495 /** Check for standard transaction types
496 @param[in] mapInputs Map of previous transactions that have outputs we're spending
497 @return True if all inputs (scriptSigs) use only standard transaction forms
498 @see CTransaction::FetchInputs
500 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
502 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
503 @return number of sigops this transaction's outputs will produce when spent
504 @see CTransaction::FetchInputs
506 int GetLegacySigOpCount() const;
508 /** Count ECDSA signature operations in pay-to-script-hash inputs.
510 @param[in] mapInputs Map of previous transactions that have outputs we're spending
511 @return maximum number of sigops required to validate this transaction's inputs
512 @see CTransaction::FetchInputs
514 int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
516 /** Amount of bitcoins spent by this transaction.
517 @return sum of all outputs (note: does not include fees)
519 int64 GetValueOut() const
522 BOOST_FOREACH(const CTxOut& txout, vout)
524 nValueOut += txout.nValue;
525 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
526 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
531 /** Amount of bitcoins coming in to this transaction
532 Note that lightweight clients may not know anything besides the hash of previous transactions,
533 so may not be able to calculate this.
535 @param[in] mapInputs Map of previous transactions that have outputs we're spending
536 @return Sum of value of all inputs (scriptSigs)
537 @see CTransaction::FetchInputs
539 int64 GetValueIn(const MapPrevTx& mapInputs) const;
541 static bool AllowFree(double dPriority)
543 // Large (in bytes) low-priority (new, small-coin) transactions
545 return dPriority > COIN * 144 / 250;
548 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
550 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
551 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
553 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
554 unsigned int nNewBlockSize = nBlockSize + nBytes;
555 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
561 // Transactions under 10K are free
562 // (about 4500bc if made of 50bc inputs)
568 // Free transaction area
569 if (nNewBlockSize < 27000)
574 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
575 if (nMinFee < nBaseFee)
576 BOOST_FOREACH(const CTxOut& txout, vout)
577 if (txout.nValue < CENT)
580 // Raise the price as the block approaches full
581 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
583 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
585 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
588 if (!MoneyRange(nMinFee))
594 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
596 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
598 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
601 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
602 return error("CTransaction::ReadFromDisk() : fseek failed");
605 // Return file pointer
608 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
609 return error("CTransaction::ReadFromDisk() : second fseek failed");
610 *pfileRet = filein.release();
615 friend bool operator==(const CTransaction& a, const CTransaction& b)
617 return (a.nVersion == b.nVersion &&
620 a.nLockTime == b.nLockTime);
623 friend bool operator!=(const CTransaction& a, const CTransaction& b)
629 std::string ToString() const
632 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
633 GetHash().ToString().substr(0,10).c_str(),
638 for (int i = 0; i < vin.size(); i++)
639 str += " " + vin[i].ToString() + "\n";
640 for (int i = 0; i < vout.size(); i++)
641 str += " " + vout[i].ToString() + "\n";
647 printf("%s", ToString().c_str());
651 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
652 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
653 bool ReadFromDisk(COutPoint prevout);
654 bool DisconnectInputs(CTxDB& txdb);
656 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
658 @param[in] txdb Transaction database
659 @param[in] mapTestPool List of pending changes to the transaction index database
660 @param[in] fBlock True if being called to add a new best-block to the chain
661 @param[in] fMiner True if being called by CreateNewBlock
662 @param[out] inputsRet Pointers to this transaction's inputs
663 @param[out] fInvalid returns true if transaction is invalid
664 @return Returns true if all inputs are in txdb or mapTestPool
666 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
667 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
669 /** Sanity check previous transactions, then, if all checks succeed,
670 mark them as spent by this transaction.
672 @param[in] inputs Previous transactions (from FetchInputs)
673 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
674 @param[in] posThisTx Position of this transaction on disk
675 @param[in] pindexBlock
676 @param[in] fBlock true if called from ConnectBlock
677 @param[in] fMiner true if called from CreateNewBlock
678 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
679 @return Returns true if all checks succeed
681 bool ConnectInputs(MapPrevTx inputs,
682 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
683 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
684 bool ClientConnectInputs();
685 bool CheckTransaction() const;
686 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
689 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
690 bool AddToMemoryPoolUnchecked();
692 bool RemoveFromMemoryPool();
699 /** A transaction with a merkle branch linking it to the block chain. */
700 class CMerkleTx : public CTransaction
704 std::vector<uint256> vMerkleBranch;
708 mutable char fMerkleVerified;
716 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
725 fMerkleVerified = false;
731 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
732 nVersion = this->nVersion;
733 READWRITE(hashBlock);
734 READWRITE(vMerkleBranch);
739 int SetMerkleBranch(const CBlock* pblock=NULL);
740 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
741 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
742 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
743 int GetBlocksToMaturity() const;
744 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
745 bool AcceptToMemoryPool();
751 /** A txdb record that contains the disk location of a transaction and the
752 * locations of transactions that spend its outputs. vSpent is really only
753 * used as a flag, but having the location is very helpful for debugging.
759 std::vector<CDiskTxPos> vSpent;
766 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
769 vSpent.resize(nOutputs);
774 if (!(nType & SER_GETHASH))
791 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
793 return (a.pos == b.pos &&
794 a.vSpent == b.vSpent);
797 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
801 int GetDepthInMainChain() const;
809 /** Nodes collect new transactions into a block, hash them into a hash tree,
810 * and scan through nonce values to make the block's hash satisfy proof-of-work
811 * requirements. When they solve the proof-of-work, they broadcast the block
812 * to everyone and the block is added to the block chain. The first transaction
813 * in the block is a special one that creates a new coin owned by the creator
816 * Blocks are appended to blk0001.dat files on disk. Their location on disk
817 * is indexed by CBlockIndex objects in memory.
824 uint256 hashPrevBlock;
825 uint256 hashMerkleRoot;
831 std::vector<CTransaction> vtx;
834 mutable std::vector<uint256> vMerkleTree;
836 // Denial-of-service detection:
838 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
847 READWRITE(this->nVersion);
848 nVersion = this->nVersion;
849 READWRITE(hashPrevBlock);
850 READWRITE(hashMerkleRoot);
855 // ConnectBlock depends on vtx being last so it can calculate offset
856 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
859 const_cast<CBlock*>(this)->vtx.clear();
880 uint256 GetHash() const
882 return Hash(BEGIN(nVersion), END(nNonce));
885 int64 GetBlockTime() const
890 void UpdateTime(const CBlockIndex* pindexPrev);
893 uint256 BuildMerkleTree() const
896 BOOST_FOREACH(const CTransaction& tx, vtx)
897 vMerkleTree.push_back(tx.GetHash());
899 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
901 for (int i = 0; i < nSize; i += 2)
903 int i2 = std::min(i+1, nSize-1);
904 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
905 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
909 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
912 std::vector<uint256> GetMerkleBranch(int nIndex) const
914 if (vMerkleTree.empty())
916 std::vector<uint256> vMerkleBranch;
918 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
920 int i = std::min(nIndex^1, nSize-1);
921 vMerkleBranch.push_back(vMerkleTree[j+i]);
925 return vMerkleBranch;
928 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
932 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
935 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
937 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
944 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
946 // Open history file to append
947 CAutoFile fileout = AppendBlockFile(nFileRet);
949 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
951 // Write index header
952 unsigned int nSize = fileout.GetSerializeSize(*this);
953 fileout << FLATDATA(pchMessageStart) << nSize;
956 nBlockPosRet = ftell(fileout);
957 if (nBlockPosRet == -1)
958 return error("CBlock::WriteToDisk() : ftell failed");
961 // Flush stdio buffers and commit to disk before returning
963 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
966 _commit(_fileno(fileout));
968 fsync(fileno(fileout));
975 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
979 // Open history file to read
980 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
982 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
983 if (!fReadTransactions)
984 filein.nType |= SER_BLOCKHEADERONLY;
990 if (!CheckProofOfWork(GetHash(), nBits))
991 return error("CBlock::ReadFromDisk() : errors in block header");
1000 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1001 GetHash().ToString().substr(0,20).c_str(),
1003 hashPrevBlock.ToString().substr(0,20).c_str(),
1004 hashMerkleRoot.ToString().substr(0,10).c_str(),
1005 nTime, nBits, nNonce,
1007 for (int i = 0; i < vtx.size(); i++)
1012 printf(" vMerkleTree: ");
1013 for (int i = 0; i < vMerkleTree.size(); i++)
1014 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1019 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1020 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1021 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1022 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1023 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1024 bool CheckBlock() const;
1028 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1036 /** The block chain is a tree shaped structure starting with the
1037 * genesis block at the root, with each block potentially having multiple
1038 * candidates to be the next block. pprev and pnext link a path through the
1039 * main/longest chain. A blockindex may have multiple pprev pointing back
1040 * to it, but pnext will only point forward to the longest branch, or will
1041 * be null if the block is not part of the longest chain.
1046 const uint256* phashBlock;
1050 unsigned int nBlockPos;
1052 CBigNum bnChainWork;
1056 uint256 hashMerkleRoot;
1059 unsigned int nNonce;
1079 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1085 nBlockPos = nBlockPosIn;
1089 nVersion = block.nVersion;
1090 hashMerkleRoot = block.hashMerkleRoot;
1091 nTime = block.nTime;
1092 nBits = block.nBits;
1093 nNonce = block.nNonce;
1096 CBlock GetBlockHeader() const
1099 block.nVersion = nVersion;
1101 block.hashPrevBlock = pprev->GetBlockHash();
1102 block.hashMerkleRoot = hashMerkleRoot;
1103 block.nTime = nTime;
1104 block.nBits = nBits;
1105 block.nNonce = nNonce;
1109 uint256 GetBlockHash() const
1114 int64 GetBlockTime() const
1116 return (int64)nTime;
1119 CBigNum GetBlockWork() const
1122 bnTarget.SetCompact(nBits);
1125 return (CBigNum(1)<<256) / (bnTarget+1);
1128 bool IsInMainChain() const
1130 return (pnext || this == pindexBest);
1133 bool CheckIndex() const
1135 return CheckProofOfWork(GetBlockHash(), nBits);
1138 bool EraseBlockFromDisk()
1140 // Open history file
1141 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1145 // Overwrite with empty null block
1153 enum { nMedianTimeSpan=11 };
1155 int64 GetMedianTimePast() const
1157 int64 pmedian[nMedianTimeSpan];
1158 int64* pbegin = &pmedian[nMedianTimeSpan];
1159 int64* pend = &pmedian[nMedianTimeSpan];
1161 const CBlockIndex* pindex = this;
1162 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1163 *(--pbegin) = pindex->GetBlockTime();
1165 std::sort(pbegin, pend);
1166 return pbegin[(pend - pbegin)/2];
1169 int64 GetMedianTime() const
1171 const CBlockIndex* pindex = this;
1172 for (int i = 0; i < nMedianTimeSpan/2; i++)
1175 return GetBlockTime();
1176 pindex = pindex->pnext;
1178 return pindex->GetMedianTimePast();
1183 std::string ToString() const
1185 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1186 pprev, pnext, nFile, nBlockPos, nHeight,
1187 hashMerkleRoot.ToString().substr(0,10).c_str(),
1188 GetBlockHash().ToString().substr(0,20).c_str());
1193 printf("%s\n", ToString().c_str());
1199 /** Used to marshal pointers into hashes for db storage. */
1200 class CDiskBlockIndex : public CBlockIndex
1212 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1214 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1215 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1220 if (!(nType & SER_GETHASH))
1221 READWRITE(nVersion);
1223 READWRITE(hashNext);
1225 READWRITE(nBlockPos);
1229 READWRITE(this->nVersion);
1230 READWRITE(hashPrev);
1231 READWRITE(hashMerkleRoot);
1237 uint256 GetBlockHash() const
1240 block.nVersion = nVersion;
1241 block.hashPrevBlock = hashPrev;
1242 block.hashMerkleRoot = hashMerkleRoot;
1243 block.nTime = nTime;
1244 block.nBits = nBits;
1245 block.nNonce = nNonce;
1246 return block.GetHash();
1250 std::string ToString() const
1252 std::string str = "CDiskBlockIndex(";
1253 str += CBlockIndex::ToString();
1254 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1255 GetBlockHash().ToString().c_str(),
1256 hashPrev.ToString().substr(0,20).c_str(),
1257 hashNext.ToString().substr(0,20).c_str());
1263 printf("%s\n", ToString().c_str());
1274 /** Describes a place in the block chain to another node such that if the
1275 * other node doesn't have the same branch, it can find a recent common trunk.
1276 * The further back it is, the further before the fork it may be.
1281 std::vector<uint256> vHave;
1288 explicit CBlockLocator(const CBlockIndex* pindex)
1293 explicit CBlockLocator(uint256 hashBlock)
1295 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1296 if (mi != mapBlockIndex.end())
1300 CBlockLocator(const std::vector<uint256>& vHaveIn)
1307 if (!(nType & SER_GETHASH))
1308 READWRITE(nVersion);
1319 return vHave.empty();
1322 void Set(const CBlockIndex* pindex)
1328 vHave.push_back(pindex->GetBlockHash());
1330 // Exponentially larger steps back
1331 for (int i = 0; pindex && i < nStep; i++)
1332 pindex = pindex->pprev;
1333 if (vHave.size() > 10)
1336 vHave.push_back(hashGenesisBlock);
1339 int GetDistanceBack()
1341 // Retrace how far back it was in the sender's branch
1344 BOOST_FOREACH(const uint256& hash, vHave)
1346 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1347 if (mi != mapBlockIndex.end())
1349 CBlockIndex* pindex = (*mi).second;
1350 if (pindex->IsInMainChain())
1360 CBlockIndex* GetBlockIndex()
1362 // Find the first block the caller has in the main chain
1363 BOOST_FOREACH(const uint256& hash, vHave)
1365 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1366 if (mi != mapBlockIndex.end())
1368 CBlockIndex* pindex = (*mi).second;
1369 if (pindex->IsInMainChain())
1373 return pindexGenesisBlock;
1376 uint256 GetBlockHash()
1378 // Find the first block the caller has in the main chain
1379 BOOST_FOREACH(const uint256& hash, vHave)
1381 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1382 if (mi != mapBlockIndex.end())
1384 CBlockIndex* pindex = (*mi).second;
1385 if (pindex->IsInMainChain())
1389 return hashGenesisBlock;
1394 CBlockIndex* pindex = GetBlockIndex();
1397 return pindex->nHeight;
1409 /** Alerts are for notifying old versions if they become too obsolete and
1410 * need to upgrade. The message is displayed in the status bar.
1411 * Alert messages are broadcast as a vector of signed data. Unserializing may
1412 * not read the entire buffer if the alert is for a newer version, but older
1413 * versions can still relay the original data.
1415 class CUnsignedAlert
1419 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1423 std::set<int> setCancel;
1424 int nMinVer; // lowest version inclusive
1425 int nMaxVer; // highest version inclusive
1426 std::set<std::string> setSubVer; // empty matches all
1430 std::string strComment;
1431 std::string strStatusBar;
1432 std::string strReserved;
1436 READWRITE(this->nVersion);
1437 nVersion = this->nVersion;
1438 READWRITE(nRelayUntil);
1439 READWRITE(nExpiration);
1442 READWRITE(setCancel);
1445 READWRITE(setSubVer);
1446 READWRITE(nPriority);
1448 READWRITE(strComment);
1449 READWRITE(strStatusBar);
1450 READWRITE(strReserved);
1467 strStatusBar.clear();
1468 strReserved.clear();
1471 std::string ToString() const
1473 std::string strSetCancel;
1474 BOOST_FOREACH(int n, setCancel)
1475 strSetCancel += strprintf("%d ", n);
1476 std::string strSetSubVer;
1477 BOOST_FOREACH(std::string str, setSubVer)
1478 strSetSubVer += "\"" + str + "\" ";
1482 " nRelayUntil = %"PRI64d"\n"
1483 " nExpiration = %"PRI64d"\n"
1491 " strComment = \"%s\"\n"
1492 " strStatusBar = \"%s\"\n"
1499 strSetCancel.c_str(),
1502 strSetSubVer.c_str(),
1505 strStatusBar.c_str());
1510 printf("%s", ToString().c_str());
1514 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1515 class CAlert : public CUnsignedAlert
1518 std::vector<unsigned char> vchMsg;
1519 std::vector<unsigned char> vchSig;
1534 CUnsignedAlert::SetNull();
1541 return (nExpiration == 0);
1544 uint256 GetHash() const
1546 return SerializeHash(*this);
1549 bool IsInEffect() const
1551 return (GetAdjustedTime() < nExpiration);
1554 bool Cancels(const CAlert& alert) const
1557 return false; // this was a no-op before 31403
1558 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1561 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1563 // TODO: rework for client-version-embedded-in-strSubVer ?
1564 return (IsInEffect() &&
1565 nMinVer <= nVersion && nVersion <= nMaxVer &&
1566 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1569 bool AppliesToMe() const
1571 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1574 bool RelayTo(CNode* pnode) const
1578 // returns true if wasn't already contained in the set
1579 if (pnode->setKnown.insert(GetHash()).second)
1581 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1583 GetAdjustedTime() < nRelayUntil)
1585 pnode->PushMessage("alert", *this);
1592 bool CheckSignature()
1595 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1596 return error("CAlert::CheckSignature() : SetPubKey failed");
1597 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1598 return error("CAlert::CheckSignature() : verify signature failed");
1600 // Now unserialize the data
1601 CDataStream sMsg(vchMsg);
1602 sMsg >> *(CUnsignedAlert*)this;
1606 bool ProcessAlert();