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;
29 static const unsigned int MAX_BLOCK_SIZE = 1000000;
30 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
31 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
32 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
33 static const unsigned int MAX_INV_SZ = 50000;
35 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
36 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
37 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
38 static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
40 static const int64 MIN_TX_FEE = CENT;
41 static const int64 MIN_RELAY_TX_FEE = CENT;
42 static const int64 MAX_MONEY = 2000000000 * COIN;
43 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
44 static const int64 MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
45 static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
47 static const unsigned int ENTROPY_SWITCH_TIME = 1362791041; // Sat, 09 Mar 2013 01:04:01 GMT
48 static const unsigned int STAKE_SWITCH_TIME = 1371686400; // Thu, 20 Jun 2013 00:00:00 GMT
49 static const unsigned int TARGETS_SWITCH_TIME = 1374278400; // Sat, 20 Jul 2013 00:00:00 GMT
50 static const unsigned int CHAINCHECKS_SWITCH_TIME = 1379635200; // Fri, 20 Sep 2013 00:00:00 GMT
51 static const unsigned int STAKECURVE_SWITCH_TIME = 1382227200; // Sun, 20 Oct 2013 00:00:00 GMT
52 static const unsigned int OUTPUT_SWITCH_TIME = 1398916800; // Thu, 01 May 2014 04:00:00 GMT
55 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
56 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
57 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
60 static const int fHaveUPnP = true;
62 static const int fHaveUPnP = false;
65 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
66 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
68 inline int64 PastDrift(int64 nTime) { return nTime - 2 * 60 * 60; } // up to 2 hours from the past
69 inline int64 FutureDrift(int64 nTime) { return nTime + 2 * 60 * 60; } // up to 2 hours from the future
71 extern libzerocoin::Params* ZCParams;
72 extern CScript COINBASE_FLAGS;
73 extern CCriticalSection cs_main;
74 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
75 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
76 extern CBlockIndex* pindexGenesisBlock;
77 extern unsigned int nStakeMinAge;
78 extern unsigned int nNodeLifespan;
79 extern int nCoinbaseMaturity;
80 extern int nBestHeight;
81 extern uint256 nBestChainTrust;
82 extern uint256 nBestInvalidTrust;
83 extern uint256 hashBestChain;
84 extern CBlockIndex* pindexBest;
85 extern unsigned int nTransactionsUpdated;
86 extern uint64 nLastBlockTx;
87 extern uint64 nLastBlockSize;
88 extern int64 nLastCoinStakeSearchInterval;
89 extern const std::string strMessageMagic;
90 extern int64 nTimeBestReceived;
91 extern CCriticalSection cs_setpwalletRegistered;
92 extern std::set<CWallet*> setpwalletRegistered;
93 extern unsigned char pchMessageStart[4];
94 extern std::map<uint256, CBlock*> mapOrphanBlocks;
97 extern int64 nTransactionFee;
98 extern int64 nMinimumInputValue;
99 extern bool fUseFastIndex;
100 extern unsigned int nDerivationMethodIndex;
102 // Minimum disk space required - used in CheckDiskSpace()
103 static const uint64 nMinDiskSpace = 52428800;
113 void RegisterWallet(CWallet* pwalletIn);
114 void UnregisterWallet(CWallet* pwalletIn);
115 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
116 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
117 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
118 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
119 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
120 bool LoadBlockIndex(bool fAllowNew=true);
121 void PrintBlockTree();
122 CBlockIndex* FindBlockByHeight(int nHeight);
123 bool ProcessMessages(CNode* pfrom);
124 bool SendMessages(CNode* pto, bool fSendTrickle);
125 bool LoadExternalBlockFile(FILE* fileIn);
127 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
128 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
129 int64 GetProofOfWorkReward(unsigned int nBits);
130 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly=false);
131 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
132 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
133 int GetNumBlocksOfPeers();
134 bool IsInitialBlockDownload();
135 std::string GetWarnings(std::string strFor);
136 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow);
137 uint256 WantedByOrphan(const CBlock* pblockOrphan);
138 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
139 void StakeMiner(CWallet *pwallet);
140 void ResendWalletTransactions();
142 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
151 READWRITE(VARINT(nFile));
152 READWRITE(VARINT(nPos));
155 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
156 return (a.nFile == b.nFile && a.nPos == b.nPos);
159 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
163 void SetNull() { nFile = -1; nPos = 0; }
164 bool IsNull() const { return (nFile == -1); }
168 /** An inpoint - a combination of a transaction and an index n into its vin */
175 CInPoint() { SetNull(); }
176 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
177 void SetNull() { ptx = NULL; n = (unsigned int) -1; }
178 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
183 /** An outpoint - a combination of a transaction hash and an index n into its vout */
190 COutPoint() { SetNull(); }
191 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
192 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
193 void SetNull() { hash = 0; n = (unsigned int) -1; }
194 bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
196 friend bool operator<(const COutPoint& a, const COutPoint& b)
198 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
201 friend bool operator==(const COutPoint& a, const COutPoint& b)
203 return (a.hash == b.hash && a.n == b.n);
206 friend bool operator!=(const COutPoint& a, const COutPoint& b)
211 std::string ToString() const
213 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
218 printf("%s\n", ToString().c_str());
225 /** An input of a transaction. It contains the location of the previous
226 * transaction's output that it claims and a signature that matches the
227 * output's public key.
234 unsigned int nSequence;
238 nSequence = std::numeric_limits<unsigned int>::max();
241 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
244 scriptSig = scriptSigIn;
245 nSequence = nSequenceIn;
248 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
250 prevout = COutPoint(hashPrevTx, nOut);
251 scriptSig = scriptSigIn;
252 nSequence = nSequenceIn;
258 READWRITE(scriptSig);
259 READWRITE(nSequence);
264 return (nSequence == std::numeric_limits<unsigned int>::max());
267 friend bool operator==(const CTxIn& a, const CTxIn& b)
269 return (a.prevout == b.prevout &&
270 a.scriptSig == b.scriptSig &&
271 a.nSequence == b.nSequence);
274 friend bool operator!=(const CTxIn& a, const CTxIn& b)
279 std::string ToStringShort() const
281 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
284 std::string ToString() const
288 str += prevout.ToString();
289 if (prevout.IsNull())
290 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
292 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
293 if (nSequence != std::numeric_limits<unsigned int>::max())
294 str += strprintf(", nSequence=%u", nSequence);
301 printf("%s\n", ToString().c_str());
308 /** An output of a transaction. It contains the public key that the next input
309 * must be able to sign with to claim it.
315 CScript scriptPubKey;
322 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
325 scriptPubKey = scriptPubKeyIn;
331 READWRITE(scriptPubKey);
337 scriptPubKey.clear();
342 return (nValue == -1);
348 scriptPubKey.clear();
353 return (nValue == 0 && scriptPubKey.empty());
356 uint256 GetHash() const
358 return SerializeHash(*this);
361 friend bool operator==(const CTxOut& a, const CTxOut& b)
363 return (a.nValue == b.nValue &&
364 a.scriptPubKey == b.scriptPubKey);
367 friend bool operator!=(const CTxOut& a, const CTxOut& b)
372 std::string ToStringShort() const
374 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0, 10).c_str());
377 std::string ToString() const
379 if (IsEmpty()) return "CTxOut(empty)";
380 if (scriptPubKey.size() < 6)
381 return "CTxOut(error)";
382 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
387 printf("%s\n", ToString().c_str());
401 // Modes for script/signature checking
404 CS_NEVER, // never validate scripts
405 CS_AFTER_CHECKPOINT, // validate scripts after the last checkpoint
406 CS_ALWAYS // always validate scripts
409 /** The basic transaction that is broadcasted on the network and contained in
410 * blocks. A transaction can contain multiple inputs and outputs.
415 static const int CURRENT_VERSION=1;
418 std::vector<CTxIn> vin;
419 std::vector<CTxOut> vout;
420 unsigned int nLockTime;
422 // Denial-of-service detection:
424 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
433 READWRITE(this->nVersion);
434 nVersion = this->nVersion;
438 READWRITE(nLockTime);
443 nVersion = CTransaction::CURRENT_VERSION;
444 nTime = GetAdjustedTime();
448 nDoS = 0; // Denial-of-service prevention
453 return (vin.empty() && vout.empty());
456 uint256 GetHash() const
458 return SerializeHash(*this);
461 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
463 // Time based nLockTime implemented in 0.1.6
466 if (nBlockHeight == 0)
467 nBlockHeight = nBestHeight;
469 nBlockTime = GetAdjustedTime();
470 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
472 BOOST_FOREACH(const CTxIn& txin, vin)
478 bool IsNewerThan(const CTransaction& old) const
480 if (vin.size() != old.vin.size())
482 for (unsigned int i = 0; i < vin.size(); i++)
483 if (vin[i].prevout != old.vin[i].prevout)
487 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
488 for (unsigned int i = 0; i < vin.size(); i++)
490 if (vin[i].nSequence != old.vin[i].nSequence)
492 if (vin[i].nSequence <= nLowest)
495 nLowest = vin[i].nSequence;
497 if (old.vin[i].nSequence < nLowest)
500 nLowest = old.vin[i].nSequence;
507 bool IsCoinBase() const
509 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
512 bool IsCoinStake() const
514 // ppcoin: the coin stake transaction is marked with the first output empty
515 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
518 /** Check for standard transaction types
519 @return True if all outputs (scriptPubKeys) use only standard transaction forms
521 bool IsStandard() const;
523 /** Check for standard transaction types
524 @param[in] mapInputs Map of previous transactions that have outputs we're spending
525 @return True if all inputs (scriptSigs) use only standard transaction forms
526 @see CTransaction::FetchInputs
528 bool AreInputsStandard(CCoinsView& mapInputs) const;
530 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
531 @return number of sigops this transaction's outputs will produce when spent
532 @see CTransaction::FetchInputs
534 unsigned int GetLegacySigOpCount() const;
536 /** Count ECDSA signature operations in pay-to-script-hash inputs.
538 @param[in] mapInputs Map of previous transactions that have outputs we're spending
539 @return maximum number of sigops required to validate this transaction's inputs
540 @see CTransaction::FetchInputs
542 unsigned int GetP2SHSigOpCount(CCoinsView& mapInputs) const;
544 /** Amount of bitcoins spent by this transaction.
545 @return sum of all outputs (note: does not include fees)
547 int64 GetValueOut() const
550 BOOST_FOREACH(const CTxOut& txout, vout)
552 nValueOut += txout.nValue;
553 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
554 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
559 /** Amount of bitcoins coming in to this transaction
560 Note that lightweight clients may not know anything besides the hash of previous transactions,
561 so may not be able to calculate this.
563 @param[in] mapInputs Map of previous transactions that have outputs we're spending
564 @return Sum of value of all inputs (scriptSigs)
565 @see CTransaction::FetchInputs
567 int64 GetValueIn(CCoinsView& mapInputs) const;
569 static bool AllowFree(double dPriority)
571 // Large (in bytes) low-priority (new, small-coin) transactions
573 return dPriority > COIN * 144 / 250;
576 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
578 friend bool operator==(const CTransaction& a, const CTransaction& b)
580 return (a.nVersion == b.nVersion &&
581 a.nTime == b.nTime &&
584 a.nLockTime == b.nLockTime);
587 friend bool operator!=(const CTransaction& a, const CTransaction& b)
592 std::string ToStringShort() const
595 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
599 std::string ToString() const
602 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
603 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
604 GetHash().ToString().substr(0,10).c_str(),
610 for (unsigned int i = 0; i < vin.size(); i++)
611 str += " " + vin[i].ToString() + "\n";
612 for (unsigned int i = 0; i < vout.size(); i++)
613 str += " " + vout[i].ToString() + "\n";
619 printf("%s", ToString().c_str());
623 // Do all possible client-mode checks
624 bool ClientCheckInputs() const;
626 // Check whether all prevouts of this transaction are present in the UTXO set represented by view
627 bool HaveInputs(CCoinsView &view) const;
629 // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
630 // This does not modify the UTXO set
631 bool CheckInputs(CCoinsView &view, enum CheckSig_mode csmode, bool fStrictPayToScriptHash=true, bool fStrictEncodings=true, CBlock *pblock=NULL) const;
633 // Apply the effects of this transaction on the UTXO set represented by view
634 bool UpdateCoins(CCoinsView &view, CTxUndo &txundo, int nHeight, unsigned int nBlockTime) const;
636 // Context-independent validity checks
637 bool CheckTransaction() const;
639 // Try to accept this transaction into the memory pool
640 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
641 bool GetCoinAge(uint64& nCoinAge) const; // Get transaction coin age
643 static CTxOut GetOutputFor(const CTxIn& input, CCoinsView& mapInputs);
647 /** wrapper for CTxOut that provides a more compact serialization */
648 class CTxOutCompressor
654 static uint64 CompressAmount(uint64 nAmount);
655 static uint64 DecompressAmount(uint64 nAmount);
657 CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
659 IMPLEMENT_SERIALIZE(({
661 uint64 nVal = CompressAmount(txout.nValue);
662 READWRITE(VARINT(nVal));
665 READWRITE(VARINT(nVal));
666 txout.nValue = DecompressAmount(nVal);
668 CScriptCompressor cscript(REF(txout.scriptPubKey));
673 /** Undo information for a CTxIn
675 * Contains the prevout's CTxOut being spent, and if this was the
676 * last output of the affected transaction, its metadata as well
677 * (coinbase or not, height, transaction version)
682 CTxOut txout; // the txout data before being spent
683 bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
684 bool fCoinStake; // if the outpoint was the last unspent: whether it belonged to a coinstake
685 unsigned int nHeight; // if the outpoint was the last unspent: its height
686 int nVersion; // if the outpoint was the last unspent: its version
687 unsigned int nTime; // if the outpoint was the last unspent: its timestamp
688 unsigned int nBlockTime; // if the outpoint was the last unspent: its block timestamp
690 CTxInUndo() : txout(), fCoinBase(false), fCoinStake(false), nHeight(0), nVersion(0), nTime(0), nBlockTime(0) {}
691 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) { }
693 unsigned int GetSerializeSize(int nType, int nVersion) const {
694 return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
695 ::GetSerializeSize(VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion) +
696 ::GetSerializeSize(VARINT(nBlockTime), nType, nVersion) +
697 (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
698 ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
701 template<typename Stream>
702 void Serialize(Stream &s, int nType, int nVersion) const {
703 ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
704 ::Serialize(s, VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion);
705 ::Serialize(s, VARINT(nBlockTime), nType, nVersion);
707 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
708 ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
711 template<typename Stream>
712 void Unserialize(Stream &s, int nType, int nVersion) {
713 unsigned int nCodeHeight = 0, nCodeTime = 0;
714 ::Unserialize(s, VARINT(nCodeHeight), nType, nVersion);
715 nHeight = nCodeHeight / 2;
716 fCoinBase = nCodeHeight & 1;
717 ::Unserialize(s, VARINT(nCodeTime), nType, nVersion);
718 nTime = nCodeTime / 2;
719 fCoinStake = nCodeTime & 1;
720 ::Unserialize(s, VARINT(nBlockTime), nType, nVersion);
722 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
723 ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
727 /** Undo information for a CTransaction */
731 // undo information for all txins
732 std::vector<CTxInUndo> vprevout;
739 /** Undo information for a CBlock */
743 std::vector<CTxUndo> vtxundo; // for all but the coinbase
749 bool WriteToDisk(CDiskBlockPos &pos)
751 // Open history file to append
752 CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
754 return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
756 // Write index header
757 unsigned int nSize = fileout.GetSerializeSize(*this);
758 fileout << FLATDATA(pchMessageStart) << nSize;
761 long fileOutPos = ftell(fileout);
763 return error("CBlockUndo::WriteToDisk() : ftell failed");
764 pos.nPos = (unsigned int)fileOutPos;
767 // Flush stdio buffers and commit to disk before returning
769 if (!IsInitialBlockDownload())
777 /** pruned version of CTransaction: only retains metadata and unspent transaction outputs
782 * - unspentness bitvector, for vout[2] and further; least significant byte first
783 * - the non-spent CTxOuts (via CTxOutCompressor)
785 * - VARINT(nTime + is_coinstake)
786 * - VARINT(nBlockTime)
788 * The nCode value consists of:
789 * - bit 1: IsCoinBase()
790 * - bit 2: vout[0] is not spent
791 * - bit 4: vout[1] is not spent
792 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
793 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
794 * least one non-spent output).
796 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e40f1d75240f1d752
797 * <><><--------------------------------------------><----><------><------>
799 * version code vout[1] height timestamp block timestamp
802 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
803 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
804 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
805 * * 8358: compact amount representation for 60000000000 (600 BTC)
806 * * 00: special txout type pay-to-pubkey-hash
807 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
809 * - time = 1389883712
811 * - block time = 1389883712
814 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b40f1d75240f1d752
815 * <><><--><--------------------------------------------------><----------------------------------------------><----><------><------>
817 * version code unspentness vout[4] vout[16] height timestamp block timestamp
820 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
821 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
822 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
823 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
824 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
825 * * 00: special txout type pay-to-pubkey-hash
826 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
827 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
828 * * bbd123: compact amount representation for 110397 (0.001 BTC)
829 * * 00: special txout type pay-to-pubkey-hash
830 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
832 * - time = 1389883712
834 * - block time = 1389883712
839 // whether transaction is a coinbase
842 // whether transaction is a coinstake
845 // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
846 std::vector<CTxOut> vout;
848 // at which height this transaction was included in the active blockchain
851 // version of the CTransaction; accesses to this value should probably check for nHeight as well,
852 // as new tx version will probably only be introduced at certain heights
855 // transaction timestamp + coinstake flag
859 unsigned int nBlockTime;
861 // construct a CCoins from a CTransaction, at a given height/timestamp
862 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) { }
865 CCoins() : fCoinBase(false), fCoinStake(false), vout(0), nHeight(0), nVersion(0), nTime(0), nBlockTime(0) { }
867 // remove spent outputs at the end of vout
869 while (vout.size() > 0 && vout.back().IsNull())
874 friend bool operator==(const CCoins &a, const CCoins &b) {
875 return a.fCoinBase == b.fCoinBase &&
876 a.fCoinStake == b.fCoinStake &&
877 a.nHeight == b.nHeight &&
878 a.nVersion == b.nVersion &&
879 a.nTime == b.nTime &&
880 a.nBlockTime == b.nBlockTime &&
883 friend bool operator!=(const CCoins &a, const CCoins &b) {
887 // calculate number of bytes for the bitmask, and its number of non-zero bytes
888 // each bit in the bitmask represents the availability of one output, but the
889 // availabilities of the first two outputs are encoded separately
890 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
891 unsigned int nLastUsedByte = 0;
892 for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
894 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
895 if (!vout[2+b*8+i].IsNull()) {
901 nLastUsedByte = b + 1;
905 nBytes += nLastUsedByte;
908 bool IsCoinBase() const {
912 bool IsCoinStake() const {
916 unsigned int GetSerializeSize(int nType, int nVersion) const {
917 unsigned int nSize = 0;
918 unsigned int nMaskSize = 0, nMaskCode = 0;
919 CalcMaskSize(nMaskSize, nMaskCode);
920 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
921 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
922 assert(fFirst || fSecond || nMaskCode);
923 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fCoinStake ? 1 : 0) + (fSecond ? 4 : 0);
925 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
926 // size of header code
927 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
931 for (unsigned int i = 0; i < vout.size(); i++)
932 if (!vout[i].IsNull())
933 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
935 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
936 // timestamp and coinstake flag
937 nSize += ::GetSerializeSize(VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion);
939 nSize += ::GetSerializeSize(VARINT(nBlockTime), nType, nVersion);
943 template<typename Stream>
944 void Serialize(Stream &s, int nType, int nVersion) const {
945 unsigned int nMaskSize = 0, nMaskCode = 0;
946 CalcMaskSize(nMaskSize, nMaskCode);
947 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
948 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
949 assert(fFirst || fSecond || nMaskCode);
950 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
952 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
954 ::Serialize(s, VARINT(nCode), nType, nVersion);
956 for (unsigned int b = 0; b<nMaskSize; b++) {
957 unsigned char chAvail = 0;
958 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
959 if (!vout[2+b*8+i].IsNull())
961 ::Serialize(s, chAvail, nType, nVersion);
964 for (unsigned int i = 0; i < vout.size(); i++) {
965 if (!vout[i].IsNull())
966 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
969 ::Serialize(s, VARINT(nHeight), nType, nVersion);
970 // transaction timestamp and coinstake flag
971 ::Serialize(s, VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion);
973 ::Serialize(s, VARINT(nBlockTime), nType, nVersion);
976 template<typename Stream>
977 void Unserialize(Stream &s, int nType, int nVersion) {
978 unsigned int nCode = 0, nCodeTime = 0;
980 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
982 ::Unserialize(s, VARINT(nCode), nType, nVersion);
983 fCoinBase = nCode & 1;
984 std::vector<bool> vAvail(2, false);
985 vAvail[0] = nCode & 2;
986 vAvail[1] = nCode & 4;
987 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
989 while (nMaskCode > 0) {
990 unsigned char chAvail = 0;
991 ::Unserialize(s, chAvail, nType, nVersion);
992 for (unsigned int p = 0; p < 8; p++) {
993 bool f = (chAvail & (1 << p)) != 0;
1000 vout.assign(vAvail.size(), CTxOut());
1001 for (unsigned int i = 0; i < vAvail.size(); i++) {
1003 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
1006 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
1007 // transaction timestamp
1008 ::Unserialize(s, VARINT(nCodeTime), nType, nVersion);
1009 nTime = nCodeTime / 2;
1010 fCoinStake = nCodeTime & 1;
1012 ::Unserialize(s, VARINT(nBlockTime), nType, nVersion);
1016 // mark an outpoint spent, and construct undo information
1017 bool Spend(const COutPoint &out, CTxInUndo &undo) {
1018 if (out.n >= vout.size())
1020 if (vout[out.n].IsNull())
1022 undo = CTxInUndo(vout[out.n]);
1023 vout[out.n].SetNull();
1025 if (vout.size() == 0) {
1026 undo.nHeight = nHeight;
1028 undo.nBlockTime = nBlockTime;
1029 undo.fCoinBase = fCoinBase;
1030 undo.fCoinStake = fCoinStake;
1031 undo.nVersion = this->nVersion;
1036 // mark a vout spent
1037 bool Spend(int nPos) {
1039 COutPoint out(0, nPos);
1040 return Spend(out, undo);
1043 // check whether a particular output is still available
1044 bool IsAvailable(unsigned int nPos) const {
1045 return (nPos < vout.size() && !vout[nPos].IsNull());
1048 // check whether the entire CCoins is spent
1049 // note that only !IsPruned() CCoins can be serialized
1050 bool IsPruned() const {
1051 BOOST_FOREACH(const CTxOut &out, vout)
1061 /** A transaction with a merkle branch linking it to the block chain. */
1062 class CMerkleTx : public CTransaction
1066 std::vector<uint256> vMerkleBranch;
1070 mutable bool fMerkleVerified;
1078 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
1087 fMerkleVerified = false;
1093 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
1094 nVersion = this->nVersion;
1095 READWRITE(hashBlock);
1096 READWRITE(vMerkleBranch);
1101 int SetMerkleBranch(const CBlock* pblock=NULL);
1102 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
1103 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
1104 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
1105 int GetBlocksToMaturity() const;
1106 bool AcceptToMemoryPool(bool fCheckInputs=true);
1111 /** Nodes collect new transactions into a block, hash them into a hash tree,
1112 * and scan through nonce values to make the block's hash satisfy proof-of-work
1113 * requirements. When they solve the proof-of-work, they broadcast the block
1114 * to everyone and the block is added to the block chain. The first transaction
1115 * in the block is a special one that creates a new coin owned by the creator
1122 static const int CURRENT_VERSION=6;
1124 uint256 hashPrevBlock;
1125 uint256 hashMerkleRoot;
1128 unsigned int nNonce;
1131 std::vector<CTransaction> vtx;
1133 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
1134 std::vector<unsigned char> vchBlockSig;
1137 mutable std::vector<uint256> vMerkleTree;
1139 // Denial-of-service detection:
1141 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
1150 READWRITE(this->nVersion);
1151 nVersion = this->nVersion;
1152 READWRITE(hashPrevBlock);
1153 READWRITE(hashMerkleRoot);
1158 // ConnectBlock depends on vtx following header to generate CDiskTxPos
1159 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1162 READWRITE(vchBlockSig);
1166 const_cast<CBlock*>(this)->vtx.clear();
1167 const_cast<CBlock*>(this)->vchBlockSig.clear();
1173 nVersion = CBlock::CURRENT_VERSION;
1180 vchBlockSig.clear();
1181 vMerkleTree.clear();
1187 return (nBits == 0);
1190 uint256 GetHash() const
1192 return scrypt_blockhash(CVOIDBEGIN(nVersion));
1195 int64 GetBlockTime() const
1197 return (int64)nTime;
1200 void UpdateTime(const CBlockIndex* pindexPrev);
1202 // ppcoin: entropy bit for stake modifier if chosen by modifier
1203 unsigned int GetStakeEntropyBit(unsigned int nTime) const
1205 // Protocol switch to support p2pool at novacoin block #9689
1206 if (nTime >= ENTROPY_SWITCH_TIME || fTestNet)
1208 // Take last bit of block hash as entropy bit
1209 unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
1210 if (fDebug && GetBoolArg("-printstakemodifier"))
1211 printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
1214 // Before novacoin block #9689 - old protocol
1215 uint160 hashSig = Hash160(vchBlockSig);
1216 if (fDebug && GetBoolArg("-printstakemodifier"))
1217 printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
1218 hashSig >>= 159; // take the first bit of the hash
1219 if (fDebug && GetBoolArg("-printstakemodifier"))
1220 printf(" entropybit=%"PRI64d"\n", hashSig.Get64());
1221 return hashSig.Get64();
1224 // ppcoin: two types of block: proof-of-work or proof-of-stake
1225 bool IsProofOfStake() const
1227 return (vtx.size() > 1 && vtx[1].IsCoinStake());
1230 bool IsProofOfWork() const
1232 return !IsProofOfStake();
1235 std::pair<COutPoint, unsigned int> GetProofOfStake() const
1237 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
1240 // ppcoin: get max transaction timestamp
1241 int64 GetMaxTransactionTime() const
1243 int64 maxTransactionTime = 0;
1244 BOOST_FOREACH(const CTransaction& tx, vtx)
1245 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
1246 return maxTransactionTime;
1249 uint256 BuildMerkleTree() const
1251 vMerkleTree.clear();
1252 BOOST_FOREACH(const CTransaction& tx, vtx)
1253 vMerkleTree.push_back(tx.GetHash());
1255 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1257 for (int i = 0; i < nSize; i += 2)
1259 int i2 = std::min(i+1, nSize-1);
1260 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1261 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1265 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1268 std::vector<uint256> GetMerkleBranch(int nIndex) const
1270 if (vMerkleTree.empty())
1272 std::vector<uint256> vMerkleBranch;
1274 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1276 int i = std::min(nIndex^1, nSize-1);
1277 vMerkleBranch.push_back(vMerkleTree[j+i]);
1281 return vMerkleBranch;
1284 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1288 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1291 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1293 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1299 bool WriteToDisk(CDiskBlockPos &pos)
1301 // Open history file to append
1302 CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1304 return error("CBlock::WriteToDisk() : OpenBlockFile failed");
1306 // Write index header
1307 unsigned int nSize = fileout.GetSerializeSize(*this);
1308 fileout << FLATDATA(pchMessageStart) << nSize;
1311 long fileOutPos = ftell(fileout);
1313 return error("CBlock::WriteToDisk() : ftell failed");
1314 pos.nPos = (unsigned int)fileOutPos;
1317 // Flush stdio buffers and commit to disk before returning
1319 if (!IsInitialBlockDownload())
1320 FileCommit(fileout);
1325 bool ReadFromDisk(const CDiskBlockPos &pos, bool fReadTransactions = true)
1329 // Open history file to read
1330 CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1332 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1333 if (!fReadTransactions)
1334 filein.nType |= SER_BLOCKHEADERONLY;
1340 catch (std::exception &e) {
1341 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1345 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1346 return error("CBlock::ReadFromDisk() : errors in block header");
1353 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
1354 GetHash().ToString().c_str(),
1356 hashPrevBlock.ToString().c_str(),
1357 hashMerkleRoot.ToString().c_str(),
1358 nTime, nBits, nNonce,
1360 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1361 for (unsigned int i = 0; i < vtx.size(); i++)
1366 printf(" vMerkleTree: ");
1367 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1368 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1372 // Undo the effects of this block (with given index) on the UTXO set represented by coins
1373 bool DisconnectBlock(CBlockIndex *pindex, CCoinsView &coins);
1375 // Apply the effects of this block (with given index) on the UTXO set represented by coins
1376 bool ConnectBlock(CBlockIndex *pindex, CCoinsView &coins, bool fJustCheck=false);
1378 // Read a block from disk
1379 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1381 // Make this block (with given index) the new tip of the active block chain
1382 bool SetBestChain(CBlockIndex* pindexNew);
1384 // Add this block to the block index, and if necessary, switch the active block chain to this
1385 bool AddToBlockIndex(const CDiskBlockPos &pos);
1387 // Context-independent validity checks
1388 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=false) const;
1390 // Store block on disk
1393 // Get total coinage consumed
1394 bool GetCoinAge(uint64& nCoinAge) const;
1396 // Generate proof-of-stake block signature
1397 bool SignBlock(CWallet& keystore);
1399 // Validate header signature
1400 bool CheckBlockSignature(bool fProofOfStake) const;
1404 class CBlockFileInfo
1407 unsigned int nBlocks; // number of blocks stored in file
1408 unsigned int nSize; // number of used bytes of block file
1409 unsigned int nUndoSize; // number of used bytes in the undo file
1410 unsigned int nHeightFirst; // lowest height of block in file
1411 unsigned int nHeightLast; // highest height of block in file
1412 uint64 nTimeFirst; // earliest time of block in file
1413 uint64 nTimeLast; // latest time of block in file
1415 IMPLEMENT_SERIALIZE(
1416 READWRITE(VARINT(nBlocks));
1417 READWRITE(VARINT(nSize));
1418 READWRITE(VARINT(nUndoSize));
1419 READWRITE(VARINT(nHeightFirst));
1420 READWRITE(VARINT(nHeightLast));
1421 READWRITE(VARINT(nTimeFirst));
1422 READWRITE(VARINT(nTimeLast));
1439 std::string ToString() const {
1440 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());
1443 // update statistics (does not update nSize)
1444 void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
1445 if (nBlocks==0 || nHeightFirst > nHeightIn)
1446 nHeightFirst = nHeightIn;
1447 if (nBlocks==0 || nTimeFirst > nTimeIn)
1448 nTimeFirst = nTimeIn;
1450 if (nHeightIn > nHeightFirst)
1451 nHeightLast = nHeightIn;
1452 if (nTimeIn > nTimeLast)
1453 nTimeLast = nTimeIn;
1458 extern CCriticalSection cs_LastBlockFile;
1459 extern CBlockFileInfo infoLastBlockFile;
1460 extern int nLastBlockFile;
1462 /** The block chain is a tree shaped structure starting with the
1463 * genesis block at the root, with each block potentially having multiple
1464 * candidates to be the next block. pprev and pnext link a path through the
1465 * main/longest chain. A blockindex may have multiple pprev pointing back
1466 * to it, but pnext will only point forward to the longest branch, or will
1467 * be null if the block is not part of the longest chain.
1472 const uint256* phashBlock;
1477 unsigned int nUndoPos;
1478 uint256 nChainTrust; // trust score of block chain
1483 unsigned int nFlags;
1486 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1487 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
1488 BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
1491 uint64 nStakeModifier; // hash modifier for proof-of-stake
1492 unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
1494 // proof-of-stake specific fields
1495 COutPoint prevoutStake;
1496 unsigned int nStakeTime;
1497 uint256 hashProofOfStake;
1501 uint256 hashMerkleRoot;
1504 unsigned int nNonce;
1520 nStakeModifierChecksum = 0;
1521 hashProofOfStake = 0;
1522 prevoutStake.SetNull();
1532 CBlockIndex(CBlock& block)
1545 nStakeModifierChecksum = 0;
1546 hashProofOfStake = 0;
1547 if (block.IsProofOfStake())
1550 prevoutStake = block.vtx[1].vin[0].prevout;
1551 nStakeTime = block.vtx[1].nTime;
1555 prevoutStake.SetNull();
1559 nVersion = block.nVersion;
1560 hashMerkleRoot = block.hashMerkleRoot;
1561 nTime = block.nTime;
1562 nBits = block.nBits;
1563 nNonce = block.nNonce;
1566 CDiskBlockPos GetBlockPos() const {
1570 CDiskBlockPos GetUndoPos() const {
1571 CDiskBlockPos ret = pos;
1575 ret.nPos = nUndoPos - 1;
1579 CBlock GetBlockHeader() const
1582 block.nVersion = nVersion;
1584 block.hashPrevBlock = pprev->GetBlockHash();
1585 block.hashMerkleRoot = hashMerkleRoot;
1586 block.nTime = nTime;
1587 block.nBits = nBits;
1588 block.nNonce = nNonce;
1592 uint256 GetBlockHash() const
1597 int64 GetBlockTime() const
1599 return (int64)nTime;
1602 uint256 GetBlockTrust() const;
1604 bool IsInMainChain() const
1606 return (pnext || this == pindexBest);
1609 bool CheckIndex() const
1614 enum { nMedianTimeSpan=11 };
1616 int64 GetMedianTimePast() const
1618 int64 pmedian[nMedianTimeSpan];
1619 int64* pbegin = &pmedian[nMedianTimeSpan];
1620 int64* pend = &pmedian[nMedianTimeSpan];
1622 const CBlockIndex* pindex = this;
1623 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1624 *(--pbegin) = pindex->GetBlockTime();
1626 std::sort(pbegin, pend);
1627 return pbegin[(pend - pbegin)/2];
1630 int64 GetMedianTime() const
1632 const CBlockIndex* pindex = this;
1633 for (int i = 0; i < nMedianTimeSpan/2; i++)
1636 return GetBlockTime();
1637 pindex = pindex->pnext;
1639 return pindex->GetMedianTimePast();
1643 * Returns true if there are nRequired or more blocks of minVersion or above
1644 * in the last nToCheck blocks, starting at pstart and going backwards.
1646 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1647 unsigned int nRequired, unsigned int nToCheck);
1649 bool IsProofOfWork() const
1651 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1654 bool IsProofOfStake() const
1656 return (nFlags & BLOCK_PROOF_OF_STAKE);
1659 void SetProofOfStake()
1661 nFlags |= BLOCK_PROOF_OF_STAKE;
1664 unsigned int GetStakeEntropyBit() const
1666 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1669 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1671 if (nEntropyBit > 1)
1673 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1677 bool GeneratedStakeModifier() const
1679 return (nFlags & BLOCK_STAKE_MODIFIER);
1682 void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1684 nStakeModifier = nModifier;
1685 if (fGeneratedStakeModifier)
1686 nFlags |= BLOCK_STAKE_MODIFIER;
1689 std::string ToString() const
1691 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)",
1692 pprev, pnext, nHeight,
1693 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1694 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1695 nStakeModifier, nStakeModifierChecksum,
1696 hashProofOfStake.ToString().c_str(),
1697 prevoutStake.ToString().c_str(), nStakeTime,
1698 hashMerkleRoot.ToString().c_str(),
1699 GetBlockHash().ToString().c_str());
1705 printf("%s\n", ToString().c_str());
1709 /** Used to marshal pointers into hashes for db storage. */
1710 class CDiskBlockIndex : public CBlockIndex
1722 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
1723 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1728 if (!(nType & SER_GETHASH))
1729 READWRITE(nVersion);
1733 READWRITE(nUndoPos);
1735 READWRITE(nMoneySupply);
1737 READWRITE(nStakeModifier);
1738 if (IsProofOfStake())
1740 READWRITE(prevoutStake);
1741 READWRITE(nStakeTime);
1742 READWRITE(hashProofOfStake);
1746 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1747 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1748 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1750 READWRITE(blockHash);
1753 READWRITE(this->nVersion);
1754 READWRITE(hashPrev);
1755 READWRITE(hashMerkleRoot);
1761 uint256 GetBlockHash() const
1763 if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
1767 block.nVersion = nVersion;
1768 block.hashPrevBlock = hashPrev;
1769 block.hashMerkleRoot = hashMerkleRoot;
1770 block.nTime = nTime;
1771 block.nBits = nBits;
1772 block.nNonce = nNonce;
1774 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1780 std::string ToString() const
1782 std::string str = "CDiskBlockIndex(";
1783 str += CBlockIndex::ToString();
1784 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
1785 GetBlockHash().ToString().c_str(),
1786 hashPrev.ToString().substr(0,20).c_str());
1792 printf("%s\n", ToString().c_str());
1797 /** Describes a place in the block chain to another node such that if the
1798 * other node doesn't have the same branch, it can find a recent common trunk.
1799 * The further back it is, the further before the fork it may be.
1804 std::vector<uint256> vHave;
1811 explicit CBlockLocator(const CBlockIndex* pindex)
1816 explicit CBlockLocator(uint256 hashBlock)
1818 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1819 if (mi != mapBlockIndex.end())
1823 CBlockLocator(const std::vector<uint256>& vHaveIn)
1830 if (!(nType & SER_GETHASH))
1831 READWRITE(nVersion);
1842 return vHave.empty();
1845 void Set(const CBlockIndex* pindex)
1851 vHave.push_back(pindex->GetBlockHash());
1853 // Exponentially larger steps back
1854 for (int i = 0; pindex && i < nStep; i++)
1855 pindex = pindex->pprev;
1856 if (vHave.size() > 10)
1859 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1862 int GetDistanceBack()
1864 // Retrace how far back it was in the sender's branch
1867 BOOST_FOREACH(const uint256& hash, vHave)
1869 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1870 if (mi != mapBlockIndex.end())
1872 CBlockIndex* pindex = (*mi).second;
1873 if (pindex->IsInMainChain())
1883 CBlockIndex* GetBlockIndex()
1885 // Find the first block the caller has in the main chain
1886 BOOST_FOREACH(const uint256& hash, vHave)
1888 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1889 if (mi != mapBlockIndex.end())
1891 CBlockIndex* pindex = (*mi).second;
1892 if (pindex->IsInMainChain())
1896 return pindexGenesisBlock;
1899 uint256 GetBlockHash()
1901 // Find the first block the caller has in the main chain
1902 BOOST_FOREACH(const uint256& hash, vHave)
1904 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1905 if (mi != mapBlockIndex.end())
1907 CBlockIndex* pindex = (*mi).second;
1908 if (pindex->IsInMainChain())
1912 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1917 CBlockIndex* pindex = GetBlockIndex();
1920 return pindex->nHeight;
1931 mutable CCriticalSection cs;
1932 std::map<uint256, CTransaction> mapTx;
1933 std::map<COutPoint, CInPoint> mapNextTx;
1935 bool accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs);
1936 bool addUnchecked(const uint256& hash, CTransaction &tx);
1937 bool remove(CTransaction &tx);
1939 void queryHashes(std::vector<uint256>& vtxid);
1940 void pruneSpent(const uint256& hash, CCoins &coins);
1942 unsigned long size()
1945 return mapTx.size();
1948 bool exists(uint256 hash)
1950 return (mapTx.count(hash) != 0);
1953 CTransaction& lookup(uint256 hash)
1959 extern CTxMemPool mempool;
1961 /** Abstract view on the open txout dataset. */
1965 // Retrieve the CCoins (unspent transaction outputs) for a given txid
1966 virtual bool GetCoins(uint256 txid, CCoins &coins);
1968 // Modify the CCoins for a given txid
1969 virtual bool SetCoins(uint256 txid, const CCoins &coins);
1971 // Just check whether we have data for a given txid.
1972 // This may (but cannot always) return true for fully spent transactions
1973 virtual bool HaveCoins(uint256 txid);
1975 // Retrieve the block index whose state this CCoinsView currently represents
1976 virtual CBlockIndex *GetBestBlock();
1978 // Modify the currently active block index
1979 virtual bool SetBestBlock(CBlockIndex *pindex);
1980 virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1983 /** CCoinsView backed by another CCoinsView */
1984 class CCoinsViewBacked : public CCoinsView
1990 CCoinsViewBacked(CCoinsView &viewIn);
1991 bool GetCoins(uint256 txid, CCoins &coins);
1992 bool SetCoins(uint256 txid, const CCoins &coins);
1993 bool HaveCoins(uint256 txid);
1994 CBlockIndex *GetBestBlock();
1995 bool SetBestBlock(CBlockIndex *pindex);
1996 void SetBackend(CCoinsView &viewIn);
1997 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2000 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
2001 class CCoinsViewCache : public CCoinsViewBacked
2004 CBlockIndex *pindexTip;
2005 std::map<uint256,CCoins> cacheCoins;
2008 CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
2009 bool GetCoins(uint256 txid, CCoins &coins);
2010 bool SetCoins(uint256 txid, const CCoins &coins);
2011 bool HaveCoins(uint256 txid);
2012 CBlockIndex *GetBestBlock();
2013 bool SetBestBlock(CBlockIndex *pindex);
2014 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2016 unsigned int GetCacheSize();
2019 /** CCoinsView that brings transactions from a memorypool into view.
2020 It does not check for spendings by memory pool transactions. */
2021 class CCoinsViewMemPool : public CCoinsViewBacked
2024 CTxMemPool &mempool;
2027 CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
2028 bool GetCoins(uint256 txid, CCoins &coins);
2029 bool HaveCoins(uint256 txid);
2032 extern CCoinsViewCache *pcoinsTip;