1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011-2012 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 = 1000000;
35 static const int64 CENT = 10000;
36 static const int64 MIN_TX_FEE = 10000;
37 static const int64 MIN_RELAY_TX_FEE = 10000;
38 static const int64 MAX_MONEY = 2000000000 * 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;
78 extern int64 nBalanceReserve;
88 void RegisterWallet(CWallet* pwalletIn);
89 void UnregisterWallet(CWallet* pwalletIn);
90 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
91 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
92 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
93 FILE* AppendBlockFile(unsigned int& nFileRet);
94 bool LoadBlockIndex(bool fAllowNew=true);
95 void PrintBlockTree();
96 bool ProcessMessages(CNode* pfrom);
97 bool SendMessages(CNode* pto, bool fSendTrickle);
98 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
99 CBlock* CreateNewBlock(CWallet* pwallet);
100 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
101 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
102 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
103 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
104 int64 GetProofOfStakeReward(int64 nCoinAge);
105 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
106 int GetNumBlocksOfPeers();
107 bool IsInitialBlockDownload();
108 std::string GetWarnings(std::string strFor);
121 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
124 bool WriteSetting(const std::string& strKey, const T& value)
127 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
129 std::string strWalletFile;
130 if (!GetWalletFile(pwallet, strWalletFile))
132 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
142 unsigned int nBlockPos;
150 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
153 nBlockPos = nBlockPosIn;
157 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
158 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
159 bool IsNull() const { return (nFile == -1); }
161 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
163 return (a.nFile == b.nFile &&
164 a.nBlockPos == b.nBlockPos &&
165 a.nTxPos == b.nTxPos);
168 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
173 std::string ToString() const
176 return strprintf("null");
178 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
183 printf("%s", ToString().c_str());
196 CInPoint() { SetNull(); }
197 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
198 void SetNull() { ptx = NULL; n = -1; }
199 bool IsNull() const { return (ptx == NULL && n == -1); }
211 COutPoint() { SetNull(); }
212 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
213 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
214 void SetNull() { hash = 0; n = -1; }
215 bool IsNull() const { return (hash == 0 && n == -1); }
217 friend bool operator<(const COutPoint& a, const COutPoint& b)
219 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
222 friend bool operator==(const COutPoint& a, const COutPoint& b)
224 return (a.hash == b.hash && a.n == b.n);
227 friend bool operator!=(const COutPoint& a, const COutPoint& b)
232 std::string ToString() const
234 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
239 printf("%s\n", ToString().c_str());
247 // An input of a transaction. It contains the location of the previous
248 // transaction's output that it claims and a signature that matches the
249 // output's public key.
256 unsigned int nSequence;
260 nSequence = UINT_MAX;
263 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
266 scriptSig = scriptSigIn;
267 nSequence = nSequenceIn;
270 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
272 prevout = COutPoint(hashPrevTx, nOut);
273 scriptSig = scriptSigIn;
274 nSequence = nSequenceIn;
280 READWRITE(scriptSig);
281 READWRITE(nSequence);
286 return (nSequence == UINT_MAX);
289 friend bool operator==(const CTxIn& a, const CTxIn& b)
291 return (a.prevout == b.prevout &&
292 a.scriptSig == b.scriptSig &&
293 a.nSequence == b.nSequence);
296 friend bool operator!=(const CTxIn& a, const CTxIn& b)
301 std::string ToString() const
304 str += strprintf("CTxIn(");
305 str += prevout.ToString();
306 if (prevout.IsNull())
307 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
309 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
310 if (nSequence != UINT_MAX)
311 str += strprintf(", nSequence=%u", nSequence);
318 printf("%s\n", ToString().c_str());
326 // An output of a transaction. It contains the public key that the next input
327 // must be able to sign with to claim it.
333 CScript scriptPubKey;
340 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
343 scriptPubKey = scriptPubKeyIn;
349 READWRITE(scriptPubKey);
355 scriptPubKey.clear();
360 return (nValue == -1);
363 bool IsCoinStake() const
365 return (nValue == 0 && scriptPubKey.empty());
368 uint256 GetHash() const
370 return SerializeHash(*this);
373 friend bool operator==(const CTxOut& a, const CTxOut& b)
375 return (a.nValue == b.nValue &&
376 a.scriptPubKey == b.scriptPubKey);
379 friend bool operator!=(const CTxOut& a, const CTxOut& b)
384 std::string ToString() const
386 if (IsCoinStake()) return "CTxOut(coinstake)";
387 if (scriptPubKey.size() < 6)
388 return "CTxOut(error)";
389 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
394 printf("%s\n", ToString().c_str());
402 // The basic transaction that is broadcasted on the network and contained in
403 // blocks. A transaction can contain multiple inputs and outputs.
410 std::vector<CTxIn> vin;
411 std::vector<CTxOut> vout;
412 unsigned int nLockTime;
414 // Denial-of-service detection:
416 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
425 READWRITE(this->nVersion);
426 nVersion = this->nVersion;
430 READWRITE(nLockTime);
436 nTime = GetAdjustedTime();
440 nDoS = 0; // Denial-of-service prevention
445 return (vin.empty() && vout.empty());
448 uint256 GetHash() const
450 return SerializeHash(*this);
453 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
455 // Time based nLockTime implemented in 0.1.6
458 if (nBlockHeight == 0)
459 nBlockHeight = nBestHeight;
461 nBlockTime = GetAdjustedTime();
462 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
464 BOOST_FOREACH(const CTxIn& txin, vin)
470 bool IsNewerThan(const CTransaction& old) const
472 if (vin.size() != old.vin.size())
474 for (int i = 0; i < vin.size(); i++)
475 if (vin[i].prevout != old.vin[i].prevout)
479 unsigned int nLowest = UINT_MAX;
480 for (int i = 0; i < vin.size(); i++)
482 if (vin[i].nSequence != old.vin[i].nSequence)
484 if (vin[i].nSequence <= nLowest)
487 nLowest = vin[i].nSequence;
489 if (old.vin[i].nSequence < nLowest)
492 nLowest = old.vin[i].nSequence;
499 bool IsCoinBase() const
501 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() == 1);
504 bool IsCoinStake() const
506 // ppcoin: the coin stake transaction is marked with the first output empty
507 return (vout.size() == 2 && vout[0].IsCoinStake());
510 int GetSigOpCount() const
513 BOOST_FOREACH(const CTxIn& txin, vin)
514 n += txin.scriptSig.GetSigOpCount();
515 BOOST_FOREACH(const CTxOut& txout, vout)
516 n += txout.scriptPubKey.GetSigOpCount();
520 bool IsStandard() const
522 BOOST_FOREACH(const CTxIn& txin, vin)
523 if (!txin.scriptSig.IsPushOnly())
524 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
525 BOOST_FOREACH(const CTxOut& txout, vout)
526 if (!::IsStandard(txout.scriptPubKey))
527 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
531 int64 GetValueOut() const
534 BOOST_FOREACH(const CTxOut& txout, vout)
536 nValueOut += txout.nValue;
537 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
538 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
543 static bool AllowFree(double dPriority)
545 // Large (in bytes) low-priority (new, small-coin) transactions
547 return dPriority > COIN * 144 / 250;
550 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, bool fForRelay=false) const
552 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
553 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
555 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
556 unsigned int nNewBlockSize = nBlockSize + nBytes;
557 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
563 // Transactions under 10K are free
564 // (about 4500bc if made of 50bc inputs)
570 // Free transaction area
571 if (nNewBlockSize < 27000)
576 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
577 if (nMinFee < nBaseFee)
578 BOOST_FOREACH(const CTxOut& txout, vout)
579 if (txout.nValue < CENT)
582 // Raise the price as the block approaches full
583 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
585 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
587 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
590 if (!MoneyRange(nMinFee))
596 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
598 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
600 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
603 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
604 return error("CTransaction::ReadFromDisk() : fseek failed");
607 // Return file pointer
610 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
611 return error("CTransaction::ReadFromDisk() : second fseek failed");
612 *pfileRet = filein.release();
617 friend bool operator==(const CTransaction& a, const CTransaction& b)
619 return (a.nVersion == b.nVersion &&
620 a.nTime == b.nTime &&
623 a.nLockTime == b.nLockTime);
626 friend bool operator!=(const CTransaction& a, const CTransaction& b)
632 std::string ToString() const
635 str += strprintf("CTransaction(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
636 GetHash().ToString().substr(0,10).c_str(),
642 for (int i = 0; i < vin.size(); i++)
643 str += " " + vin[i].ToString() + "\n";
644 for (int i = 0; i < vout.size(); i++)
645 str += " " + vout[i].ToString() + "\n";
651 printf("%s", ToString().c_str());
655 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
656 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
657 bool ReadFromDisk(COutPoint prevout);
658 bool DisconnectInputs(CTxDB& txdb);
659 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
660 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
661 bool ClientConnectInputs();
662 bool CheckTransaction() const;
663 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
664 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
666 bool AddToMemoryPoolUnchecked();
668 bool RemoveFromMemoryPool();
669 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
677 // A transaction with a merkle branch linking it to the block chain
679 class CMerkleTx : public CTransaction
683 std::vector<uint256> vMerkleBranch;
687 mutable char fMerkleVerified;
695 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
704 fMerkleVerified = false;
710 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
711 nVersion = this->nVersion;
712 READWRITE(hashBlock);
713 READWRITE(vMerkleBranch);
718 int SetMerkleBranch(const CBlock* pblock=NULL);
719 int GetDepthInMainChain(int& nHeightRet) const;
720 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
721 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
722 int GetBlocksToMaturity() const;
723 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
724 bool AcceptToMemoryPool();
731 // A txdb record that contains the disk location of a transaction and the
732 // locations of transactions that spend its outputs. vSpent is really only
733 // used as a flag, but having the location is very helpful for debugging.
739 std::vector<CDiskTxPos> vSpent;
746 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
749 vSpent.resize(nOutputs);
754 if (!(nType & SER_GETHASH))
771 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
773 return (a.pos == b.pos &&
774 a.vSpent == b.vSpent);
777 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
781 int GetDepthInMainChain() const;
789 // Nodes collect new transactions into a block, hash them into a hash tree,
790 // and scan through nonce values to make the block's hash satisfy proof-of-work
791 // requirements. When they solve the proof-of-work, they broadcast the block
792 // to everyone and the block is added to the block chain. The first transaction
793 // in the block is a special one that creates a new coin owned by the creator
796 // Blocks are appended to blk0001.dat files on disk. Their location on disk
797 // is indexed by CBlockIndex objects in memory.
804 uint256 hashPrevBlock;
805 uint256 hashMerkleRoot;
811 std::vector<CTransaction> vtx;
814 mutable std::vector<uint256> vMerkleTree;
816 // Denial-of-service detection:
818 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
827 READWRITE(this->nVersion);
828 nVersion = this->nVersion;
829 READWRITE(hashPrevBlock);
830 READWRITE(hashMerkleRoot);
835 // ConnectBlock depends on vtx being last so it can calculate offset
836 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
839 const_cast<CBlock*>(this)->vtx.clear();
860 uint256 GetHash() const
862 return Hash(BEGIN(nVersion), END(nNonce));
865 int64 GetBlockTime() const
870 // ppcoin: get max transaction timestamp
871 int64 GetMaxTransactionTime() const
873 int64 maxTransactionTime = 0;
874 BOOST_FOREACH(const CTransaction& tx, vtx)
875 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
876 return maxTransactionTime;
879 int GetSigOpCount() const
882 BOOST_FOREACH(const CTransaction& tx, vtx)
883 n += tx.GetSigOpCount();
888 uint256 BuildMerkleTree() const
891 BOOST_FOREACH(const CTransaction& tx, vtx)
892 vMerkleTree.push_back(tx.GetHash());
894 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
896 for (int i = 0; i < nSize; i += 2)
898 int i2 = std::min(i+1, nSize-1);
899 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
900 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
904 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
907 std::vector<uint256> GetMerkleBranch(int nIndex) const
909 if (vMerkleTree.empty())
911 std::vector<uint256> vMerkleBranch;
913 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
915 int i = std::min(nIndex^1, nSize-1);
916 vMerkleBranch.push_back(vMerkleTree[j+i]);
920 return vMerkleBranch;
923 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
927 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
930 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
932 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
939 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
941 // Open history file to append
942 CAutoFile fileout = AppendBlockFile(nFileRet);
944 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
946 // Write index header
947 unsigned int nSize = fileout.GetSerializeSize(*this);
948 fileout << FLATDATA(pchMessageStart) << nSize;
951 nBlockPosRet = ftell(fileout);
952 if (nBlockPosRet == -1)
953 return error("CBlock::WriteToDisk() : ftell failed");
956 // Flush stdio buffers and commit to disk before returning
958 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
961 _commit(_fileno(fileout));
963 fsync(fileno(fileout));
970 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
974 // Open history file to read
975 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
977 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
978 if (!fReadTransactions)
979 filein.nType |= SER_BLOCKHEADERONLY;
985 if (!CheckProofOfWork(GetHash(), nBits))
986 return error("CBlock::ReadFromDisk() : errors in block header");
995 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
996 GetHash().ToString().substr(0,20).c_str(),
998 hashPrevBlock.ToString().substr(0,20).c_str(),
999 hashMerkleRoot.ToString().substr(0,10).c_str(),
1000 nTime, nBits, nNonce,
1002 for (int i = 0; i < vtx.size(); i++)
1007 printf(" vMerkleTree: ");
1008 for (int i = 0; i < vMerkleTree.size(); i++)
1009 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1014 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1015 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1016 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1017 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1018 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1019 bool CheckBlock() const;
1021 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1030 // The block chain is a tree shaped structure starting with the
1031 // genesis block at the root, with each block potentially having multiple
1032 // candidates to be the next block. pprev and pnext link a path through the
1033 // main/longest chain. A blockindex may have multiple pprev pointing back
1034 // to it, but pnext will only point forward to the longest branch, or will
1035 // be null if the block is not part of the longest chain.
1040 const uint256* phashBlock;
1044 unsigned int nBlockPos;
1045 uint64 nChainTrust;// ppcoin: trust score of chain, in the unit of coin-days
1047 int nCheckpoint; // ppcoin: chain auto checkpoint height
1051 uint256 hashMerkleRoot;
1054 unsigned int nNonce;
1075 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1081 nBlockPos = nBlockPosIn;
1086 nVersion = block.nVersion;
1087 hashMerkleRoot = block.hashMerkleRoot;
1088 nTime = block.nTime;
1089 nBits = block.nBits;
1090 nNonce = block.nNonce;
1093 CBlock GetBlockHeader() const
1096 block.nVersion = nVersion;
1098 block.hashPrevBlock = pprev->GetBlockHash();
1099 block.hashMerkleRoot = hashMerkleRoot;
1100 block.nTime = nTime;
1101 block.nBits = nBits;
1102 block.nNonce = nNonce;
1106 uint256 GetBlockHash() const
1111 int64 GetBlockTime() const
1113 return (int64)nTime;
1116 int64 GetBlockTrust() const
1118 return (nChainTrust - (pprev? pprev->nChainTrust : 0));
1121 bool IsInMainChain() const
1123 return (pnext || this == pindexBest);
1126 bool CheckIndex() const
1128 return CheckProofOfWork(GetBlockHash(), nBits);
1131 bool EraseBlockFromDisk()
1133 // Open history file
1134 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1138 // Overwrite with empty null block
1146 enum { nMedianTimeSpan=11 };
1148 int64 GetMedianTimePast() const
1150 int64 pmedian[nMedianTimeSpan];
1151 int64* pbegin = &pmedian[nMedianTimeSpan];
1152 int64* pend = &pmedian[nMedianTimeSpan];
1154 const CBlockIndex* pindex = this;
1155 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1156 *(--pbegin) = pindex->GetBlockTime();
1158 std::sort(pbegin, pend);
1159 return pbegin[(pend - pbegin)/2];
1162 int64 GetMedianTime() const
1164 const CBlockIndex* pindex = this;
1165 for (int i = 0; i < nMedianTimeSpan/2; i++)
1168 return GetBlockTime();
1169 pindex = pindex->pnext;
1171 return pindex->GetMedianTimePast();
1176 std::string ToString() const
1178 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nChainTrust=%"PRI64d" nHeight=%d, nCheckpoint=%d, merkle=%s, hashBlock=%s)",
1179 pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight, nCheckpoint,
1180 hashMerkleRoot.ToString().substr(0,10).c_str(),
1181 GetBlockHash().ToString().substr(0,20).c_str());
1186 printf("%s\n", ToString().c_str());
1193 // Used to marshal pointers into hashes for db storage.
1195 class CDiskBlockIndex : public CBlockIndex
1207 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1209 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1210 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1215 if (!(nType & SER_GETHASH))
1216 READWRITE(nVersion);
1218 READWRITE(hashNext);
1220 READWRITE(nBlockPos);
1221 READWRITE(nChainTrust);
1223 READWRITE(nCheckpoint);
1226 READWRITE(this->nVersion);
1227 READWRITE(hashPrev);
1228 READWRITE(hashMerkleRoot);
1234 uint256 GetBlockHash() const
1237 block.nVersion = nVersion;
1238 block.hashPrevBlock = hashPrev;
1239 block.hashMerkleRoot = hashMerkleRoot;
1240 block.nTime = nTime;
1241 block.nBits = nBits;
1242 block.nNonce = nNonce;
1243 return block.GetHash();
1247 std::string ToString() const
1249 std::string str = "CDiskBlockIndex(";
1250 str += CBlockIndex::ToString();
1251 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1252 GetBlockHash().ToString().c_str(),
1253 hashPrev.ToString().substr(0,20).c_str(),
1254 hashNext.ToString().substr(0,20).c_str());
1260 printf("%s\n", ToString().c_str());
1272 // Describes a place in the block chain to another node such that if the
1273 // other node doesn't have the same branch, it can find a recent common trunk.
1274 // The further back it is, the further before the fork it may be.
1279 std::vector<uint256> vHave;
1286 explicit CBlockLocator(const CBlockIndex* pindex)
1291 explicit CBlockLocator(uint256 hashBlock)
1293 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1294 if (mi != mapBlockIndex.end())
1300 if (!(nType & SER_GETHASH))
1301 READWRITE(nVersion);
1312 return vHave.empty();
1315 void Set(const CBlockIndex* pindex)
1321 vHave.push_back(pindex->GetBlockHash());
1323 // Exponentially larger steps back
1324 for (int i = 0; pindex && i < nStep; i++)
1325 pindex = pindex->pprev;
1326 if (vHave.size() > 10)
1329 vHave.push_back(hashGenesisBlock);
1332 int GetDistanceBack()
1334 // Retrace how far back it was in the sender's branch
1337 BOOST_FOREACH(const uint256& hash, vHave)
1339 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1340 if (mi != mapBlockIndex.end())
1342 CBlockIndex* pindex = (*mi).second;
1343 if (pindex->IsInMainChain())
1353 CBlockIndex* GetBlockIndex()
1355 // Find the first block the caller has in the main chain
1356 BOOST_FOREACH(const uint256& hash, vHave)
1358 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1359 if (mi != mapBlockIndex.end())
1361 CBlockIndex* pindex = (*mi).second;
1362 if (pindex->IsInMainChain())
1366 return pindexGenesisBlock;
1369 uint256 GetBlockHash()
1371 // Find the first block the caller has in the main chain
1372 BOOST_FOREACH(const uint256& hash, vHave)
1374 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1375 if (mi != mapBlockIndex.end())
1377 CBlockIndex* pindex = (*mi).second;
1378 if (pindex->IsInMainChain())
1382 return hashGenesisBlock;
1387 CBlockIndex* pindex = GetBlockIndex();
1390 return pindex->nHeight;
1403 // Alerts are for notifying old versions if they become too obsolete and
1404 // need to upgrade. The message is displayed in the status bar.
1405 // Alert messages are broadcast as a vector of signed data. Unserializing may
1406 // not read the entire buffer if the alert is for a newer version, but older
1407 // versions can still relay the original data.
1409 class CUnsignedAlert
1413 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1417 std::set<int> setCancel;
1418 int nMinVer; // lowest version inclusive
1419 int nMaxVer; // highest version inclusive
1420 std::set<std::string> setSubVer; // empty matches all
1424 std::string strComment;
1425 std::string strStatusBar;
1426 std::string strReserved;
1430 READWRITE(this->nVersion);
1431 nVersion = this->nVersion;
1432 READWRITE(nRelayUntil);
1433 READWRITE(nExpiration);
1436 READWRITE(setCancel);
1439 READWRITE(setSubVer);
1440 READWRITE(nPriority);
1442 READWRITE(strComment);
1443 READWRITE(strStatusBar);
1444 READWRITE(strReserved);
1461 strStatusBar.clear();
1462 strReserved.clear();
1465 std::string ToString() const
1467 std::string strSetCancel;
1468 BOOST_FOREACH(int n, setCancel)
1469 strSetCancel += strprintf("%d ", n);
1470 std::string strSetSubVer;
1471 BOOST_FOREACH(std::string str, setSubVer)
1472 strSetSubVer += "\"" + str + "\" ";
1476 " nRelayUntil = %"PRI64d"\n"
1477 " nExpiration = %"PRI64d"\n"
1485 " strComment = \"%s\"\n"
1486 " strStatusBar = \"%s\"\n"
1493 strSetCancel.c_str(),
1496 strSetSubVer.c_str(),
1499 strStatusBar.c_str());
1504 printf("%s", ToString().c_str());
1508 class CAlert : public CUnsignedAlert
1511 std::vector<unsigned char> vchMsg;
1512 std::vector<unsigned char> vchSig;
1527 CUnsignedAlert::SetNull();
1534 return (nExpiration == 0);
1537 uint256 GetHash() const
1539 return SerializeHash(*this);
1542 bool IsInEffect() const
1544 return (GetAdjustedTime() < nExpiration);
1547 bool Cancels(const CAlert& alert) const
1550 return false; // this was a no-op before 31403
1551 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1554 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1556 return (IsInEffect() &&
1557 nMinVer <= nVersion && nVersion <= nMaxVer &&
1558 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1561 bool AppliesToMe() const
1563 return AppliesTo(VERSION, ::pszSubVer);
1566 bool RelayTo(CNode* pnode) const
1570 // returns true if wasn't already contained in the set
1571 if (pnode->setKnown.insert(GetHash()).second)
1573 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1575 GetAdjustedTime() < nRelayUntil)
1577 pnode->PushMessage("alert", *this);
1584 bool CheckSignature()
1587 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1588 return error("CAlert::CheckSignature() : SetPubKey failed");
1589 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1590 return error("CAlert::CheckSignature() : verify signature failed");
1592 // Now unserialize the data
1593 CDataStream sMsg(vchMsg);
1594 sMsg >> *(CUnsignedAlert*)this;
1598 bool ProcessAlert();