1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
26 class CRequestTracker;
30 static const int CLIENT_VERSION = 59900;
31 static const bool VERSION_IS_BETA = true;
32 extern const std::string CLIENT_NAME;
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 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;
57 extern CCriticalSection cs_main;
58 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
59 extern uint256 hashGenesisBlock;
60 extern CBlockIndex* pindexGenesisBlock;
61 extern int nBestHeight;
62 extern CBigNum bnBestChainWork;
63 extern CBigNum bnBestInvalidWork;
64 extern uint256 hashBestChain;
65 extern CBlockIndex* pindexBest;
66 extern unsigned int nTransactionsUpdated;
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 int fGenerateBitcoins;
75 extern int64 nTransactionFee;
76 extern int fLimitProcessors;
77 extern int nLimitProcessors;
78 extern int fMinimizeToTray;
79 extern int fMinimizeOnClose;
90 void RegisterWallet(CWallet* pwalletIn);
91 void UnregisterWallet(CWallet* pwalletIn);
92 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
93 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
94 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
95 FILE* AppendBlockFile(unsigned int& nFileRet);
96 bool LoadBlockIndex(bool fAllowNew=true);
97 void PrintBlockTree();
98 bool ProcessMessages(CNode* pfrom);
99 bool SendMessages(CNode* pto, bool fSendTrickle);
100 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
101 CBlock* CreateNewBlock(CReserveKey& reservekey);
102 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
103 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
104 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
105 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
106 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
107 int GetNumBlocksOfPeers();
108 bool IsInitialBlockDownload();
109 std::string GetWarnings(std::string strFor);
122 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
125 bool WriteSetting(const std::string& strKey, const T& value)
128 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
130 std::string strWalletFile;
131 if (!GetWalletFile(pwallet, strWalletFile))
133 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
143 unsigned int nBlockPos;
151 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
154 nBlockPos = nBlockPosIn;
158 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
159 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
160 bool IsNull() const { return (nFile == -1); }
162 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
164 return (a.nFile == b.nFile &&
165 a.nBlockPos == b.nBlockPos &&
166 a.nTxPos == b.nTxPos);
169 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
174 std::string ToString() const
177 return strprintf("null");
179 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
184 printf("%s", ToString().c_str());
197 CInPoint() { SetNull(); }
198 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
199 void SetNull() { ptx = NULL; n = -1; }
200 bool IsNull() const { return (ptx == NULL && n == -1); }
212 COutPoint() { SetNull(); }
213 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
214 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
215 void SetNull() { hash = 0; n = -1; }
216 bool IsNull() const { return (hash == 0 && n == -1); }
218 friend bool operator<(const COutPoint& a, const COutPoint& b)
220 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
223 friend bool operator==(const COutPoint& a, const COutPoint& b)
225 return (a.hash == b.hash && a.n == b.n);
228 friend bool operator!=(const COutPoint& a, const COutPoint& b)
233 std::string ToString() const
235 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
240 printf("%s\n", ToString().c_str());
248 // An input of a transaction. It contains the location of the previous
249 // transaction's output that it claims and a signature that matches the
250 // output's public key.
257 unsigned int nSequence;
261 nSequence = UINT_MAX;
264 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
267 scriptSig = scriptSigIn;
268 nSequence = nSequenceIn;
271 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
273 prevout = COutPoint(hashPrevTx, nOut);
274 scriptSig = scriptSigIn;
275 nSequence = nSequenceIn;
281 READWRITE(scriptSig);
282 READWRITE(nSequence);
287 return (nSequence == UINT_MAX);
290 friend bool operator==(const CTxIn& a, const CTxIn& b)
292 return (a.prevout == b.prevout &&
293 a.scriptSig == b.scriptSig &&
294 a.nSequence == b.nSequence);
297 friend bool operator!=(const CTxIn& a, const CTxIn& b)
302 std::string ToString() const
305 str += strprintf("CTxIn(");
306 str += prevout.ToString();
307 if (prevout.IsNull())
308 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
310 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
311 if (nSequence != UINT_MAX)
312 str += strprintf(", nSequence=%u", nSequence);
319 printf("%s\n", ToString().c_str());
327 // An output of a transaction. It contains the public key that the next input
328 // must be able to sign with to claim it.
334 CScript scriptPubKey;
341 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
344 scriptPubKey = scriptPubKeyIn;
350 READWRITE(scriptPubKey);
356 scriptPubKey.clear();
361 return (nValue == -1);
364 uint256 GetHash() const
366 return SerializeHash(*this);
369 friend bool operator==(const CTxOut& a, const CTxOut& b)
371 return (a.nValue == b.nValue &&
372 a.scriptPubKey == b.scriptPubKey);
375 friend bool operator!=(const CTxOut& a, const CTxOut& b)
380 std::string ToString() const
382 if (scriptPubKey.size() < 6)
383 return "CTxOut(error)";
384 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
389 printf("%s\n", ToString().c_str());
397 // The basic transaction that is broadcasted on the network and contained in
398 // blocks. A transaction can contain multiple inputs and outputs.
404 std::vector<CTxIn> vin;
405 std::vector<CTxOut> vout;
406 unsigned int nLockTime;
408 // Denial-of-service detection:
410 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
419 READWRITE(this->nVersion);
420 nVersion = this->nVersion;
423 READWRITE(nLockTime);
432 nDoS = 0; // Denial-of-service prevention
437 return (vin.empty() && vout.empty());
440 uint256 GetHash() const
442 return SerializeHash(*this);
445 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
447 // Time based nLockTime implemented in 0.1.6
450 if (nBlockHeight == 0)
451 nBlockHeight = nBestHeight;
453 nBlockTime = GetAdjustedTime();
454 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
456 BOOST_FOREACH(const CTxIn& txin, vin)
462 bool IsNewerThan(const CTransaction& old) const
464 if (vin.size() != old.vin.size())
466 for (int i = 0; i < vin.size(); i++)
467 if (vin[i].prevout != old.vin[i].prevout)
471 unsigned int nLowest = UINT_MAX;
472 for (int i = 0; i < vin.size(); i++)
474 if (vin[i].nSequence != old.vin[i].nSequence)
476 if (vin[i].nSequence <= nLowest)
479 nLowest = vin[i].nSequence;
481 if (old.vin[i].nSequence < nLowest)
484 nLowest = old.vin[i].nSequence;
491 bool IsCoinBase() const
493 return (vin.size() == 1 && vin[0].prevout.IsNull());
496 bool IsStandard() const;
497 bool AreInputsStandard(std::map<uint256, std::pair<CTxIndex, CTransaction> > mapInputs) const;
499 int64 GetValueOut() const
502 BOOST_FOREACH(const CTxOut& txout, vout)
504 nValueOut += txout.nValue;
505 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
506 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
511 static bool AllowFree(double dPriority)
513 // Large (in bytes) low-priority (new, small-coin) transactions
515 return dPriority > COIN * 144 / 250;
518 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
520 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
521 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
523 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
524 unsigned int nNewBlockSize = nBlockSize + nBytes;
525 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
531 // Transactions under 10K are free
532 // (about 4500bc if made of 50bc inputs)
538 // Free transaction area
539 if (nNewBlockSize < 27000)
544 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
545 if (nMinFee < nBaseFee)
546 BOOST_FOREACH(const CTxOut& txout, vout)
547 if (txout.nValue < CENT)
550 // Raise the price as the block approaches full
551 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
553 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
555 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
558 if (!MoneyRange(nMinFee))
564 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
566 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
568 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
571 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
572 return error("CTransaction::ReadFromDisk() : fseek failed");
575 // Return file pointer
578 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
579 return error("CTransaction::ReadFromDisk() : second fseek failed");
580 *pfileRet = filein.release();
585 friend bool operator==(const CTransaction& a, const CTransaction& b)
587 return (a.nVersion == b.nVersion &&
590 a.nLockTime == b.nLockTime);
593 friend bool operator!=(const CTransaction& a, const CTransaction& b)
599 std::string ToString() const
602 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
603 GetHash().ToString().substr(0,10).c_str(),
608 for (int i = 0; i < vin.size(); i++)
609 str += " " + vin[i].ToString() + "\n";
610 for (int i = 0; i < vout.size(); i++)
611 str += " " + vout[i].ToString() + "\n";
617 printf("%s", ToString().c_str());
621 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
622 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
623 bool ReadFromDisk(COutPoint prevout);
624 bool DisconnectInputs(CTxDB& txdb);
626 // Fetch from memory and/or disk. inputsRet keys are transaction hashes.
627 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
628 bool fBlock, bool fMiner, std::map<uint256, std::pair<CTxIndex, CTransaction> >& inputsRet);
629 bool ConnectInputs(std::map<uint256, std::pair<CTxIndex, CTransaction> > inputs,
630 std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
631 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64 nMinFee=0);
632 bool ClientConnectInputs();
633 bool CheckTransaction() const;
634 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
635 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
637 bool AddToMemoryPoolUnchecked();
639 bool RemoveFromMemoryPool();
647 // A transaction with a merkle branch linking it to the block chain
649 class CMerkleTx : public CTransaction
653 std::vector<uint256> vMerkleBranch;
657 mutable char fMerkleVerified;
665 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
674 fMerkleVerified = false;
680 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
681 nVersion = this->nVersion;
682 READWRITE(hashBlock);
683 READWRITE(vMerkleBranch);
688 int SetMerkleBranch(const CBlock* pblock=NULL);
689 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
690 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
691 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
692 int GetBlocksToMaturity() const;
693 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
694 bool AcceptToMemoryPool();
701 // A txdb record that contains the disk location of a transaction and the
702 // locations of transactions that spend its outputs. vSpent is really only
703 // used as a flag, but having the location is very helpful for debugging.
709 std::vector<CDiskTxPos> vSpent;
716 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
719 vSpent.resize(nOutputs);
724 if (!(nType & SER_GETHASH))
741 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
743 return (a.pos == b.pos &&
744 a.vSpent == b.vSpent);
747 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
751 int GetDepthInMainChain() const;
760 // Nodes collect new transactions into a block, hash them into a hash tree,
761 // and scan through nonce values to make the block's hash satisfy proof-of-work
762 // requirements. When they solve the proof-of-work, they broadcast the block
763 // to everyone and the block is added to the block chain. The first transaction
764 // in the block is a special one that creates a new coin owned by the creator
767 // Blocks are appended to blk0001.dat files on disk. Their location on disk
768 // is indexed by CBlockIndex objects in memory.
775 uint256 hashPrevBlock;
776 uint256 hashMerkleRoot;
782 std::vector<CTransaction> vtx;
785 mutable std::vector<uint256> vMerkleTree;
787 // Denial-of-service detection:
789 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
798 READWRITE(this->nVersion);
799 nVersion = this->nVersion;
800 READWRITE(hashPrevBlock);
801 READWRITE(hashMerkleRoot);
806 // ConnectBlock depends on vtx being last so it can calculate offset
807 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
810 const_cast<CBlock*>(this)->vtx.clear();
831 uint256 GetHash() const
833 return Hash(BEGIN(nVersion), END(nNonce));
836 int64 GetBlockTime() const
843 uint256 BuildMerkleTree() const
846 BOOST_FOREACH(const CTransaction& tx, vtx)
847 vMerkleTree.push_back(tx.GetHash());
849 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
851 for (int i = 0; i < nSize; i += 2)
853 int i2 = std::min(i+1, nSize-1);
854 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
855 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
859 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
862 std::vector<uint256> GetMerkleBranch(int nIndex) const
864 if (vMerkleTree.empty())
866 std::vector<uint256> vMerkleBranch;
868 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
870 int i = std::min(nIndex^1, nSize-1);
871 vMerkleBranch.push_back(vMerkleTree[j+i]);
875 return vMerkleBranch;
878 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
882 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
885 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
887 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
894 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
896 // Open history file to append
897 CAutoFile fileout = AppendBlockFile(nFileRet);
899 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
901 // Write index header
902 unsigned int nSize = fileout.GetSerializeSize(*this);
903 fileout << FLATDATA(pchMessageStart) << nSize;
906 nBlockPosRet = ftell(fileout);
907 if (nBlockPosRet == -1)
908 return error("CBlock::WriteToDisk() : ftell failed");
911 // Flush stdio buffers and commit to disk before returning
913 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
916 _commit(_fileno(fileout));
918 fsync(fileno(fileout));
925 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
929 // Open history file to read
930 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
932 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
933 if (!fReadTransactions)
934 filein.nType |= SER_BLOCKHEADERONLY;
940 if (!CheckProofOfWork(GetHash(), nBits))
941 return error("CBlock::ReadFromDisk() : errors in block header");
950 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
951 GetHash().ToString().substr(0,20).c_str(),
953 hashPrevBlock.ToString().substr(0,20).c_str(),
954 hashMerkleRoot.ToString().substr(0,10).c_str(),
955 nTime, nBits, nNonce,
957 for (int i = 0; i < vtx.size(); i++)
962 printf(" vMerkleTree: ");
963 for (int i = 0; i < vMerkleTree.size(); i++)
964 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
969 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
970 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
971 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
972 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
973 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
974 bool CheckBlock() const;
984 // The block chain is a tree shaped structure starting with the
985 // genesis block at the root, with each block potentially having multiple
986 // candidates to be the next block. pprev and pnext link a path through the
987 // main/longest chain. A blockindex may have multiple pprev pointing back
988 // to it, but pnext will only point forward to the longest branch, or will
989 // be null if the block is not part of the longest chain.
994 const uint256* phashBlock;
998 unsigned int nBlockPos;
1000 CBigNum bnChainWork;
1004 uint256 hashMerkleRoot;
1007 unsigned int nNonce;
1027 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1033 nBlockPos = nBlockPosIn;
1037 nVersion = block.nVersion;
1038 hashMerkleRoot = block.hashMerkleRoot;
1039 nTime = block.nTime;
1040 nBits = block.nBits;
1041 nNonce = block.nNonce;
1044 CBlock GetBlockHeader() const
1047 block.nVersion = nVersion;
1049 block.hashPrevBlock = pprev->GetBlockHash();
1050 block.hashMerkleRoot = hashMerkleRoot;
1051 block.nTime = nTime;
1052 block.nBits = nBits;
1053 block.nNonce = nNonce;
1057 uint256 GetBlockHash() const
1062 int64 GetBlockTime() const
1064 return (int64)nTime;
1067 CBigNum GetBlockWork() const
1070 bnTarget.SetCompact(nBits);
1073 return (CBigNum(1)<<256) / (bnTarget+1);
1076 bool IsInMainChain() const
1078 return (pnext || this == pindexBest);
1081 bool CheckIndex() const
1083 return CheckProofOfWork(GetBlockHash(), nBits);
1086 bool EraseBlockFromDisk()
1088 // Open history file
1089 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1093 // Overwrite with empty null block
1101 enum { nMedianTimeSpan=11 };
1103 int64 GetMedianTimePast() const
1105 int64 pmedian[nMedianTimeSpan];
1106 int64* pbegin = &pmedian[nMedianTimeSpan];
1107 int64* pend = &pmedian[nMedianTimeSpan];
1109 const CBlockIndex* pindex = this;
1110 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1111 *(--pbegin) = pindex->GetBlockTime();
1113 std::sort(pbegin, pend);
1114 return pbegin[(pend - pbegin)/2];
1117 int64 GetMedianTime() const
1119 const CBlockIndex* pindex = this;
1120 for (int i = 0; i < nMedianTimeSpan/2; i++)
1123 return GetBlockTime();
1124 pindex = pindex->pnext;
1126 return pindex->GetMedianTimePast();
1131 std::string ToString() const
1133 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1134 pprev, pnext, nFile, nBlockPos, nHeight,
1135 hashMerkleRoot.ToString().substr(0,10).c_str(),
1136 GetBlockHash().ToString().substr(0,20).c_str());
1141 printf("%s\n", ToString().c_str());
1148 // Used to marshal pointers into hashes for db storage.
1150 class CDiskBlockIndex : public CBlockIndex
1162 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1164 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1165 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1170 if (!(nType & SER_GETHASH))
1171 READWRITE(nVersion);
1173 READWRITE(hashNext);
1175 READWRITE(nBlockPos);
1179 READWRITE(this->nVersion);
1180 READWRITE(hashPrev);
1181 READWRITE(hashMerkleRoot);
1187 uint256 GetBlockHash() const
1190 block.nVersion = nVersion;
1191 block.hashPrevBlock = hashPrev;
1192 block.hashMerkleRoot = hashMerkleRoot;
1193 block.nTime = nTime;
1194 block.nBits = nBits;
1195 block.nNonce = nNonce;
1196 return block.GetHash();
1200 std::string ToString() const
1202 std::string str = "CDiskBlockIndex(";
1203 str += CBlockIndex::ToString();
1204 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1205 GetBlockHash().ToString().c_str(),
1206 hashPrev.ToString().substr(0,20).c_str(),
1207 hashNext.ToString().substr(0,20).c_str());
1213 printf("%s\n", ToString().c_str());
1225 // Describes a place in the block chain to another node such that if the
1226 // other node doesn't have the same branch, it can find a recent common trunk.
1227 // The further back it is, the further before the fork it may be.
1232 std::vector<uint256> vHave;
1239 explicit CBlockLocator(const CBlockIndex* pindex)
1244 explicit CBlockLocator(uint256 hashBlock)
1246 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1247 if (mi != mapBlockIndex.end())
1251 CBlockLocator(const std::vector<uint256>& vHaveIn)
1258 if (!(nType & SER_GETHASH))
1259 READWRITE(nVersion);
1270 return vHave.empty();
1273 void Set(const CBlockIndex* pindex)
1279 vHave.push_back(pindex->GetBlockHash());
1281 // Exponentially larger steps back
1282 for (int i = 0; pindex && i < nStep; i++)
1283 pindex = pindex->pprev;
1284 if (vHave.size() > 10)
1287 vHave.push_back(hashGenesisBlock);
1290 int GetDistanceBack()
1292 // Retrace how far back it was in the sender's branch
1295 BOOST_FOREACH(const uint256& hash, vHave)
1297 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1298 if (mi != mapBlockIndex.end())
1300 CBlockIndex* pindex = (*mi).second;
1301 if (pindex->IsInMainChain())
1311 CBlockIndex* GetBlockIndex()
1313 // Find the first block the caller has in the main chain
1314 BOOST_FOREACH(const uint256& hash, vHave)
1316 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1317 if (mi != mapBlockIndex.end())
1319 CBlockIndex* pindex = (*mi).second;
1320 if (pindex->IsInMainChain())
1324 return pindexGenesisBlock;
1327 uint256 GetBlockHash()
1329 // Find the first block the caller has in the main chain
1330 BOOST_FOREACH(const uint256& hash, vHave)
1332 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1333 if (mi != mapBlockIndex.end())
1335 CBlockIndex* pindex = (*mi).second;
1336 if (pindex->IsInMainChain())
1340 return hashGenesisBlock;
1345 CBlockIndex* pindex = GetBlockIndex();
1348 return pindex->nHeight;
1361 // Alerts are for notifying old versions if they become too obsolete and
1362 // need to upgrade. The message is displayed in the status bar.
1363 // Alert messages are broadcast as a vector of signed data. Unserializing may
1364 // not read the entire buffer if the alert is for a newer version, but older
1365 // versions can still relay the original data.
1367 class CUnsignedAlert
1371 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1375 std::set<int> setCancel;
1376 int nMinVer; // lowest version inclusive
1377 int nMaxVer; // highest version inclusive
1378 std::set<std::string> setSubVer; // empty matches all
1382 std::string strComment;
1383 std::string strStatusBar;
1384 std::string strReserved;
1388 READWRITE(this->nVersion);
1389 nVersion = this->nVersion;
1390 READWRITE(nRelayUntil);
1391 READWRITE(nExpiration);
1394 READWRITE(setCancel);
1397 READWRITE(setSubVer);
1398 READWRITE(nPriority);
1400 READWRITE(strComment);
1401 READWRITE(strStatusBar);
1402 READWRITE(strReserved);
1419 strStatusBar.clear();
1420 strReserved.clear();
1423 std::string ToString() const
1425 std::string strSetCancel;
1426 BOOST_FOREACH(int n, setCancel)
1427 strSetCancel += strprintf("%d ", n);
1428 std::string strSetSubVer;
1429 BOOST_FOREACH(std::string str, setSubVer)
1430 strSetSubVer += "\"" + str + "\" ";
1434 " nRelayUntil = %"PRI64d"\n"
1435 " nExpiration = %"PRI64d"\n"
1443 " strComment = \"%s\"\n"
1444 " strStatusBar = \"%s\"\n"
1451 strSetCancel.c_str(),
1454 strSetSubVer.c_str(),
1457 strStatusBar.c_str());
1462 printf("%s", ToString().c_str());
1466 class CAlert : public CUnsignedAlert
1469 std::vector<unsigned char> vchMsg;
1470 std::vector<unsigned char> vchSig;
1485 CUnsignedAlert::SetNull();
1492 return (nExpiration == 0);
1495 uint256 GetHash() const
1497 return SerializeHash(*this);
1500 bool IsInEffect() const
1502 return (GetAdjustedTime() < nExpiration);
1505 bool Cancels(const CAlert& alert) const
1508 return false; // this was a no-op before 31403
1509 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1512 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1514 // TODO: rework for client-version-embedded-in-strSubVer ?
1515 return (IsInEffect() &&
1516 nMinVer <= nVersion && nVersion <= nMaxVer &&
1517 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1520 bool AppliesToMe() const
1522 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1525 bool RelayTo(CNode* pnode) const
1529 // returns true if wasn't already contained in the set
1530 if (pnode->setKnown.insert(GetHash()).second)
1532 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1534 GetAdjustedTime() < nRelayUntil)
1536 pnode->PushMessage("alert", *this);
1543 bool CheckSignature()
1546 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1547 return error("CAlert::CheckSignature() : SetPubKey failed");
1548 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1549 return error("CAlert::CheckSignature() : verify signature failed");
1551 // Now unserialize the data
1552 CDataStream sMsg(vchMsg);
1553 sMsg >> *(CUnsignedAlert*)this;
1557 bool ProcessAlert();