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.
27 class CRequestTracker;
31 static const unsigned int MAX_BLOCK_SIZE = 1000000;
32 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
33 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
34 static const int64 COIN = 100000000;
35 static const int64 CENT = 1000000;
36 static const int64 MIN_TX_FEE = 50000;
37 static const int64 MIN_RELAY_TX_FEE = 10000;
38 static const int64 MAX_MONEY = 21000000 * COIN;
39 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
40 static const int COINBASE_MATURITY = 100;
41 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
42 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
44 static const int fHaveUPnP = true;
46 static const int fHaveUPnP = false;
54 extern CCriticalSection cs_main;
55 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
56 extern uint256 hashGenesisBlock;
57 extern CBigNum bnProofOfWorkLimit;
58 extern CBlockIndex* pindexGenesisBlock;
59 extern int nBestHeight;
60 extern CBigNum bnBestChainWork;
61 extern CBigNum bnBestInvalidWork;
62 extern uint256 hashBestChain;
63 extern CBlockIndex* pindexBest;
64 extern unsigned int nTransactionsUpdated;
65 extern double dHashesPerSec;
66 extern int64 nHPSTimerStart;
67 extern int64 nTimeBestReceived;
68 extern CCriticalSection cs_setpwalletRegistered;
69 extern std::set<CWallet*> setpwalletRegistered;
72 extern int fGenerateBitcoins;
73 extern int64 nTransactionFee;
74 extern int fLimitProcessors;
75 extern int nLimitProcessors;
76 extern int fMinimizeToTray;
77 extern int fMinimizeOnClose;
88 void RegisterWallet(CWallet* pwalletIn);
89 void UnregisterWallet(CWallet* pwalletIn);
90 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
91 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
92 FILE* AppendBlockFile(unsigned int& nFileRet);
93 bool LoadBlockIndex(bool fAllowNew=true);
94 void PrintBlockTree();
95 bool ProcessMessages(CNode* pfrom);
96 bool SendMessages(CNode* pto, bool fSendTrickle);
97 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
98 CBlock* CreateNewBlock(CReserveKey& reservekey);
99 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
100 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
101 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
102 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
103 int GetTotalBlocksEstimate();
104 bool IsInitialBlockDownload();
105 std::string GetWarnings(std::string strFor);
118 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
121 bool WriteSetting(const std::string& strKey, const T& value)
124 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126 std::string strWalletFile;
127 if (!GetWalletFile(pwallet, strWalletFile))
129 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
139 unsigned int nBlockPos;
147 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
150 nBlockPos = nBlockPosIn;
154 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
155 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
156 bool IsNull() const { return (nFile == -1); }
158 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
160 return (a.nFile == b.nFile &&
161 a.nBlockPos == b.nBlockPos &&
162 a.nTxPos == b.nTxPos);
165 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
170 std::string ToString() const
173 return strprintf("null");
175 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
180 printf("%s", ToString().c_str());
193 CInPoint() { SetNull(); }
194 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
195 void SetNull() { ptx = NULL; n = -1; }
196 bool IsNull() const { return (ptx == NULL && n == -1); }
208 COutPoint() { SetNull(); }
209 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
210 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
211 void SetNull() { hash = 0; n = -1; }
212 bool IsNull() const { return (hash == 0 && n == -1); }
214 friend bool operator<(const COutPoint& a, const COutPoint& b)
216 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
219 friend bool operator==(const COutPoint& a, const COutPoint& b)
221 return (a.hash == b.hash && a.n == b.n);
224 friend bool operator!=(const COutPoint& a, const COutPoint& b)
229 std::string ToString() const
231 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
236 printf("%s\n", ToString().c_str());
244 // An input of a transaction. It contains the location of the previous
245 // transaction's output that it claims and a signature that matches the
246 // output's public key.
253 unsigned int nSequence;
257 nSequence = UINT_MAX;
260 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
263 scriptSig = scriptSigIn;
264 nSequence = nSequenceIn;
267 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
269 prevout = COutPoint(hashPrevTx, nOut);
270 scriptSig = scriptSigIn;
271 nSequence = nSequenceIn;
277 READWRITE(scriptSig);
278 READWRITE(nSequence);
283 return (nSequence == UINT_MAX);
286 friend bool operator==(const CTxIn& a, const CTxIn& b)
288 return (a.prevout == b.prevout &&
289 a.scriptSig == b.scriptSig &&
290 a.nSequence == b.nSequence);
293 friend bool operator!=(const CTxIn& a, const CTxIn& b)
298 std::string ToString() const
301 str += strprintf("CTxIn(");
302 str += prevout.ToString();
303 if (prevout.IsNull())
304 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
306 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
307 if (nSequence != UINT_MAX)
308 str += strprintf(", nSequence=%u", nSequence);
315 printf("%s\n", ToString().c_str());
323 // An output of a transaction. It contains the public key that the next input
324 // must be able to sign with to claim it.
330 CScript scriptPubKey;
337 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
340 scriptPubKey = scriptPubKeyIn;
346 READWRITE(scriptPubKey);
352 scriptPubKey.clear();
357 return (nValue == -1);
360 uint256 GetHash() const
362 return SerializeHash(*this);
365 friend bool operator==(const CTxOut& a, const CTxOut& b)
367 return (a.nValue == b.nValue &&
368 a.scriptPubKey == b.scriptPubKey);
371 friend bool operator!=(const CTxOut& a, const CTxOut& b)
376 std::string ToString() const
378 if (scriptPubKey.size() < 6)
379 return "CTxOut(error)";
380 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
385 printf("%s\n", ToString().c_str());
393 // The basic transaction that is broadcasted on the network and contained in
394 // blocks. A transaction can contain multiple inputs and outputs.
400 std::vector<CTxIn> vin;
401 std::vector<CTxOut> vout;
402 unsigned int nLockTime;
412 READWRITE(this->nVersion);
413 nVersion = this->nVersion;
416 READWRITE(nLockTime);
429 return (vin.empty() && vout.empty());
432 uint256 GetHash() const
434 return SerializeHash(*this);
437 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
439 // Time based nLockTime implemented in 0.1.6
442 if (nBlockHeight == 0)
443 nBlockHeight = nBestHeight;
445 nBlockTime = GetAdjustedTime();
446 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
448 BOOST_FOREACH(const CTxIn& txin, vin)
454 bool IsNewerThan(const CTransaction& old) const
456 if (vin.size() != old.vin.size())
458 for (int i = 0; i < vin.size(); i++)
459 if (vin[i].prevout != old.vin[i].prevout)
463 unsigned int nLowest = UINT_MAX;
464 for (int i = 0; i < vin.size(); i++)
466 if (vin[i].nSequence != old.vin[i].nSequence)
468 if (vin[i].nSequence <= nLowest)
471 nLowest = vin[i].nSequence;
473 if (old.vin[i].nSequence < nLowest)
476 nLowest = old.vin[i].nSequence;
483 bool IsCoinBase() const
485 return (vin.size() == 1 && vin[0].prevout.IsNull());
488 int GetSigOpCount() const
491 BOOST_FOREACH(const CTxIn& txin, vin)
492 n += txin.scriptSig.GetSigOpCount();
493 BOOST_FOREACH(const CTxOut& txout, vout)
494 n += txout.scriptPubKey.GetSigOpCount();
498 bool IsStandard() const
500 BOOST_FOREACH(const CTxIn& txin, vin)
501 if (!txin.scriptSig.IsPushOnly())
502 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
503 BOOST_FOREACH(const CTxOut& txout, vout)
504 if (!::IsStandard(txout.scriptPubKey))
505 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
509 int64 GetValueOut() const
512 BOOST_FOREACH(const CTxOut& txout, vout)
514 nValueOut += txout.nValue;
515 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
516 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
521 static bool AllowFree(double dPriority)
523 // Large (in bytes) low-priority (new, small-coin) transactions
525 return dPriority > COIN * 144 / 250;
528 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
530 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
531 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
533 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
534 unsigned int nNewBlockSize = nBlockSize + nBytes;
535 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
541 // Transactions under 10K are free
542 // (about 4500bc if made of 50bc inputs)
548 // Free transaction area
549 if (nNewBlockSize < 27000)
554 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
555 if (nMinFee < nBaseFee)
556 BOOST_FOREACH(const CTxOut& txout, vout)
557 if (txout.nValue < CENT)
560 // Raise the price as the block approaches full
561 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
563 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
565 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
568 if (!MoneyRange(nMinFee))
574 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
576 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
578 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
581 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
582 return error("CTransaction::ReadFromDisk() : fseek failed");
585 // Return file pointer
588 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
589 return error("CTransaction::ReadFromDisk() : second fseek failed");
590 *pfileRet = filein.release();
595 friend bool operator==(const CTransaction& a, const CTransaction& b)
597 return (a.nVersion == b.nVersion &&
600 a.nLockTime == b.nLockTime);
603 friend bool operator!=(const CTransaction& a, const CTransaction& b)
609 std::string ToString() const
612 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
613 GetHash().ToString().substr(0,10).c_str(),
618 for (int i = 0; i < vin.size(); i++)
619 str += " " + vin[i].ToString() + "\n";
620 for (int i = 0; i < vout.size(); i++)
621 str += " " + vout[i].ToString() + "\n";
627 printf("%s", ToString().c_str());
631 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
632 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
633 bool ReadFromDisk(COutPoint prevout);
634 bool DisconnectInputs(CTxDB& txdb);
635 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
636 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
637 bool ClientConnectInputs();
638 bool CheckTransaction() const;
639 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
640 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
642 bool AddToMemoryPoolUnchecked();
644 bool RemoveFromMemoryPool();
652 // A transaction with a merkle branch linking it to the block chain
654 class CMerkleTx : public CTransaction
658 std::vector<uint256> vMerkleBranch;
662 mutable char fMerkleVerified;
670 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
679 fMerkleVerified = false;
685 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
686 nVersion = this->nVersion;
687 READWRITE(hashBlock);
688 READWRITE(vMerkleBranch);
693 int SetMerkleBranch(const CBlock* pblock=NULL);
694 int GetDepthInMainChain(int& nHeightRet) const;
695 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
696 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
697 int GetBlocksToMaturity() const;
698 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
699 bool AcceptToMemoryPool();
706 // A txdb record that contains the disk location of a transaction and the
707 // locations of transactions that spend its outputs. vSpent is really only
708 // used as a flag, but having the location is very helpful for debugging.
714 std::vector<CDiskTxPos> vSpent;
721 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
724 vSpent.resize(nOutputs);
729 if (!(nType & SER_GETHASH))
746 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
748 return (a.pos == b.pos &&
749 a.vSpent == b.vSpent);
752 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
756 int GetDepthInMainChain() const;
764 // Nodes collect new transactions into a block, hash them into a hash tree,
765 // and scan through nonce values to make the block's hash satisfy proof-of-work
766 // requirements. When they solve the proof-of-work, they broadcast the block
767 // to everyone and the block is added to the block chain. The first transaction
768 // in the block is a special one that creates a new coin owned by the creator
771 // Blocks are appended to blk0001.dat files on disk. Their location on disk
772 // is indexed by CBlockIndex objects in memory.
779 uint256 hashPrevBlock;
780 uint256 hashMerkleRoot;
786 std::vector<CTransaction> vtx;
789 mutable std::vector<uint256> vMerkleTree;
799 READWRITE(this->nVersion);
800 nVersion = this->nVersion;
801 READWRITE(hashPrevBlock);
802 READWRITE(hashMerkleRoot);
807 // ConnectBlock depends on vtx being last so it can calculate offset
808 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
811 const_cast<CBlock*>(this)->vtx.clear();
831 uint256 GetHash() const
833 return Hash(BEGIN(nVersion), END(nNonce));
836 int64 GetBlockTime() const
841 int GetSigOpCount() const
844 BOOST_FOREACH(const CTransaction& tx, vtx)
845 n += tx.GetSigOpCount();
850 uint256 BuildMerkleTree() const
853 BOOST_FOREACH(const CTransaction& tx, vtx)
854 vMerkleTree.push_back(tx.GetHash());
856 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
858 for (int i = 0; i < nSize; i += 2)
860 int i2 = std::min(i+1, nSize-1);
861 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
862 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
866 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
869 std::vector<uint256> GetMerkleBranch(int nIndex) const
871 if (vMerkleTree.empty())
873 std::vector<uint256> vMerkleBranch;
875 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
877 int i = std::min(nIndex^1, nSize-1);
878 vMerkleBranch.push_back(vMerkleTree[j+i]);
882 return vMerkleBranch;
885 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
889 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
892 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
894 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
901 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
903 // Open history file to append
904 CAutoFile fileout = AppendBlockFile(nFileRet);
906 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
908 // Write index header
909 unsigned int nSize = fileout.GetSerializeSize(*this);
910 fileout << FLATDATA(pchMessageStart) << nSize;
913 nBlockPosRet = ftell(fileout);
914 if (nBlockPosRet == -1)
915 return error("CBlock::WriteToDisk() : ftell failed");
918 // Flush stdio buffers and commit to disk before returning
920 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
923 _commit(_fileno(fileout));
925 fsync(fileno(fileout));
932 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
936 // Open history file to read
937 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
939 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
940 if (!fReadTransactions)
941 filein.nType |= SER_BLOCKHEADERONLY;
947 if (!CheckProofOfWork(GetHash(), nBits))
948 return error("CBlock::ReadFromDisk() : errors in block header");
957 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
958 GetHash().ToString().substr(0,20).c_str(),
960 hashPrevBlock.ToString().substr(0,20).c_str(),
961 hashMerkleRoot.ToString().substr(0,10).c_str(),
962 nTime, nBits, nNonce,
964 for (int i = 0; i < vtx.size(); i++)
969 printf(" vMerkleTree: ");
970 for (int i = 0; i < vMerkleTree.size(); i++)
971 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
976 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
977 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
978 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
979 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
980 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
981 bool CheckBlock() const;
991 // The block chain is a tree shaped structure starting with the
992 // genesis block at the root, with each block potentially having multiple
993 // candidates to be the next block. pprev and pnext link a path through the
994 // main/longest chain. A blockindex may have multiple pprev pointing back
995 // to it, but pnext will only point forward to the longest branch, or will
996 // be null if the block is not part of the longest chain.
1001 const uint256* phashBlock;
1005 unsigned int nBlockPos;
1007 CBigNum bnChainWork;
1011 uint256 hashMerkleRoot;
1014 unsigned int nNonce;
1034 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1040 nBlockPos = nBlockPosIn;
1044 nVersion = block.nVersion;
1045 hashMerkleRoot = block.hashMerkleRoot;
1046 nTime = block.nTime;
1047 nBits = block.nBits;
1048 nNonce = block.nNonce;
1051 CBlock GetBlockHeader() const
1054 block.nVersion = nVersion;
1056 block.hashPrevBlock = pprev->GetBlockHash();
1057 block.hashMerkleRoot = hashMerkleRoot;
1058 block.nTime = nTime;
1059 block.nBits = nBits;
1060 block.nNonce = nNonce;
1064 uint256 GetBlockHash() const
1069 int64 GetBlockTime() const
1071 return (int64)nTime;
1074 CBigNum GetBlockWork() const
1077 bnTarget.SetCompact(nBits);
1080 return (CBigNum(1)<<256) / (bnTarget+1);
1083 bool IsInMainChain() const
1085 return (pnext || this == pindexBest);
1088 bool CheckIndex() const
1090 return CheckProofOfWork(GetBlockHash(), nBits);
1093 bool EraseBlockFromDisk()
1095 // Open history file
1096 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1100 // Overwrite with empty null block
1108 enum { nMedianTimeSpan=11 };
1110 int64 GetMedianTimePast() const
1112 int64 pmedian[nMedianTimeSpan];
1113 int64* pbegin = &pmedian[nMedianTimeSpan];
1114 int64* pend = &pmedian[nMedianTimeSpan];
1116 const CBlockIndex* pindex = this;
1117 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1118 *(--pbegin) = pindex->GetBlockTime();
1120 std::sort(pbegin, pend);
1121 return pbegin[(pend - pbegin)/2];
1124 int64 GetMedianTime() const
1126 const CBlockIndex* pindex = this;
1127 for (int i = 0; i < nMedianTimeSpan/2; i++)
1130 return GetBlockTime();
1131 pindex = pindex->pnext;
1133 return pindex->GetMedianTimePast();
1138 std::string ToString() const
1140 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1141 pprev, pnext, nFile, nBlockPos, nHeight,
1142 hashMerkleRoot.ToString().substr(0,10).c_str(),
1143 GetBlockHash().ToString().substr(0,20).c_str());
1148 printf("%s\n", ToString().c_str());
1155 // Used to marshal pointers into hashes for db storage.
1157 class CDiskBlockIndex : public CBlockIndex
1169 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1171 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1172 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1177 if (!(nType & SER_GETHASH))
1178 READWRITE(nVersion);
1180 READWRITE(hashNext);
1182 READWRITE(nBlockPos);
1186 READWRITE(this->nVersion);
1187 READWRITE(hashPrev);
1188 READWRITE(hashMerkleRoot);
1194 uint256 GetBlockHash() const
1197 block.nVersion = nVersion;
1198 block.hashPrevBlock = hashPrev;
1199 block.hashMerkleRoot = hashMerkleRoot;
1200 block.nTime = nTime;
1201 block.nBits = nBits;
1202 block.nNonce = nNonce;
1203 return block.GetHash();
1207 std::string ToString() const
1209 std::string str = "CDiskBlockIndex(";
1210 str += CBlockIndex::ToString();
1211 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1212 GetBlockHash().ToString().c_str(),
1213 hashPrev.ToString().substr(0,20).c_str(),
1214 hashNext.ToString().substr(0,20).c_str());
1220 printf("%s\n", ToString().c_str());
1232 // Describes a place in the block chain to another node such that if the
1233 // other node doesn't have the same branch, it can find a recent common trunk.
1234 // The further back it is, the further before the fork it may be.
1239 std::vector<uint256> vHave;
1246 explicit CBlockLocator(const CBlockIndex* pindex)
1251 explicit CBlockLocator(uint256 hashBlock)
1253 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1254 if (mi != mapBlockIndex.end())
1260 if (!(nType & SER_GETHASH))
1261 READWRITE(nVersion);
1272 return vHave.empty();
1275 void Set(const CBlockIndex* pindex)
1281 vHave.push_back(pindex->GetBlockHash());
1283 // Exponentially larger steps back
1284 for (int i = 0; pindex && i < nStep; i++)
1285 pindex = pindex->pprev;
1286 if (vHave.size() > 10)
1289 vHave.push_back(hashGenesisBlock);
1292 int GetDistanceBack()
1294 // Retrace how far back it was in the sender's branch
1297 BOOST_FOREACH(const uint256& hash, vHave)
1299 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1300 if (mi != mapBlockIndex.end())
1302 CBlockIndex* pindex = (*mi).second;
1303 if (pindex->IsInMainChain())
1313 CBlockIndex* GetBlockIndex()
1315 // Find the first block the caller has in the main chain
1316 BOOST_FOREACH(const uint256& hash, vHave)
1318 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1319 if (mi != mapBlockIndex.end())
1321 CBlockIndex* pindex = (*mi).second;
1322 if (pindex->IsInMainChain())
1326 return pindexGenesisBlock;
1329 uint256 GetBlockHash()
1331 // Find the first block the caller has in the main chain
1332 BOOST_FOREACH(const uint256& hash, vHave)
1334 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1335 if (mi != mapBlockIndex.end())
1337 CBlockIndex* pindex = (*mi).second;
1338 if (pindex->IsInMainChain())
1342 return hashGenesisBlock;
1347 CBlockIndex* pindex = GetBlockIndex();
1350 return pindex->nHeight;
1363 // Alerts are for notifying old versions if they become too obsolete and
1364 // need to upgrade. The message is displayed in the status bar.
1365 // Alert messages are broadcast as a vector of signed data. Unserializing may
1366 // not read the entire buffer if the alert is for a newer version, but older
1367 // versions can still relay the original data.
1369 class CUnsignedAlert
1373 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1377 std::set<int> setCancel;
1378 int nMinVer; // lowest version inclusive
1379 int nMaxVer; // highest version inclusive
1380 std::set<std::string> setSubVer; // empty matches all
1384 std::string strComment;
1385 std::string strStatusBar;
1386 std::string strReserved;
1390 READWRITE(this->nVersion);
1391 nVersion = this->nVersion;
1392 READWRITE(nRelayUntil);
1393 READWRITE(nExpiration);
1396 READWRITE(setCancel);
1399 READWRITE(setSubVer);
1400 READWRITE(nPriority);
1402 READWRITE(strComment);
1403 READWRITE(strStatusBar);
1404 READWRITE(strReserved);
1421 strStatusBar.clear();
1422 strReserved.clear();
1425 std::string ToString() const
1427 std::string strSetCancel;
1428 BOOST_FOREACH(int n, setCancel)
1429 strSetCancel += strprintf("%d ", n);
1430 std::string strSetSubVer;
1431 BOOST_FOREACH(std::string str, setSubVer)
1432 strSetSubVer += "\"" + str + "\" ";
1436 " nRelayUntil = %"PRI64d"\n"
1437 " nExpiration = %"PRI64d"\n"
1445 " strComment = \"%s\"\n"
1446 " strStatusBar = \"%s\"\n"
1453 strSetCancel.c_str(),
1456 strSetSubVer.c_str(),
1459 strStatusBar.c_str());
1464 printf("%s", ToString().c_str());
1468 class CAlert : public CUnsignedAlert
1471 std::vector<unsigned char> vchMsg;
1472 std::vector<unsigned char> vchSig;
1487 CUnsignedAlert::SetNull();
1494 return (nExpiration == 0);
1497 uint256 GetHash() const
1499 return SerializeHash(*this);
1502 bool IsInEffect() const
1504 return (GetAdjustedTime() < nExpiration);
1507 bool Cancels(const CAlert& alert) const
1510 return false; // this was a no-op before 31403
1511 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1514 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1516 return (IsInEffect() &&
1517 nMinVer <= nVersion && nVersion <= nMaxVer &&
1518 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1521 bool AppliesToMe() const
1523 return AppliesTo(VERSION, ::pszSubVer);
1526 bool RelayTo(CNode* pnode) const
1530 // returns true if wasn't already contained in the set
1531 if (pnode->setKnown.insert(GetHash()).second)
1533 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1535 GetAdjustedTime() < nRelayUntil)
1537 pnode->PushMessage("alert", *this);
1544 bool CheckSignature()
1547 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1548 return error("CAlert::CheckSignature() : SetPubKey failed");
1549 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1550 return error("CAlert::CheckSignature() : verify signature failed");
1552 // Now unserialize the data
1553 CDataStream sMsg(vchMsg);
1554 sMsg >> *(CUnsignedAlert*)this;
1558 bool ProcessAlert();
1571 extern std::map<uint256, CTransaction> mapTransactions;