]> Git Repo - VerusCoin.git/blob - src/main.h
Remove CheckSig_mode and move logic out of CheckInputs()
[VerusCoin.git] / src / main.h
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.
5 #ifndef BITCOIN_MAIN_H
6 #define BITCOIN_MAIN_H
7
8 #include "bignum.h"
9 #include "sync.h"
10 #include "net.h"
11 #include "script.h"
12
13 #include <list>
14
15 class CWallet;
16 class CBlock;
17 class CBlockIndex;
18 class CKeyItem;
19 class CReserveKey;
20
21 class CAddress;
22 class CInv;
23 class CNode;
24
25 struct CBlockIndexWorkComparator;
26
27 /** The maximum allowed size for a serialized block, in bytes (network rule) */
28 static const unsigned int MAX_BLOCK_SIZE = 1000000;
29 /** The maximum size for mined blocks */
30 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
31 /** The maximum allowed number of signature check operations in a block (network rule) */
32 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
33 /** The maximum number of orphan transactions kept in memory */
34 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
35 /** The maximum number of entries in an 'inv' protocol message */
36 static const unsigned int MAX_INV_SZ = 50000;
37 /** The maximum size of a blk?????.dat file (since 0.8) */
38 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
39 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
40 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
41 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
42 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
43 /** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
44 static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
45 /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
46 static const int64 MIN_TX_FEE = 50000;
47 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
48 static const int64 MIN_RELAY_TX_FEE = 10000;
49 /** No amount larger than this (in satoshi) is valid */
50 static const int64 MAX_MONEY = 21000000 * COIN;
51 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
52 /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
53 static const int COINBASE_MATURITY = 100;
54 /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
55 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
56 #ifdef USE_UPNP
57 static const int fHaveUPnP = true;
58 #else
59 static const int fHaveUPnP = false;
60 #endif
61
62
63 extern CScript COINBASE_FLAGS;
64
65
66
67
68
69
70 extern CCriticalSection cs_main;
71 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
72 extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
73 extern uint256 hashGenesisBlock;
74 extern CBlockIndex* pindexGenesisBlock;
75 extern int nBestHeight;
76 extern CBigNum bnBestChainWork;
77 extern CBigNum bnBestInvalidWork;
78 extern uint256 hashBestChain;
79 extern CBlockIndex* pindexBest;
80 extern unsigned int nTransactionsUpdated;
81 extern uint64 nLastBlockTx;
82 extern uint64 nLastBlockSize;
83 extern const std::string strMessageMagic;
84 extern double dHashesPerSec;
85 extern int64 nHPSTimerStart;
86 extern int64 nTimeBestReceived;
87 extern CCriticalSection cs_setpwalletRegistered;
88 extern std::set<CWallet*> setpwalletRegistered;
89 extern unsigned char pchMessageStart[4];
90 extern bool fImporting;
91 extern bool fReindex;
92 extern bool fBenchmark;
93 extern unsigned int nCoinCacheSize;
94
95 // Settings
96 extern int64 nTransactionFee;
97
98 // Minimum disk space required - used in CheckDiskSpace()
99 static const uint64 nMinDiskSpace = 52428800;
100
101
102 class CReserveKey;
103 class CCoinsDB;
104 class CBlockTreeDB;
105 class CDiskBlockPos;
106 class CCoins;
107 class CTxUndo;
108 class CCoinsView;
109 class CCoinsViewCache;
110
111 /** Register a wallet to receive updates from core */
112 void RegisterWallet(CWallet* pwalletIn);
113 /** Unregister a wallet from core */
114 void UnregisterWallet(CWallet* pwalletIn);
115 /** Push an updated transaction to all registered wallets */
116 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
117 /** Process an incoming block */
118 bool ProcessBlock(CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
119 /** Check whether enough disk space is available for an incoming block */
120 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
121 /** Open a block file (blk?????.dat) */
122 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
123 /** Open an undo file (rev?????.dat) */
124 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
125 /** Import blocks from an external file */
126 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
127 /** Load the block tree and coins database from disk */
128 bool LoadBlockIndex();
129 /** Print the loaded block tree */
130 void PrintBlockTree();
131 /** Find a block by height in the currently-connected chain */
132 CBlockIndex* FindBlockByHeight(int nHeight);
133 /** Process protocol messages received from a given node */
134 bool ProcessMessages(CNode* pfrom);
135 /** Send queued protocol messages to be sent to a give node */
136 bool SendMessages(CNode* pto, bool fSendTrickle);
137 /** Run the importer thread, which deals with reindexing, loading bootstrap.dat, and whatever is passed to -loadblock */
138 void ThreadImport(void *parg);
139 /** Run the miner threads */
140 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
141 /** Generate a new block, without valid proof-of-work */
142 CBlock* CreateNewBlock(CReserveKey& reservekey);
143 /** Modify the extranonce in a block */
144 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
145 /** Do mining precalculation */
146 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
147 /** Check mined block */
148 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
149 /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
150 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
151 /** Calculate the minimum amount of work a received block needs, without knowing its direct parent */
152 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
153 /** Get the number of active peers */
154 int GetNumBlocksOfPeers();
155 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
156 bool IsInitialBlockDownload();
157 /** Format a string that describes several potential problems detected by the core */
158 std::string GetWarnings(std::string strFor);
159 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
160 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
161 /** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */
162 bool SetBestChain(CBlockIndex* pindexNew);
163 /** Find the best known block, and make it the tip of the block chain */
164 bool ConnectBestBlock();
165 /** Create a new block index entry for a given block hash */
166 CBlockIndex * InsertBlockIndex(uint256 hash);
167 /** Verify a signature */
168 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
169
170
171
172
173
174
175
176
177
178
179
180 static inline std::string BlockHashStr(const uint256& hash)
181 {
182     return hash.ToString();
183 }
184
185 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
186
187 class CDiskBlockPos
188 {
189 public:
190     int nFile;
191     unsigned int nPos;
192
193     IMPLEMENT_SERIALIZE(
194         READWRITE(VARINT(nFile));
195         READWRITE(VARINT(nPos));
196     )
197
198     CDiskBlockPos() {
199         SetNull();
200     }
201
202     CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
203         nFile = nFileIn;
204         nPos = nPosIn;
205     }
206
207     friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
208         return (a.nFile == b.nFile && a.nPos == b.nPos);
209     }
210
211     friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
212         return !(a == b);
213     }
214
215     void SetNull() { nFile = -1; nPos = 0; }
216     bool IsNull() const { return (nFile == -1); }
217 };
218
219
220
221
222 /** An inpoint - a combination of a transaction and an index n into its vin */
223 class CInPoint
224 {
225 public:
226     CTransaction* ptx;
227     unsigned int n;
228
229     CInPoint() { SetNull(); }
230     CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
231     void SetNull() { ptx = NULL; n = (unsigned int) -1; }
232     bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
233 };
234
235
236
237 /** An outpoint - a combination of a transaction hash and an index n into its vout */
238 class COutPoint
239 {
240 public:
241     uint256 hash;
242     unsigned int n;
243
244     COutPoint() { SetNull(); }
245     COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
246     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
247     void SetNull() { hash = 0; n = (unsigned int) -1; }
248     bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
249
250     friend bool operator<(const COutPoint& a, const COutPoint& b)
251     {
252         return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
253     }
254
255     friend bool operator==(const COutPoint& a, const COutPoint& b)
256     {
257         return (a.hash == b.hash && a.n == b.n);
258     }
259
260     friend bool operator!=(const COutPoint& a, const COutPoint& b)
261     {
262         return !(a == b);
263     }
264
265     std::string ToString() const
266     {
267         return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
268     }
269
270     void print() const
271     {
272         printf("%s\n", ToString().c_str());
273     }
274 };
275
276
277
278
279 /** An input of a transaction.  It contains the location of the previous
280  * transaction's output that it claims and a signature that matches the
281  * output's public key.
282  */
283 class CTxIn
284 {
285 public:
286     COutPoint prevout;
287     CScript scriptSig;
288     unsigned int nSequence;
289
290     CTxIn()
291     {
292         nSequence = std::numeric_limits<unsigned int>::max();
293     }
294
295     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
296     {
297         prevout = prevoutIn;
298         scriptSig = scriptSigIn;
299         nSequence = nSequenceIn;
300     }
301
302     CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
303     {
304         prevout = COutPoint(hashPrevTx, nOut);
305         scriptSig = scriptSigIn;
306         nSequence = nSequenceIn;
307     }
308
309     IMPLEMENT_SERIALIZE
310     (
311         READWRITE(prevout);
312         READWRITE(scriptSig);
313         READWRITE(nSequence);
314     )
315
316     bool IsFinal() const
317     {
318         return (nSequence == std::numeric_limits<unsigned int>::max());
319     }
320
321     friend bool operator==(const CTxIn& a, const CTxIn& b)
322     {
323         return (a.prevout   == b.prevout &&
324                 a.scriptSig == b.scriptSig &&
325                 a.nSequence == b.nSequence);
326     }
327
328     friend bool operator!=(const CTxIn& a, const CTxIn& b)
329     {
330         return !(a == b);
331     }
332
333     std::string ToString() const
334     {
335         std::string str;
336         str += "CTxIn(";
337         str += prevout.ToString();
338         if (prevout.IsNull())
339             str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
340         else
341             str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
342         if (nSequence != std::numeric_limits<unsigned int>::max())
343             str += strprintf(", nSequence=%u", nSequence);
344         str += ")";
345         return str;
346     }
347
348     void print() const
349     {
350         printf("%s\n", ToString().c_str());
351     }
352 };
353
354
355
356
357 /** An output of a transaction.  It contains the public key that the next input
358  * must be able to sign with to claim it.
359  */
360 class CTxOut
361 {
362 public:
363     int64 nValue;
364     CScript scriptPubKey;
365
366     CTxOut()
367     {
368         SetNull();
369     }
370
371     CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
372     {
373         nValue = nValueIn;
374         scriptPubKey = scriptPubKeyIn;
375     }
376
377     IMPLEMENT_SERIALIZE
378     (
379         READWRITE(nValue);
380         READWRITE(scriptPubKey);
381     )
382
383     void SetNull()
384     {
385         nValue = -1;
386         scriptPubKey.clear();
387     }
388
389     bool IsNull() const
390     {
391         return (nValue == -1);
392     }
393
394     uint256 GetHash() const
395     {
396         return SerializeHash(*this);
397     }
398
399     friend bool operator==(const CTxOut& a, const CTxOut& b)
400     {
401         return (a.nValue       == b.nValue &&
402                 a.scriptPubKey == b.scriptPubKey);
403     }
404
405     friend bool operator!=(const CTxOut& a, const CTxOut& b)
406     {
407         return !(a == b);
408     }
409
410     std::string ToString() const
411     {
412         if (scriptPubKey.size() < 6)
413             return "CTxOut(error)";
414         return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
415     }
416
417     void print() const
418     {
419         printf("%s\n", ToString().c_str());
420     }
421 };
422
423
424
425
426 enum GetMinFee_mode
427 {
428     GMF_BLOCK,
429     GMF_RELAY,
430     GMF_SEND,
431 };
432
433 /** The basic transaction that is broadcasted on the network and contained in
434  * blocks.  A transaction can contain multiple inputs and outputs.
435  */
436 class CTransaction
437 {
438 public:
439     static const int CURRENT_VERSION=1;
440     int nVersion;
441     std::vector<CTxIn> vin;
442     std::vector<CTxOut> vout;
443     unsigned int nLockTime;
444
445     // Denial-of-service detection:
446     mutable int nDoS;
447     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
448
449     CTransaction()
450     {
451         SetNull();
452     }
453
454     IMPLEMENT_SERIALIZE
455     (
456         READWRITE(this->nVersion);
457         nVersion = this->nVersion;
458         READWRITE(vin);
459         READWRITE(vout);
460         READWRITE(nLockTime);
461     )
462
463     void SetNull()
464     {
465         nVersion = CTransaction::CURRENT_VERSION;
466         vin.clear();
467         vout.clear();
468         nLockTime = 0;
469         nDoS = 0;  // Denial-of-service prevention
470     }
471
472     bool IsNull() const
473     {
474         return (vin.empty() && vout.empty());
475     }
476
477     uint256 GetHash() const
478     {
479         return SerializeHash(*this);
480     }
481
482     bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
483     {
484         // Time based nLockTime implemented in 0.1.6
485         if (nLockTime == 0)
486             return true;
487         if (nBlockHeight == 0)
488             nBlockHeight = nBestHeight;
489         if (nBlockTime == 0)
490             nBlockTime = GetAdjustedTime();
491         if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
492             return true;
493         BOOST_FOREACH(const CTxIn& txin, vin)
494             if (!txin.IsFinal())
495                 return false;
496         return true;
497     }
498
499     bool IsNewerThan(const CTransaction& old) const
500     {
501         if (vin.size() != old.vin.size())
502             return false;
503         for (unsigned int i = 0; i < vin.size(); i++)
504             if (vin[i].prevout != old.vin[i].prevout)
505                 return false;
506
507         bool fNewer = false;
508         unsigned int nLowest = std::numeric_limits<unsigned int>::max();
509         for (unsigned int i = 0; i < vin.size(); i++)
510         {
511             if (vin[i].nSequence != old.vin[i].nSequence)
512             {
513                 if (vin[i].nSequence <= nLowest)
514                 {
515                     fNewer = false;
516                     nLowest = vin[i].nSequence;
517                 }
518                 if (old.vin[i].nSequence < nLowest)
519                 {
520                     fNewer = true;
521                     nLowest = old.vin[i].nSequence;
522                 }
523             }
524         }
525         return fNewer;
526     }
527
528     bool IsCoinBase() const
529     {
530         return (vin.size() == 1 && vin[0].prevout.IsNull());
531     }
532
533     /** Check for standard transaction types
534         @return True if all outputs (scriptPubKeys) use only standard transaction forms
535     */
536     bool IsStandard() const;
537
538     /** Check for standard transaction types
539         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
540         @return True if all inputs (scriptSigs) use only standard transaction forms
541         @see CTransaction::FetchInputs
542     */
543     bool AreInputsStandard(CCoinsViewCache& mapInputs) const;
544
545     /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
546         @return number of sigops this transaction's outputs will produce when spent
547         @see CTransaction::FetchInputs
548     */
549     unsigned int GetLegacySigOpCount() const;
550
551     /** Count ECDSA signature operations in pay-to-script-hash inputs.
552
553         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
554         @return maximum number of sigops required to validate this transaction's inputs
555         @see CTransaction::FetchInputs
556      */
557     unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const;
558
559     /** Amount of bitcoins spent by this transaction.
560         @return sum of all outputs (note: does not include fees)
561      */
562     int64 GetValueOut() const
563     {
564         int64 nValueOut = 0;
565         BOOST_FOREACH(const CTxOut& txout, vout)
566         {
567             nValueOut += txout.nValue;
568             if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
569                 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
570         }
571         return nValueOut;
572     }
573
574     /** Amount of bitcoins coming in to this transaction
575         Note that lightweight clients may not know anything besides the hash of previous transactions,
576         so may not be able to calculate this.
577
578         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
579         @return Sum of value of all inputs (scriptSigs)
580         @see CTransaction::FetchInputs
581      */
582     int64 GetValueIn(CCoinsViewCache& mapInputs) const;
583
584     static bool AllowFree(double dPriority)
585     {
586         // Large (in bytes) low-priority (new, small-coin) transactions
587         // need a fee.
588         return dPriority > COIN * 144 / 250;
589     }
590
591     int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const;
592
593     friend bool operator==(const CTransaction& a, const CTransaction& b)
594     {
595         return (a.nVersion  == b.nVersion &&
596                 a.vin       == b.vin &&
597                 a.vout      == b.vout &&
598                 a.nLockTime == b.nLockTime);
599     }
600
601     friend bool operator!=(const CTransaction& a, const CTransaction& b)
602     {
603         return !(a == b);
604     }
605
606
607     std::string ToString() const
608     {
609         std::string str;
610         str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
611             GetHash().ToString().substr(0,10).c_str(),
612             nVersion,
613             vin.size(),
614             vout.size(),
615             nLockTime);
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";
620         return str;
621     }
622
623     void print() const
624     {
625         printf("%s", ToString().c_str());
626     }
627
628
629     // Do all possible client-mode checks
630     bool ClientCheckInputs() const;
631
632     // Check whether all prevouts of this transaction are present in the UTXO set represented by view
633     bool HaveInputs(CCoinsViewCache &view) const;
634
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, bool fScriptChecks = true, unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC) const;
638
639     // Apply the effects of this transaction on the UTXO set represented by view
640     bool UpdateCoins(CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash) const;
641
642     // Context-independent validity checks
643     bool CheckTransaction() const;
644
645     // Try to accept this transaction into the memory pool
646     bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
647
648 protected:
649     static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs);
650 };
651
652 /** wrapper for CTxOut that provides a more compact serialization */
653 class CTxOutCompressor
654 {
655 private:
656     CTxOut &txout;
657
658 public:
659     static uint64 CompressAmount(uint64 nAmount);
660     static uint64 DecompressAmount(uint64 nAmount);
661
662     CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
663
664     IMPLEMENT_SERIALIZE(({
665         if (!fRead) {
666             uint64 nVal = CompressAmount(txout.nValue);
667             READWRITE(VARINT(nVal));
668         } else {
669             uint64 nVal = 0;
670             READWRITE(VARINT(nVal));
671             txout.nValue = DecompressAmount(nVal);
672         }
673         CScriptCompressor cscript(REF(txout.scriptPubKey));
674         READWRITE(cscript);
675     });)
676 };
677
678 /** Undo information for a CTxIn
679  *
680  *  Contains the prevout's CTxOut being spent, and if this was the
681  *  last output of the affected transaction, its metadata as well
682  *  (coinbase or not, height, transaction version)
683  */
684 class CTxInUndo
685 {
686 public:
687     CTxOut txout;         // the txout data before being spent
688     bool fCoinBase;       // if the outpoint was the last unspent: whether it belonged to a coinbase
689     unsigned int nHeight; // if the outpoint was the last unspent: its height
690     int nVersion;         // if the outpoint was the last unspent: its version
691
692     CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
693     CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
694
695     unsigned int GetSerializeSize(int nType, int nVersion) const {
696         return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
697                (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
698                ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
699     }
700
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         if (nHeight > 0)
705             ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
706         ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
707     }
708
709     template<typename Stream>
710     void Unserialize(Stream &s, int nType, int nVersion) {
711         unsigned int nCode = 0;
712         ::Unserialize(s, VARINT(nCode), nType, nVersion);
713         nHeight = nCode / 2;
714         fCoinBase = nCode & 1;
715         if (nHeight > 0)
716             ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
717         ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
718     }
719 };
720
721 /** Undo information for a CTransaction */
722 class CTxUndo
723 {
724 public:
725     // undo information for all txins
726     std::vector<CTxInUndo> vprevout;
727
728     IMPLEMENT_SERIALIZE(
729         READWRITE(vprevout);
730     )
731 };
732
733 /** Undo information for a CBlock */
734 class CBlockUndo
735 {
736 public:
737     std::vector<CTxUndo> vtxundo; // for all but the coinbase
738
739     IMPLEMENT_SERIALIZE(
740         READWRITE(vtxundo);
741     )
742
743     bool WriteToDisk(CDiskBlockPos &pos)
744     {
745         // Open history file to append
746         CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
747         if (!fileout)
748             return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
749
750         // Write index header
751         unsigned int nSize = fileout.GetSerializeSize(*this);
752         fileout << FLATDATA(pchMessageStart) << nSize;
753
754         // Write undo data
755         long fileOutPos = ftell(fileout);
756         if (fileOutPos < 0)
757             return error("CBlockUndo::WriteToDisk() : ftell failed");
758         pos.nPos = (unsigned int)fileOutPos;
759         fileout << *this;
760
761         // Flush stdio buffers and commit to disk before returning
762         fflush(fileout);
763         if (!IsInitialBlockDownload())
764             FileCommit(fileout);
765
766         return true;
767     }
768 };
769
770 /** pruned version of CTransaction: only retains metadata and unspent transaction outputs
771  *
772  * Serialized format:
773  * - VARINT(nVersion)
774  * - VARINT(nCode)
775  * - unspentness bitvector, for vout[2] and further; least significant byte first
776  * - the non-spent CTxOuts (via CTxOutCompressor)
777  * - VARINT(nHeight)
778  *
779  * The nCode value consists of:
780  * - bit 1: IsCoinBase()
781  * - bit 2: vout[0] is not spent
782  * - bit 4: vout[1] is not spent
783  * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
784  *   - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
785  *     least one non-spent output).
786  *
787  * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
788  *          <><><--------------------------------------------><---->
789  *          |  \                  |                             /
790  *    version   code             vout[1]                  height
791  *
792  *    - version = 1
793  *    - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
794  *    - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
795  *    - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
796  *               * 8358: compact amount representation for 60000000000 (600 BTC)
797  *               * 00: special txout type pay-to-pubkey-hash
798  *               * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
799  *    - height = 203998
800  *
801  *
802  * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
803  *          <><><--><--------------------------------------------------><----------------------------------------------><---->
804  *         /  \   \                     |                                                           |                     /
805  *  version  code  unspentness       vout[4]                                                     vout[16]           height
806  *
807  *  - version = 1
808  *  - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
809  *                2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
810  *  - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
811  *  - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
812  *             * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
813  *             * 00: special txout type pay-to-pubkey-hash
814  *             * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
815  *  - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
816  *              * bbd123: compact amount representation for 110397 (0.001 BTC)
817  *              * 00: special txout type pay-to-pubkey-hash
818  *              * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
819  *  - height = 120891
820  */
821 class CCoins
822 {
823 public:
824     // whether transaction is a coinbase
825     bool fCoinBase;
826
827     // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
828     std::vector<CTxOut> vout;
829
830     // at which height this transaction was included in the active block chain
831     int nHeight;
832
833     // version of the CTransaction; accesses to this value should probably check for nHeight as well,
834     // as new tx version will probably only be introduced at certain heights
835     int nVersion;
836
837     // construct a CCoins from a CTransaction, at a given height
838     CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { }
839
840     // empty constructor
841     CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
842
843     // remove spent outputs at the end of vout
844     void Cleanup() {
845         while (vout.size() > 0 && vout.back().IsNull())
846             vout.pop_back();
847     }
848
849     // equality test
850     friend bool operator==(const CCoins &a, const CCoins &b) {
851          return a.fCoinBase == b.fCoinBase &&
852                 a.nHeight == b.nHeight &&
853                 a.nVersion == b.nVersion &&
854                 a.vout == b.vout;
855     }
856     friend bool operator!=(const CCoins &a, const CCoins &b) {
857         return !(a == b);
858     }
859
860     // calculate number of bytes for the bitmask, and its number of non-zero bytes
861     // each bit in the bitmask represents the availability of one output, but the
862     // availabilities of the first two outputs are encoded separately
863     void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
864         unsigned int nLastUsedByte = 0;
865         for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
866             bool fZero = true;
867             for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
868                 if (!vout[2+b*8+i].IsNull()) {
869                     fZero = false;
870                     continue;
871                 }
872             }
873             if (!fZero) {
874                 nLastUsedByte = b + 1;
875                 nNonzeroBytes++;
876             }
877         }
878         nBytes += nLastUsedByte;
879     }
880
881     bool IsCoinBase() const {
882         return fCoinBase;
883     }
884
885     unsigned int GetSerializeSize(int nType, int nVersion) const {
886         unsigned int nSize = 0;
887         unsigned int nMaskSize = 0, nMaskCode = 0;
888         CalcMaskSize(nMaskSize, nMaskCode);
889         bool fFirst = vout.size() > 0 && !vout[0].IsNull();
890         bool fSecond = vout.size() > 1 && !vout[1].IsNull();
891         assert(fFirst || fSecond || nMaskCode);
892         unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
893         // version
894         nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
895         // size of header code
896         nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
897         // spentness bitmask
898         nSize += nMaskSize;
899         // txouts themself
900         for (unsigned int i = 0; i < vout.size(); i++)
901             if (!vout[i].IsNull())
902                 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
903         // height
904         nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
905         return nSize;
906     }
907
908     template<typename Stream>
909     void Serialize(Stream &s, int nType, int nVersion) const {
910         unsigned int nMaskSize = 0, nMaskCode = 0;
911         CalcMaskSize(nMaskSize, nMaskCode);
912         bool fFirst = vout.size() > 0 && !vout[0].IsNull();
913         bool fSecond = vout.size() > 1 && !vout[1].IsNull();
914         assert(fFirst || fSecond || nMaskCode);
915         unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
916         // version
917         ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
918         // header code
919         ::Serialize(s, VARINT(nCode), nType, nVersion);
920         // spentness bitmask
921         for (unsigned int b = 0; b<nMaskSize; b++) {
922             unsigned char chAvail = 0;
923             for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
924                 if (!vout[2+b*8+i].IsNull())
925                     chAvail |= (1 << i);
926             ::Serialize(s, chAvail, nType, nVersion);
927         }
928         // txouts themself
929         for (unsigned int i = 0; i < vout.size(); i++) {
930             if (!vout[i].IsNull())
931                 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
932         }
933         // coinbase height
934         ::Serialize(s, VARINT(nHeight), nType, nVersion);
935     }
936
937     template<typename Stream>
938     void Unserialize(Stream &s, int nType, int nVersion) {
939         unsigned int nCode = 0;
940         // version
941         ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
942         // header code
943         ::Unserialize(s, VARINT(nCode), nType, nVersion);
944         fCoinBase = nCode & 1;
945         std::vector<bool> vAvail(2, false);
946         vAvail[0] = nCode & 2;
947         vAvail[1] = nCode & 4;
948         unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
949         // spentness bitmask
950         while (nMaskCode > 0) {
951             unsigned char chAvail = 0;
952             ::Unserialize(s, chAvail, nType, nVersion);
953             for (unsigned int p = 0; p < 8; p++) {
954                 bool f = (chAvail & (1 << p)) != 0;
955                 vAvail.push_back(f);
956             }
957             if (chAvail != 0)
958                 nMaskCode--;
959         }
960         // txouts themself
961         vout.assign(vAvail.size(), CTxOut());
962         for (unsigned int i = 0; i < vAvail.size(); i++) {
963             if (vAvail[i])
964                 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
965         }
966         // coinbase height
967         ::Unserialize(s, VARINT(nHeight), nType, nVersion);
968         Cleanup();
969     }
970
971     // mark an outpoint spent, and construct undo information
972     bool Spend(const COutPoint &out, CTxInUndo &undo) {
973         if (out.n >= vout.size())
974             return false;
975         if (vout[out.n].IsNull())
976             return false;
977         undo = CTxInUndo(vout[out.n]);
978         vout[out.n].SetNull();
979         Cleanup();
980         if (vout.size() == 0) {
981             undo.nHeight = nHeight;
982             undo.fCoinBase = fCoinBase;
983             undo.nVersion = this->nVersion;
984         }
985         return true;
986     }
987
988     // mark a vout spent
989     bool Spend(int nPos) {
990         CTxInUndo undo;
991         COutPoint out(0, nPos);
992         return Spend(out, undo);
993     }
994
995     // check whether a particular output is still available
996     bool IsAvailable(unsigned int nPos) const {
997         return (nPos < vout.size() && !vout[nPos].IsNull());
998     }
999
1000     // check whether the entire CCoins is spent
1001     // note that only !IsPruned() CCoins can be serialized
1002     bool IsPruned() const {
1003         BOOST_FOREACH(const CTxOut &out, vout)
1004             if (!out.IsNull())
1005                 return false;
1006         return true;
1007     }
1008 };
1009
1010 /** Closure representing one script verification
1011  *  Note that this stores references to the spending transaction */
1012 class CScriptCheck
1013 {
1014 private:
1015     CScript scriptPubKey;
1016     const CTransaction *ptxTo;
1017     unsigned int nIn;
1018     unsigned int nFlags;
1019     int nHashType;
1020
1021 public:
1022     CScriptCheck() {}
1023     CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
1024         scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
1025         ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
1026
1027     bool operator()() const;
1028
1029     void swap(CScriptCheck &check) {
1030         scriptPubKey.swap(check.scriptPubKey);
1031         std::swap(ptxTo, check.ptxTo);
1032         std::swap(nIn, check.nIn);
1033         std::swap(nFlags, check.nFlags);
1034         std::swap(nHashType, check.nHashType);
1035     }
1036 };
1037
1038 /** A transaction with a merkle branch linking it to the block chain. */
1039 class CMerkleTx : public CTransaction
1040 {
1041 public:
1042     uint256 hashBlock;
1043     std::vector<uint256> vMerkleBranch;
1044     int nIndex;
1045
1046     // memory only
1047     mutable bool fMerkleVerified;
1048
1049
1050     CMerkleTx()
1051     {
1052         Init();
1053     }
1054
1055     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
1056     {
1057         Init();
1058     }
1059
1060     void Init()
1061     {
1062         hashBlock = 0;
1063         nIndex = -1;
1064         fMerkleVerified = false;
1065     }
1066
1067
1068     IMPLEMENT_SERIALIZE
1069     (
1070         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
1071         nVersion = this->nVersion;
1072         READWRITE(hashBlock);
1073         READWRITE(vMerkleBranch);
1074         READWRITE(nIndex);
1075     )
1076
1077
1078     int SetMerkleBranch(const CBlock* pblock=NULL);
1079     int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
1080     int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
1081     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
1082     int GetBlocksToMaturity() const;
1083     bool AcceptToMemoryPool(bool fCheckInputs=true);
1084 };
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097 /** Nodes collect new transactions into a block, hash them into a hash tree,
1098  * and scan through nonce values to make the block's hash satisfy proof-of-work
1099  * requirements.  When they solve the proof-of-work, they broadcast the block
1100  * to everyone and the block is added to the block chain.  The first transaction
1101  * in the block is a special one that creates a new coin owned by the creator
1102  * of the block.
1103  */
1104 class CBlockHeader
1105 {
1106 public:
1107     // header
1108     static const int CURRENT_VERSION=2;
1109     int nVersion;
1110     uint256 hashPrevBlock;
1111     uint256 hashMerkleRoot;
1112     unsigned int nTime;
1113     unsigned int nBits;
1114     unsigned int nNonce;
1115
1116     CBlockHeader()
1117     {
1118         SetNull();
1119     }
1120
1121     IMPLEMENT_SERIALIZE
1122     (
1123         READWRITE(this->nVersion);
1124         nVersion = this->nVersion;
1125         READWRITE(hashPrevBlock);
1126         READWRITE(hashMerkleRoot);
1127         READWRITE(nTime);
1128         READWRITE(nBits);
1129         READWRITE(nNonce);
1130     )
1131
1132     void SetNull()
1133     {
1134         nVersion = CBlockHeader::CURRENT_VERSION;
1135         hashPrevBlock = 0;
1136         hashMerkleRoot = 0;
1137         nTime = 0;
1138         nBits = 0;
1139         nNonce = 0;
1140     }
1141
1142     bool IsNull() const
1143     {
1144         return (nBits == 0);
1145     }
1146
1147     uint256 GetHash() const
1148     {
1149         return Hash(BEGIN(nVersion), END(nNonce));
1150     }
1151
1152     int64 GetBlockTime() const
1153     {
1154         return (int64)nTime;
1155     }
1156
1157     void UpdateTime(const CBlockIndex* pindexPrev);
1158 };
1159
1160 class CBlock : public CBlockHeader
1161 {
1162 public:
1163     // network and disk
1164     std::vector<CTransaction> vtx;
1165
1166     // memory only
1167     mutable std::vector<uint256> vMerkleTree;
1168
1169     // Denial-of-service detection:
1170     mutable int nDoS;
1171     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
1172
1173     CBlock()
1174     {
1175         SetNull();
1176     }
1177
1178     CBlock(const CBlockHeader &header)
1179     {
1180         SetNull();
1181         *((CBlockHeader*)this) = header;
1182     }
1183
1184     IMPLEMENT_SERIALIZE
1185     (
1186         READWRITE(*(CBlockHeader*)this);
1187         READWRITE(vtx);
1188     )
1189
1190     void SetNull()
1191     {
1192         CBlockHeader::SetNull();
1193         vtx.clear();
1194         vMerkleTree.clear();
1195         nDoS = 0;
1196     }
1197
1198     uint256 BuildMerkleTree() const
1199     {
1200         vMerkleTree.clear();
1201         BOOST_FOREACH(const CTransaction& tx, vtx)
1202             vMerkleTree.push_back(tx.GetHash());
1203         int j = 0;
1204         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1205         {
1206             for (int i = 0; i < nSize; i += 2)
1207             {
1208                 int i2 = std::min(i+1, nSize-1);
1209                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
1210                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1211             }
1212             j += nSize;
1213         }
1214         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1215     }
1216
1217     const uint256 &GetTxHash(unsigned int nIndex) const {
1218         assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
1219         assert(nIndex < vtx.size());
1220         return vMerkleTree[nIndex];
1221     }
1222
1223     std::vector<uint256> GetMerkleBranch(int nIndex) const
1224     {
1225         if (vMerkleTree.empty())
1226             BuildMerkleTree();
1227         std::vector<uint256> vMerkleBranch;
1228         int j = 0;
1229         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1230         {
1231             int i = std::min(nIndex^1, nSize-1);
1232             vMerkleBranch.push_back(vMerkleTree[j+i]);
1233             nIndex >>= 1;
1234             j += nSize;
1235         }
1236         return vMerkleBranch;
1237     }
1238
1239     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1240     {
1241         if (nIndex == -1)
1242             return 0;
1243         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1244         {
1245             if (nIndex & 1)
1246                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1247             else
1248                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1249             nIndex >>= 1;
1250         }
1251         return hash;
1252     }
1253
1254
1255     bool WriteToDisk(CDiskBlockPos &pos)
1256     {
1257         // Open history file to append
1258         CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1259         if (!fileout)
1260             return error("CBlock::WriteToDisk() : OpenBlockFile failed");
1261
1262         // Write index header
1263         unsigned int nSize = fileout.GetSerializeSize(*this);
1264         fileout << FLATDATA(pchMessageStart) << nSize;
1265
1266         // Write block
1267         long fileOutPos = ftell(fileout);
1268         if (fileOutPos < 0)
1269             return error("CBlock::WriteToDisk() : ftell failed");
1270         pos.nPos = (unsigned int)fileOutPos;
1271         fileout << *this;
1272
1273         // Flush stdio buffers and commit to disk before returning
1274         fflush(fileout);
1275         if (!IsInitialBlockDownload())
1276             FileCommit(fileout);
1277
1278         return true;
1279     }
1280
1281     bool ReadFromDisk(const CDiskBlockPos &pos)
1282     {
1283         SetNull();
1284
1285         // Open history file to read
1286         CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1287         if (!filein)
1288             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1289
1290         // Read block
1291         try {
1292             filein >> *this;
1293         }
1294         catch (std::exception &e) {
1295             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1296         }
1297
1298         // Check the header
1299         if (!CheckProofOfWork(GetHash(), nBits))
1300             return error("CBlock::ReadFromDisk() : errors in block header");
1301
1302         return true;
1303     }
1304
1305
1306
1307     void print() const
1308     {
1309         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
1310             BlockHashStr(GetHash()).c_str(),
1311             nVersion,
1312             BlockHashStr(hashPrevBlock).c_str(),
1313             hashMerkleRoot.ToString().substr(0,10).c_str(),
1314             nTime, nBits, nNonce,
1315             vtx.size());
1316         for (unsigned int i = 0; i < vtx.size(); i++)
1317         {
1318             printf("  ");
1319             vtx[i].print();
1320         }
1321         printf("  vMerkleTree: ");
1322         for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1323             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1324         printf("\n");
1325     }
1326
1327
1328     // Undo the effects of this block (with given index) on the UTXO set represented by coins
1329     bool DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &coins);
1330
1331     // Apply the effects of this block (with given index) on the UTXO set represented by coins
1332     bool ConnectBlock(CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
1333
1334     // Read a block from disk
1335     bool ReadFromDisk(const CBlockIndex* pindex);
1336
1337     // Add this block to the block index, and if necessary, switch the active block chain to this
1338     bool AddToBlockIndex(const CDiskBlockPos &pos);
1339
1340     // Context-independent validity checks
1341     bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
1342
1343     // Store block on disk
1344     // if dbp is provided, the file is known to already reside on disk
1345     bool AcceptBlock(CDiskBlockPos *dbp = NULL);
1346 };
1347
1348
1349
1350
1351
1352 class CBlockFileInfo
1353 {
1354 public:
1355     unsigned int nBlocks;      // number of blocks stored in file
1356     unsigned int nSize;        // number of used bytes of block file
1357     unsigned int nUndoSize;    // number of used bytes in the undo file
1358     unsigned int nHeightFirst; // lowest height of block in file
1359     unsigned int nHeightLast;  // highest height of block in file
1360     uint64 nTimeFirst;         // earliest time of block in file
1361     uint64 nTimeLast;          // latest time of block in file
1362
1363     IMPLEMENT_SERIALIZE(
1364         READWRITE(VARINT(nBlocks));
1365         READWRITE(VARINT(nSize));
1366         READWRITE(VARINT(nUndoSize));
1367         READWRITE(VARINT(nHeightFirst));
1368         READWRITE(VARINT(nHeightLast));
1369         READWRITE(VARINT(nTimeFirst));
1370         READWRITE(VARINT(nTimeLast));
1371      )
1372
1373      void SetNull() {
1374          nBlocks = 0;
1375          nSize = 0;
1376          nUndoSize = 0;
1377          nHeightFirst = 0;
1378          nHeightLast = 0;
1379          nTimeFirst = 0;
1380          nTimeLast = 0;
1381      }
1382
1383      CBlockFileInfo() {
1384          SetNull();
1385      }
1386
1387      std::string ToString() const {
1388          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());
1389      }
1390
1391      // update statistics (does not update nSize)
1392      void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
1393          if (nBlocks==0 || nHeightFirst > nHeightIn)
1394              nHeightFirst = nHeightIn;
1395          if (nBlocks==0 || nTimeFirst > nTimeIn)
1396              nTimeFirst = nTimeIn;
1397          nBlocks++;
1398          if (nHeightIn > nHeightFirst)
1399              nHeightLast = nHeightIn;
1400          if (nTimeIn > nTimeLast)
1401              nTimeLast = nTimeIn;
1402      }
1403 };
1404
1405 extern CCriticalSection cs_LastBlockFile;
1406 extern CBlockFileInfo infoLastBlockFile;
1407 extern int nLastBlockFile;
1408
1409 enum BlockStatus {
1410     BLOCK_VALID_UNKNOWN      =    0,
1411     BLOCK_VALID_HEADER       =    1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
1412     BLOCK_VALID_TREE         =    2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
1413     BLOCK_VALID_TRANSACTIONS =    3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
1414     BLOCK_VALID_CHAIN        =    4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
1415     BLOCK_VALID_SCRIPTS      =    5, // scripts/signatures ok
1416     BLOCK_VALID_MASK         =    7,
1417
1418     BLOCK_HAVE_DATA          =    8, // full block available in blk*.dat
1419     BLOCK_HAVE_UNDO          =   16, // undo data available in rev*.dat
1420     BLOCK_HAVE_MASK          =   24,
1421
1422     BLOCK_FAILED_VALID       =   32, // stage after last reached validness failed
1423     BLOCK_FAILED_CHILD       =   64, // descends from failed block
1424     BLOCK_FAILED_MASK        =   96
1425 };
1426
1427 /** The block chain is a tree shaped structure starting with the
1428  * genesis block at the root, with each block potentially having multiple
1429  * candidates to be the next block.  pprev and pnext link a path through the
1430  * main/longest chain.  A blockindex may have multiple pprev pointing back
1431  * to it, but pnext will only point forward to the longest branch, or will
1432  * be null if the block is not part of the longest chain.
1433  */
1434 class CBlockIndex
1435 {
1436 public:
1437     // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
1438     const uint256* phashBlock;
1439
1440     // pointer to the index of the predecessor of this block
1441     CBlockIndex* pprev;
1442
1443     // (memory only) pointer to the index of the *active* successor of this block
1444     CBlockIndex* pnext;
1445
1446     // height of the entry in the chain. The genesis block has height 0
1447     int nHeight;
1448
1449     // Which # file this block is stored in (blk?????.dat)
1450     int nFile;
1451
1452     // Byte offset within blk?????.dat where this block's data is stored
1453     unsigned int nDataPos;
1454
1455     // Byte offset within rev?????.dat where this block's undo data is stored
1456     unsigned int nUndoPos;
1457
1458     // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
1459     CBigNum bnChainWork;
1460
1461     // Number of transactions in this block.
1462     // Note: in a potential headers-first mode, this number cannot be relied upon
1463     unsigned int nTx;
1464
1465     // (memory only) Number of transactions in the chain up to and including this block
1466     unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
1467
1468     // Verification status of this block. See enum BlockStatus
1469     unsigned int nStatus;
1470
1471     // block header
1472     int nVersion;
1473     uint256 hashMerkleRoot;
1474     unsigned int nTime;
1475     unsigned int nBits;
1476     unsigned int nNonce;
1477
1478
1479     CBlockIndex()
1480     {
1481         phashBlock = NULL;
1482         pprev = NULL;
1483         pnext = NULL;
1484         nHeight = 0;
1485         nFile = 0;
1486         nDataPos = 0;
1487         nUndoPos = 0;
1488         bnChainWork = 0;
1489         nTx = 0;
1490         nChainTx = 0;
1491         nStatus = 0;
1492
1493         nVersion       = 0;
1494         hashMerkleRoot = 0;
1495         nTime          = 0;
1496         nBits          = 0;
1497         nNonce         = 0;
1498     }
1499
1500     CBlockIndex(CBlockHeader& block)
1501     {
1502         phashBlock = NULL;
1503         pprev = NULL;
1504         pnext = NULL;
1505         nHeight = 0;
1506         nFile = 0;
1507         nDataPos = 0;
1508         nUndoPos = 0;
1509         bnChainWork = 0;
1510         nTx = 0;
1511         nChainTx = 0;
1512         nStatus = 0;
1513
1514         nVersion       = block.nVersion;
1515         hashMerkleRoot = block.hashMerkleRoot;
1516         nTime          = block.nTime;
1517         nBits          = block.nBits;
1518         nNonce         = block.nNonce;
1519     }
1520
1521     CDiskBlockPos GetBlockPos() const {
1522         CDiskBlockPos ret;
1523         if (nStatus & BLOCK_HAVE_DATA) {
1524             ret.nFile = nFile;
1525             ret.nPos  = nDataPos;
1526         }
1527         return ret;
1528     }
1529
1530     CDiskBlockPos GetUndoPos() const {
1531         CDiskBlockPos ret;
1532         if (nStatus & BLOCK_HAVE_UNDO) {
1533             ret.nFile = nFile;
1534             ret.nPos  = nUndoPos;
1535         }
1536         return ret;
1537     }
1538
1539     CBlockHeader GetBlockHeader() const
1540     {
1541         CBlockHeader block;
1542         block.nVersion       = nVersion;
1543         if (pprev)
1544             block.hashPrevBlock = pprev->GetBlockHash();
1545         block.hashMerkleRoot = hashMerkleRoot;
1546         block.nTime          = nTime;
1547         block.nBits          = nBits;
1548         block.nNonce         = nNonce;
1549         return block;
1550     }
1551
1552     uint256 GetBlockHash() const
1553     {
1554         return *phashBlock;
1555     }
1556
1557     int64 GetBlockTime() const
1558     {
1559         return (int64)nTime;
1560     }
1561
1562     CBigNum GetBlockWork() const
1563     {
1564         CBigNum bnTarget;
1565         bnTarget.SetCompact(nBits);
1566         if (bnTarget <= 0)
1567             return 0;
1568         return (CBigNum(1)<<256) / (bnTarget+1);
1569     }
1570
1571     bool IsInMainChain() const
1572     {
1573         return (pnext || this == pindexBest);
1574     }
1575
1576     bool CheckIndex() const
1577     {
1578         return CheckProofOfWork(GetBlockHash(), nBits);
1579     }
1580
1581     enum { nMedianTimeSpan=11 };
1582
1583     int64 GetMedianTimePast() const
1584     {
1585         int64 pmedian[nMedianTimeSpan];
1586         int64* pbegin = &pmedian[nMedianTimeSpan];
1587         int64* pend = &pmedian[nMedianTimeSpan];
1588
1589         const CBlockIndex* pindex = this;
1590         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1591             *(--pbegin) = pindex->GetBlockTime();
1592
1593         std::sort(pbegin, pend);
1594         return pbegin[(pend - pbegin)/2];
1595     }
1596
1597     int64 GetMedianTime() const
1598     {
1599         const CBlockIndex* pindex = this;
1600         for (int i = 0; i < nMedianTimeSpan/2; i++)
1601         {
1602             if (!pindex->pnext)
1603                 return GetBlockTime();
1604             pindex = pindex->pnext;
1605         }
1606         return pindex->GetMedianTimePast();
1607     }
1608
1609     /**
1610      * Returns true if there are nRequired or more blocks of minVersion or above
1611      * in the last nToCheck blocks, starting at pstart and going backwards.
1612      */
1613     static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1614                                 unsigned int nRequired, unsigned int nToCheck);
1615
1616     std::string ToString() const
1617     {
1618         return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
1619             pprev, pnext, nHeight,
1620             hashMerkleRoot.ToString().substr(0,10).c_str(),
1621             BlockHashStr(GetBlockHash()).c_str());
1622     }
1623
1624     void print() const
1625     {
1626         printf("%s\n", ToString().c_str());
1627     }
1628 };
1629
1630 struct CBlockIndexWorkComparator
1631 {
1632     bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
1633         if (pa->bnChainWork > pb->bnChainWork) return false;
1634         if (pa->bnChainWork < pb->bnChainWork) return true;
1635
1636         if (pa->GetBlockHash() < pb->GetBlockHash()) return false;
1637         if (pa->GetBlockHash() > pb->GetBlockHash()) return true;
1638
1639         return false; // identical blocks
1640     }
1641 };
1642
1643
1644
1645 /** Used to marshal pointers into hashes for db storage. */
1646 class CDiskBlockIndex : public CBlockIndex
1647 {
1648 public:
1649     uint256 hashPrev;
1650
1651     CDiskBlockIndex() {
1652         hashPrev = 0;
1653     }
1654
1655     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
1656         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1657     }
1658
1659     IMPLEMENT_SERIALIZE
1660     (
1661         if (!(nType & SER_GETHASH))
1662             READWRITE(VARINT(nVersion));
1663
1664         READWRITE(VARINT(nHeight));
1665         READWRITE(VARINT(nStatus));
1666         READWRITE(VARINT(nTx));
1667         if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
1668             READWRITE(VARINT(nFile));
1669         if (nStatus & BLOCK_HAVE_DATA)
1670             READWRITE(VARINT(nDataPos));
1671         if (nStatus & BLOCK_HAVE_UNDO)
1672             READWRITE(VARINT(nUndoPos));
1673
1674         // block header
1675         READWRITE(this->nVersion);
1676         READWRITE(hashPrev);
1677         READWRITE(hashMerkleRoot);
1678         READWRITE(nTime);
1679         READWRITE(nBits);
1680         READWRITE(nNonce);
1681     )
1682
1683     uint256 GetBlockHash() const
1684     {
1685         CBlockHeader block;
1686         block.nVersion        = nVersion;
1687         block.hashPrevBlock   = hashPrev;
1688         block.hashMerkleRoot  = hashMerkleRoot;
1689         block.nTime           = nTime;
1690         block.nBits           = nBits;
1691         block.nNonce          = nNonce;
1692         return block.GetHash();
1693     }
1694
1695
1696     std::string ToString() const
1697     {
1698         std::string str = "CDiskBlockIndex(";
1699         str += CBlockIndex::ToString();
1700         str += strprintf("\n                hashBlock=%s, hashPrev=%s)",
1701             GetBlockHash().ToString().c_str(),
1702             BlockHashStr(hashPrev).c_str());
1703         return str;
1704     }
1705
1706     void print() const
1707     {
1708         printf("%s\n", ToString().c_str());
1709     }
1710 };
1711
1712
1713
1714
1715
1716
1717
1718
1719 /** Describes a place in the block chain to another node such that if the
1720  * other node doesn't have the same branch, it can find a recent common trunk.
1721  * The further back it is, the further before the fork it may be.
1722  */
1723 class CBlockLocator
1724 {
1725 protected:
1726     std::vector<uint256> vHave;
1727 public:
1728
1729     CBlockLocator()
1730     {
1731     }
1732
1733     explicit CBlockLocator(const CBlockIndex* pindex)
1734     {
1735         Set(pindex);
1736     }
1737
1738     explicit CBlockLocator(uint256 hashBlock)
1739     {
1740         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1741         if (mi != mapBlockIndex.end())
1742             Set((*mi).second);
1743     }
1744
1745     CBlockLocator(const std::vector<uint256>& vHaveIn)
1746     {
1747         vHave = vHaveIn;
1748     }
1749
1750     IMPLEMENT_SERIALIZE
1751     (
1752         if (!(nType & SER_GETHASH))
1753             READWRITE(nVersion);
1754         READWRITE(vHave);
1755     )
1756
1757     void SetNull()
1758     {
1759         vHave.clear();
1760     }
1761
1762     bool IsNull()
1763     {
1764         return vHave.empty();
1765     }
1766
1767     void Set(const CBlockIndex* pindex)
1768     {
1769         vHave.clear();
1770         int nStep = 1;
1771         while (pindex)
1772         {
1773             vHave.push_back(pindex->GetBlockHash());
1774
1775             // Exponentially larger steps back
1776             for (int i = 0; pindex && i < nStep; i++)
1777                 pindex = pindex->pprev;
1778             if (vHave.size() > 10)
1779                 nStep *= 2;
1780         }
1781         vHave.push_back(hashGenesisBlock);
1782     }
1783
1784     int GetDistanceBack()
1785     {
1786         // Retrace how far back it was in the sender's branch
1787         int nDistance = 0;
1788         int nStep = 1;
1789         BOOST_FOREACH(const uint256& hash, vHave)
1790         {
1791             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1792             if (mi != mapBlockIndex.end())
1793             {
1794                 CBlockIndex* pindex = (*mi).second;
1795                 if (pindex->IsInMainChain())
1796                     return nDistance;
1797             }
1798             nDistance += nStep;
1799             if (nDistance > 10)
1800                 nStep *= 2;
1801         }
1802         return nDistance;
1803     }
1804
1805     CBlockIndex* GetBlockIndex()
1806     {
1807         // Find the first block the caller has in the main chain
1808         BOOST_FOREACH(const uint256& hash, vHave)
1809         {
1810             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1811             if (mi != mapBlockIndex.end())
1812             {
1813                 CBlockIndex* pindex = (*mi).second;
1814                 if (pindex->IsInMainChain())
1815                     return pindex;
1816             }
1817         }
1818         return pindexGenesisBlock;
1819     }
1820
1821     uint256 GetBlockHash()
1822     {
1823         // Find the first block the caller has in the main chain
1824         BOOST_FOREACH(const uint256& hash, vHave)
1825         {
1826             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1827             if (mi != mapBlockIndex.end())
1828             {
1829                 CBlockIndex* pindex = (*mi).second;
1830                 if (pindex->IsInMainChain())
1831                     return hash;
1832             }
1833         }
1834         return hashGenesisBlock;
1835     }
1836
1837     int GetHeight()
1838     {
1839         CBlockIndex* pindex = GetBlockIndex();
1840         if (!pindex)
1841             return 0;
1842         return pindex->nHeight;
1843     }
1844 };
1845
1846
1847
1848
1849
1850
1851
1852
1853 class CTxMemPool
1854 {
1855 public:
1856     mutable CCriticalSection cs;
1857     std::map<uint256, CTransaction> mapTx;
1858     std::map<COutPoint, CInPoint> mapNextTx;
1859
1860     bool accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs);
1861     bool addUnchecked(const uint256& hash, CTransaction &tx);
1862     bool remove(const CTransaction &tx, bool fRecursive = false);
1863     bool removeConflicts(const CTransaction &tx);
1864     void clear();
1865     void queryHashes(std::vector<uint256>& vtxid);
1866     void pruneSpent(const uint256& hash, CCoins &coins);
1867
1868     unsigned long size()
1869     {
1870         LOCK(cs);
1871         return mapTx.size();
1872     }
1873
1874     bool exists(uint256 hash)
1875     {
1876         return (mapTx.count(hash) != 0);
1877     }
1878
1879     CTransaction& lookup(uint256 hash)
1880     {
1881         return mapTx[hash];
1882     }
1883 };
1884
1885 extern CTxMemPool mempool;
1886
1887 struct CCoinsStats
1888 {
1889     int nHeight;
1890     uint64 nTransactions;
1891     uint64 nTransactionOutputs;
1892     uint64 nSerializedSize;
1893
1894     CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0) {}
1895 };
1896
1897 /** Abstract view on the open txout dataset. */
1898 class CCoinsView
1899 {
1900 public:
1901     // Retrieve the CCoins (unspent transaction outputs) for a given txid
1902     virtual bool GetCoins(uint256 txid, CCoins &coins);
1903
1904     // Modify the CCoins for a given txid
1905     virtual bool SetCoins(uint256 txid, const CCoins &coins);
1906
1907     // Just check whether we have data for a given txid.
1908     // This may (but cannot always) return true for fully spent transactions
1909     virtual bool HaveCoins(uint256 txid);
1910
1911     // Retrieve the block index whose state this CCoinsView currently represents
1912     virtual CBlockIndex *GetBestBlock();
1913
1914     // Modify the currently active block index
1915     virtual bool SetBestBlock(CBlockIndex *pindex);
1916
1917     // Do a bulk modification (multiple SetCoins + one SetBestBlock)
1918     virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1919
1920     // Calculate statistics about the unspent transaction output set
1921     virtual bool GetStats(CCoinsStats &stats);
1922
1923     // As we use CCoinsViews polymorphically, have a virtual destructor
1924     virtual ~CCoinsView() {}
1925 };
1926
1927 /** CCoinsView backed by another CCoinsView */
1928 class CCoinsViewBacked : public CCoinsView
1929 {
1930 protected:
1931     CCoinsView *base;
1932
1933 public:
1934     CCoinsViewBacked(CCoinsView &viewIn);
1935     bool GetCoins(uint256 txid, CCoins &coins);
1936     bool SetCoins(uint256 txid, const CCoins &coins);
1937     bool HaveCoins(uint256 txid);
1938     CBlockIndex *GetBestBlock();
1939     bool SetBestBlock(CBlockIndex *pindex);
1940     void SetBackend(CCoinsView &viewIn);
1941     bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1942     bool GetStats(CCoinsStats &stats);
1943 };
1944
1945 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
1946 class CCoinsViewCache : public CCoinsViewBacked
1947 {
1948 protected:
1949     CBlockIndex *pindexTip;
1950     std::map<uint256,CCoins> cacheCoins;
1951
1952 public:
1953     CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
1954
1955     // Standard CCoinsView methods
1956     bool GetCoins(uint256 txid, CCoins &coins);
1957     bool SetCoins(uint256 txid, const CCoins &coins);
1958     bool HaveCoins(uint256 txid);
1959     CBlockIndex *GetBestBlock();
1960     bool SetBestBlock(CBlockIndex *pindex);
1961     bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1962
1963     // Return a modifiable reference to a CCoins. Check HaveCoins first.
1964     // Many methods explicitly require a CCoinsViewCache because of this method, to reduce
1965     // copying.
1966     CCoins &GetCoins(uint256 txid);
1967
1968     // Push the modifications applied to this cache to its base.
1969     // Failure to call this method before destruction will cause the changes to be forgotten.
1970     bool Flush();
1971
1972     // Calculate the size of the cache (in number of transactions)
1973     unsigned int GetCacheSize();
1974
1975 private:
1976     std::map<uint256,CCoins>::iterator FetchCoins(uint256 txid);
1977 };
1978
1979 /** CCoinsView that brings transactions from a memorypool into view.
1980     It does not check for spendings by memory pool transactions. */
1981 class CCoinsViewMemPool : public CCoinsViewBacked
1982 {
1983 protected:
1984     CTxMemPool &mempool;
1985
1986 public:
1987     CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
1988     bool GetCoins(uint256 txid, CCoins &coins);
1989     bool HaveCoins(uint256 txid);
1990 };
1991
1992 /** Global variable that points to the active CCoinsView (protected by cs_main) */
1993 extern CCoinsViewCache *pcoinsTip;
1994
1995 /** Global variable that points to the active block tree (protected by cs_main) */
1996 extern CBlockTreeDB *pblocktree;
1997
1998 #endif
This page took 0.132263 seconds and 4 git commands to generate.