1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
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 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
103 int GetNumBlocksOfPeers();
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;
404 // Denial-of-service detection:
406 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
415 READWRITE(this->nVersion);
416 nVersion = this->nVersion;
419 READWRITE(nLockTime);
428 nDoS = 0; // Denial-of-service prevention
433 return (vin.empty() && vout.empty());
436 uint256 GetHash() const
438 return SerializeHash(*this);
441 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
443 // Time based nLockTime implemented in 0.1.6
446 if (nBlockHeight == 0)
447 nBlockHeight = nBestHeight;
449 nBlockTime = GetAdjustedTime();
450 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
452 BOOST_FOREACH(const CTxIn& txin, vin)
458 bool IsNewerThan(const CTransaction& old) const
460 if (vin.size() != old.vin.size())
462 for (int i = 0; i < vin.size(); i++)
463 if (vin[i].prevout != old.vin[i].prevout)
467 unsigned int nLowest = UINT_MAX;
468 for (int i = 0; i < vin.size(); i++)
470 if (vin[i].nSequence != old.vin[i].nSequence)
472 if (vin[i].nSequence <= nLowest)
475 nLowest = vin[i].nSequence;
477 if (old.vin[i].nSequence < nLowest)
480 nLowest = old.vin[i].nSequence;
487 bool IsCoinBase() const
489 return (vin.size() == 1 && vin[0].prevout.IsNull());
492 int GetSigOpCount() const
495 BOOST_FOREACH(const CTxIn& txin, vin)
496 n += txin.scriptSig.GetSigOpCount();
497 BOOST_FOREACH(const CTxOut& txout, vout)
498 n += txout.scriptPubKey.GetSigOpCount();
502 bool IsStandard() const
504 BOOST_FOREACH(const CTxIn& txin, vin)
505 if (!txin.scriptSig.IsPushOnly())
506 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
507 BOOST_FOREACH(const CTxOut& txout, vout)
508 if (!::IsStandard(txout.scriptPubKey))
509 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
513 int64 GetValueOut() const
516 BOOST_FOREACH(const CTxOut& txout, vout)
518 nValueOut += txout.nValue;
519 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
520 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
525 static bool AllowFree(double dPriority)
527 // Large (in bytes) low-priority (new, small-coin) transactions
529 return dPriority > COIN * 144 / 250;
532 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
534 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
535 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
537 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
538 unsigned int nNewBlockSize = nBlockSize + nBytes;
539 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
545 // Transactions under 10K are free
546 // (about 4500bc if made of 50bc inputs)
552 // Free transaction area
553 if (nNewBlockSize < 27000)
558 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
559 if (nMinFee < nBaseFee)
560 BOOST_FOREACH(const CTxOut& txout, vout)
561 if (txout.nValue < CENT)
564 // Raise the price as the block approaches full
565 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
567 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
569 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
572 if (!MoneyRange(nMinFee))
578 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
580 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
582 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
585 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
586 return error("CTransaction::ReadFromDisk() : fseek failed");
589 // Return file pointer
592 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
593 return error("CTransaction::ReadFromDisk() : second fseek failed");
594 *pfileRet = filein.release();
599 friend bool operator==(const CTransaction& a, const CTransaction& b)
601 return (a.nVersion == b.nVersion &&
604 a.nLockTime == b.nLockTime);
607 friend bool operator!=(const CTransaction& a, const CTransaction& b)
613 std::string ToString() const
616 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
617 GetHash().ToString().substr(0,10).c_str(),
622 for (int i = 0; i < vin.size(); i++)
623 str += " " + vin[i].ToString() + "\n";
624 for (int i = 0; i < vout.size(); i++)
625 str += " " + vout[i].ToString() + "\n";
631 printf("%s", ToString().c_str());
635 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
636 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
637 bool ReadFromDisk(COutPoint prevout);
638 bool DisconnectInputs(CTxDB& txdb);
639 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
640 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee,
642 bool ClientConnectInputs();
643 bool CheckTransaction() const;
644 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
645 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
647 bool AddToMemoryPoolUnchecked();
649 bool RemoveFromMemoryPool();
657 // A transaction with a merkle branch linking it to the block chain
659 class CMerkleTx : public CTransaction
663 std::vector<uint256> vMerkleBranch;
667 mutable char fMerkleVerified;
675 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
684 fMerkleVerified = false;
690 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
691 nVersion = this->nVersion;
692 READWRITE(hashBlock);
693 READWRITE(vMerkleBranch);
698 int SetMerkleBranch(const CBlock* pblock=NULL);
699 int GetDepthInMainChain(int& nHeightRet) const;
700 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
701 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
702 int GetBlocksToMaturity() const;
703 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
704 bool AcceptToMemoryPool();
711 // A txdb record that contains the disk location of a transaction and the
712 // locations of transactions that spend its outputs. vSpent is really only
713 // used as a flag, but having the location is very helpful for debugging.
719 std::vector<CDiskTxPos> vSpent;
726 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
729 vSpent.resize(nOutputs);
734 if (!(nType & SER_GETHASH))
751 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
753 return (a.pos == b.pos &&
754 a.vSpent == b.vSpent);
757 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
761 int GetDepthInMainChain() const;
769 // Nodes collect new transactions into a block, hash them into a hash tree,
770 // and scan through nonce values to make the block's hash satisfy proof-of-work
771 // requirements. When they solve the proof-of-work, they broadcast the block
772 // to everyone and the block is added to the block chain. The first transaction
773 // in the block is a special one that creates a new coin owned by the creator
776 // Blocks are appended to blk0001.dat files on disk. Their location on disk
777 // is indexed by CBlockIndex objects in memory.
784 uint256 hashPrevBlock;
785 uint256 hashMerkleRoot;
791 std::vector<CTransaction> vtx;
794 mutable std::vector<uint256> vMerkleTree;
796 // Denial-of-service detection:
798 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
807 READWRITE(this->nVersion);
808 nVersion = this->nVersion;
809 READWRITE(hashPrevBlock);
810 READWRITE(hashMerkleRoot);
815 // ConnectBlock depends on vtx being last so it can calculate offset
816 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
819 const_cast<CBlock*>(this)->vtx.clear();
840 uint256 GetHash() const
842 return Hash(BEGIN(nVersion), END(nNonce));
845 int64 GetBlockTime() const
850 int GetSigOpCount() const
853 BOOST_FOREACH(const CTransaction& tx, vtx)
854 n += tx.GetSigOpCount();
859 uint256 BuildMerkleTree() const
862 BOOST_FOREACH(const CTransaction& tx, vtx)
863 vMerkleTree.push_back(tx.GetHash());
865 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
867 for (int i = 0; i < nSize; i += 2)
869 int i2 = std::min(i+1, nSize-1);
870 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
871 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
875 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
878 std::vector<uint256> GetMerkleBranch(int nIndex) const
880 if (vMerkleTree.empty())
882 std::vector<uint256> vMerkleBranch;
884 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
886 int i = std::min(nIndex^1, nSize-1);
887 vMerkleBranch.push_back(vMerkleTree[j+i]);
891 return vMerkleBranch;
894 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
898 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
901 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
903 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
910 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
912 // Open history file to append
913 CAutoFile fileout = AppendBlockFile(nFileRet);
915 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
917 // Write index header
918 unsigned int nSize = fileout.GetSerializeSize(*this);
919 fileout << FLATDATA(pchMessageStart) << nSize;
922 nBlockPosRet = ftell(fileout);
923 if (nBlockPosRet == -1)
924 return error("CBlock::WriteToDisk() : ftell failed");
927 // Flush stdio buffers and commit to disk before returning
929 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
932 _commit(_fileno(fileout));
934 fsync(fileno(fileout));
941 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
945 // Open history file to read
946 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
948 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
949 if (!fReadTransactions)
950 filein.nType |= SER_BLOCKHEADERONLY;
956 if (!CheckProofOfWork(GetHash(), nBits))
957 return error("CBlock::ReadFromDisk() : errors in block header");
966 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
967 GetHash().ToString().substr(0,20).c_str(),
969 hashPrevBlock.ToString().substr(0,20).c_str(),
970 hashMerkleRoot.ToString().substr(0,10).c_str(),
971 nTime, nBits, nNonce,
973 for (int i = 0; i < vtx.size(); i++)
978 printf(" vMerkleTree: ");
979 for (int i = 0; i < vMerkleTree.size(); i++)
980 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
985 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
986 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
987 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
988 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
989 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
990 bool CheckBlock() const;
1000 // The block chain is a tree shaped structure starting with the
1001 // genesis block at the root, with each block potentially having multiple
1002 // candidates to be the next block. pprev and pnext link a path through the
1003 // main/longest chain. A blockindex may have multiple pprev pointing back
1004 // to it, but pnext will only point forward to the longest branch, or will
1005 // be null if the block is not part of the longest chain.
1010 const uint256* phashBlock;
1014 unsigned int nBlockPos;
1016 CBigNum bnChainWork;
1020 uint256 hashMerkleRoot;
1023 unsigned int nNonce;
1043 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1049 nBlockPos = nBlockPosIn;
1053 nVersion = block.nVersion;
1054 hashMerkleRoot = block.hashMerkleRoot;
1055 nTime = block.nTime;
1056 nBits = block.nBits;
1057 nNonce = block.nNonce;
1060 CBlock GetBlockHeader() const
1063 block.nVersion = nVersion;
1065 block.hashPrevBlock = pprev->GetBlockHash();
1066 block.hashMerkleRoot = hashMerkleRoot;
1067 block.nTime = nTime;
1068 block.nBits = nBits;
1069 block.nNonce = nNonce;
1073 uint256 GetBlockHash() const
1078 int64 GetBlockTime() const
1080 return (int64)nTime;
1083 CBigNum GetBlockWork() const
1086 bnTarget.SetCompact(nBits);
1089 return (CBigNum(1)<<256) / (bnTarget+1);
1092 bool IsInMainChain() const
1094 return (pnext || this == pindexBest);
1097 bool CheckIndex() const
1099 return CheckProofOfWork(GetBlockHash(), nBits);
1102 bool EraseBlockFromDisk()
1104 // Open history file
1105 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1109 // Overwrite with empty null block
1117 enum { nMedianTimeSpan=11 };
1119 int64 GetMedianTimePast() const
1121 int64 pmedian[nMedianTimeSpan];
1122 int64* pbegin = &pmedian[nMedianTimeSpan];
1123 int64* pend = &pmedian[nMedianTimeSpan];
1125 const CBlockIndex* pindex = this;
1126 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1127 *(--pbegin) = pindex->GetBlockTime();
1129 std::sort(pbegin, pend);
1130 return pbegin[(pend - pbegin)/2];
1133 int64 GetMedianTime() const
1135 const CBlockIndex* pindex = this;
1136 for (int i = 0; i < nMedianTimeSpan/2; i++)
1139 return GetBlockTime();
1140 pindex = pindex->pnext;
1142 return pindex->GetMedianTimePast();
1147 std::string ToString() const
1149 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1150 pprev, pnext, nFile, nBlockPos, nHeight,
1151 hashMerkleRoot.ToString().substr(0,10).c_str(),
1152 GetBlockHash().ToString().substr(0,20).c_str());
1157 printf("%s\n", ToString().c_str());
1164 // Used to marshal pointers into hashes for db storage.
1166 class CDiskBlockIndex : public CBlockIndex
1178 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1180 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1181 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1186 if (!(nType & SER_GETHASH))
1187 READWRITE(nVersion);
1189 READWRITE(hashNext);
1191 READWRITE(nBlockPos);
1195 READWRITE(this->nVersion);
1196 READWRITE(hashPrev);
1197 READWRITE(hashMerkleRoot);
1203 uint256 GetBlockHash() const
1206 block.nVersion = nVersion;
1207 block.hashPrevBlock = hashPrev;
1208 block.hashMerkleRoot = hashMerkleRoot;
1209 block.nTime = nTime;
1210 block.nBits = nBits;
1211 block.nNonce = nNonce;
1212 return block.GetHash();
1216 std::string ToString() const
1218 std::string str = "CDiskBlockIndex(";
1219 str += CBlockIndex::ToString();
1220 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1221 GetBlockHash().ToString().c_str(),
1222 hashPrev.ToString().substr(0,20).c_str(),
1223 hashNext.ToString().substr(0,20).c_str());
1229 printf("%s\n", ToString().c_str());
1241 // Describes a place in the block chain to another node such that if the
1242 // other node doesn't have the same branch, it can find a recent common trunk.
1243 // The further back it is, the further before the fork it may be.
1248 std::vector<uint256> vHave;
1255 explicit CBlockLocator(const CBlockIndex* pindex)
1260 explicit CBlockLocator(uint256 hashBlock)
1262 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1263 if (mi != mapBlockIndex.end())
1269 if (!(nType & SER_GETHASH))
1270 READWRITE(nVersion);
1281 return vHave.empty();
1284 void Set(const CBlockIndex* pindex)
1290 vHave.push_back(pindex->GetBlockHash());
1292 // Exponentially larger steps back
1293 for (int i = 0; pindex && i < nStep; i++)
1294 pindex = pindex->pprev;
1295 if (vHave.size() > 10)
1298 vHave.push_back(hashGenesisBlock);
1301 int GetDistanceBack()
1303 // Retrace how far back it was in the sender's branch
1306 BOOST_FOREACH(const uint256& hash, vHave)
1308 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1309 if (mi != mapBlockIndex.end())
1311 CBlockIndex* pindex = (*mi).second;
1312 if (pindex->IsInMainChain())
1322 CBlockIndex* GetBlockIndex()
1324 // Find the first block the caller has in the main chain
1325 BOOST_FOREACH(const uint256& hash, vHave)
1327 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1328 if (mi != mapBlockIndex.end())
1330 CBlockIndex* pindex = (*mi).second;
1331 if (pindex->IsInMainChain())
1335 return pindexGenesisBlock;
1338 uint256 GetBlockHash()
1340 // Find the first block the caller has in the main chain
1341 BOOST_FOREACH(const uint256& hash, vHave)
1343 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1344 if (mi != mapBlockIndex.end())
1346 CBlockIndex* pindex = (*mi).second;
1347 if (pindex->IsInMainChain())
1351 return hashGenesisBlock;
1356 CBlockIndex* pindex = GetBlockIndex();
1359 return pindex->nHeight;
1372 // Alerts are for notifying old versions if they become too obsolete and
1373 // need to upgrade. The message is displayed in the status bar.
1374 // Alert messages are broadcast as a vector of signed data. Unserializing may
1375 // not read the entire buffer if the alert is for a newer version, but older
1376 // versions can still relay the original data.
1378 class CUnsignedAlert
1382 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1386 std::set<int> setCancel;
1387 int nMinVer; // lowest version inclusive
1388 int nMaxVer; // highest version inclusive
1389 std::set<std::string> setSubVer; // empty matches all
1393 std::string strComment;
1394 std::string strStatusBar;
1395 std::string strReserved;
1399 READWRITE(this->nVersion);
1400 nVersion = this->nVersion;
1401 READWRITE(nRelayUntil);
1402 READWRITE(nExpiration);
1405 READWRITE(setCancel);
1408 READWRITE(setSubVer);
1409 READWRITE(nPriority);
1411 READWRITE(strComment);
1412 READWRITE(strStatusBar);
1413 READWRITE(strReserved);
1430 strStatusBar.clear();
1431 strReserved.clear();
1434 std::string ToString() const
1436 std::string strSetCancel;
1437 BOOST_FOREACH(int n, setCancel)
1438 strSetCancel += strprintf("%d ", n);
1439 std::string strSetSubVer;
1440 BOOST_FOREACH(std::string str, setSubVer)
1441 strSetSubVer += "\"" + str + "\" ";
1445 " nRelayUntil = %"PRI64d"\n"
1446 " nExpiration = %"PRI64d"\n"
1454 " strComment = \"%s\"\n"
1455 " strStatusBar = \"%s\"\n"
1462 strSetCancel.c_str(),
1465 strSetSubVer.c_str(),
1468 strStatusBar.c_str());
1473 printf("%s", ToString().c_str());
1477 class CAlert : public CUnsignedAlert
1480 std::vector<unsigned char> vchMsg;
1481 std::vector<unsigned char> vchSig;
1496 CUnsignedAlert::SetNull();
1503 return (nExpiration == 0);
1506 uint256 GetHash() const
1508 return SerializeHash(*this);
1511 bool IsInEffect() const
1513 return (GetAdjustedTime() < nExpiration);
1516 bool Cancels(const CAlert& alert) const
1519 return false; // this was a no-op before 31403
1520 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1523 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1525 return (IsInEffect() &&
1526 nMinVer <= nVersion && nVersion <= nMaxVer &&
1527 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1530 bool AppliesToMe() const
1532 return AppliesTo(VERSION, ::pszSubVer);
1535 bool RelayTo(CNode* pnode) const
1539 // returns true if wasn't already contained in the set
1540 if (pnode->setKnown.insert(GetHash()).second)
1542 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1544 GetAdjustedTime() < nRelayUntil)
1546 pnode->PushMessage("alert", *this);
1553 bool CheckSignature()
1556 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1557 return error("CAlert::CheckSignature() : SetPubKey failed");
1558 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1559 return error("CAlert::CheckSignature() : verify signature failed");
1561 // Now unserialize the data
1562 CDataStream sMsg(vchMsg);
1563 sMsg >> *(CUnsignedAlert*)this;
1567 bool ProcessAlert();