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;
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, CWallet* pwallet);
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 int64 GetProofOfStakeReward(int64 nCoinAge);
104 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
105 int GetNumBlocksOfPeers();
106 bool IsInitialBlockDownload();
107 std::string GetWarnings(std::string strFor);
120 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
123 bool WriteSetting(const std::string& strKey, const T& value)
126 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
128 std::string strWalletFile;
129 if (!GetWalletFile(pwallet, strWalletFile))
131 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
141 unsigned int nBlockPos;
149 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
152 nBlockPos = nBlockPosIn;
156 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
157 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
158 bool IsNull() const { return (nFile == -1); }
160 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
162 return (a.nFile == b.nFile &&
163 a.nBlockPos == b.nBlockPos &&
164 a.nTxPos == b.nTxPos);
167 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
172 std::string ToString() const
175 return strprintf("null");
177 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
182 printf("%s", ToString().c_str());
195 CInPoint() { SetNull(); }
196 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
197 void SetNull() { ptx = NULL; n = -1; }
198 bool IsNull() const { return (ptx == NULL && n == -1); }
210 COutPoint() { SetNull(); }
211 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
212 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
213 void SetNull() { hash = 0; n = -1; }
214 bool IsNull() const { return (hash == 0 && n == -1); }
216 friend bool operator<(const COutPoint& a, const COutPoint& b)
218 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
221 friend bool operator==(const COutPoint& a, const COutPoint& b)
223 return (a.hash == b.hash && a.n == b.n);
226 friend bool operator!=(const COutPoint& a, const COutPoint& b)
231 std::string ToString() const
233 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
238 printf("%s\n", ToString().c_str());
246 // An input of a transaction. It contains the location of the previous
247 // transaction's output that it claims and a signature that matches the
248 // output's public key.
255 unsigned int nSequence;
259 nSequence = UINT_MAX;
262 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
265 scriptSig = scriptSigIn;
266 nSequence = nSequenceIn;
269 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
271 prevout = COutPoint(hashPrevTx, nOut);
272 scriptSig = scriptSigIn;
273 nSequence = nSequenceIn;
279 READWRITE(scriptSig);
280 READWRITE(nSequence);
285 return (nSequence == UINT_MAX);
288 friend bool operator==(const CTxIn& a, const CTxIn& b)
290 return (a.prevout == b.prevout &&
291 a.scriptSig == b.scriptSig &&
292 a.nSequence == b.nSequence);
295 friend bool operator!=(const CTxIn& a, const CTxIn& b)
300 std::string ToString() const
303 str += strprintf("CTxIn(");
304 str += prevout.ToString();
305 if (prevout.IsNull())
306 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
308 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
309 if (nSequence != UINT_MAX)
310 str += strprintf(", nSequence=%u", nSequence);
317 printf("%s\n", ToString().c_str());
325 // An output of a transaction. It contains the public key that the next input
326 // must be able to sign with to claim it.
332 CScript scriptPubKey;
339 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
342 scriptPubKey = scriptPubKeyIn;
348 READWRITE(scriptPubKey);
354 scriptPubKey.clear();
359 return (nValue == -1);
362 bool IsCoinStake() const
364 return (nValue == 0 && scriptPubKey.empty());
367 uint256 GetHash() const
369 return SerializeHash(*this);
372 friend bool operator==(const CTxOut& a, const CTxOut& b)
374 return (a.nValue == b.nValue &&
375 a.scriptPubKey == b.scriptPubKey);
378 friend bool operator!=(const CTxOut& a, const CTxOut& b)
383 std::string ToString() const
385 if (IsCoinStake()) return "CTxOut(coinstake)";
386 if (scriptPubKey.size() < 6)
387 return "CTxOut(error)";
388 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
393 printf("%s\n", ToString().c_str());
401 // The basic transaction that is broadcasted on the network and contained in
402 // blocks. A transaction can contain multiple inputs and outputs.
409 std::vector<CTxIn> vin;
410 std::vector<CTxOut> vout;
411 unsigned int nLockTime;
413 // Denial-of-service detection:
415 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
424 READWRITE(this->nVersion);
425 nVersion = this->nVersion;
429 READWRITE(nLockTime);
435 nTime = GetAdjustedTime();
439 nDoS = 0; // Denial-of-service prevention
444 return (vin.empty() && vout.empty());
447 uint256 GetHash() const
449 return SerializeHash(*this);
452 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
454 // Time based nLockTime implemented in 0.1.6
457 if (nBlockHeight == 0)
458 nBlockHeight = nBestHeight;
460 nBlockTime = GetAdjustedTime();
461 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
463 BOOST_FOREACH(const CTxIn& txin, vin)
469 bool IsNewerThan(const CTransaction& old) const
471 if (vin.size() != old.vin.size())
473 for (int i = 0; i < vin.size(); i++)
474 if (vin[i].prevout != old.vin[i].prevout)
478 unsigned int nLowest = UINT_MAX;
479 for (int i = 0; i < vin.size(); i++)
481 if (vin[i].nSequence != old.vin[i].nSequence)
483 if (vin[i].nSequence <= nLowest)
486 nLowest = vin[i].nSequence;
488 if (old.vin[i].nSequence < nLowest)
491 nLowest = old.vin[i].nSequence;
498 bool IsCoinBase() const
500 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() == 1);
503 bool IsCoinStake() const
505 // ppcoin: the coin stake transaction is marked with the first output empty
506 return (vout.size() == 2 && vout[0].IsCoinStake());
509 int GetSigOpCount() const
512 BOOST_FOREACH(const CTxIn& txin, vin)
513 n += txin.scriptSig.GetSigOpCount();
514 BOOST_FOREACH(const CTxOut& txout, vout)
515 n += txout.scriptPubKey.GetSigOpCount();
519 bool IsStandard() const
521 BOOST_FOREACH(const CTxIn& txin, vin)
522 if (!txin.scriptSig.IsPushOnly())
523 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
524 BOOST_FOREACH(const CTxOut& txout, vout)
525 if (!::IsStandard(txout.scriptPubKey))
526 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
530 int64 GetValueOut() const
533 BOOST_FOREACH(const CTxOut& txout, vout)
535 nValueOut += txout.nValue;
536 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
537 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
542 static bool AllowFree(double dPriority)
544 // Large (in bytes) low-priority (new, small-coin) transactions
546 return dPriority > COIN * 144 / 250;
549 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, bool fForRelay=false) const
551 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
552 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
554 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
555 unsigned int nNewBlockSize = nBlockSize + nBytes;
556 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
562 // Transactions under 10K are free
563 // (about 4500bc if made of 50bc inputs)
569 // Free transaction area
570 if (nNewBlockSize < 27000)
575 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
576 if (nMinFee < nBaseFee)
577 BOOST_FOREACH(const CTxOut& txout, vout)
578 if (txout.nValue < CENT)
581 // Raise the price as the block approaches full
582 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
584 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
586 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
589 if (!MoneyRange(nMinFee))
595 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
597 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
599 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
602 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
603 return error("CTransaction::ReadFromDisk() : fseek failed");
606 // Return file pointer
609 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
610 return error("CTransaction::ReadFromDisk() : second fseek failed");
611 *pfileRet = filein.release();
616 friend bool operator==(const CTransaction& a, const CTransaction& b)
618 return (a.nVersion == b.nVersion &&
619 a.nTime == b.nTime &&
622 a.nLockTime == b.nLockTime);
625 friend bool operator!=(const CTransaction& a, const CTransaction& b)
631 std::string ToString() const
634 str += strprintf("CTransaction(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
635 GetHash().ToString().substr(0,10).c_str(),
641 for (int i = 0; i < vin.size(); i++)
642 str += " " + vin[i].ToString() + "\n";
643 for (int i = 0; i < vout.size(); i++)
644 str += " " + vout[i].ToString() + "\n";
650 printf("%s", ToString().c_str());
654 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
655 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
656 bool ReadFromDisk(COutPoint prevout);
657 bool DisconnectInputs(CTxDB& txdb);
658 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
659 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
660 bool ClientConnectInputs();
661 bool CheckTransaction() const;
662 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
663 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
665 bool AddToMemoryPoolUnchecked();
667 bool RemoveFromMemoryPool();
668 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: get transaction coin age
676 // A transaction with a merkle branch linking it to the block chain
678 class CMerkleTx : public CTransaction
682 std::vector<uint256> vMerkleBranch;
686 mutable char fMerkleVerified;
694 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
703 fMerkleVerified = false;
709 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
710 nVersion = this->nVersion;
711 READWRITE(hashBlock);
712 READWRITE(vMerkleBranch);
717 int SetMerkleBranch(const CBlock* pblock=NULL);
718 int GetDepthInMainChain(int& nHeightRet) const;
719 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
720 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
721 int GetBlocksToMaturity() const;
722 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
723 bool AcceptToMemoryPool();
730 // A txdb record that contains the disk location of a transaction and the
731 // locations of transactions that spend its outputs. vSpent is really only
732 // used as a flag, but having the location is very helpful for debugging.
738 std::vector<CDiskTxPos> vSpent;
745 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
748 vSpent.resize(nOutputs);
753 if (!(nType & SER_GETHASH))
770 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
772 return (a.pos == b.pos &&
773 a.vSpent == b.vSpent);
776 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
780 int GetDepthInMainChain() const;
788 // Nodes collect new transactions into a block, hash them into a hash tree,
789 // and scan through nonce values to make the block's hash satisfy proof-of-work
790 // requirements. When they solve the proof-of-work, they broadcast the block
791 // to everyone and the block is added to the block chain. The first transaction
792 // in the block is a special one that creates a new coin owned by the creator
795 // Blocks are appended to blk0001.dat files on disk. Their location on disk
796 // is indexed by CBlockIndex objects in memory.
803 uint256 hashPrevBlock;
804 uint256 hashMerkleRoot;
810 std::vector<CTransaction> vtx;
813 mutable std::vector<uint256> vMerkleTree;
815 // Denial-of-service detection:
817 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
826 READWRITE(this->nVersion);
827 nVersion = this->nVersion;
828 READWRITE(hashPrevBlock);
829 READWRITE(hashMerkleRoot);
834 // ConnectBlock depends on vtx being last so it can calculate offset
835 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
838 const_cast<CBlock*>(this)->vtx.clear();
859 uint256 GetHash() const
861 return Hash(BEGIN(nVersion), END(nNonce));
864 int64 GetBlockTime() const
869 // ppcoin: get max transaction timestamp
870 int64 GetMaxTransactionTime() const
872 int64 maxTransactionTime = 0;
873 BOOST_FOREACH(const CTransaction& tx, vtx)
874 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
875 return maxTransactionTime;
878 int GetSigOpCount() const
881 BOOST_FOREACH(const CTransaction& tx, vtx)
882 n += tx.GetSigOpCount();
887 uint256 BuildMerkleTree() const
890 BOOST_FOREACH(const CTransaction& tx, vtx)
891 vMerkleTree.push_back(tx.GetHash());
893 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
895 for (int i = 0; i < nSize; i += 2)
897 int i2 = std::min(i+1, nSize-1);
898 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
899 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
903 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
906 std::vector<uint256> GetMerkleBranch(int nIndex) const
908 if (vMerkleTree.empty())
910 std::vector<uint256> vMerkleBranch;
912 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
914 int i = std::min(nIndex^1, nSize-1);
915 vMerkleBranch.push_back(vMerkleTree[j+i]);
919 return vMerkleBranch;
922 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
926 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
929 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
931 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
938 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
940 // Open history file to append
941 CAutoFile fileout = AppendBlockFile(nFileRet);
943 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
945 // Write index header
946 unsigned int nSize = fileout.GetSerializeSize(*this);
947 fileout << FLATDATA(pchMessageStart) << nSize;
950 nBlockPosRet = ftell(fileout);
951 if (nBlockPosRet == -1)
952 return error("CBlock::WriteToDisk() : ftell failed");
955 // Flush stdio buffers and commit to disk before returning
957 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
960 _commit(_fileno(fileout));
962 fsync(fileno(fileout));
969 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
973 // Open history file to read
974 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
976 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
977 if (!fReadTransactions)
978 filein.nType |= SER_BLOCKHEADERONLY;
984 if (!CheckProofOfWork(GetHash(), nBits))
985 return error("CBlock::ReadFromDisk() : errors in block header");
994 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
995 GetHash().ToString().substr(0,20).c_str(),
997 hashPrevBlock.ToString().substr(0,20).c_str(),
998 hashMerkleRoot.ToString().substr(0,10).c_str(),
999 nTime, nBits, nNonce,
1001 for (int i = 0; i < vtx.size(); i++)
1006 printf(" vMerkleTree: ");
1007 for (int i = 0; i < vMerkleTree.size(); i++)
1008 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1013 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1014 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1015 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1016 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1017 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1018 bool CheckBlock() const;
1020 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1029 // The block chain is a tree shaped structure starting with the
1030 // genesis block at the root, with each block potentially having multiple
1031 // candidates to be the next block. pprev and pnext link a path through the
1032 // main/longest chain. A blockindex may have multiple pprev pointing back
1033 // to it, but pnext will only point forward to the longest branch, or will
1034 // be null if the block is not part of the longest chain.
1039 const uint256* phashBlock;
1043 unsigned int nBlockPos;
1044 uint64 nChainTrust;// ppcoin: trust score of chain, in the unit of coin-days
1046 int nCheckpoint; // ppcoin: chain auto checkpoint height
1050 uint256 hashMerkleRoot;
1053 unsigned int nNonce;
1074 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1080 nBlockPos = nBlockPosIn;
1085 nVersion = block.nVersion;
1086 hashMerkleRoot = block.hashMerkleRoot;
1087 nTime = block.nTime;
1088 nBits = block.nBits;
1089 nNonce = block.nNonce;
1092 CBlock GetBlockHeader() const
1095 block.nVersion = nVersion;
1097 block.hashPrevBlock = pprev->GetBlockHash();
1098 block.hashMerkleRoot = hashMerkleRoot;
1099 block.nTime = nTime;
1100 block.nBits = nBits;
1101 block.nNonce = nNonce;
1105 uint256 GetBlockHash() const
1110 int64 GetBlockTime() const
1112 return (int64)nTime;
1115 int64 GetBlockTrust() const
1117 return (nChainTrust - (pprev? pprev->nChainTrust : 0));
1120 bool IsInMainChain() const
1122 return (pnext || this == pindexBest);
1125 bool CheckIndex() const
1127 return CheckProofOfWork(GetBlockHash(), nBits);
1130 bool EraseBlockFromDisk()
1132 // Open history file
1133 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1137 // Overwrite with empty null block
1145 enum { nMedianTimeSpan=11 };
1147 int64 GetMedianTimePast() const
1149 int64 pmedian[nMedianTimeSpan];
1150 int64* pbegin = &pmedian[nMedianTimeSpan];
1151 int64* pend = &pmedian[nMedianTimeSpan];
1153 const CBlockIndex* pindex = this;
1154 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1155 *(--pbegin) = pindex->GetBlockTime();
1157 std::sort(pbegin, pend);
1158 return pbegin[(pend - pbegin)/2];
1161 int64 GetMedianTime() const
1163 const CBlockIndex* pindex = this;
1164 for (int i = 0; i < nMedianTimeSpan/2; i++)
1167 return GetBlockTime();
1168 pindex = pindex->pnext;
1170 return pindex->GetMedianTimePast();
1175 std::string ToString() const
1177 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nChainTrust=%"PRI64d" nHeight=%d, nCheckpoint=%d, merkle=%s, hashBlock=%s)",
1178 pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight, nCheckpoint,
1179 hashMerkleRoot.ToString().substr(0,10).c_str(),
1180 GetBlockHash().ToString().substr(0,20).c_str());
1185 printf("%s\n", ToString().c_str());
1192 // Used to marshal pointers into hashes for db storage.
1194 class CDiskBlockIndex : public CBlockIndex
1206 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1208 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1209 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1214 if (!(nType & SER_GETHASH))
1215 READWRITE(nVersion);
1217 READWRITE(hashNext);
1219 READWRITE(nBlockPos);
1220 READWRITE(nChainTrust);
1222 READWRITE(nCheckpoint);
1225 READWRITE(this->nVersion);
1226 READWRITE(hashPrev);
1227 READWRITE(hashMerkleRoot);
1233 uint256 GetBlockHash() const
1236 block.nVersion = nVersion;
1237 block.hashPrevBlock = hashPrev;
1238 block.hashMerkleRoot = hashMerkleRoot;
1239 block.nTime = nTime;
1240 block.nBits = nBits;
1241 block.nNonce = nNonce;
1242 return block.GetHash();
1246 std::string ToString() const
1248 std::string str = "CDiskBlockIndex(";
1249 str += CBlockIndex::ToString();
1250 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1251 GetBlockHash().ToString().c_str(),
1252 hashPrev.ToString().substr(0,20).c_str(),
1253 hashNext.ToString().substr(0,20).c_str());
1259 printf("%s\n", ToString().c_str());
1271 // Describes a place in the block chain to another node such that if the
1272 // other node doesn't have the same branch, it can find a recent common trunk.
1273 // The further back it is, the further before the fork it may be.
1278 std::vector<uint256> vHave;
1285 explicit CBlockLocator(const CBlockIndex* pindex)
1290 explicit CBlockLocator(uint256 hashBlock)
1292 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1293 if (mi != mapBlockIndex.end())
1299 if (!(nType & SER_GETHASH))
1300 READWRITE(nVersion);
1311 return vHave.empty();
1314 void Set(const CBlockIndex* pindex)
1320 vHave.push_back(pindex->GetBlockHash());
1322 // Exponentially larger steps back
1323 for (int i = 0; pindex && i < nStep; i++)
1324 pindex = pindex->pprev;
1325 if (vHave.size() > 10)
1328 vHave.push_back(hashGenesisBlock);
1331 int GetDistanceBack()
1333 // Retrace how far back it was in the sender's branch
1336 BOOST_FOREACH(const uint256& hash, vHave)
1338 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1339 if (mi != mapBlockIndex.end())
1341 CBlockIndex* pindex = (*mi).second;
1342 if (pindex->IsInMainChain())
1352 CBlockIndex* GetBlockIndex()
1354 // Find the first block the caller has in the main chain
1355 BOOST_FOREACH(const uint256& hash, vHave)
1357 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1358 if (mi != mapBlockIndex.end())
1360 CBlockIndex* pindex = (*mi).second;
1361 if (pindex->IsInMainChain())
1365 return pindexGenesisBlock;
1368 uint256 GetBlockHash()
1370 // Find the first block the caller has in the main chain
1371 BOOST_FOREACH(const uint256& hash, vHave)
1373 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1374 if (mi != mapBlockIndex.end())
1376 CBlockIndex* pindex = (*mi).second;
1377 if (pindex->IsInMainChain())
1381 return hashGenesisBlock;
1386 CBlockIndex* pindex = GetBlockIndex();
1389 return pindex->nHeight;
1402 // Alerts are for notifying old versions if they become too obsolete and
1403 // need to upgrade. The message is displayed in the status bar.
1404 // Alert messages are broadcast as a vector of signed data. Unserializing may
1405 // not read the entire buffer if the alert is for a newer version, but older
1406 // versions can still relay the original data.
1408 class CUnsignedAlert
1412 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1416 std::set<int> setCancel;
1417 int nMinVer; // lowest version inclusive
1418 int nMaxVer; // highest version inclusive
1419 std::set<std::string> setSubVer; // empty matches all
1423 std::string strComment;
1424 std::string strStatusBar;
1425 std::string strReserved;
1429 READWRITE(this->nVersion);
1430 nVersion = this->nVersion;
1431 READWRITE(nRelayUntil);
1432 READWRITE(nExpiration);
1435 READWRITE(setCancel);
1438 READWRITE(setSubVer);
1439 READWRITE(nPriority);
1441 READWRITE(strComment);
1442 READWRITE(strStatusBar);
1443 READWRITE(strReserved);
1460 strStatusBar.clear();
1461 strReserved.clear();
1464 std::string ToString() const
1466 std::string strSetCancel;
1467 BOOST_FOREACH(int n, setCancel)
1468 strSetCancel += strprintf("%d ", n);
1469 std::string strSetSubVer;
1470 BOOST_FOREACH(std::string str, setSubVer)
1471 strSetSubVer += "\"" + str + "\" ";
1475 " nRelayUntil = %"PRI64d"\n"
1476 " nExpiration = %"PRI64d"\n"
1484 " strComment = \"%s\"\n"
1485 " strStatusBar = \"%s\"\n"
1492 strSetCancel.c_str(),
1495 strSetSubVer.c_str(),
1498 strStatusBar.c_str());
1503 printf("%s", ToString().c_str());
1507 class CAlert : public CUnsignedAlert
1510 std::vector<unsigned char> vchMsg;
1511 std::vector<unsigned char> vchSig;
1526 CUnsignedAlert::SetNull();
1533 return (nExpiration == 0);
1536 uint256 GetHash() const
1538 return SerializeHash(*this);
1541 bool IsInEffect() const
1543 return (GetAdjustedTime() < nExpiration);
1546 bool Cancels(const CAlert& alert) const
1549 return false; // this was a no-op before 31403
1550 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1553 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1555 return (IsInEffect() &&
1556 nMinVer <= nVersion && nVersion <= nMaxVer &&
1557 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1560 bool AppliesToMe() const
1562 return AppliesTo(VERSION, ::pszSubVer);
1565 bool RelayTo(CNode* pnode) const
1569 // returns true if wasn't already contained in the set
1570 if (pnode->setKnown.insert(GetHash()).second)
1572 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1574 GetAdjustedTime() < nRelayUntil)
1576 pnode->PushMessage("alert", *this);
1583 bool CheckSignature()
1586 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1587 return error("CAlert::CheckSignature() : SetPubKey failed");
1588 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1589 return error("CAlert::CheckSignature() : verify signature failed");
1591 // Now unserialize the data
1592 CDataStream sMsg(vchMsg);
1593 sMsg >> *(CUnsignedAlert*)this;
1597 bool ProcessAlert();