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