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;
29 static const int CLIENT_VERSION = 59900;
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 int64 COIN = 100000000;
37 static const int64 CENT = 1000000;
38 static const int64 MIN_TX_FEE = 50000;
39 static const int64 MIN_RELAY_TX_FEE = 10000;
40 static const int64 MAX_MONEY = 21000000 * COIN;
41 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
42 static const int COINBASE_MATURITY = 100;
43 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
44 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
46 static const int fHaveUPnP = true;
48 static const int fHaveUPnP = false;
56 extern CCriticalSection cs_main;
57 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
58 extern uint256 hashGenesisBlock;
59 extern CBlockIndex* pindexGenesisBlock;
60 extern int nBestHeight;
61 extern CBigNum bnBestChainWork;
62 extern CBigNum bnBestInvalidWork;
63 extern uint256 hashBestChain;
64 extern CBlockIndex* pindexBest;
65 extern unsigned int nTransactionsUpdated;
66 extern double dHashesPerSec;
67 extern int64 nHPSTimerStart;
68 extern int64 nTimeBestReceived;
69 extern CCriticalSection cs_setpwalletRegistered;
70 extern std::set<CWallet*> setpwalletRegistered;
73 extern int fGenerateBitcoins;
74 extern int64 nTransactionFee;
75 extern int fLimitProcessors;
76 extern int nLimitProcessors;
77 extern int fMinimizeToTray;
78 extern int fMinimizeOnClose;
89 void RegisterWallet(CWallet* pwalletIn);
90 void UnregisterWallet(CWallet* pwalletIn);
91 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
92 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
93 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
94 FILE* AppendBlockFile(unsigned int& nFileRet);
95 bool LoadBlockIndex(bool fAllowNew=true);
96 void PrintBlockTree();
97 bool ProcessMessages(CNode* pfrom);
98 bool SendMessages(CNode* pto, bool fSendTrickle);
99 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
100 CBlock* CreateNewBlock(CReserveKey& reservekey);
101 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
102 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
103 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
104 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
105 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
106 int GetNumBlocksOfPeers();
107 bool IsInitialBlockDownload();
108 std::string GetWarnings(std::string strFor);
121 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
124 bool WriteSetting(const std::string& strKey, const T& value)
127 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
129 std::string strWalletFile;
130 if (!GetWalletFile(pwallet, strWalletFile))
132 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
142 unsigned int nBlockPos;
150 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
153 nBlockPos = nBlockPosIn;
157 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
158 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
159 bool IsNull() const { return (nFile == -1); }
161 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
163 return (a.nFile == b.nFile &&
164 a.nBlockPos == b.nBlockPos &&
165 a.nTxPos == b.nTxPos);
168 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
173 std::string ToString() const
176 return strprintf("null");
178 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
183 printf("%s", ToString().c_str());
196 CInPoint() { SetNull(); }
197 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
198 void SetNull() { ptx = NULL; n = -1; }
199 bool IsNull() const { return (ptx == NULL && n == -1); }
211 COutPoint() { SetNull(); }
212 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
213 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
214 void SetNull() { hash = 0; n = -1; }
215 bool IsNull() const { return (hash == 0 && n == -1); }
217 friend bool operator<(const COutPoint& a, const COutPoint& b)
219 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
222 friend bool operator==(const COutPoint& a, const COutPoint& b)
224 return (a.hash == b.hash && a.n == b.n);
227 friend bool operator!=(const COutPoint& a, const COutPoint& b)
232 std::string ToString() const
234 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
239 printf("%s\n", ToString().c_str());
247 // An input of a transaction. It contains the location of the previous
248 // transaction's output that it claims and a signature that matches the
249 // output's public key.
256 unsigned int nSequence;
260 nSequence = std::numeric_limits<unsigned int>::max();
263 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
266 scriptSig = scriptSigIn;
267 nSequence = nSequenceIn;
270 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
272 prevout = COutPoint(hashPrevTx, nOut);
273 scriptSig = scriptSigIn;
274 nSequence = nSequenceIn;
280 READWRITE(scriptSig);
281 READWRITE(nSequence);
286 return (nSequence == std::numeric_limits<unsigned int>::max());
289 friend bool operator==(const CTxIn& a, const CTxIn& b)
291 return (a.prevout == b.prevout &&
292 a.scriptSig == b.scriptSig &&
293 a.nSequence == b.nSequence);
296 friend bool operator!=(const CTxIn& a, const CTxIn& b)
301 std::string ToString() const
304 str += strprintf("CTxIn(");
305 str += prevout.ToString();
306 if (prevout.IsNull())
307 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
309 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
310 if (nSequence != std::numeric_limits<unsigned int>::max())
311 str += strprintf(", nSequence=%u", nSequence);
318 printf("%s\n", ToString().c_str());
326 // An output of a transaction. It contains the public key that the next input
327 // must be able to sign with to claim it.
333 CScript scriptPubKey;
340 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
343 scriptPubKey = scriptPubKeyIn;
349 READWRITE(scriptPubKey);
355 scriptPubKey.clear();
360 return (nValue == -1);
363 uint256 GetHash() const
365 return SerializeHash(*this);
368 friend bool operator==(const CTxOut& a, const CTxOut& b)
370 return (a.nValue == b.nValue &&
371 a.scriptPubKey == b.scriptPubKey);
374 friend bool operator!=(const CTxOut& a, const CTxOut& b)
379 std::string ToString() const
381 if (scriptPubKey.size() < 6)
382 return "CTxOut(error)";
383 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
388 printf("%s\n", ToString().c_str());
403 // The basic transaction that is broadcasted on the network and contained in
404 // blocks. A transaction can contain multiple inputs and outputs.
410 std::vector<CTxIn> vin;
411 std::vector<CTxOut> vout;
412 unsigned int nLockTime;
414 // Denial-of-service detection:
416 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
425 READWRITE(this->nVersion);
426 nVersion = this->nVersion;
429 READWRITE(nLockTime);
438 nDoS = 0; // Denial-of-service prevention
443 return (vin.empty() && vout.empty());
446 uint256 GetHash() const
448 return SerializeHash(*this);
451 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
453 // Time based nLockTime implemented in 0.1.6
456 if (nBlockHeight == 0)
457 nBlockHeight = nBestHeight;
459 nBlockTime = GetAdjustedTime();
460 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
462 BOOST_FOREACH(const CTxIn& txin, vin)
468 bool IsNewerThan(const CTransaction& old) const
470 if (vin.size() != old.vin.size())
472 for (int i = 0; i < vin.size(); i++)
473 if (vin[i].prevout != old.vin[i].prevout)
477 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
478 for (int i = 0; i < vin.size(); i++)
480 if (vin[i].nSequence != old.vin[i].nSequence)
482 if (vin[i].nSequence <= nLowest)
485 nLowest = vin[i].nSequence;
487 if (old.vin[i].nSequence < nLowest)
490 nLowest = old.vin[i].nSequence;
497 bool IsCoinBase() const
499 return (vin.size() == 1 && vin[0].prevout.IsNull());
502 bool IsStandard() const;
503 bool AreInputsStandard(std::map<uint256, std::pair<CTxIndex, CTransaction> > mapInputs) const;
505 int64 GetValueOut() const
508 BOOST_FOREACH(const CTxOut& txout, vout)
510 nValueOut += txout.nValue;
511 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
512 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
517 static bool AllowFree(double dPriority)
519 // Large (in bytes) low-priority (new, small-coin) transactions
521 return dPriority > COIN * 144 / 250;
524 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
526 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
527 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
529 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
530 unsigned int nNewBlockSize = nBlockSize + nBytes;
531 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
537 // Transactions under 10K are free
538 // (about 4500bc if made of 50bc inputs)
544 // Free transaction area
545 if (nNewBlockSize < 27000)
550 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
551 if (nMinFee < nBaseFee)
552 BOOST_FOREACH(const CTxOut& txout, vout)
553 if (txout.nValue < CENT)
556 // Raise the price as the block approaches full
557 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
559 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
561 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
564 if (!MoneyRange(nMinFee))
570 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
572 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
574 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
577 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
578 return error("CTransaction::ReadFromDisk() : fseek failed");
581 // Return file pointer
584 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
585 return error("CTransaction::ReadFromDisk() : second fseek failed");
586 *pfileRet = filein.release();
591 friend bool operator==(const CTransaction& a, const CTransaction& b)
593 return (a.nVersion == b.nVersion &&
596 a.nLockTime == b.nLockTime);
599 friend bool operator!=(const CTransaction& a, const CTransaction& b)
605 std::string ToString() const
608 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
609 GetHash().ToString().substr(0,10).c_str(),
614 for (int i = 0; i < vin.size(); i++)
615 str += " " + vin[i].ToString() + "\n";
616 for (int i = 0; i < vout.size(); i++)
617 str += " " + vout[i].ToString() + "\n";
623 printf("%s", ToString().c_str());
627 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
628 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
629 bool ReadFromDisk(COutPoint prevout);
630 bool DisconnectInputs(CTxDB& txdb);
632 // Fetch from memory and/or disk. inputsRet keys are transaction hashes.
633 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
634 bool fBlock, bool fMiner, std::map<uint256, std::pair<CTxIndex, CTransaction> >& inputsRet);
635 bool ConnectInputs(std::map<uint256, std::pair<CTxIndex, CTransaction> > inputs,
636 std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
637 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64 nMinFee=0);
638 bool ClientConnectInputs();
639 bool CheckTransaction() const;
640 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
641 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
643 bool AddToMemoryPoolUnchecked();
645 bool RemoveFromMemoryPool();
653 // A transaction with a merkle branch linking it to the block chain
655 class CMerkleTx : public CTransaction
659 std::vector<uint256> vMerkleBranch;
663 mutable char fMerkleVerified;
671 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
680 fMerkleVerified = false;
686 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
687 nVersion = this->nVersion;
688 READWRITE(hashBlock);
689 READWRITE(vMerkleBranch);
694 int SetMerkleBranch(const CBlock* pblock=NULL);
695 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
696 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
697 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
698 int GetBlocksToMaturity() const;
699 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
700 bool AcceptToMemoryPool();
707 // A txdb record that contains the disk location of a transaction and the
708 // locations of transactions that spend its outputs. vSpent is really only
709 // used as a flag, but having the location is very helpful for debugging.
715 std::vector<CDiskTxPos> vSpent;
722 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
725 vSpent.resize(nOutputs);
730 if (!(nType & SER_GETHASH))
747 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
749 return (a.pos == b.pos &&
750 a.vSpent == b.vSpent);
753 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
757 int GetDepthInMainChain() const;
766 // Nodes collect new transactions into a block, hash them into a hash tree,
767 // and scan through nonce values to make the block's hash satisfy proof-of-work
768 // requirements. When they solve the proof-of-work, they broadcast the block
769 // to everyone and the block is added to the block chain. The first transaction
770 // in the block is a special one that creates a new coin owned by the creator
773 // Blocks are appended to blk0001.dat files on disk. Their location on disk
774 // is indexed by CBlockIndex objects in memory.
781 uint256 hashPrevBlock;
782 uint256 hashMerkleRoot;
788 std::vector<CTransaction> vtx;
791 mutable std::vector<uint256> vMerkleTree;
793 // Denial-of-service detection:
795 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
804 READWRITE(this->nVersion);
805 nVersion = this->nVersion;
806 READWRITE(hashPrevBlock);
807 READWRITE(hashMerkleRoot);
812 // ConnectBlock depends on vtx being last so it can calculate offset
813 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
816 const_cast<CBlock*>(this)->vtx.clear();
837 uint256 GetHash() const
839 return Hash(BEGIN(nVersion), END(nNonce));
842 int64 GetBlockTime() const
849 uint256 BuildMerkleTree() const
852 BOOST_FOREACH(const CTransaction& tx, vtx)
853 vMerkleTree.push_back(tx.GetHash());
855 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
857 for (int i = 0; i < nSize; i += 2)
859 int i2 = std::min(i+1, nSize-1);
860 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
861 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
865 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
868 std::vector<uint256> GetMerkleBranch(int nIndex) const
870 if (vMerkleTree.empty())
872 std::vector<uint256> vMerkleBranch;
874 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
876 int i = std::min(nIndex^1, nSize-1);
877 vMerkleBranch.push_back(vMerkleTree[j+i]);
881 return vMerkleBranch;
884 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
888 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
891 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
893 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
900 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
902 // Open history file to append
903 CAutoFile fileout = AppendBlockFile(nFileRet);
905 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
907 // Write index header
908 unsigned int nSize = fileout.GetSerializeSize(*this);
909 fileout << FLATDATA(pchMessageStart) << nSize;
912 nBlockPosRet = ftell(fileout);
913 if (nBlockPosRet == -1)
914 return error("CBlock::WriteToDisk() : ftell failed");
917 // Flush stdio buffers and commit to disk before returning
919 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
922 _commit(_fileno(fileout));
924 fsync(fileno(fileout));
931 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
935 // Open history file to read
936 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
938 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
939 if (!fReadTransactions)
940 filein.nType |= SER_BLOCKHEADERONLY;
946 if (!CheckProofOfWork(GetHash(), nBits))
947 return error("CBlock::ReadFromDisk() : errors in block header");
956 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
957 GetHash().ToString().substr(0,20).c_str(),
959 hashPrevBlock.ToString().substr(0,20).c_str(),
960 hashMerkleRoot.ToString().substr(0,10).c_str(),
961 nTime, nBits, nNonce,
963 for (int i = 0; i < vtx.size(); i++)
968 printf(" vMerkleTree: ");
969 for (int i = 0; i < vMerkleTree.size(); i++)
970 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
975 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
976 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
977 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
978 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
979 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
980 bool CheckBlock() const;
990 // The block chain is a tree shaped structure starting with the
991 // genesis block at the root, with each block potentially having multiple
992 // candidates to be the next block. pprev and pnext link a path through the
993 // main/longest chain. A blockindex may have multiple pprev pointing back
994 // to it, but pnext will only point forward to the longest branch, or will
995 // be null if the block is not part of the longest chain.
1000 const uint256* phashBlock;
1004 unsigned int nBlockPos;
1006 CBigNum bnChainWork;
1010 uint256 hashMerkleRoot;
1013 unsigned int nNonce;
1033 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1039 nBlockPos = nBlockPosIn;
1043 nVersion = block.nVersion;
1044 hashMerkleRoot = block.hashMerkleRoot;
1045 nTime = block.nTime;
1046 nBits = block.nBits;
1047 nNonce = block.nNonce;
1050 CBlock GetBlockHeader() const
1053 block.nVersion = nVersion;
1055 block.hashPrevBlock = pprev->GetBlockHash();
1056 block.hashMerkleRoot = hashMerkleRoot;
1057 block.nTime = nTime;
1058 block.nBits = nBits;
1059 block.nNonce = nNonce;
1063 uint256 GetBlockHash() const
1068 int64 GetBlockTime() const
1070 return (int64)nTime;
1073 CBigNum GetBlockWork() const
1076 bnTarget.SetCompact(nBits);
1079 return (CBigNum(1)<<256) / (bnTarget+1);
1082 bool IsInMainChain() const
1084 return (pnext || this == pindexBest);
1087 bool CheckIndex() const
1089 return CheckProofOfWork(GetBlockHash(), nBits);
1092 bool EraseBlockFromDisk()
1094 // Open history file
1095 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1099 // Overwrite with empty null block
1107 enum { nMedianTimeSpan=11 };
1109 int64 GetMedianTimePast() const
1111 int64 pmedian[nMedianTimeSpan];
1112 int64* pbegin = &pmedian[nMedianTimeSpan];
1113 int64* pend = &pmedian[nMedianTimeSpan];
1115 const CBlockIndex* pindex = this;
1116 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1117 *(--pbegin) = pindex->GetBlockTime();
1119 std::sort(pbegin, pend);
1120 return pbegin[(pend - pbegin)/2];
1123 int64 GetMedianTime() const
1125 const CBlockIndex* pindex = this;
1126 for (int i = 0; i < nMedianTimeSpan/2; i++)
1129 return GetBlockTime();
1130 pindex = pindex->pnext;
1132 return pindex->GetMedianTimePast();
1137 std::string ToString() const
1139 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1140 pprev, pnext, nFile, nBlockPos, nHeight,
1141 hashMerkleRoot.ToString().substr(0,10).c_str(),
1142 GetBlockHash().ToString().substr(0,20).c_str());
1147 printf("%s\n", ToString().c_str());
1154 // Used to marshal pointers into hashes for db storage.
1156 class CDiskBlockIndex : public CBlockIndex
1168 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1170 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1171 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1176 if (!(nType & SER_GETHASH))
1177 READWRITE(nVersion);
1179 READWRITE(hashNext);
1181 READWRITE(nBlockPos);
1185 READWRITE(this->nVersion);
1186 READWRITE(hashPrev);
1187 READWRITE(hashMerkleRoot);
1193 uint256 GetBlockHash() const
1196 block.nVersion = nVersion;
1197 block.hashPrevBlock = hashPrev;
1198 block.hashMerkleRoot = hashMerkleRoot;
1199 block.nTime = nTime;
1200 block.nBits = nBits;
1201 block.nNonce = nNonce;
1202 return block.GetHash();
1206 std::string ToString() const
1208 std::string str = "CDiskBlockIndex(";
1209 str += CBlockIndex::ToString();
1210 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1211 GetBlockHash().ToString().c_str(),
1212 hashPrev.ToString().substr(0,20).c_str(),
1213 hashNext.ToString().substr(0,20).c_str());
1219 printf("%s\n", ToString().c_str());
1231 // Describes a place in the block chain to another node such that if the
1232 // other node doesn't have the same branch, it can find a recent common trunk.
1233 // The further back it is, the further before the fork it may be.
1238 std::vector<uint256> vHave;
1245 explicit CBlockLocator(const CBlockIndex* pindex)
1250 explicit CBlockLocator(uint256 hashBlock)
1252 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1253 if (mi != mapBlockIndex.end())
1257 CBlockLocator(const std::vector<uint256>& vHaveIn)
1264 if (!(nType & SER_GETHASH))
1265 READWRITE(nVersion);
1276 return vHave.empty();
1279 void Set(const CBlockIndex* pindex)
1285 vHave.push_back(pindex->GetBlockHash());
1287 // Exponentially larger steps back
1288 for (int i = 0; pindex && i < nStep; i++)
1289 pindex = pindex->pprev;
1290 if (vHave.size() > 10)
1293 vHave.push_back(hashGenesisBlock);
1296 int GetDistanceBack()
1298 // Retrace how far back it was in the sender's branch
1301 BOOST_FOREACH(const uint256& hash, vHave)
1303 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1304 if (mi != mapBlockIndex.end())
1306 CBlockIndex* pindex = (*mi).second;
1307 if (pindex->IsInMainChain())
1317 CBlockIndex* GetBlockIndex()
1319 // Find the first block the caller has in the main chain
1320 BOOST_FOREACH(const uint256& hash, vHave)
1322 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1323 if (mi != mapBlockIndex.end())
1325 CBlockIndex* pindex = (*mi).second;
1326 if (pindex->IsInMainChain())
1330 return pindexGenesisBlock;
1333 uint256 GetBlockHash()
1335 // Find the first block the caller has in the main chain
1336 BOOST_FOREACH(const uint256& hash, vHave)
1338 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1339 if (mi != mapBlockIndex.end())
1341 CBlockIndex* pindex = (*mi).second;
1342 if (pindex->IsInMainChain())
1346 return hashGenesisBlock;
1351 CBlockIndex* pindex = GetBlockIndex();
1354 return pindex->nHeight;
1367 // Alerts are for notifying old versions if they become too obsolete and
1368 // need to upgrade. The message is displayed in the status bar.
1369 // Alert messages are broadcast as a vector of signed data. Unserializing may
1370 // not read the entire buffer if the alert is for a newer version, but older
1371 // versions can still relay the original data.
1373 class CUnsignedAlert
1377 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1381 std::set<int> setCancel;
1382 int nMinVer; // lowest version inclusive
1383 int nMaxVer; // highest version inclusive
1384 std::set<std::string> setSubVer; // empty matches all
1388 std::string strComment;
1389 std::string strStatusBar;
1390 std::string strReserved;
1394 READWRITE(this->nVersion);
1395 nVersion = this->nVersion;
1396 READWRITE(nRelayUntil);
1397 READWRITE(nExpiration);
1400 READWRITE(setCancel);
1403 READWRITE(setSubVer);
1404 READWRITE(nPriority);
1406 READWRITE(strComment);
1407 READWRITE(strStatusBar);
1408 READWRITE(strReserved);
1425 strStatusBar.clear();
1426 strReserved.clear();
1429 std::string ToString() const
1431 std::string strSetCancel;
1432 BOOST_FOREACH(int n, setCancel)
1433 strSetCancel += strprintf("%d ", n);
1434 std::string strSetSubVer;
1435 BOOST_FOREACH(std::string str, setSubVer)
1436 strSetSubVer += "\"" + str + "\" ";
1440 " nRelayUntil = %"PRI64d"\n"
1441 " nExpiration = %"PRI64d"\n"
1449 " strComment = \"%s\"\n"
1450 " strStatusBar = \"%s\"\n"
1457 strSetCancel.c_str(),
1460 strSetSubVer.c_str(),
1463 strStatusBar.c_str());
1468 printf("%s", ToString().c_str());
1472 class CAlert : public CUnsignedAlert
1475 std::vector<unsigned char> vchMsg;
1476 std::vector<unsigned char> vchSig;
1491 CUnsignedAlert::SetNull();
1498 return (nExpiration == 0);
1501 uint256 GetHash() const
1503 return SerializeHash(*this);
1506 bool IsInEffect() const
1508 return (GetAdjustedTime() < nExpiration);
1511 bool Cancels(const CAlert& alert) const
1514 return false; // this was a no-op before 31403
1515 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1518 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1520 // TODO: rework for client-version-embedded-in-strSubVer ?
1521 return (IsInEffect() &&
1522 nMinVer <= nVersion && nVersion <= nMaxVer &&
1523 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1526 bool AppliesToMe() const
1528 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1531 bool RelayTo(CNode* pnode) const
1535 // returns true if wasn't already contained in the set
1536 if (pnode->setKnown.insert(GetHash()).second)
1538 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1540 GetAdjustedTime() < nRelayUntil)
1542 pnode->PushMessage("alert", *this);
1549 bool CheckSignature()
1552 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1553 return error("CAlert::CheckSignature() : SetPubKey failed");
1554 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1555 return error("CAlert::CheckSignature() : verify signature failed");
1557 // Now unserialize the data
1558 CDataStream sMsg(vchMsg);
1559 sMsg >> *(CUnsignedAlert*)this;
1563 bool ProcessAlert();