1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // 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 = 10000;
35 static const int64 CENT = 100;
36 static const int64 MIN_TX_FEE = 10000;
37 static const int64 MIN_RELAY_TX_FEE = 10000;
38 static const int64 MAX_MONEY = 800000000000000 * 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 CBlockIndex* pindexGenesisBlock;
58 extern int nBestHeight;
59 extern uint64 nBestChainTrust;
60 extern uint64 nBestInvalidTrust;
61 extern uint256 hashBestChain;
62 extern CBlockIndex* pindexBest;
63 extern unsigned int nTransactionsUpdated;
64 extern double dHashesPerSec;
65 extern int64 nHPSTimerStart;
66 extern int64 nTimeBestReceived;
67 extern CCriticalSection cs_setpwalletRegistered;
68 extern std::set<CWallet*> setpwalletRegistered;
71 extern int fGenerateBitcoins;
72 extern int64 nTransactionFee;
73 extern int fLimitProcessors;
74 extern int nLimitProcessors;
75 extern int fMinimizeToTray;
76 extern int fMinimizeOnClose;
87 void RegisterWallet(CWallet* pwalletIn);
88 void UnregisterWallet(CWallet* pwalletIn);
89 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
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 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
104 int GetNumBlocksOfPeers();
105 bool IsInitialBlockDownload();
106 std::string GetWarnings(std::string strFor);
119 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
122 bool WriteSetting(const std::string& strKey, const T& value)
125 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
127 std::string strWalletFile;
128 if (!GetWalletFile(pwallet, strWalletFile))
130 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
140 unsigned int nBlockPos;
148 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
151 nBlockPos = nBlockPosIn;
155 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
156 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
157 bool IsNull() const { return (nFile == -1); }
159 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
161 return (a.nFile == b.nFile &&
162 a.nBlockPos == b.nBlockPos &&
163 a.nTxPos == b.nTxPos);
166 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
171 std::string ToString() const
174 return strprintf("null");
176 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
181 printf("%s", ToString().c_str());
194 CInPoint() { SetNull(); }
195 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
196 void SetNull() { ptx = NULL; n = -1; }
197 bool IsNull() const { return (ptx == NULL && n == -1); }
209 COutPoint() { SetNull(); }
210 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
211 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
212 void SetNull() { hash = 0; n = -1; }
213 bool IsNull() const { return (hash == 0 && n == -1); }
215 friend bool operator<(const COutPoint& a, const COutPoint& b)
217 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
220 friend bool operator==(const COutPoint& a, const COutPoint& b)
222 return (a.hash == b.hash && a.n == b.n);
225 friend bool operator!=(const COutPoint& a, const COutPoint& b)
230 std::string ToString() const
232 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
237 printf("%s\n", ToString().c_str());
245 // An input of a transaction. It contains the location of the previous
246 // transaction's output that it claims and a signature that matches the
247 // output's public key.
254 unsigned int nSequence;
258 nSequence = UINT_MAX;
261 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
264 scriptSig = scriptSigIn;
265 nSequence = nSequenceIn;
268 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
270 prevout = COutPoint(hashPrevTx, nOut);
271 scriptSig = scriptSigIn;
272 nSequence = nSequenceIn;
278 READWRITE(scriptSig);
279 READWRITE(nSequence);
284 return (nSequence == UINT_MAX);
287 friend bool operator==(const CTxIn& a, const CTxIn& b)
289 return (a.prevout == b.prevout &&
290 a.scriptSig == b.scriptSig &&
291 a.nSequence == b.nSequence);
294 friend bool operator!=(const CTxIn& a, const CTxIn& b)
299 std::string ToString() const
302 str += strprintf("CTxIn(");
303 str += prevout.ToString();
304 if (prevout.IsNull())
305 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
307 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
308 if (nSequence != UINT_MAX)
309 str += strprintf(", nSequence=%u", nSequence);
316 printf("%s\n", ToString().c_str());
324 // An output of a transaction. It contains the public key that the next input
325 // must be able to sign with to claim it.
331 CScript scriptPubKey;
338 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
341 scriptPubKey = scriptPubKeyIn;
347 READWRITE(scriptPubKey);
353 scriptPubKey.clear();
358 return (nValue == -1);
361 uint256 GetHash() const
363 return SerializeHash(*this);
366 friend bool operator==(const CTxOut& a, const CTxOut& b)
368 return (a.nValue == b.nValue &&
369 a.scriptPubKey == b.scriptPubKey);
372 friend bool operator!=(const CTxOut& a, const CTxOut& b)
377 std::string ToString() const
379 if (scriptPubKey.size() < 6)
380 return "CTxOut(error)";
381 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
386 printf("%s\n", ToString().c_str());
394 // The basic transaction that is broadcasted on the network and contained in
395 // blocks. A transaction can contain multiple inputs and outputs.
402 std::vector<CTxIn> vin;
403 std::vector<CTxOut> vout;
404 unsigned int nLockTime;
406 // Denial-of-service detection:
408 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
417 READWRITE(this->nVersion);
418 nVersion = this->nVersion;
422 READWRITE(nLockTime);
428 nTime = GetAdjustedTime();
432 nDoS = 0; // Denial-of-service prevention
437 return (vin.empty() && vout.empty());
440 uint256 GetHash() const
442 return SerializeHash(*this);
445 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
447 // Time based nLockTime implemented in 0.1.6
450 if (nBlockHeight == 0)
451 nBlockHeight = nBestHeight;
453 nBlockTime = GetAdjustedTime();
454 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
456 BOOST_FOREACH(const CTxIn& txin, vin)
462 bool IsNewerThan(const CTransaction& old) const
464 if (vin.size() != old.vin.size())
466 for (int i = 0; i < vin.size(); i++)
467 if (vin[i].prevout != old.vin[i].prevout)
471 unsigned int nLowest = UINT_MAX;
472 for (int i = 0; i < vin.size(); i++)
474 if (vin[i].nSequence != old.vin[i].nSequence)
476 if (vin[i].nSequence <= nLowest)
479 nLowest = vin[i].nSequence;
481 if (old.vin[i].nSequence < nLowest)
484 nLowest = old.vin[i].nSequence;
491 bool IsCoinBase() const
493 return (vin.size() == 1 && vin[0].prevout.IsNull());
496 int GetSigOpCount() const
499 BOOST_FOREACH(const CTxIn& txin, vin)
500 n += txin.scriptSig.GetSigOpCount();
501 BOOST_FOREACH(const CTxOut& txout, vout)
502 n += txout.scriptPubKey.GetSigOpCount();
506 bool IsStandard() const
508 BOOST_FOREACH(const CTxIn& txin, vin)
509 if (!txin.scriptSig.IsPushOnly())
510 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
511 BOOST_FOREACH(const CTxOut& txout, vout)
512 if (!::IsStandard(txout.scriptPubKey))
513 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
517 int64 GetValueOut() const
520 BOOST_FOREACH(const CTxOut& txout, vout)
522 nValueOut += txout.nValue;
523 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
524 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
529 static bool AllowFree(double dPriority)
531 // Large (in bytes) low-priority (new, small-coin) transactions
533 return dPriority > COIN * 144 / 250;
536 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
538 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
539 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
541 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
542 unsigned int nNewBlockSize = nBlockSize + nBytes;
543 int64 nMinFee = nBaseFee; // ppcoin: simplify transaction fee
549 // Transactions under 10K are free
550 // (about 4500bc if made of 50bc inputs)
556 // Free transaction area
557 if (nNewBlockSize < 27000)
562 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
563 if (nMinFee < nBaseFee)
564 BOOST_FOREACH(const CTxOut& txout, vout)
565 if (txout.nValue < CENT)
568 // Raise the price as the block approaches full
569 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
571 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
573 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
576 if (!MoneyRange(nMinFee))
582 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
584 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
586 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
589 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
590 return error("CTransaction::ReadFromDisk() : fseek failed");
593 // Return file pointer
596 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
597 return error("CTransaction::ReadFromDisk() : second fseek failed");
598 *pfileRet = filein.release();
603 friend bool operator==(const CTransaction& a, const CTransaction& b)
605 return (a.nVersion == b.nVersion &&
606 a.nTime == b.nTime &&
609 a.nLockTime == b.nLockTime);
612 friend bool operator!=(const CTransaction& a, const CTransaction& b)
618 std::string ToString() const
621 str += strprintf("CTransaction(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
622 GetHash().ToString().substr(0,10).c_str(),
628 for (int i = 0; i < vin.size(); i++)
629 str += " " + vin[i].ToString() + "\n";
630 for (int i = 0; i < vout.size(); i++)
631 str += " " + vout[i].ToString() + "\n";
637 printf("%s", ToString().c_str());
641 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
642 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
643 bool ReadFromDisk(COutPoint prevout);
644 bool DisconnectInputs(CTxDB& txdb);
645 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
646 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
647 bool ClientConnectInputs();
648 bool CheckTransaction() const;
649 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
650 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
652 bool AddToMemoryPoolUnchecked();
654 bool RemoveFromMemoryPool();
662 // A transaction with a merkle branch linking it to the block chain
664 class CMerkleTx : public CTransaction
668 std::vector<uint256> vMerkleBranch;
672 mutable char fMerkleVerified;
680 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
689 fMerkleVerified = false;
695 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
696 nVersion = this->nVersion;
697 READWRITE(hashBlock);
698 READWRITE(vMerkleBranch);
703 int SetMerkleBranch(const CBlock* pblock=NULL);
704 int GetDepthInMainChain(int& nHeightRet) const;
705 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
706 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
707 int GetBlocksToMaturity() const;
708 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
709 bool AcceptToMemoryPool();
716 // A txdb record that contains the disk location of a transaction and the
717 // locations of transactions that spend its outputs. vSpent is really only
718 // used as a flag, but having the location is very helpful for debugging.
724 std::vector<CDiskTxPos> vSpent;
731 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
734 vSpent.resize(nOutputs);
739 if (!(nType & SER_GETHASH))
756 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
758 return (a.pos == b.pos &&
759 a.vSpent == b.vSpent);
762 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
766 int GetDepthInMainChain() const;
774 // Nodes collect new transactions into a block, hash them into a hash tree,
775 // and scan through nonce values to make the block's hash satisfy proof-of-work
776 // requirements. When they solve the proof-of-work, they broadcast the block
777 // to everyone and the block is added to the block chain. The first transaction
778 // in the block is a special one that creates a new coin owned by the creator
781 // Blocks are appended to blk0001.dat files on disk. Their location on disk
782 // is indexed by CBlockIndex objects in memory.
789 uint256 hashPrevBlock;
790 uint256 hashMerkleRoot;
796 std::vector<CTransaction> vtx;
799 mutable std::vector<uint256> vMerkleTree;
801 // Denial-of-service detection:
803 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
812 READWRITE(this->nVersion);
813 nVersion = this->nVersion;
814 READWRITE(hashPrevBlock);
815 READWRITE(hashMerkleRoot);
820 // ConnectBlock depends on vtx being last so it can calculate offset
821 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
824 const_cast<CBlock*>(this)->vtx.clear();
845 uint256 GetHash() const
847 return Hash(BEGIN(nVersion), END(nNonce));
850 int64 GetBlockTime() const
855 // ppcoin: get max transaction timestamp
856 int64 GetMaxTransactionTime() const
858 int64 maxTransactionTime = 0;
859 BOOST_FOREACH(const CTransaction& tx, vtx)
860 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
861 return maxTransactionTime;
864 int GetSigOpCount() const
867 BOOST_FOREACH(const CTransaction& tx, vtx)
868 n += tx.GetSigOpCount();
873 uint256 BuildMerkleTree() const
876 BOOST_FOREACH(const CTransaction& tx, vtx)
877 vMerkleTree.push_back(tx.GetHash());
879 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
881 for (int i = 0; i < nSize; i += 2)
883 int i2 = std::min(i+1, nSize-1);
884 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
885 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
889 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
892 std::vector<uint256> GetMerkleBranch(int nIndex) const
894 if (vMerkleTree.empty())
896 std::vector<uint256> vMerkleBranch;
898 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
900 int i = std::min(nIndex^1, nSize-1);
901 vMerkleBranch.push_back(vMerkleTree[j+i]);
905 return vMerkleBranch;
908 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
912 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
915 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
917 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
924 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
926 // Open history file to append
927 CAutoFile fileout = AppendBlockFile(nFileRet);
929 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
931 // Write index header
932 unsigned int nSize = fileout.GetSerializeSize(*this);
933 fileout << FLATDATA(pchMessageStart) << nSize;
936 nBlockPosRet = ftell(fileout);
937 if (nBlockPosRet == -1)
938 return error("CBlock::WriteToDisk() : ftell failed");
941 // Flush stdio buffers and commit to disk before returning
943 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
946 _commit(_fileno(fileout));
948 fsync(fileno(fileout));
955 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
959 // Open history file to read
960 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
962 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
963 if (!fReadTransactions)
964 filein.nType |= SER_BLOCKHEADERONLY;
970 if (!CheckProofOfWork(GetHash(), nBits))
971 return error("CBlock::ReadFromDisk() : errors in block header");
980 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
981 GetHash().ToString().substr(0,20).c_str(),
983 hashPrevBlock.ToString().substr(0,20).c_str(),
984 hashMerkleRoot.ToString().substr(0,10).c_str(),
985 nTime, nBits, nNonce,
987 for (int i = 0; i < vtx.size(); i++)
992 printf(" vMerkleTree: ");
993 for (int i = 0; i < vMerkleTree.size(); i++)
994 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
999 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1000 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1001 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1002 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1003 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1004 bool CheckBlock() const;
1006 uint64 GetBlockCoinAge(); // ppcoin: calculate total coin age spent in block
1015 // The block chain is a tree shaped structure starting with the
1016 // genesis block at the root, with each block potentially having multiple
1017 // candidates to be the next block. pprev and pnext link a path through the
1018 // main/longest chain. A blockindex may have multiple pprev pointing back
1019 // to it, but pnext will only point forward to the longest branch, or will
1020 // be null if the block is not part of the longest chain.
1025 const uint256* phashBlock;
1029 unsigned int nBlockPos;
1030 uint64 nChainTrust;// ppcoin: trust score of chain, in the unit of coin-days
1032 int nCheckpoint; // ppcoin: chain auto checkpoint height
1036 uint256 hashMerkleRoot;
1039 unsigned int nNonce;
1060 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1066 nBlockPos = nBlockPosIn;
1071 nVersion = block.nVersion;
1072 hashMerkleRoot = block.hashMerkleRoot;
1073 nTime = block.nTime;
1074 nBits = block.nBits;
1075 nNonce = block.nNonce;
1078 CBlock GetBlockHeader() const
1081 block.nVersion = nVersion;
1083 block.hashPrevBlock = pprev->GetBlockHash();
1084 block.hashMerkleRoot = hashMerkleRoot;
1085 block.nTime = nTime;
1086 block.nBits = nBits;
1087 block.nNonce = nNonce;
1091 uint256 GetBlockHash() const
1096 int64 GetBlockTime() const
1098 return (int64)nTime;
1101 int64 GetBlockTrust() const
1103 return (nChainTrust - pprev->nChainTrust);
1106 bool IsInMainChain() const
1108 return (pnext || this == pindexBest);
1111 bool CheckIndex() const
1113 return CheckProofOfWork(GetBlockHash(), nBits);
1116 bool EraseBlockFromDisk()
1118 // Open history file
1119 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1123 // Overwrite with empty null block
1131 enum { nMedianTimeSpan=11 };
1133 int64 GetMedianTimePast() const
1135 int64 pmedian[nMedianTimeSpan];
1136 int64* pbegin = &pmedian[nMedianTimeSpan];
1137 int64* pend = &pmedian[nMedianTimeSpan];
1139 const CBlockIndex* pindex = this;
1140 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1141 *(--pbegin) = pindex->GetBlockTime();
1143 std::sort(pbegin, pend);
1144 return pbegin[(pend - pbegin)/2];
1147 int64 GetMedianTime() const
1149 const CBlockIndex* pindex = this;
1150 for (int i = 0; i < nMedianTimeSpan/2; i++)
1153 return GetBlockTime();
1154 pindex = pindex->pnext;
1156 return pindex->GetMedianTimePast();
1161 std::string ToString() const
1163 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nChainTrust=%"PRI64d" nHeight=%d, nCheckpoint=%d, merkle=%s, hashBlock=%s)",
1164 pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight, nCheckpoint,
1165 hashMerkleRoot.ToString().substr(0,10).c_str(),
1166 GetBlockHash().ToString().substr(0,20).c_str());
1171 printf("%s\n", ToString().c_str());
1178 // Used to marshal pointers into hashes for db storage.
1180 class CDiskBlockIndex : public CBlockIndex
1192 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1194 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1195 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1200 if (!(nType & SER_GETHASH))
1201 READWRITE(nVersion);
1203 READWRITE(hashNext);
1205 READWRITE(nBlockPos);
1206 READWRITE(nChainTrust);
1208 READWRITE(nCheckpoint);
1211 READWRITE(this->nVersion);
1212 READWRITE(hashPrev);
1213 READWRITE(hashMerkleRoot);
1219 uint256 GetBlockHash() const
1222 block.nVersion = nVersion;
1223 block.hashPrevBlock = hashPrev;
1224 block.hashMerkleRoot = hashMerkleRoot;
1225 block.nTime = nTime;
1226 block.nBits = nBits;
1227 block.nNonce = nNonce;
1228 return block.GetHash();
1232 std::string ToString() const
1234 std::string str = "CDiskBlockIndex(";
1235 str += CBlockIndex::ToString();
1236 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1237 GetBlockHash().ToString().c_str(),
1238 hashPrev.ToString().substr(0,20).c_str(),
1239 hashNext.ToString().substr(0,20).c_str());
1245 printf("%s\n", ToString().c_str());
1257 // Describes a place in the block chain to another node such that if the
1258 // other node doesn't have the same branch, it can find a recent common trunk.
1259 // The further back it is, the further before the fork it may be.
1264 std::vector<uint256> vHave;
1271 explicit CBlockLocator(const CBlockIndex* pindex)
1276 explicit CBlockLocator(uint256 hashBlock)
1278 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1279 if (mi != mapBlockIndex.end())
1285 if (!(nType & SER_GETHASH))
1286 READWRITE(nVersion);
1297 return vHave.empty();
1300 void Set(const CBlockIndex* pindex)
1306 vHave.push_back(pindex->GetBlockHash());
1308 // Exponentially larger steps back
1309 for (int i = 0; pindex && i < nStep; i++)
1310 pindex = pindex->pprev;
1311 if (vHave.size() > 10)
1314 vHave.push_back(hashGenesisBlock);
1317 int GetDistanceBack()
1319 // Retrace how far back it was in the sender's branch
1322 BOOST_FOREACH(const uint256& hash, vHave)
1324 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1325 if (mi != mapBlockIndex.end())
1327 CBlockIndex* pindex = (*mi).second;
1328 if (pindex->IsInMainChain())
1338 CBlockIndex* GetBlockIndex()
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 pindexGenesisBlock;
1354 uint256 GetBlockHash()
1356 // Find the first block the caller has in the main chain
1357 BOOST_FOREACH(const uint256& hash, vHave)
1359 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1360 if (mi != mapBlockIndex.end())
1362 CBlockIndex* pindex = (*mi).second;
1363 if (pindex->IsInMainChain())
1367 return hashGenesisBlock;
1372 CBlockIndex* pindex = GetBlockIndex();
1375 return pindex->nHeight;
1388 // Alerts are for notifying old versions if they become too obsolete and
1389 // need to upgrade. The message is displayed in the status bar.
1390 // Alert messages are broadcast as a vector of signed data. Unserializing may
1391 // not read the entire buffer if the alert is for a newer version, but older
1392 // versions can still relay the original data.
1394 class CUnsignedAlert
1398 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1402 std::set<int> setCancel;
1403 int nMinVer; // lowest version inclusive
1404 int nMaxVer; // highest version inclusive
1405 std::set<std::string> setSubVer; // empty matches all
1409 std::string strComment;
1410 std::string strStatusBar;
1411 std::string strReserved;
1415 READWRITE(this->nVersion);
1416 nVersion = this->nVersion;
1417 READWRITE(nRelayUntil);
1418 READWRITE(nExpiration);
1421 READWRITE(setCancel);
1424 READWRITE(setSubVer);
1425 READWRITE(nPriority);
1427 READWRITE(strComment);
1428 READWRITE(strStatusBar);
1429 READWRITE(strReserved);
1446 strStatusBar.clear();
1447 strReserved.clear();
1450 std::string ToString() const
1452 std::string strSetCancel;
1453 BOOST_FOREACH(int n, setCancel)
1454 strSetCancel += strprintf("%d ", n);
1455 std::string strSetSubVer;
1456 BOOST_FOREACH(std::string str, setSubVer)
1457 strSetSubVer += "\"" + str + "\" ";
1461 " nRelayUntil = %"PRI64d"\n"
1462 " nExpiration = %"PRI64d"\n"
1470 " strComment = \"%s\"\n"
1471 " strStatusBar = \"%s\"\n"
1478 strSetCancel.c_str(),
1481 strSetSubVer.c_str(),
1484 strStatusBar.c_str());
1489 printf("%s", ToString().c_str());
1493 class CAlert : public CUnsignedAlert
1496 std::vector<unsigned char> vchMsg;
1497 std::vector<unsigned char> vchSig;
1512 CUnsignedAlert::SetNull();
1519 return (nExpiration == 0);
1522 uint256 GetHash() const
1524 return SerializeHash(*this);
1527 bool IsInEffect() const
1529 return (GetAdjustedTime() < nExpiration);
1532 bool Cancels(const CAlert& alert) const
1535 return false; // this was a no-op before 31403
1536 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1539 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1541 return (IsInEffect() &&
1542 nMinVer <= nVersion && nVersion <= nMaxVer &&
1543 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1546 bool AppliesToMe() const
1548 return AppliesTo(VERSION, ::pszSubVer);
1551 bool RelayTo(CNode* pnode) const
1555 // returns true if wasn't already contained in the set
1556 if (pnode->setKnown.insert(GetHash()).second)
1558 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1560 GetAdjustedTime() < nRelayUntil)
1562 pnode->PushMessage("alert", *this);
1569 bool CheckSignature()
1572 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1573 return error("CAlert::CheckSignature() : SetPubKey failed");
1574 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1575 return error("CAlert::CheckSignature() : verify signature failed");
1577 // Now unserialize the data
1578 CDataStream sMsg(vchMsg);
1579 sMsg >> *(CUnsignedAlert*)this;
1583 bool ProcessAlert();