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 unsigned int MAX_BLOCK_SIZE = 1000000;
31 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
32 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
33 static const int64 COIN = 100000000;
34 static const int64 CENT = 1000000;
35 static const int64 MIN_TX_FEE = 50000;
36 static const int64 MIN_RELAY_TX_FEE = 10000;
37 static const int64 MAX_MONEY = 21000000 * COIN;
38 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
39 static const int COINBASE_MATURITY = 100;
40 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
41 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
43 static const int fHaveUPnP = true;
45 static const int fHaveUPnP = false;
53 extern CCriticalSection cs_main;
54 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
55 extern uint256 hashGenesisBlock;
56 extern CBlockIndex* pindexGenesisBlock;
57 extern int nBestHeight;
58 extern CBigNum bnBestChainWork;
59 extern CBigNum bnBestInvalidWork;
60 extern uint256 hashBestChain;
61 extern CBlockIndex* pindexBest;
62 extern unsigned int nTransactionsUpdated;
63 extern double dHashesPerSec;
64 extern int64 nHPSTimerStart;
65 extern int64 nTimeBestReceived;
66 extern CCriticalSection cs_setpwalletRegistered;
67 extern std::set<CWallet*> setpwalletRegistered;
70 extern int fGenerateBitcoins;
71 extern int64 nTransactionFee;
72 extern int fLimitProcessors;
73 extern int nLimitProcessors;
74 extern int fMinimizeToTray;
75 extern int fMinimizeOnClose;
86 void RegisterWallet(CWallet* pwalletIn);
87 void UnregisterWallet(CWallet* pwalletIn);
88 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
89 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
90 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
91 FILE* AppendBlockFile(unsigned int& nFileRet);
92 bool LoadBlockIndex(bool fAllowNew=true);
93 void PrintBlockTree();
94 bool ProcessMessages(CNode* pfrom);
95 bool SendMessages(CNode* pto, bool fSendTrickle);
96 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
97 CBlock* CreateNewBlock(CReserveKey& reservekey);
98 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
99 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
100 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
101 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
102 int GetNumBlocksOfPeers();
103 bool IsInitialBlockDownload();
104 std::string GetWarnings(std::string strFor);
117 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
120 bool WriteSetting(const std::string& strKey, const T& value)
123 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
125 std::string strWalletFile;
126 if (!GetWalletFile(pwallet, strWalletFile))
128 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
138 unsigned int nBlockPos;
146 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
149 nBlockPos = nBlockPosIn;
153 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
154 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
155 bool IsNull() const { return (nFile == -1); }
157 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
159 return (a.nFile == b.nFile &&
160 a.nBlockPos == b.nBlockPos &&
161 a.nTxPos == b.nTxPos);
164 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
169 std::string ToString() const
172 return strprintf("null");
174 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
179 printf("%s", ToString().c_str());
192 CInPoint() { SetNull(); }
193 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
194 void SetNull() { ptx = NULL; n = -1; }
195 bool IsNull() const { return (ptx == NULL && n == -1); }
207 COutPoint() { SetNull(); }
208 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
209 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
210 void SetNull() { hash = 0; n = -1; }
211 bool IsNull() const { return (hash == 0 && n == -1); }
213 friend bool operator<(const COutPoint& a, const COutPoint& b)
215 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
218 friend bool operator==(const COutPoint& a, const COutPoint& b)
220 return (a.hash == b.hash && a.n == b.n);
223 friend bool operator!=(const COutPoint& a, const COutPoint& b)
228 std::string ToString() const
230 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
235 printf("%s\n", ToString().c_str());
243 // An input of a transaction. It contains the location of the previous
244 // transaction's output that it claims and a signature that matches the
245 // output's public key.
252 unsigned int nSequence;
256 nSequence = UINT_MAX;
259 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
262 scriptSig = scriptSigIn;
263 nSequence = nSequenceIn;
266 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
268 prevout = COutPoint(hashPrevTx, nOut);
269 scriptSig = scriptSigIn;
270 nSequence = nSequenceIn;
276 READWRITE(scriptSig);
277 READWRITE(nSequence);
282 return (nSequence == UINT_MAX);
285 friend bool operator==(const CTxIn& a, const CTxIn& b)
287 return (a.prevout == b.prevout &&
288 a.scriptSig == b.scriptSig &&
289 a.nSequence == b.nSequence);
292 friend bool operator!=(const CTxIn& a, const CTxIn& b)
297 std::string ToString() const
300 str += strprintf("CTxIn(");
301 str += prevout.ToString();
302 if (prevout.IsNull())
303 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
305 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
306 if (nSequence != UINT_MAX)
307 str += strprintf(", nSequence=%u", nSequence);
314 printf("%s\n", ToString().c_str());
322 // An output of a transaction. It contains the public key that the next input
323 // must be able to sign with to claim it.
329 CScript scriptPubKey;
336 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
339 scriptPubKey = scriptPubKeyIn;
345 READWRITE(scriptPubKey);
351 scriptPubKey.clear();
356 return (nValue == -1);
359 uint256 GetHash() const
361 return SerializeHash(*this);
364 friend bool operator==(const CTxOut& a, const CTxOut& b)
366 return (a.nValue == b.nValue &&
367 a.scriptPubKey == b.scriptPubKey);
370 friend bool operator!=(const CTxOut& a, const CTxOut& b)
375 std::string ToString() const
377 if (scriptPubKey.size() < 6)
378 return "CTxOut(error)";
379 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
384 printf("%s\n", ToString().c_str());
392 // The basic transaction that is broadcasted on the network and contained in
393 // blocks. A transaction can contain multiple inputs and outputs.
399 std::vector<CTxIn> vin;
400 std::vector<CTxOut> vout;
401 unsigned int nLockTime;
403 // Denial-of-service detection:
405 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
414 READWRITE(this->nVersion);
415 nVersion = this->nVersion;
418 READWRITE(nLockTime);
427 nDoS = 0; // Denial-of-service prevention
432 return (vin.empty() && vout.empty());
435 uint256 GetHash() const
437 return SerializeHash(*this);
440 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
442 // Time based nLockTime implemented in 0.1.6
445 if (nBlockHeight == 0)
446 nBlockHeight = nBestHeight;
448 nBlockTime = GetAdjustedTime();
449 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
451 BOOST_FOREACH(const CTxIn& txin, vin)
457 bool IsNewerThan(const CTransaction& old) const
459 if (vin.size() != old.vin.size())
461 for (int i = 0; i < vin.size(); i++)
462 if (vin[i].prevout != old.vin[i].prevout)
466 unsigned int nLowest = UINT_MAX;
467 for (int i = 0; i < vin.size(); i++)
469 if (vin[i].nSequence != old.vin[i].nSequence)
471 if (vin[i].nSequence <= nLowest)
474 nLowest = vin[i].nSequence;
476 if (old.vin[i].nSequence < nLowest)
479 nLowest = old.vin[i].nSequence;
486 bool IsCoinBase() const
488 return (vin.size() == 1 && vin[0].prevout.IsNull());
491 int GetSigOpCount() const
494 BOOST_FOREACH(const CTxIn& txin, vin)
495 n += txin.scriptSig.GetSigOpCount();
496 BOOST_FOREACH(const CTxOut& txout, vout)
497 n += txout.scriptPubKey.GetSigOpCount();
501 bool IsStandard() const
503 BOOST_FOREACH(const CTxIn& txin, vin)
504 if (!txin.scriptSig.IsPushOnly())
505 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
506 BOOST_FOREACH(const CTxOut& txout, vout)
507 if (!::IsStandard(txout.scriptPubKey))
508 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
512 int64 GetValueOut() const
515 BOOST_FOREACH(const CTxOut& txout, vout)
517 nValueOut += txout.nValue;
518 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
519 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
524 static bool AllowFree(double dPriority)
526 // Large (in bytes) low-priority (new, small-coin) transactions
528 return dPriority > COIN * 144 / 250;
531 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
533 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
534 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
536 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
537 unsigned int nNewBlockSize = nBlockSize + nBytes;
538 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
544 // Transactions under 10K are free
545 // (about 4500bc if made of 50bc inputs)
551 // Free transaction area
552 if (nNewBlockSize < 27000)
557 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
558 if (nMinFee < nBaseFee)
559 BOOST_FOREACH(const CTxOut& txout, vout)
560 if (txout.nValue < CENT)
563 // Raise the price as the block approaches full
564 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
566 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
568 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
571 if (!MoneyRange(nMinFee))
577 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
579 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
581 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
584 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
585 return error("CTransaction::ReadFromDisk() : fseek failed");
588 // Return file pointer
591 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
592 return error("CTransaction::ReadFromDisk() : second fseek failed");
593 *pfileRet = filein.release();
598 friend bool operator==(const CTransaction& a, const CTransaction& b)
600 return (a.nVersion == b.nVersion &&
603 a.nLockTime == b.nLockTime);
606 friend bool operator!=(const CTransaction& a, const CTransaction& b)
612 std::string ToString() const
615 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
616 GetHash().ToString().substr(0,10).c_str(),
621 for (int i = 0; i < vin.size(); i++)
622 str += " " + vin[i].ToString() + "\n";
623 for (int i = 0; i < vout.size(); i++)
624 str += " " + vout[i].ToString() + "\n";
630 printf("%s", ToString().c_str());
634 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
635 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
636 bool ReadFromDisk(COutPoint prevout);
637 bool DisconnectInputs(CTxDB& txdb);
638 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
639 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
640 bool ClientConnectInputs();
641 bool CheckTransaction() const;
642 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
643 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
645 bool AddToMemoryPoolUnchecked();
647 bool RemoveFromMemoryPool();
655 // A transaction with a merkle branch linking it to the block chain
657 class CMerkleTx : public CTransaction
661 std::vector<uint256> vMerkleBranch;
665 mutable char fMerkleVerified;
673 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
682 fMerkleVerified = false;
688 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
689 nVersion = this->nVersion;
690 READWRITE(hashBlock);
691 READWRITE(vMerkleBranch);
696 int SetMerkleBranch(const CBlock* pblock=NULL);
697 int GetDepthInMainChain(int& nHeightRet) const;
698 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
699 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
700 int GetBlocksToMaturity() const;
701 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
702 bool AcceptToMemoryPool();
709 // A txdb record that contains the disk location of a transaction and the
710 // locations of transactions that spend its outputs. vSpent is really only
711 // used as a flag, but having the location is very helpful for debugging.
717 std::vector<CDiskTxPos> vSpent;
724 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
727 vSpent.resize(nOutputs);
732 if (!(nType & SER_GETHASH))
749 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
751 return (a.pos == b.pos &&
752 a.vSpent == b.vSpent);
755 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
759 int GetDepthInMainChain() const;
767 // Nodes collect new transactions into a block, hash them into a hash tree,
768 // and scan through nonce values to make the block's hash satisfy proof-of-work
769 // requirements. When they solve the proof-of-work, they broadcast the block
770 // to everyone and the block is added to the block chain. The first transaction
771 // in the block is a special one that creates a new coin owned by the creator
774 // Blocks are appended to blk0001.dat files on disk. Their location on disk
775 // is indexed by CBlockIndex objects in memory.
782 uint256 hashPrevBlock;
783 uint256 hashMerkleRoot;
789 std::vector<CTransaction> vtx;
792 mutable std::vector<uint256> vMerkleTree;
794 // Denial-of-service detection:
796 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
805 READWRITE(this->nVersion);
806 nVersion = this->nVersion;
807 READWRITE(hashPrevBlock);
808 READWRITE(hashMerkleRoot);
813 // ConnectBlock depends on vtx being last so it can calculate offset
814 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
817 const_cast<CBlock*>(this)->vtx.clear();
838 uint256 GetHash() const
840 return Hash(BEGIN(nVersion), END(nNonce));
843 int64 GetBlockTime() const
848 int GetSigOpCount() const
851 BOOST_FOREACH(const CTransaction& tx, vtx)
852 n += tx.GetSigOpCount();
857 uint256 BuildMerkleTree() const
860 BOOST_FOREACH(const CTransaction& tx, vtx)
861 vMerkleTree.push_back(tx.GetHash());
863 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
865 for (int i = 0; i < nSize; i += 2)
867 int i2 = std::min(i+1, nSize-1);
868 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
869 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
873 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
876 std::vector<uint256> GetMerkleBranch(int nIndex) const
878 if (vMerkleTree.empty())
880 std::vector<uint256> vMerkleBranch;
882 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
884 int i = std::min(nIndex^1, nSize-1);
885 vMerkleBranch.push_back(vMerkleTree[j+i]);
889 return vMerkleBranch;
892 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
896 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
899 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
901 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
908 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
910 // Open history file to append
911 CAutoFile fileout = AppendBlockFile(nFileRet);
913 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
915 // Write index header
916 unsigned int nSize = fileout.GetSerializeSize(*this);
917 fileout << FLATDATA(pchMessageStart) << nSize;
920 nBlockPosRet = ftell(fileout);
921 if (nBlockPosRet == -1)
922 return error("CBlock::WriteToDisk() : ftell failed");
925 // Flush stdio buffers and commit to disk before returning
927 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
930 _commit(_fileno(fileout));
932 fsync(fileno(fileout));
939 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
943 // Open history file to read
944 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
946 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
947 if (!fReadTransactions)
948 filein.nType |= SER_BLOCKHEADERONLY;
954 if (!CheckProofOfWork(GetHash(), nBits))
955 return error("CBlock::ReadFromDisk() : errors in block header");
964 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
965 GetHash().ToString().substr(0,20).c_str(),
967 hashPrevBlock.ToString().substr(0,20).c_str(),
968 hashMerkleRoot.ToString().substr(0,10).c_str(),
969 nTime, nBits, nNonce,
971 for (int i = 0; i < vtx.size(); i++)
976 printf(" vMerkleTree: ");
977 for (int i = 0; i < vMerkleTree.size(); i++)
978 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
983 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
984 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
985 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
986 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
987 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
988 bool CheckBlock() const;
998 // The block chain is a tree shaped structure starting with the
999 // genesis block at the root, with each block potentially having multiple
1000 // candidates to be the next block. pprev and pnext link a path through the
1001 // main/longest chain. A blockindex may have multiple pprev pointing back
1002 // to it, but pnext will only point forward to the longest branch, or will
1003 // be null if the block is not part of the longest chain.
1008 const uint256* phashBlock;
1012 unsigned int nBlockPos;
1014 CBigNum bnChainWork;
1018 uint256 hashMerkleRoot;
1021 unsigned int nNonce;
1041 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1047 nBlockPos = nBlockPosIn;
1051 nVersion = block.nVersion;
1052 hashMerkleRoot = block.hashMerkleRoot;
1053 nTime = block.nTime;
1054 nBits = block.nBits;
1055 nNonce = block.nNonce;
1058 CBlock GetBlockHeader() const
1061 block.nVersion = nVersion;
1063 block.hashPrevBlock = pprev->GetBlockHash();
1064 block.hashMerkleRoot = hashMerkleRoot;
1065 block.nTime = nTime;
1066 block.nBits = nBits;
1067 block.nNonce = nNonce;
1071 uint256 GetBlockHash() const
1076 int64 GetBlockTime() const
1078 return (int64)nTime;
1081 CBigNum GetBlockWork() const
1084 bnTarget.SetCompact(nBits);
1087 return (CBigNum(1)<<256) / (bnTarget+1);
1090 bool IsInMainChain() const
1092 return (pnext || this == pindexBest);
1095 bool CheckIndex() const
1097 return CheckProofOfWork(GetBlockHash(), nBits);
1100 bool EraseBlockFromDisk()
1102 // Open history file
1103 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1107 // Overwrite with empty null block
1115 enum { nMedianTimeSpan=11 };
1117 int64 GetMedianTimePast() const
1119 int64 pmedian[nMedianTimeSpan];
1120 int64* pbegin = &pmedian[nMedianTimeSpan];
1121 int64* pend = &pmedian[nMedianTimeSpan];
1123 const CBlockIndex* pindex = this;
1124 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1125 *(--pbegin) = pindex->GetBlockTime();
1127 std::sort(pbegin, pend);
1128 return pbegin[(pend - pbegin)/2];
1131 int64 GetMedianTime() const
1133 const CBlockIndex* pindex = this;
1134 for (int i = 0; i < nMedianTimeSpan/2; i++)
1137 return GetBlockTime();
1138 pindex = pindex->pnext;
1140 return pindex->GetMedianTimePast();
1145 std::string ToString() const
1147 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1148 pprev, pnext, nFile, nBlockPos, nHeight,
1149 hashMerkleRoot.ToString().substr(0,10).c_str(),
1150 GetBlockHash().ToString().substr(0,20).c_str());
1155 printf("%s\n", ToString().c_str());
1162 // Used to marshal pointers into hashes for db storage.
1164 class CDiskBlockIndex : public CBlockIndex
1176 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1178 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1179 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1184 if (!(nType & SER_GETHASH))
1185 READWRITE(nVersion);
1187 READWRITE(hashNext);
1189 READWRITE(nBlockPos);
1193 READWRITE(this->nVersion);
1194 READWRITE(hashPrev);
1195 READWRITE(hashMerkleRoot);
1201 uint256 GetBlockHash() const
1204 block.nVersion = nVersion;
1205 block.hashPrevBlock = hashPrev;
1206 block.hashMerkleRoot = hashMerkleRoot;
1207 block.nTime = nTime;
1208 block.nBits = nBits;
1209 block.nNonce = nNonce;
1210 return block.GetHash();
1214 std::string ToString() const
1216 std::string str = "CDiskBlockIndex(";
1217 str += CBlockIndex::ToString();
1218 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1219 GetBlockHash().ToString().c_str(),
1220 hashPrev.ToString().substr(0,20).c_str(),
1221 hashNext.ToString().substr(0,20).c_str());
1227 printf("%s\n", ToString().c_str());
1239 // Describes a place in the block chain to another node such that if the
1240 // other node doesn't have the same branch, it can find a recent common trunk.
1241 // The further back it is, the further before the fork it may be.
1246 std::vector<uint256> vHave;
1253 explicit CBlockLocator(const CBlockIndex* pindex)
1258 explicit CBlockLocator(uint256 hashBlock)
1260 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1261 if (mi != mapBlockIndex.end())
1267 if (!(nType & SER_GETHASH))
1268 READWRITE(nVersion);
1279 return vHave.empty();
1282 void Set(const CBlockIndex* pindex)
1288 vHave.push_back(pindex->GetBlockHash());
1290 // Exponentially larger steps back
1291 for (int i = 0; pindex && i < nStep; i++)
1292 pindex = pindex->pprev;
1293 if (vHave.size() > 10)
1296 vHave.push_back(hashGenesisBlock);
1299 int GetDistanceBack()
1301 // Retrace how far back it was in the sender's branch
1304 BOOST_FOREACH(const uint256& hash, vHave)
1306 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1307 if (mi != mapBlockIndex.end())
1309 CBlockIndex* pindex = (*mi).second;
1310 if (pindex->IsInMainChain())
1320 CBlockIndex* GetBlockIndex()
1322 // Find the first block the caller has in the main chain
1323 BOOST_FOREACH(const uint256& hash, vHave)
1325 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1326 if (mi != mapBlockIndex.end())
1328 CBlockIndex* pindex = (*mi).second;
1329 if (pindex->IsInMainChain())
1333 return pindexGenesisBlock;
1336 uint256 GetBlockHash()
1338 // Find the first block the caller has in the main chain
1339 BOOST_FOREACH(const uint256& hash, vHave)
1341 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1342 if (mi != mapBlockIndex.end())
1344 CBlockIndex* pindex = (*mi).second;
1345 if (pindex->IsInMainChain())
1349 return hashGenesisBlock;
1354 CBlockIndex* pindex = GetBlockIndex();
1357 return pindex->nHeight;
1370 // Alerts are for notifying old versions if they become too obsolete and
1371 // need to upgrade. The message is displayed in the status bar.
1372 // Alert messages are broadcast as a vector of signed data. Unserializing may
1373 // not read the entire buffer if the alert is for a newer version, but older
1374 // versions can still relay the original data.
1376 class CUnsignedAlert
1380 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1384 std::set<int> setCancel;
1385 int nMinVer; // lowest version inclusive
1386 int nMaxVer; // highest version inclusive
1387 std::set<std::string> setSubVer; // empty matches all
1391 std::string strComment;
1392 std::string strStatusBar;
1393 std::string strReserved;
1397 READWRITE(this->nVersion);
1398 nVersion = this->nVersion;
1399 READWRITE(nRelayUntil);
1400 READWRITE(nExpiration);
1403 READWRITE(setCancel);
1406 READWRITE(setSubVer);
1407 READWRITE(nPriority);
1409 READWRITE(strComment);
1410 READWRITE(strStatusBar);
1411 READWRITE(strReserved);
1428 strStatusBar.clear();
1429 strReserved.clear();
1432 std::string ToString() const
1434 std::string strSetCancel;
1435 BOOST_FOREACH(int n, setCancel)
1436 strSetCancel += strprintf("%d ", n);
1437 std::string strSetSubVer;
1438 BOOST_FOREACH(std::string str, setSubVer)
1439 strSetSubVer += "\"" + str + "\" ";
1443 " nRelayUntil = %"PRI64d"\n"
1444 " nExpiration = %"PRI64d"\n"
1452 " strComment = \"%s\"\n"
1453 " strStatusBar = \"%s\"\n"
1460 strSetCancel.c_str(),
1463 strSetSubVer.c_str(),
1466 strStatusBar.c_str());
1471 printf("%s", ToString().c_str());
1475 class CAlert : public CUnsignedAlert
1478 std::vector<unsigned char> vchMsg;
1479 std::vector<unsigned char> vchSig;
1494 CUnsignedAlert::SetNull();
1501 return (nExpiration == 0);
1504 uint256 GetHash() const
1506 return SerializeHash(*this);
1509 bool IsInEffect() const
1511 return (GetAdjustedTime() < nExpiration);
1514 bool Cancels(const CAlert& alert) const
1517 return false; // this was a no-op before 31403
1518 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1521 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1523 return (IsInEffect() &&
1524 nMinVer <= nVersion && nVersion <= nMaxVer &&
1525 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1528 bool AppliesToMe() const
1530 return AppliesTo(VERSION, ::pszSubVer);
1533 bool RelayTo(CNode* pnode) const
1537 // returns true if wasn't already contained in the set
1538 if (pnode->setKnown.insert(GetHash()).second)
1540 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1542 GetAdjustedTime() < nRelayUntil)
1544 pnode->PushMessage("alert", *this);
1551 bool CheckSignature()
1554 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1555 return error("CAlert::CheckSignature() : SetPubKey failed");
1556 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1557 return error("CAlert::CheckSignature() : verify signature failed");
1559 // Now unserialize the data
1560 CDataStream sMsg(vchMsg);
1561 sMsg >> *(CUnsignedAlert*)this;
1565 bool ProcessAlert();