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 COPYING or http://www.opensource.org/licenses/mit-license.php.
13 #include "zerocoin/Zerocoin.h"
26 class CRequestTracker;
28 class CBlockIndexTrustComparator;
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 unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
33 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
34 static const unsigned int MAX_INV_SZ = 50000;
36 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
37 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
38 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
39 static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
41 static const int64 MIN_TX_FEE = CENT;
42 static const int64 MIN_RELAY_TX_FEE = CENT;
43 static const int64 MAX_MONEY = 2000000000 * COIN;
44 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
45 static const int64 MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
46 static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
48 static const unsigned int ENTROPY_SWITCH_TIME = 1362791041; // Sat, 09 Mar 2013 01:04:01 GMT
49 static const unsigned int STAKE_SWITCH_TIME = 1371686400; // Thu, 20 Jun 2013 00:00:00 GMT
50 static const unsigned int TARGETS_SWITCH_TIME = 1374278400; // Sat, 20 Jul 2013 00:00:00 GMT
51 static const unsigned int CHAINCHECKS_SWITCH_TIME = 1379635200; // Fri, 20 Sep 2013 00:00:00 GMT
52 static const unsigned int STAKECURVE_SWITCH_TIME = 1382227200; // Sun, 20 Oct 2013 00:00:00 GMT
53 static const unsigned int OUTPUT_SWITCH_TIME = 1398916800; // Thu, 01 May 2014 04:00:00 GMT
56 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
57 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
58 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
61 static const int fHaveUPnP = true;
63 static const int fHaveUPnP = false;
66 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
67 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
69 inline int64 PastDrift(int64 nTime) { return nTime - 2 * 60 * 60; } // up to 2 hours from the past
70 inline int64 FutureDrift(int64 nTime) { return nTime + 2 * 60 * 60; } // up to 2 hours from the future
72 extern libzerocoin::Params* ZCParams;
73 extern CScript COINBASE_FLAGS;
74 extern CCriticalSection cs_main;
75 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
76 extern std::set<CBlockIndex*, CBlockIndexTrustComparator> setBlockIndexValid;
77 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
78 extern CBlockIndex* pindexGenesisBlock;
79 extern unsigned int nStakeMinAge;
80 extern unsigned int nNodeLifespan;
81 extern int nCoinbaseMaturity;
82 extern int nBestHeight;
83 extern uint256 nBestChainTrust;
84 extern uint256 nBestInvalidTrust;
85 extern uint256 hashBestChain;
86 extern CBlockIndex* pindexBest;
87 extern unsigned int nTransactionsUpdated;
88 extern uint64 nLastBlockTx;
89 extern uint64 nLastBlockSize;
90 extern int64 nLastCoinStakeSearchInterval;
91 extern const std::string strMessageMagic;
92 extern int64 nTimeBestReceived;
93 extern CCriticalSection cs_setpwalletRegistered;
94 extern std::set<CWallet*> setpwalletRegistered;
95 extern unsigned char pchMessageStart[4];
96 extern std::map<uint256, CBlock*> mapOrphanBlocks;
99 extern int64 nTransactionFee;
100 extern int64 nMinimumInputValue;
101 extern bool fUseFastIndex;
102 extern unsigned int nDerivationMethodIndex;
104 // Minimum disk space required - used in CheckDiskSpace()
105 static const uint64 nMinDiskSpace = 52428800;
114 class CCoinsViewCache;
116 void RegisterWallet(CWallet* pwalletIn);
117 void UnregisterWallet(CWallet* pwalletIn);
118 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
119 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
120 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
121 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
122 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
123 bool LoadBlockIndex(bool fAllowNew=true);
124 void PrintBlockTree();
125 CBlockIndex* FindBlockByHeight(int nHeight);
126 bool ProcessMessages(CNode* pfrom);
127 bool SendMessages(CNode* pto, bool fSendTrickle);
128 bool LoadExternalBlockFile(FILE* fileIn);
130 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
131 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
132 int64 GetProofOfWorkReward(unsigned int nBits);
133 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly=false);
134 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
135 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
136 int GetNumBlocksOfPeers();
137 bool IsInitialBlockDownload();
138 std::string GetWarnings(std::string strFor);
139 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow);
140 bool SetBestChain(CBlockIndex* pindexNew);
141 bool ConnectBestBlock();
142 CBlockIndex * InsertBlockIndex(uint256 hash);
143 uint256 WantedByOrphan(const CBlock* pblockOrphan);
144 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
145 void StakeMiner(CWallet *pwallet);
146 void ResendWalletTransactions(bool fForce=false);
148 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
157 READWRITE(VARINT(nFile));
158 READWRITE(VARINT(nPos));
161 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
162 return (a.nFile == b.nFile && a.nPos == b.nPos);
165 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
169 void SetNull() { nFile = -1; nPos = 0; }
170 bool IsNull() const { return (nFile == -1); }
174 /** An inpoint - a combination of a transaction and an index n into its vin */
181 CInPoint() { SetNull(); }
182 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
183 void SetNull() { ptx = NULL; n = (unsigned int) -1; }
184 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
189 /** An outpoint - a combination of a transaction hash and an index n into its vout */
196 COutPoint() { SetNull(); }
197 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
198 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
199 void SetNull() { hash = 0; n = (unsigned int) -1; }
200 bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
202 friend bool operator<(const COutPoint& a, const COutPoint& b)
204 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
207 friend bool operator==(const COutPoint& a, const COutPoint& b)
209 return (a.hash == b.hash && a.n == b.n);
212 friend bool operator!=(const COutPoint& a, const COutPoint& b)
217 std::string ToString() const
219 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
224 printf("%s\n", ToString().c_str());
231 /** An input of a transaction. It contains the location of the previous
232 * transaction's output that it claims and a signature that matches the
233 * output's public key.
240 unsigned int nSequence;
244 nSequence = std::numeric_limits<unsigned int>::max();
247 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
250 scriptSig = scriptSigIn;
251 nSequence = nSequenceIn;
254 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
256 prevout = COutPoint(hashPrevTx, nOut);
257 scriptSig = scriptSigIn;
258 nSequence = nSequenceIn;
264 READWRITE(scriptSig);
265 READWRITE(nSequence);
270 return (nSequence == std::numeric_limits<unsigned int>::max());
273 friend bool operator==(const CTxIn& a, const CTxIn& b)
275 return (a.prevout == b.prevout &&
276 a.scriptSig == b.scriptSig &&
277 a.nSequence == b.nSequence);
280 friend bool operator!=(const CTxIn& a, const CTxIn& b)
285 std::string ToStringShort() const
287 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
290 std::string ToString() const
294 str += prevout.ToString();
295 if (prevout.IsNull())
296 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
298 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
299 if (nSequence != std::numeric_limits<unsigned int>::max())
300 str += strprintf(", nSequence=%u", nSequence);
307 printf("%s\n", ToString().c_str());
314 /** An output of a transaction. It contains the public key that the next input
315 * must be able to sign with to claim it.
321 CScript scriptPubKey;
328 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
331 scriptPubKey = scriptPubKeyIn;
337 READWRITE(scriptPubKey);
343 scriptPubKey.clear();
348 return (nValue == -1);
354 scriptPubKey.clear();
359 return (nValue == 0 && scriptPubKey.empty());
362 uint256 GetHash() const
364 return SerializeHash(*this);
367 friend bool operator==(const CTxOut& a, const CTxOut& b)
369 return (a.nValue == b.nValue &&
370 a.scriptPubKey == b.scriptPubKey);
373 friend bool operator!=(const CTxOut& a, const CTxOut& b)
378 std::string ToStringShort() const
380 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0, 10).c_str());
383 std::string ToString() const
385 if (IsEmpty()) return "CTxOut(empty)";
386 if (scriptPubKey.size() < 6)
387 return "CTxOut(error)";
388 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
393 printf("%s\n", ToString().c_str());
407 // Modes for script/signature checking
410 CS_NEVER, // never validate scripts
411 CS_AFTER_CHECKPOINT, // validate scripts after the last checkpoint
412 CS_ALWAYS // always validate scripts
415 /** The basic transaction that is broadcasted on the network and contained in
416 * blocks. A transaction can contain multiple inputs and outputs.
421 static const int CURRENT_VERSION=1;
424 std::vector<CTxIn> vin;
425 std::vector<CTxOut> vout;
426 unsigned int nLockTime;
428 // Denial-of-service detection:
430 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
439 READWRITE(this->nVersion);
440 nVersion = this->nVersion;
444 READWRITE(nLockTime);
449 nVersion = CTransaction::CURRENT_VERSION;
450 nTime = GetAdjustedTime();
454 nDoS = 0; // Denial-of-service prevention
459 return (vin.empty() && vout.empty());
462 uint256 GetHash() const
464 return SerializeHash(*this);
467 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
469 // Time based nLockTime implemented in 0.1.6
472 if (nBlockHeight == 0)
473 nBlockHeight = nBestHeight;
475 nBlockTime = GetAdjustedTime();
476 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
478 BOOST_FOREACH(const CTxIn& txin, vin)
484 bool IsNewerThan(const CTransaction& old) const
486 if (vin.size() != old.vin.size())
488 for (unsigned int i = 0; i < vin.size(); i++)
489 if (vin[i].prevout != old.vin[i].prevout)
493 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
494 for (unsigned int i = 0; i < vin.size(); i++)
496 if (vin[i].nSequence != old.vin[i].nSequence)
498 if (vin[i].nSequence <= nLowest)
501 nLowest = vin[i].nSequence;
503 if (old.vin[i].nSequence < nLowest)
506 nLowest = old.vin[i].nSequence;
513 bool IsCoinBase() const
515 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
518 bool IsCoinStake() const
520 // ppcoin: the coin stake transaction is marked with the first output empty
521 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
524 /** Check for standard transaction types
525 @return True if all outputs (scriptPubKeys) use only standard transaction forms
527 bool IsStandard() const;
529 /** Check for standard transaction types
530 @param[in] mapInputs Map of previous transactions that have outputs we're spending
531 @return True if all inputs (scriptSigs) use only standard transaction forms
532 @see CTransaction::FetchInputs
534 bool AreInputsStandard(CCoinsViewCache& mapInputs) const;
536 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
537 @return number of sigops this transaction's outputs will produce when spent
538 @see CTransaction::FetchInputs
540 unsigned int GetLegacySigOpCount() const;
542 /** Count ECDSA signature operations in pay-to-script-hash inputs.
544 @param[in] mapInputs Map of previous transactions that have outputs we're spending
545 @return maximum number of sigops required to validate this transaction's inputs
546 @see CTransaction::FetchInputs
548 unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const;
550 /** Amount of bitcoins spent by this transaction.
551 @return sum of all outputs (note: does not include fees)
553 int64 GetValueOut() const
556 BOOST_FOREACH(const CTxOut& txout, vout)
558 nValueOut += txout.nValue;
559 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
560 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
565 /** Amount of bitcoins coming in to this transaction
566 Note that lightweight clients may not know anything besides the hash of previous transactions,
567 so may not be able to calculate this.
569 @param[in] mapInputs Map of previous transactions that have outputs we're spending
570 @return Sum of value of all inputs (scriptSigs)
571 @see CTransaction::FetchInputs
573 int64 GetValueIn(CCoinsViewCache& mapInputs) const;
575 static bool AllowFree(double dPriority)
577 // Large (in bytes) low-priority (new, small-coin) transactions
579 return dPriority > COIN * 144 / 250;
582 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
584 friend bool operator==(const CTransaction& a, const CTransaction& b)
586 return (a.nVersion == b.nVersion &&
587 a.nTime == b.nTime &&
590 a.nLockTime == b.nLockTime);
593 friend bool operator!=(const CTransaction& a, const CTransaction& b)
598 std::string ToStringShort() const
601 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
605 std::string ToString() const
608 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
609 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
610 GetHash().ToString().substr(0,10).c_str(),
616 for (unsigned int i = 0; i < vin.size(); i++)
617 str += " " + vin[i].ToString() + "\n";
618 for (unsigned int i = 0; i < vout.size(); i++)
619 str += " " + vout[i].ToString() + "\n";
625 printf("%s", ToString().c_str());
629 // Do all possible client-mode checks
630 bool ClientCheckInputs() const;
632 // Check whether all prevouts of this transaction are present in the UTXO set represented by view
633 bool HaveInputs(CCoinsViewCache &view) const;
635 // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
636 // This does not modify the UTXO set
637 bool CheckInputs(CCoinsViewCache &view, enum CheckSig_mode csmode, bool fStrictPayToScriptHash=true, bool fStrictEncodings=true, CBlock *pblock=NULL) const;
639 // Apply the effects of this transaction on the UTXO set represented by view
640 bool UpdateCoins(CCoinsViewCache &view, CTxUndo &txundo, int nHeight, unsigned int nBlockTime, const uint256 &txhash) const;
642 // Context-independent validity checks
643 bool CheckTransaction() const;
645 // Try to accept this transaction into the memory pool
646 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
647 bool GetCoinAge(uint64& nCoinAge) const; // Get transaction coin age
649 static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs);
653 /** wrapper for CTxOut that provides a more compact serialization */
654 class CTxOutCompressor
660 static uint64 CompressAmount(uint64 nAmount);
661 static uint64 DecompressAmount(uint64 nAmount);
663 CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
665 IMPLEMENT_SERIALIZE(({
667 uint64 nVal = CompressAmount(txout.nValue);
668 READWRITE(VARINT(nVal));
671 READWRITE(VARINT(nVal));
672 txout.nValue = DecompressAmount(nVal);
674 CScriptCompressor cscript(REF(txout.scriptPubKey));
679 /** Undo information for a CTxIn
681 * Contains the prevout's CTxOut being spent, and if this was the
682 * last output of the affected transaction, its metadata as well
683 * (coinbase or not, height, transaction version)
688 CTxOut txout; // the txout data before being spent
689 bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
690 bool fCoinStake; // if the outpoint was the last unspent: whether it belonged to a coinstake
691 unsigned int nHeight; // if the outpoint was the last unspent: its height
692 int nVersion; // if the outpoint was the last unspent: its version
693 unsigned int nTime; // if the outpoint was the last unspent: its timestamp
694 unsigned int nBlockTime; // if the outpoint was the last unspent: its block timestamp
696 CTxInUndo() : txout(), fCoinBase(false), fCoinStake(false), nHeight(0), nVersion(0), nTime(0), nBlockTime(0) {}
697 CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, bool fCoinStakeIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0, int nTimeIn = 0, int nBlockTimeIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), fCoinStake(fCoinStakeIn), nHeight(nHeightIn), nVersion(nVersionIn), nTime(nTimeIn), nBlockTime(nBlockTimeIn) { }
699 unsigned int GetSerializeSize(int nType, int nVersion) const {
700 return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
701 ::GetSerializeSize(VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion) +
702 ::GetSerializeSize(VARINT(nBlockTime), nType, nVersion) +
703 (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
704 ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
707 template<typename Stream>
708 void Serialize(Stream &s, int nType, int nVersion) const {
709 ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
710 ::Serialize(s, VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion);
711 ::Serialize(s, VARINT(nBlockTime), nType, nVersion);
713 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
714 ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
717 template<typename Stream>
718 void Unserialize(Stream &s, int nType, int nVersion) {
719 unsigned int nCodeHeight = 0, nCodeTime = 0;
720 ::Unserialize(s, VARINT(nCodeHeight), nType, nVersion);
721 nHeight = nCodeHeight / 2;
722 fCoinBase = nCodeHeight & 1;
723 ::Unserialize(s, VARINT(nCodeTime), nType, nVersion);
724 nTime = nCodeTime / 2;
725 fCoinStake = nCodeTime & 1;
726 ::Unserialize(s, VARINT(nBlockTime), nType, nVersion);
728 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
729 ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
733 /** Undo information for a CTransaction */
737 // undo information for all txins
738 std::vector<CTxInUndo> vprevout;
745 /** Undo information for a CBlock */
749 std::vector<CTxUndo> vtxundo; // for all but the coinbase
755 bool WriteToDisk(CDiskBlockPos &pos)
757 // Open history file to append
758 CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
760 return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
762 // Write index header
763 unsigned int nSize = fileout.GetSerializeSize(*this);
764 fileout << FLATDATA(pchMessageStart) << nSize;
767 long fileOutPos = ftell(fileout);
769 return error("CBlockUndo::WriteToDisk() : ftell failed");
770 pos.nPos = (unsigned int)fileOutPos;
773 // Flush stdio buffers and commit to disk before returning
775 if (!IsInitialBlockDownload())
783 /** pruned version of CTransaction: only retains metadata and unspent transaction outputs
789 * - unspentness bitvector, for vout[2] and further; least significant byte first
790 * - the non-spent CTxOuts (via CTxOutCompressor)
792 * - VARINT(nTime + is_coinstake)
793 * - VARINT(nBlockTime)
795 * The nFlag value consists of:
796 * - bit 1: is coinbase
797 * - bit 2: is coinstake
800 * The nCode value consists of:
801 * - bit 2: vout[0] is not spent
802 * - bit 4: vout[1] is not spent
803 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
804 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
805 * least one non-spent output).
807 * Example: 010004835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e40f1d75240f1d752
808 * <><><><--------------------------------------------><----><------><------>
810 * version | code vout[1] height timestamp block timestamp
815 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
816 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
817 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
818 * * 8358: compact amount representation for 60000000000 (600 BTC)
819 * * 00: special txout type pay-to-pubkey-hash
820 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
822 * - time = 1389883712
825 * - block time = 1389883712
828 * Example: 010508044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b40f1d75240f1d752
829 * <><><><--><--------------------------------------------------><----------------------------------------------><----><------><------>
831 * version | code unspentness vout[4] vout[16] height timestamp block timestamp
836 * - code = 8 (neither vout[0] or vout[1] are unspent,
837 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
838 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
839 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
840 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
841 * * 00: special txout type pay-to-pubkey-hash
842 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
843 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
844 * * bbd123: compact amount representation for 110397 (0.001 BTC)
845 * * 00: special txout type pay-to-pubkey-hash
846 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
848 * - time = 1389883712
851 * - block time = 1389883712
853 * Example: 010686af3b40f1d75240f1d752
854 * <><><----><------><------>
856 * version flags height timestamp block timestamp
859 * - flags = 6 (00000110)
861 * - time = 1389883712
864 * - block time = 1389883712
869 // whether transaction is a coinbase
872 // whether transaction is a coinstake
875 // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
876 std::vector<CTxOut> vout;
878 // at which height this transaction was included in the active blockchain
881 // version of the CTransaction; accesses to this value should probably check for nHeight as well,
882 // as new tx version will probably only be introduced at certain heights
885 // transaction timestamp + coinstake flag
889 unsigned int nBlockTime;
891 // construct a CCoins from a CTransaction, at a given height/timestamp
892 CCoins(const CTransaction &tx, int nHeightIn, int nBlockTimeIn) : fCoinBase(tx.IsCoinBase()), fCoinStake(tx.IsCoinStake()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion), nTime(tx.nTime), nBlockTime(nBlockTimeIn) { }
895 CCoins() : fCoinBase(false), fCoinStake(false), vout(0), nHeight(0), nVersion(0), nTime(0), nBlockTime(0) { }
897 // remove spent outputs at the end of vout
899 while (vout.size() > 0 && (vout.back().IsNull() || vout.back().IsEmpty()))
904 friend bool operator==(const CCoins &a, const CCoins &b) {
905 return a.fCoinBase == b.fCoinBase &&
906 a.fCoinStake == b.fCoinStake &&
907 a.nHeight == b.nHeight &&
908 a.nVersion == b.nVersion &&
909 a.nTime == b.nTime &&
910 a.nBlockTime == b.nBlockTime &&
913 friend bool operator!=(const CCoins &a, const CCoins &b) {
917 // calculate number of bytes for the bitmask, and its number of non-zero bytes
918 // each bit in the bitmask represents the availability of one output, but the
919 // availabilities of the first two outputs are encoded separately
920 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
921 unsigned int nLastUsedByte = 0;
922 for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
924 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
925 if (!vout[2+b*8+i].IsNull()) {
931 nLastUsedByte = b + 1;
935 nBytes += nLastUsedByte;
938 bool IsCoinBase() const {
942 bool IsCoinStake() const {
946 unsigned int GetSerializeSize(int nType, int nVersion) const {
947 unsigned int nSize = 0;
948 bool fPruned = IsPruned();
951 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
952 unsigned char nFlags = 0;
953 // coinbase, coinstake and prune flags
954 nFlags = (fCoinBase ? 1 : 0)<<0 | (fCoinStake ? 1 : 0)<<1 | (fPruned ? 1 : 0)<<2;
956 nSize += ::GetSerializeSize(VARINT(nFlags), nType, nVersion);
959 unsigned int nMaskSize = 0, nMaskCode = 0;
960 CalcMaskSize(nMaskSize, nMaskCode);
961 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
962 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
964 assert(fFirst || fSecond || nMaskCode);
965 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
966 // size of header code
967 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
971 for (unsigned int i = 0; i < vout.size(); i++)
972 if (!vout[i].IsNull())
973 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
975 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
976 // timestamp and coinstake flag
977 nSize += ::GetSerializeSize(VARINT(nTime), nType, nVersion);
979 nSize += ::GetSerializeSize(VARINT(nBlockTime), nType, nVersion);
983 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
985 nSize += ::GetSerializeSize(VARINT(nTime), nType, nVersion);
986 // size of block timestamp
987 nSize += ::GetSerializeSize(VARINT(nBlockTime), nType, nVersion);
993 template<typename Stream>
994 void Serialize(Stream &s, int nType, int nVersion) const {
995 bool fPruned = IsPruned();
996 unsigned char nFlags = 0;
997 nFlags = (fCoinBase ? 1 : 0)<<0 | (fCoinStake ? 1 : 0)<<1 | (fPruned ? 1 : 0)<<2;
1000 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
1002 ::Serialize(s, VARINT(nFlags), nType, nVersion);
1005 unsigned int nMaskSize = 0, nMaskCode = 0;
1006 CalcMaskSize(nMaskSize, nMaskCode);
1007 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
1008 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
1010 assert(fFirst || fSecond || nMaskCode);
1012 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
1015 ::Serialize(s, VARINT(nCode), nType, nVersion);
1016 // spentness bitmask
1017 for (unsigned int b = 0; b<nMaskSize; b++) {
1018 unsigned char chAvail = 0;
1019 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
1020 if (!vout[2+b*8+i].IsNull())
1021 chAvail |= (1 << i);
1022 ::Serialize(s, chAvail, nType, nVersion);
1025 for (unsigned int i = 0; i < vout.size(); i++) {
1026 if (!vout[i].IsNull())
1027 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
1030 ::Serialize(s, VARINT(nHeight), nType, nVersion);
1031 // transaction timestamp and coinstake flag
1032 ::Serialize(s, VARINT(nTime), nType, nVersion);
1034 ::Serialize(s, VARINT(nBlockTime), nType, nVersion);
1038 ::Serialize(s, VARINT(nHeight), nType, nVersion);
1039 // transaction timestamp
1040 ::Serialize(s, VARINT(nTime), nType, nVersion);
1042 ::Serialize(s, VARINT(nBlockTime), nType, nVersion);
1046 template<typename Stream>
1047 void Unserialize(Stream &s, int nType, int nVersion) {
1048 unsigned char nFlags = 0;
1051 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
1052 // coinbase and coinstake flags
1053 ::Unserialize(s, VARINT(nFlags), nType, nVersion);
1055 fCoinBase = nFlags & (1<<0);
1056 fCoinStake = nFlags & (1<<1);
1057 bool fPruned = nFlags & (1<<2);
1060 unsigned int nCode = 0;
1062 ::Unserialize(s, VARINT(nCode), nType, nVersion);
1063 std::vector<bool> vAvail(2, false);
1064 vAvail[0] = nCode & 2;
1065 vAvail[1] = nCode & 4;
1066 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
1067 // spentness bitmask
1068 while (nMaskCode > 0) {
1069 unsigned char chAvail = 0;
1070 ::Unserialize(s, chAvail, nType, nVersion);
1071 for (unsigned int p = 0; p < 8; p++) {
1072 bool f = (chAvail & (1 << p)) != 0;
1073 vAvail.push_back(f);
1079 vout.assign(vAvail.size(), CTxOut());
1080 for (unsigned int i = 0; i < vAvail.size(); i++) {
1082 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
1085 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
1086 // transaction timestamp
1087 ::Unserialize(s, VARINT(nTime), nType, nVersion);
1090 ::Unserialize(s, VARINT(nBlockTime), nType, nVersion);
1094 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
1095 // transaction timestamp
1096 ::Unserialize(s, VARINT(nTime), nType, nVersion);
1098 ::Unserialize(s, VARINT(nBlockTime), nType, nVersion);
1103 // mark an outpoint spent, and construct undo information
1104 bool Spend(const COutPoint &out, CTxInUndo &undo) {
1105 if (out.n >= vout.size())
1107 if (vout[out.n].IsNull())
1109 undo = CTxInUndo(vout[out.n]);
1110 vout[out.n].SetNull();
1112 if (vout.size() == 0) {
1113 undo.nHeight = nHeight;
1115 undo.nBlockTime = nBlockTime;
1116 undo.fCoinBase = fCoinBase;
1117 undo.fCoinStake = fCoinStake;
1118 undo.nVersion = this->nVersion;
1123 // mark a vout spent
1124 bool Spend(int nPos) {
1126 COutPoint out(0, nPos);
1127 return Spend(out, undo);
1130 // check whether a particular output is still available
1131 bool IsAvailable(unsigned int nPos) const {
1132 return (nPos < vout.size() && !vout[nPos].IsNull());
1135 // check whether the entire CCoins is spent
1136 // note that only !IsPruned() CCoins can be serialized
1137 bool IsPruned() const {
1138 if (vout.size() == 0)
1141 BOOST_FOREACH(const CTxOut &out, vout)
1152 /** A transaction with a merkle branch linking it to the block chain. */
1153 class CMerkleTx : public CTransaction
1157 std::vector<uint256> vMerkleBranch;
1161 mutable bool fMerkleVerified;
1169 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
1178 fMerkleVerified = false;
1184 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
1185 nVersion = this->nVersion;
1186 READWRITE(hashBlock);
1187 READWRITE(vMerkleBranch);
1192 int SetMerkleBranch(const CBlock* pblock=NULL);
1193 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
1194 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
1195 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
1196 int GetBlocksToMaturity() const;
1197 bool AcceptToMemoryPool(bool fCheckInputs=true);
1202 /** Nodes collect new transactions into a block, hash them into a hash tree,
1203 * and scan through nonce values to make the block's hash satisfy proof-of-work
1204 * requirements. When they solve the proof-of-work, they broadcast the block
1205 * to everyone and the block is added to the block chain. The first transaction
1206 * in the block is a special one that creates a new coin owned by the creator
1213 static const int CURRENT_VERSION=6;
1215 uint256 hashPrevBlock;
1216 uint256 hashMerkleRoot;
1219 unsigned int nNonce;
1222 std::vector<CTransaction> vtx;
1224 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
1225 std::vector<unsigned char> vchBlockSig;
1228 mutable std::vector<uint256> vMerkleTree;
1230 // Denial-of-service detection:
1232 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
1241 READWRITE(this->nVersion);
1242 nVersion = this->nVersion;
1243 READWRITE(hashPrevBlock);
1244 READWRITE(hashMerkleRoot);
1249 // ConnectBlock depends on vtx following header to generate CDiskTxPos
1250 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1253 READWRITE(vchBlockSig);
1257 const_cast<CBlock*>(this)->vtx.clear();
1258 const_cast<CBlock*>(this)->vchBlockSig.clear();
1264 nVersion = CBlock::CURRENT_VERSION;
1271 vchBlockSig.clear();
1272 vMerkleTree.clear();
1278 return (nBits == 0);
1281 uint256 GetHash() const
1283 return scrypt_blockhash(CVOIDBEGIN(nVersion));
1286 int64 GetBlockTime() const
1288 return (int64)nTime;
1291 void UpdateTime(const CBlockIndex* pindexPrev);
1293 // ppcoin: entropy bit for stake modifier if chosen by modifier
1294 unsigned int GetStakeEntropyBit(unsigned int nTime) const
1296 // Protocol switch to support p2pool at novacoin block #9689
1297 if (nTime >= ENTROPY_SWITCH_TIME || fTestNet)
1299 // Take last bit of block hash as entropy bit
1300 unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
1301 if (fDebug && GetBoolArg("-printstakemodifier"))
1302 printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
1305 // Before novacoin block #9689 - old protocol
1306 uint160 hashSig = Hash160(vchBlockSig);
1307 if (fDebug && GetBoolArg("-printstakemodifier"))
1308 printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
1309 hashSig >>= 159; // take the first bit of the hash
1310 if (fDebug && GetBoolArg("-printstakemodifier"))
1311 printf(" entropybit=%"PRI64d"\n", hashSig.Get64());
1312 return hashSig.Get64();
1315 // ppcoin: two types of block: proof-of-work or proof-of-stake
1316 bool IsProofOfStake() const
1318 return (vtx.size() > 1 && vtx[1].IsCoinStake());
1321 bool IsProofOfWork() const
1323 return !IsProofOfStake();
1326 std::pair<COutPoint, unsigned int> GetProofOfStake() const
1328 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
1331 // ppcoin: get max transaction timestamp
1332 int64 GetMaxTransactionTime() const
1334 int64 maxTransactionTime = 0;
1335 BOOST_FOREACH(const CTransaction& tx, vtx)
1336 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
1337 return maxTransactionTime;
1340 uint256 BuildMerkleTree() const
1342 vMerkleTree.clear();
1343 BOOST_FOREACH(const CTransaction& tx, vtx)
1344 vMerkleTree.push_back(tx.GetHash());
1346 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1348 for (int i = 0; i < nSize; i += 2)
1350 int i2 = std::min(i+1, nSize-1);
1351 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1352 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1356 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1359 const uint256 &GetTxHash(unsigned int nIndex) const {
1360 assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
1361 assert(nIndex < vtx.size());
1362 return vMerkleTree[nIndex];
1365 std::vector<uint256> GetMerkleBranch(int nIndex) const
1367 if (vMerkleTree.empty())
1369 std::vector<uint256> vMerkleBranch;
1371 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1373 int i = std::min(nIndex^1, nSize-1);
1374 vMerkleBranch.push_back(vMerkleTree[j+i]);
1378 return vMerkleBranch;
1381 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1385 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1388 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1390 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1396 bool WriteToDisk(CDiskBlockPos &pos)
1398 // Open history file to append
1399 CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1401 return error("CBlock::WriteToDisk() : OpenBlockFile failed");
1403 // Write index header
1404 unsigned int nSize = fileout.GetSerializeSize(*this);
1405 fileout << FLATDATA(pchMessageStart) << nSize;
1408 long fileOutPos = ftell(fileout);
1410 return error("CBlock::WriteToDisk() : ftell failed");
1411 pos.nPos = (unsigned int)fileOutPos;
1414 // Flush stdio buffers and commit to disk before returning
1416 if (!IsInitialBlockDownload())
1417 FileCommit(fileout);
1422 bool ReadFromDisk(const CDiskBlockPos &pos, bool fReadTransactions = true)
1426 // Open history file to read
1427 CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1429 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1430 if (!fReadTransactions)
1431 filein.nType |= SER_BLOCKHEADERONLY;
1437 catch (std::exception &e) {
1438 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1442 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1443 return error("CBlock::ReadFromDisk() : errors in block header");
1450 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
1451 GetHash().ToString().c_str(),
1453 hashPrevBlock.ToString().c_str(),
1454 hashMerkleRoot.ToString().c_str(),
1455 nTime, nBits, nNonce,
1457 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1458 for (unsigned int i = 0; i < vtx.size(); i++)
1463 printf(" vMerkleTree: ");
1464 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1465 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1469 // Undo the effects of this block (with given index) on the UTXO set represented by coins
1470 bool DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &coins);
1472 // Apply the effects of this block (with given index) on the UTXO set represented by coins
1473 bool ConnectBlock(CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
1475 // Read a block from disk
1476 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1478 // Add this block to the block index, and if necessary, switch the active block chain to this
1479 bool AddToBlockIndex(const CDiskBlockPos &pos);
1481 // Context-independent validity checks
1482 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=false) const;
1484 // Store block on disk
1487 // Get total coinage consumed
1488 bool GetCoinAge(uint64& nCoinAge) const;
1490 // Generate proof-of-stake block signature
1491 bool SignBlock(CWallet& keystore);
1493 // Get generator key
1494 bool GetGenerator(CKey& GeneratorKey) const;
1496 // Validate proof-of-stake block signature
1497 bool CheckSignature(bool& fFatal, uint256& hashProofOfStake) const;
1499 // Legacy proof-of-work signature
1500 bool CheckLegacySignature() const;
1504 class CBlockFileInfo
1507 unsigned int nBlocks; // number of blocks stored in file
1508 unsigned int nSize; // number of used bytes of block file
1509 unsigned int nUndoSize; // number of used bytes in the undo file
1510 unsigned int nHeightFirst; // lowest height of block in file
1511 unsigned int nHeightLast; // highest height of block in file
1512 uint64 nTimeFirst; // earliest time of block in file
1513 uint64 nTimeLast; // latest time of block in file
1515 IMPLEMENT_SERIALIZE(
1516 READWRITE(VARINT(nBlocks));
1517 READWRITE(VARINT(nSize));
1518 READWRITE(VARINT(nUndoSize));
1519 READWRITE(VARINT(nHeightFirst));
1520 READWRITE(VARINT(nHeightLast));
1521 READWRITE(VARINT(nTimeFirst));
1522 READWRITE(VARINT(nTimeLast));
1539 std::string ToString() const {
1540 return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u..%u, time=%s..%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str());
1543 // update statistics (does not update nSize)
1544 void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
1545 if (nBlocks==0 || nHeightFirst > nHeightIn)
1546 nHeightFirst = nHeightIn;
1547 if (nBlocks==0 || nTimeFirst > nTimeIn)
1548 nTimeFirst = nTimeIn;
1550 if (nHeightIn > nHeightFirst)
1551 nHeightLast = nHeightIn;
1552 if (nTimeIn > nTimeLast)
1553 nTimeLast = nTimeIn;
1558 extern CCriticalSection cs_LastBlockFile;
1559 extern CBlockFileInfo infoLastBlockFile;
1560 extern int nLastBlockFile;
1563 BLOCK_VALID_UNKNOWN = 0,
1564 BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
1565 BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
1566 BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
1567 BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
1568 BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
1569 BLOCK_VALID_MASK = 7,
1571 BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
1572 BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
1573 BLOCK_HAVE_MASK = 24,
1575 BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
1576 BLOCK_FAILED_CHILD = 64, // descends from failed block
1577 BLOCK_FAILED_MASK = 96
1580 /** The block chain is a tree shaped structure starting with the
1581 * genesis block at the root, with each block potentially having multiple
1582 * candidates to be the next block. pprev and pnext link a path through the
1583 * main/longest chain. A blockindex may have multiple pprev pointing back
1584 * to it, but pnext will only point forward to the longest branch, or will
1585 * be null if the block is not part of the longest chain.
1590 // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
1591 const uint256* phashBlock;
1593 // pointer to the index of the predecessor of this block
1596 // (memory only) pointer to the index of the *active* successor of this block
1599 // height of the entry in the chain. The genesis block has height 0
1602 // Which # file this block is stored in (blk?????.dat)
1605 // Byte offset within blk?????.dat where this block's data is stored
1606 unsigned int nDataPos;
1608 // Byte offset within rev?????.dat where this block's undo data is stored
1609 unsigned int nUndoPos;
1611 // (memory only) Trust score of block chain up to and including this block
1612 uint256 nChainTrust;
1614 // Number of transactions in this block.
1617 // (memory only) Number of transactions in the chain up to and including this block
1618 unsigned int nChainTx;
1620 // Verification status of this block. See enum BlockStatus for detailed info
1621 unsigned int nStatus;
1623 // Coins amount created by this block
1626 // Total coins created in this block chain up to and including this block
1630 unsigned int nFlags;
1633 // is proof-of-stake block
1634 BLOCK_PROOF_OF_STAKE = (1 << 0),
1635 // entropy bit for stake modifier
1636 BLOCK_STAKE_ENTROPY = (1 << 1),
1637 // regenerated stake modifier
1638 BLOCK_STAKE_MODIFIER = (1 << 2),
1641 // Hash modifier for proof-of-stake kernel
1642 uint64 nStakeModifier;
1644 // Checksum of index in-memory only
1645 unsigned int nStakeModifierChecksum;
1647 // Predecessor of coinstake transaction
1648 COutPoint prevoutStake;
1650 // Timestamp of coinstake transaction
1651 unsigned int nStakeTime;
1654 uint256 hashProofOfStake;
1658 uint256 hashMerkleRoot;
1661 unsigned int nNonce;
1680 nStakeModifierChecksum = 0;
1681 hashProofOfStake = 0;
1682 prevoutStake.SetNull();
1692 CBlockIndex(CBlock& block)
1709 nStakeModifierChecksum = 0;
1710 hashProofOfStake = 0;
1711 if (block.IsProofOfStake())
1714 prevoutStake = block.vtx[1].vin[0].prevout;
1715 nStakeTime = block.vtx[1].nTime;
1719 prevoutStake.SetNull();
1723 nVersion = block.nVersion;
1724 hashMerkleRoot = block.hashMerkleRoot;
1725 nTime = block.nTime;
1726 nBits = block.nBits;
1727 nNonce = block.nNonce;
1730 CDiskBlockPos GetBlockPos() const {
1732 if (nStatus & BLOCK_HAVE_DATA) {
1734 ret.nPos = nDataPos;
1740 CDiskBlockPos GetUndoPos() const {
1742 if (nStatus & BLOCK_HAVE_UNDO) {
1744 ret.nPos = nUndoPos;
1750 CBlock GetBlockHeader() const
1753 block.nVersion = nVersion;
1755 block.hashPrevBlock = pprev->GetBlockHash();
1756 block.hashMerkleRoot = hashMerkleRoot;
1757 block.nTime = nTime;
1758 block.nBits = nBits;
1759 block.nNonce = nNonce;
1763 uint256 GetBlockHash() const
1768 int64 GetBlockTime() const
1770 return (int64)nTime;
1773 uint256 GetBlockTrust() const;
1775 bool IsInMainChain() const
1777 return (pnext || this == pindexBest);
1780 bool CheckIndex() const
1785 enum { nMedianTimeSpan=11 };
1787 int64 GetMedianTimePast() const
1789 int64 pmedian[nMedianTimeSpan];
1790 int64* pbegin = &pmedian[nMedianTimeSpan];
1791 int64* pend = &pmedian[nMedianTimeSpan];
1793 const CBlockIndex* pindex = this;
1794 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1795 *(--pbegin) = pindex->GetBlockTime();
1797 std::sort(pbegin, pend);
1798 return pbegin[(pend - pbegin)/2];
1801 int64 GetMedianTime() const
1803 const CBlockIndex* pindex = this;
1804 for (int i = 0; i < nMedianTimeSpan/2; i++)
1807 return GetBlockTime();
1808 pindex = pindex->pnext;
1810 return pindex->GetMedianTimePast();
1814 * Returns true if there are nRequired or more blocks of minVersion or above
1815 * in the last nToCheck blocks, starting at pstart and going backwards.
1817 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1818 unsigned int nRequired, unsigned int nToCheck);
1820 bool IsProofOfWork() const
1822 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1825 bool IsProofOfStake() const
1827 return (nFlags & BLOCK_PROOF_OF_STAKE);
1830 void SetProofOfStake()
1832 nFlags |= BLOCK_PROOF_OF_STAKE;
1835 unsigned int GetStakeEntropyBit() const
1837 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1840 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1842 if (nEntropyBit > 1)
1844 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1848 bool GeneratedStakeModifier() const
1850 return (nFlags & BLOCK_STAKE_MODIFIER);
1853 void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1855 nStakeModifier = nModifier;
1856 if (fGeneratedStakeModifier)
1857 nFlags |= BLOCK_STAKE_MODIFIER;
1860 std::string ToString() const
1862 return strprintf("CBlockIndex(nprev=%p, pnext=%p nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1863 pprev, pnext, nHeight,
1864 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1865 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1866 nStakeModifier, nStakeModifierChecksum,
1867 hashProofOfStake.ToString().c_str(),
1868 prevoutStake.ToString().c_str(), nStakeTime,
1869 hashMerkleRoot.ToString().c_str(),
1870 GetBlockHash().ToString().c_str());
1876 printf("%s\n", ToString().c_str());
1880 struct CBlockIndexTrustComparator
1882 bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
1883 if (pa->nChainTrust > pb->nChainTrust) return false;
1884 if (pa->nChainTrust < pb->nChainTrust) return true;
1886 return false; // identical blocks
1890 /** Used to marshal pointers into hashes for db storage. */
1891 class CDiskBlockIndex : public CBlockIndex
1903 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
1904 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1909 if (!(nType & SER_GETHASH))
1910 READWRITE(VARINT(nVersion));
1912 READWRITE(VARINT(nHeight));
1913 READWRITE(VARINT(nStatus));
1914 READWRITE(VARINT(nTx));
1915 if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
1916 READWRITE(VARINT(nFile));
1917 if (nStatus & BLOCK_HAVE_DATA)
1918 READWRITE(VARINT(nDataPos));
1919 if (nStatus & BLOCK_HAVE_UNDO)
1920 READWRITE(VARINT(nUndoPos));
1922 READWRITE(nMoneySupply);
1924 READWRITE(nStakeModifier);
1925 if (IsProofOfStake())
1927 READWRITE(prevoutStake);
1928 READWRITE(nStakeTime);
1929 READWRITE(hashProofOfStake);
1933 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1934 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1935 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1937 READWRITE(blockHash);
1940 READWRITE(this->nVersion);
1941 READWRITE(hashPrev);
1942 READWRITE(hashMerkleRoot);
1948 uint256 GetBlockHash() const
1950 if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
1954 block.nVersion = nVersion;
1955 block.hashPrevBlock = hashPrev;
1956 block.hashMerkleRoot = hashMerkleRoot;
1957 block.nTime = nTime;
1958 block.nBits = nBits;
1959 block.nNonce = nNonce;
1961 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1967 std::string ToString() const
1969 std::string str = "CDiskBlockIndex(";
1970 str += CBlockIndex::ToString();
1971 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
1972 GetBlockHash().ToString().c_str(),
1973 hashPrev.ToString().substr(0,20).c_str());
1979 printf("%s\n", ToString().c_str());
1984 /** Describes a place in the block chain to another node such that if the
1985 * other node doesn't have the same branch, it can find a recent common trunk.
1986 * The further back it is, the further before the fork it may be.
1991 std::vector<uint256> vHave;
1998 explicit CBlockLocator(const CBlockIndex* pindex)
2003 explicit CBlockLocator(uint256 hashBlock)
2005 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
2006 if (mi != mapBlockIndex.end())
2010 CBlockLocator(const std::vector<uint256>& vHaveIn)
2017 if (!(nType & SER_GETHASH))
2018 READWRITE(nVersion);
2029 return vHave.empty();
2032 void Set(const CBlockIndex* pindex)
2038 vHave.push_back(pindex->GetBlockHash());
2040 // Exponentially larger steps back
2041 for (int i = 0; pindex && i < nStep; i++)
2042 pindex = pindex->pprev;
2043 if (vHave.size() > 10)
2046 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2049 int GetDistanceBack()
2051 // Retrace how far back it was in the sender's branch
2054 BOOST_FOREACH(const uint256& hash, vHave)
2056 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2057 if (mi != mapBlockIndex.end())
2059 CBlockIndex* pindex = (*mi).second;
2060 if (pindex->IsInMainChain())
2070 CBlockIndex* GetBlockIndex()
2072 // Find the first block the caller has in the main chain
2073 BOOST_FOREACH(const uint256& hash, vHave)
2075 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2076 if (mi != mapBlockIndex.end())
2078 CBlockIndex* pindex = (*mi).second;
2079 if (pindex->IsInMainChain())
2083 return pindexGenesisBlock;
2086 uint256 GetBlockHash()
2088 // Find the first block the caller has in the main chain
2089 BOOST_FOREACH(const uint256& hash, vHave)
2091 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2092 if (mi != mapBlockIndex.end())
2094 CBlockIndex* pindex = (*mi).second;
2095 if (pindex->IsInMainChain())
2099 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
2104 CBlockIndex* pindex = GetBlockIndex();
2107 return pindex->nHeight;
2118 mutable CCriticalSection cs;
2119 std::map<uint256, CTransaction> mapTx;
2120 std::map<COutPoint, CInPoint> mapNextTx;
2122 bool accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs);
2123 bool addUnchecked(const uint256& hash, CTransaction &tx);
2124 bool remove(CTransaction &tx);
2126 void queryHashes(std::vector<uint256>& vtxid);
2127 void pruneSpent(const uint256& hash, CCoins &coins);
2129 unsigned long size()
2132 return mapTx.size();
2135 bool exists(uint256 hash)
2137 return (mapTx.count(hash) != 0);
2140 CTransaction& lookup(uint256 hash)
2146 extern CTxMemPool mempool;
2151 uint64 nTransactions;
2152 uint64 nPrunedTransactions;
2153 uint64 nTransactionOutputs;
2154 uint64 nSerializedSize;
2156 CCoinsStats() : nHeight(0), nTransactions(0), nPrunedTransactions(0), nTransactionOutputs(0), nSerializedSize(0) {}
2159 /** Abstract view on the open txout dataset. */
2163 // Retrieve the CCoins (unspent transaction outputs) for a given txid
2164 virtual bool GetCoins(uint256 txid, CCoins &coins);
2166 // Modify the CCoins for a given txid
2167 virtual bool SetCoins(uint256 txid, const CCoins &coins);
2169 // Just check whether we have data for a given txid.
2170 // This may (but cannot always) return true for fully spent transactions
2171 virtual bool HaveCoins(uint256 txid);
2173 // Retrieve the block index whose state this CCoinsView currently represents
2174 virtual CBlockIndex *GetBestBlock();
2176 // Modify the currently active block index
2177 virtual bool SetBestBlock(CBlockIndex *pindex);
2178 virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2179 virtual bool GetStats(CCoinsStats &stats);
2182 /** CCoinsView backed by another CCoinsView */
2183 class CCoinsViewBacked : public CCoinsView
2189 CCoinsViewBacked(CCoinsView &viewIn);
2190 bool GetCoins(uint256 txid, CCoins &coins);
2191 bool SetCoins(uint256 txid, const CCoins &coins);
2192 bool HaveCoins(uint256 txid);
2193 CBlockIndex *GetBestBlock();
2194 bool SetBestBlock(CBlockIndex *pindex);
2195 void SetBackend(CCoinsView &viewIn);
2196 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2197 bool GetStats(CCoinsStats &stats);
2200 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
2201 class CCoinsViewCache : public CCoinsViewBacked
2204 CBlockIndex *pindexTip;
2205 std::map<uint256,CCoins> cacheCoins;
2206 std::map<uint256,CCoins> cacheCoinsReadOnly;
2209 CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
2210 bool GetCoins(uint256 txid, CCoins &coins);
2211 bool GetCoinsReadOnly(uint256 txid, CCoins &coins);
2212 bool SetCoins(uint256 txid, const CCoins &coins);
2213 bool HaveCoins(uint256 txid);
2214 CCoins &GetCoins(uint256 txid);
2215 CBlockIndex *GetBestBlock();
2216 bool SetBestBlock(CBlockIndex *pindex);
2217 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2219 unsigned int GetCacheSize();
2221 std::map<uint256,CCoins>::iterator FetchCoins(uint256 txid);
2224 /** CCoinsView that brings transactions from a memorypool into view.
2225 It does not check for spendings by memory pool transactions. */
2226 class CCoinsViewMemPool : public CCoinsViewBacked
2229 CTxMemPool &mempool;
2232 CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
2233 bool GetCoins(uint256 txid, CCoins &coins);
2234 bool HaveCoins(uint256 txid);
2237 /** Global variable that points to the active CCoinsView (protected by cs_main) */
2238 extern CCoinsViewCache *pcoinsTip;
2240 /** Global variable that points to the active block tree (protected by cs_main) */
2241 extern CBlockTreeDB *pblocktree;