]> Git Repo - VerusCoin.git/blob - src/main.h
Merge pull request #4790
[VerusCoin.git] / src / main.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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
6 #ifndef BITCOIN_MAIN_H
7 #define BITCOIN_MAIN_H
8
9 #if defined(HAVE_CONFIG_H)
10 #include "config/bitcoin-config.h"
11 #endif
12
13 #include "chainparams.h"
14 #include "coins.h"
15 #include "core.h"
16 #include "net.h"
17 #include "pow.h"
18 #include "script.h"
19 #include "sync.h"
20 #include "txmempool.h"
21 #include "uint256.h"
22
23 #include <algorithm>
24 #include <exception>
25 #include <map>
26 #include <set>
27 #include <stdint.h>
28 #include <string>
29 #include <utility>
30 #include <vector>
31
32 class CBlockIndex;
33 class CBloomFilter;
34 class CInv;
35
36 /** The maximum allowed size for a serialized block, in bytes (network rule) */
37 static const unsigned int MAX_BLOCK_SIZE = 1000000;
38 /** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/
39 static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 750000;
40 static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
41 /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
42 static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 50000;
43 /** The maximum size for transactions we're willing to relay/mine */
44 static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
45 /** The maximum allowed number of signature check operations in a block (network rule) */
46 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
47 /** Maxiumum number of signature check operations in an IsStandard() P2SH script */
48 static const unsigned int MAX_P2SH_SIGOPS = 15;
49 /** The maximum number of sigops we're willing to relay/mine in a single tx */
50 static const unsigned int MAX_TX_SIGOPS = MAX_BLOCK_SIGOPS/5;
51 /** The maximum number of orphan transactions kept in memory */
52 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
53 /** Default for -maxorphanblocks, maximum number of orphan blocks kept in memory */
54 static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS = 750;
55 /** The maximum size of a blk?????.dat file (since 0.8) */
56 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
57 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
58 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
59 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
60 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
61 /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
62 static const int COINBASE_MATURITY = 100;
63 /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
64 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
65 /** Maximum number of script-checking threads allowed */
66 static const int MAX_SCRIPTCHECK_THREADS = 16;
67 /** -par default (number of script-checking threads, 0 = auto) */
68 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
69 /** Number of blocks that can be requested at any given time from a single peer. */
70 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 128;
71 /** Timeout in seconds before considering a block download peer unresponsive. */
72 static const unsigned int BLOCK_DOWNLOAD_TIMEOUT = 60;
73
74 /** "reject" message codes **/
75 static const unsigned char REJECT_MALFORMED = 0x01;
76 static const unsigned char REJECT_INVALID = 0x10;
77 static const unsigned char REJECT_OBSOLETE = 0x11;
78 static const unsigned char REJECT_DUPLICATE = 0x12;
79 static const unsigned char REJECT_NONSTANDARD = 0x40;
80 static const unsigned char REJECT_DUST = 0x41;
81 static const unsigned char REJECT_INSUFFICIENTFEE = 0x42;
82 static const unsigned char REJECT_CHECKPOINT = 0x43;
83
84
85 extern CScript COINBASE_FLAGS;
86 extern CCriticalSection cs_main;
87 extern CTxMemPool mempool;
88 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
89 extern uint64_t nLastBlockTx;
90 extern uint64_t nLastBlockSize;
91 extern const std::string strMessageMagic;
92 extern int64_t nTimeBestReceived;
93 extern CWaitableCriticalSection csBestBlock;
94 extern CConditionVariable cvBlockChange;
95 extern bool fImporting;
96 extern bool fReindex;
97 extern int nScriptCheckThreads;
98 extern bool fTxIndex;
99 extern bool fIsBareMultisigStd;
100 extern unsigned int nCoinCacheSize;
101 extern CFeeRate minRelayTxFee;
102
103 // Minimum disk space required - used in CheckDiskSpace()
104 static const uint64_t nMinDiskSpace = 52428800;
105
106
107 class CBlockTreeDB;
108 struct CDiskBlockPos;
109 class CTxUndo;
110 class CScriptCheck;
111 class CValidationState;
112 class CWalletInterface;
113 struct CNodeStateStats;
114
115 struct CBlockTemplate;
116
117 /** Register a wallet to receive updates from core */
118 void RegisterWallet(CWalletInterface* pwalletIn);
119 /** Unregister a wallet from core */
120 void UnregisterWallet(CWalletInterface* pwalletIn);
121 /** Unregister all wallets from core */
122 void UnregisterAllWallets();
123 /** Push an updated transaction to all registered wallets */
124 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL);
125
126 /** Register with a network node to receive its signals */
127 void RegisterNodeSignals(CNodeSignals& nodeSignals);
128 /** Unregister a network node */
129 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
130
131 void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd);
132
133 /** Process an incoming block */
134 bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
135 /** Check whether enough disk space is available for an incoming block */
136 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
137 /** Open a block file (blk?????.dat) */
138 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
139 /** Open an undo file (rev?????.dat) */
140 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
141 /** Import blocks from an external file */
142 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
143 /** Initialize a new block tree database + block data on disk */
144 bool InitBlockIndex();
145 /** Load the block tree and coins database from disk */
146 bool LoadBlockIndex();
147 /** Unload database information */
148 void UnloadBlockIndex();
149 /** Print the loaded block tree */
150 void PrintBlockTree();
151 /** Process protocol messages received from a given node */
152 bool ProcessMessages(CNode* pfrom);
153 /** Send queued protocol messages to be sent to a give node */
154 bool SendMessages(CNode* pto, bool fSendTrickle);
155 /** Run an instance of the script checking thread */
156 void ThreadScriptCheck();
157 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
158 bool IsInitialBlockDownload();
159 /** Format a string that describes several potential problems detected by the core */
160 std::string GetWarnings(std::string strFor);
161 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
162 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
163 /** Find the best known block, and make it the tip of the block chain */
164 bool ActivateBestChain(CValidationState &state, CBlock *pblock = NULL);
165 int64_t GetBlockValue(int nHeight, int64_t nFees);
166
167 /** Create a new block index entry for a given block hash */
168 CBlockIndex * InsertBlockIndex(uint256 hash);
169 /** Verify a signature */
170 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
171 /** Abort with a message */
172 bool AbortNode(const std::string &msg);
173 /** Get statistics from node state */
174 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
175 /** Increase a node's misbehavior score. */
176 void Misbehaving(NodeId nodeid, int howmuch);
177
178
179 /** (try to) add transaction to memory pool **/
180 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
181                         bool* pfMissingInputs, bool fRejectInsaneFee=false);
182
183
184
185
186
187
188
189
190 struct CNodeStateStats {
191     int nMisbehavior;
192     int nSyncHeight;
193 };
194
195 struct CDiskBlockPos
196 {
197     int nFile;
198     unsigned int nPos;
199
200     ADD_SERIALIZE_METHODS;
201
202     template <typename Stream, typename Operation>
203     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
204         READWRITE(VARINT(nFile));
205         READWRITE(VARINT(nPos));
206     }
207
208     CDiskBlockPos() {
209         SetNull();
210     }
211
212     CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
213         nFile = nFileIn;
214         nPos = nPosIn;
215     }
216
217     friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
218         return (a.nFile == b.nFile && a.nPos == b.nPos);
219     }
220
221     friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
222         return !(a == b);
223     }
224
225     void SetNull() { nFile = -1; nPos = 0; }
226     bool IsNull() const { return (nFile == -1); }
227 };
228
229 struct CDiskTxPos : public CDiskBlockPos
230 {
231     unsigned int nTxOffset; // after header
232
233     ADD_SERIALIZE_METHODS;
234
235     template <typename Stream, typename Operation>
236     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
237         READWRITE(*(CDiskBlockPos*)this);
238         READWRITE(VARINT(nTxOffset));
239     }
240
241     CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
242     }
243
244     CDiskTxPos() {
245         SetNull();
246     }
247
248     void SetNull() {
249         CDiskBlockPos::SetNull();
250         nTxOffset = 0;
251     }
252 };
253
254
255 int64_t GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
256
257 //
258 // Check transaction inputs, and make sure any
259 // pay-to-script-hash transactions are evaluating IsStandard scripts
260 //
261 // Why bother? To avoid denial-of-service attacks; an attacker
262 // can submit a standard HASH... OP_EQUAL transaction,
263 // which will get accepted into blocks. The redemption
264 // script can be anything; an attacker could use a very
265 // expensive-to-check-upon-redemption script like:
266 //   DUP CHECKSIG DROP ... repeated 100 times... OP_1
267 //
268
269 /** Check for standard transaction types
270     @param[in] mapInputs    Map of previous transactions that have outputs we're spending
271     @return True if all inputs (scriptSigs) use only standard transaction forms
272 */
273 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs);
274
275 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
276     @return number of sigops this transaction's outputs will produce when spent
277     @see CTransaction::FetchInputs
278 */
279 unsigned int GetLegacySigOpCount(const CTransaction& tx);
280
281 /** Count ECDSA signature operations in pay-to-script-hash inputs.
282
283     @param[in] mapInputs        Map of previous transactions that have outputs we're spending
284     @return maximum number of sigops required to validate this transaction's inputs
285     @see CTransaction::FetchInputs
286  */
287 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
288
289
290 // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
291 // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
292 // instead of being performed inline.
293 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks = true,
294                  unsigned int flags = STANDARD_SCRIPT_VERIFY_FLAGS,
295                  std::vector<CScriptCheck> *pvChecks = NULL);
296
297 // Apply the effects of this transaction on the UTXO set represented by view
298 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight);
299
300 // Context-independent validity checks
301 bool CheckTransaction(const CTransaction& tx, CValidationState& state);
302
303 /** Check for standard transaction types
304     @return True if all outputs (scriptPubKeys) use only standard transaction forms
305 */
306 bool IsStandardTx(const CTransaction& tx, std::string& reason);
307
308 bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0);
309
310 /** Undo information for a CBlock */
311 class CBlockUndo
312 {
313 public:
314     std::vector<CTxUndo> vtxundo; // for all but the coinbase
315
316     ADD_SERIALIZE_METHODS;
317
318     template <typename Stream, typename Operation>
319     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
320         READWRITE(vtxundo);
321     }
322
323     bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock);
324     bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock);
325 };
326
327
328 /** Closure representing one script verification
329  *  Note that this stores references to the spending transaction */
330 class CScriptCheck
331 {
332 private:
333     CScript scriptPubKey;
334     const CTransaction *ptxTo;
335     unsigned int nIn;
336     unsigned int nFlags;
337     int nHashType;
338
339 public:
340     CScriptCheck(): ptxTo(0), nIn(0), nFlags(0), nHashType(0) {}
341     CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
342         scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
343         ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
344
345     bool operator()() const;
346
347     void swap(CScriptCheck &check) {
348         scriptPubKey.swap(check.scriptPubKey);
349         std::swap(ptxTo, check.ptxTo);
350         std::swap(nIn, check.nIn);
351         std::swap(nFlags, check.nFlags);
352         std::swap(nHashType, check.nHashType);
353     }
354 };
355
356 /** Data structure that represents a partial merkle tree.
357  *
358  * It respresents a subset of the txid's of a known block, in a way that
359  * allows recovery of the list of txid's and the merkle root, in an
360  * authenticated way.
361  *
362  * The encoding works as follows: we traverse the tree in depth-first order,
363  * storing a bit for each traversed node, signifying whether the node is the
364  * parent of at least one matched leaf txid (or a matched txid itself). In
365  * case we are at the leaf level, or this bit is 0, its merkle node hash is
366  * stored, and its children are not explorer further. Otherwise, no hash is
367  * stored, but we recurse into both (or the only) child branch. During
368  * decoding, the same depth-first traversal is performed, consuming bits and
369  * hashes as they written during encoding.
370  *
371  * The serialization is fixed and provides a hard guarantee about the
372  * encoded size:
373  *
374  *   SIZE <= 10 + ceil(32.25*N)
375  *
376  * Where N represents the number of leaf nodes of the partial tree. N itself
377  * is bounded by:
378  *
379  *   N <= total_transactions
380  *   N <= 1 + matched_transactions*tree_height
381  *
382  * The serialization format:
383  *  - uint32     total_transactions (4 bytes)
384  *  - varint     number of hashes   (1-3 bytes)
385  *  - uint256[]  hashes in depth-first order (<= 32*N bytes)
386  *  - varint     number of bytes of flag bits (1-3 bytes)
387  *  - byte[]     flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
388  * The size constraints follow from this.
389  */
390 class CPartialMerkleTree
391 {
392 protected:
393     // the total number of transactions in the block
394     unsigned int nTransactions;
395
396     // node-is-parent-of-matched-txid bits
397     std::vector<bool> vBits;
398
399     // txids and internal hashes
400     std::vector<uint256> vHash;
401
402     // flag set when encountering invalid data
403     bool fBad;
404
405     // helper function to efficiently calculate the number of nodes at given height in the merkle tree
406     unsigned int CalcTreeWidth(int height) {
407         return (nTransactions+(1 << height)-1) >> height;
408     }
409
410     // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
411     uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
412
413     // recursive function that traverses tree nodes, storing the data as bits and hashes
414     void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
415
416     // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
417     // it returns the hash of the respective node.
418     uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
419
420 public:
421
422     // serialization implementation
423     ADD_SERIALIZE_METHODS;
424
425     template <typename Stream, typename Operation>
426     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
427         READWRITE(nTransactions);
428         READWRITE(vHash);
429         std::vector<unsigned char> vBytes;
430         if (ser_action.ForRead()) {
431             READWRITE(vBytes);
432             CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
433             us.vBits.resize(vBytes.size() * 8);
434             for (unsigned int p = 0; p < us.vBits.size(); p++)
435                 us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
436             us.fBad = false;
437         } else {
438             vBytes.resize((vBits.size()+7)/8);
439             for (unsigned int p = 0; p < vBits.size(); p++)
440                 vBytes[p / 8] |= vBits[p] << (p % 8);
441             READWRITE(vBytes);
442         }
443     }
444
445     // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
446     CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
447
448     CPartialMerkleTree();
449
450     // extract the matching txid's represented by this partial merkle tree.
451     // returns the merkle root, or 0 in case of failure
452     uint256 ExtractMatches(std::vector<uint256> &vMatch);
453 };
454
455
456
457 /** Functions for disk access for blocks */
458 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos);
459 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos);
460 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex);
461
462
463 /** Functions for validating blocks and updating the block tree */
464
465 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
466  *  In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
467  *  will be true if no problems were found. Otherwise, the return value will be false in case
468  *  of problems. Note that in any case, coins may be modified. */
469 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
470
471 // Apply the effects of this block (with given index) on the UTXO set represented by coins
472 bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
473
474 // Add this block to the block index, and if necessary, switch the active block chain to this
475 bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos);
476
477 // Context-independent validity checks
478 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
479 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
480
481 // Store block on disk
482 // if dbp is provided, the file is known to already reside on disk
483 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex **pindex, CDiskBlockPos* dbp = NULL);
484 bool AcceptBlockHeader(CBlockHeader& block, CValidationState& state, CBlockIndex **ppindex= NULL);
485
486
487
488 class CBlockFileInfo
489 {
490 public:
491     unsigned int nBlocks;      // number of blocks stored in file
492     unsigned int nSize;        // number of used bytes of block file
493     unsigned int nUndoSize;    // number of used bytes in the undo file
494     unsigned int nHeightFirst; // lowest height of block in file
495     unsigned int nHeightLast;  // highest height of block in file
496     uint64_t nTimeFirst;         // earliest time of block in file
497     uint64_t nTimeLast;          // latest time of block in file
498
499     ADD_SERIALIZE_METHODS;
500
501     template <typename Stream, typename Operation>
502     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
503         READWRITE(VARINT(nBlocks));
504         READWRITE(VARINT(nSize));
505         READWRITE(VARINT(nUndoSize));
506         READWRITE(VARINT(nHeightFirst));
507         READWRITE(VARINT(nHeightLast));
508         READWRITE(VARINT(nTimeFirst));
509         READWRITE(VARINT(nTimeLast));
510     }
511
512      void SetNull() {
513          nBlocks = 0;
514          nSize = 0;
515          nUndoSize = 0;
516          nHeightFirst = 0;
517          nHeightLast = 0;
518          nTimeFirst = 0;
519          nTimeLast = 0;
520      }
521
522      CBlockFileInfo() {
523          SetNull();
524      }
525
526      std::string ToString() const;
527
528      // update statistics (does not update nSize)
529      void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
530          if (nBlocks==0 || nHeightFirst > nHeightIn)
531              nHeightFirst = nHeightIn;
532          if (nBlocks==0 || nTimeFirst > nTimeIn)
533              nTimeFirst = nTimeIn;
534          nBlocks++;
535          if (nHeightIn > nHeightLast)
536              nHeightLast = nHeightIn;
537          if (nTimeIn > nTimeLast)
538              nTimeLast = nTimeIn;
539      }
540 };
541
542 enum BlockStatus {
543     BLOCK_VALID_UNKNOWN      =    0,
544     BLOCK_VALID_HEADER       =    1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
545     BLOCK_VALID_TREE         =    2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
546     BLOCK_VALID_TRANSACTIONS =    3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
547     BLOCK_VALID_CHAIN        =    4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
548     BLOCK_VALID_SCRIPTS      =    5, // scripts/signatures ok
549     BLOCK_VALID_MASK         =   BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
550                                  BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
551
552     BLOCK_HAVE_DATA          =    8, // full block available in blk*.dat
553     BLOCK_HAVE_UNDO          =   16, // undo data available in rev*.dat
554     BLOCK_HAVE_MASK          =   BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
555
556     BLOCK_FAILED_VALID       =   32, // stage after last reached validness failed
557     BLOCK_FAILED_CHILD       =   64, // descends from failed block
558     BLOCK_FAILED_MASK        =   BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
559 };
560
561 /** The block chain is a tree shaped structure starting with the
562  * genesis block at the root, with each block potentially having multiple
563  * candidates to be the next block. A blockindex may have multiple pprev pointing
564  * to it, but at most one of them can be part of the currently active branch.
565  */
566 class CBlockIndex
567 {
568 public:
569     // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
570     const uint256* phashBlock;
571
572     // pointer to the index of the predecessor of this block
573     CBlockIndex* pprev;
574
575     // pointer to the index of some further predecessor of this block
576     CBlockIndex* pskip;
577
578     // height of the entry in the chain. The genesis block has height 0
579     int nHeight;
580
581     // Which # file this block is stored in (blk?????.dat)
582     int nFile;
583
584     // Byte offset within blk?????.dat where this block's data is stored
585     unsigned int nDataPos;
586
587     // Byte offset within rev?????.dat where this block's undo data is stored
588     unsigned int nUndoPos;
589
590     // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
591     uint256 nChainWork;
592
593     // Number of transactions in this block.
594     // Note: in a potential headers-first mode, this number cannot be relied upon
595     unsigned int nTx;
596
597     // (memory only) Number of transactions in the chain up to and including this block
598     unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
599
600     // Verification status of this block. See enum BlockStatus
601     unsigned int nStatus;
602
603     // block header
604     int nVersion;
605     uint256 hashMerkleRoot;
606     unsigned int nTime;
607     unsigned int nBits;
608     unsigned int nNonce;
609
610     // (memory only) Sequencial id assigned to distinguish order in which blocks are received.
611     uint32_t nSequenceId;
612
613     void SetNull()
614     {
615         phashBlock = NULL;
616         pprev = NULL;
617         pskip = NULL;
618         nHeight = 0;
619         nFile = 0;
620         nDataPos = 0;
621         nUndoPos = 0;
622         nChainWork = 0;
623         nTx = 0;
624         nChainTx = 0;
625         nStatus = 0;
626         nSequenceId = 0;
627
628         nVersion       = 0;
629         hashMerkleRoot = 0;
630         nTime          = 0;
631         nBits          = 0;
632         nNonce         = 0;
633     }
634
635     CBlockIndex()
636     {
637         SetNull();
638     }
639
640     CBlockIndex(CBlockHeader& block)
641     {
642         SetNull();
643
644         nVersion       = block.nVersion;
645         hashMerkleRoot = block.hashMerkleRoot;
646         nTime          = block.nTime;
647         nBits          = block.nBits;
648         nNonce         = block.nNonce;
649     }
650
651     CDiskBlockPos GetBlockPos() const {
652         CDiskBlockPos ret;
653         if (nStatus & BLOCK_HAVE_DATA) {
654             ret.nFile = nFile;
655             ret.nPos  = nDataPos;
656         }
657         return ret;
658     }
659
660     CDiskBlockPos GetUndoPos() const {
661         CDiskBlockPos ret;
662         if (nStatus & BLOCK_HAVE_UNDO) {
663             ret.nFile = nFile;
664             ret.nPos  = nUndoPos;
665         }
666         return ret;
667     }
668
669     CBlockHeader GetBlockHeader() const
670     {
671         CBlockHeader block;
672         block.nVersion       = nVersion;
673         if (pprev)
674             block.hashPrevBlock = pprev->GetBlockHash();
675         block.hashMerkleRoot = hashMerkleRoot;
676         block.nTime          = nTime;
677         block.nBits          = nBits;
678         block.nNonce         = nNonce;
679         return block;
680     }
681
682     uint256 GetBlockHash() const
683     {
684         return *phashBlock;
685     }
686
687     int64_t GetBlockTime() const
688     {
689         return (int64_t)nTime;
690     }
691
692     uint256 GetBlockWork() const
693     {
694         return GetProofIncrement(nBits);
695     }
696
697     enum { nMedianTimeSpan=11 };
698
699     int64_t GetMedianTimePast() const
700     {
701         int64_t pmedian[nMedianTimeSpan];
702         int64_t* pbegin = &pmedian[nMedianTimeSpan];
703         int64_t* pend = &pmedian[nMedianTimeSpan];
704
705         const CBlockIndex* pindex = this;
706         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
707             *(--pbegin) = pindex->GetBlockTime();
708
709         std::sort(pbegin, pend);
710         return pbegin[(pend - pbegin)/2];
711     }
712
713     /**
714      * Returns true if there are nRequired or more blocks of minVersion or above
715      * in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart 
716      * and going backwards.
717      */
718     static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
719                                 unsigned int nRequired);
720
721     std::string ToString() const
722     {
723         return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
724             pprev, nHeight,
725             hashMerkleRoot.ToString(),
726             GetBlockHash().ToString());
727     }
728
729     // Check whether this block index entry is valid up to the passed validity level.
730     bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
731     {
732         assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
733         if (nStatus & BLOCK_FAILED_MASK)
734             return false;
735         return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
736     }
737
738     // Raise the validity level of this block index entry.
739     // Returns true if the validity was changed.
740     bool RaiseValidity(enum BlockStatus nUpTo)
741     {
742         assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
743         if (nStatus & BLOCK_FAILED_MASK)
744             return false;
745         if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
746             nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
747             return true;
748         }
749         return false;
750     }
751
752     // Build the skiplist pointer for this entry.
753     void BuildSkip();
754
755     // Efficiently find an ancestor of this block.
756     CBlockIndex* GetAncestor(int height);
757     const CBlockIndex* GetAncestor(int height) const;
758 };
759
760 /** Used to marshal pointers into hashes for db storage. */
761 class CDiskBlockIndex : public CBlockIndex
762 {
763 public:
764     uint256 hashPrev;
765
766     CDiskBlockIndex() {
767         hashPrev = 0;
768     }
769
770     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
771         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
772     }
773
774     ADD_SERIALIZE_METHODS;
775
776     template <typename Stream, typename Operation>
777     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
778         if (!(nType & SER_GETHASH))
779             READWRITE(VARINT(nVersion));
780
781         READWRITE(VARINT(nHeight));
782         READWRITE(VARINT(nStatus));
783         READWRITE(VARINT(nTx));
784         if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
785             READWRITE(VARINT(nFile));
786         if (nStatus & BLOCK_HAVE_DATA)
787             READWRITE(VARINT(nDataPos));
788         if (nStatus & BLOCK_HAVE_UNDO)
789             READWRITE(VARINT(nUndoPos));
790
791         // block header
792         READWRITE(this->nVersion);
793         READWRITE(hashPrev);
794         READWRITE(hashMerkleRoot);
795         READWRITE(nTime);
796         READWRITE(nBits);
797         READWRITE(nNonce);
798     }
799
800     uint256 GetBlockHash() const
801     {
802         CBlockHeader block;
803         block.nVersion        = nVersion;
804         block.hashPrevBlock   = hashPrev;
805         block.hashMerkleRoot  = hashMerkleRoot;
806         block.nTime           = nTime;
807         block.nBits           = nBits;
808         block.nNonce          = nNonce;
809         return block.GetHash();
810     }
811
812
813     std::string ToString() const
814     {
815         std::string str = "CDiskBlockIndex(";
816         str += CBlockIndex::ToString();
817         str += strprintf("\n                hashBlock=%s, hashPrev=%s)",
818             GetBlockHash().ToString(),
819             hashPrev.ToString());
820         return str;
821     }
822 };
823
824 /** Capture information about block/transaction validation */
825 class CValidationState {
826 private:
827     enum mode_state {
828         MODE_VALID,   // everything ok
829         MODE_INVALID, // network rule violation (DoS value may be set)
830         MODE_ERROR,   // run-time error
831     } mode;
832     int nDoS;
833     std::string strRejectReason;
834     unsigned char chRejectCode;
835     bool corruptionPossible;
836 public:
837     CValidationState() : mode(MODE_VALID), nDoS(0), chRejectCode(0), corruptionPossible(false) {}
838     bool DoS(int level, bool ret = false,
839              unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="",
840              bool corruptionIn=false) {
841         chRejectCode = chRejectCodeIn;
842         strRejectReason = strRejectReasonIn;
843         corruptionPossible = corruptionIn;
844         if (mode == MODE_ERROR)
845             return ret;
846         nDoS += level;
847         mode = MODE_INVALID;
848         return ret;
849     }
850     bool Invalid(bool ret = false,
851                  unsigned char _chRejectCode=0, std::string _strRejectReason="") {
852         return DoS(0, ret, _chRejectCode, _strRejectReason);
853     }
854     bool Error(std::string strRejectReasonIn="") {
855         if (mode == MODE_VALID)
856             strRejectReason = strRejectReasonIn;
857         mode = MODE_ERROR;
858         return false;
859     }
860     bool Abort(const std::string &msg) {
861         AbortNode(msg);
862         return Error(msg);
863     }
864     bool IsValid() const {
865         return mode == MODE_VALID;
866     }
867     bool IsInvalid() const {
868         return mode == MODE_INVALID;
869     }
870     bool IsError() const {
871         return mode == MODE_ERROR;
872     }
873     bool IsInvalid(int &nDoSOut) const {
874         if (IsInvalid()) {
875             nDoSOut = nDoS;
876             return true;
877         }
878         return false;
879     }
880     bool CorruptionPossible() const {
881         return corruptionPossible;
882     }
883     unsigned char GetRejectCode() const { return chRejectCode; }
884     std::string GetRejectReason() const { return strRejectReason; }
885 };
886
887 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
888 class CVerifyDB {
889 public:
890     CVerifyDB();
891     ~CVerifyDB();
892     bool VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
893 };
894
895 /** An in-memory indexed chain of blocks. */
896 class CChain {
897 private:
898     std::vector<CBlockIndex*> vChain;
899
900 public:
901     /** Returns the index entry for the genesis block of this chain, or NULL if none. */
902     CBlockIndex *Genesis() const {
903         return vChain.size() > 0 ? vChain[0] : NULL;
904     }
905
906     /** Returns the index entry for the tip of this chain, or NULL if none. */
907     CBlockIndex *Tip() const {
908         return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
909     }
910
911     /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
912     CBlockIndex *operator[](int nHeight) const {
913         if (nHeight < 0 || nHeight >= (int)vChain.size())
914             return NULL;
915         return vChain[nHeight];
916     }
917
918     /** Compare two chains efficiently. */
919     friend bool operator==(const CChain &a, const CChain &b) {
920         return a.vChain.size() == b.vChain.size() &&
921                a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
922     }
923
924     /** Efficiently check whether a block is present in this chain. */
925     bool Contains(const CBlockIndex *pindex) const {
926         return (*this)[pindex->nHeight] == pindex;
927     }
928
929     /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
930     CBlockIndex *Next(const CBlockIndex *pindex) const {
931         if (Contains(pindex))
932             return (*this)[pindex->nHeight + 1];
933         else
934             return NULL;
935     }
936
937     /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
938     int Height() const {
939         return vChain.size() - 1;
940     }
941
942     /** Set/initialize a chain with a given tip. Returns the forking point. */
943     CBlockIndex *SetTip(CBlockIndex *pindex);
944
945     /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
946     CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
947
948     /** Find the last common block between this chain and a locator. */
949     CBlockIndex *FindFork(const CBlockLocator &locator) const;
950
951     /** Find the last common block between this chain and a block index entry. */
952     const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
953 };
954
955 /** The currently-connected chain of blocks. */
956 extern CChain chainActive;
957
958 /** Global variable that points to the active CCoinsView (protected by cs_main) */
959 extern CCoinsViewCache *pcoinsTip;
960
961 /** Global variable that points to the active block tree (protected by cs_main) */
962 extern CBlockTreeDB *pblocktree;
963
964 struct CBlockTemplate
965 {
966     CBlock block;
967     std::vector<int64_t> vTxFees;
968     std::vector<int64_t> vTxSigOps;
969 };
970
971
972
973
974
975
976 /** Used to relay blocks as header + vector<merkle branch>
977  * to filtered nodes.
978  */
979 class CMerkleBlock
980 {
981 public:
982     // Public only for unit testing
983     CBlockHeader header;
984     CPartialMerkleTree txn;
985
986 public:
987     // Public only for unit testing and relay testing
988     // (not relayed)
989     std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
990
991     // Create from a CBlock, filtering transactions according to filter
992     // Note that this will call IsRelevantAndUpdate on the filter for each transaction,
993     // thus the filter will likely be modified.
994     CMerkleBlock(const CBlock& block, CBloomFilter& filter);
995
996     ADD_SERIALIZE_METHODS;
997
998     template <typename Stream, typename Operation>
999     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
1000         READWRITE(header);
1001         READWRITE(txn);
1002     }
1003 };
1004
1005
1006 class CWalletInterface {
1007 protected:
1008     virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock) =0;
1009     virtual void EraseFromWallet(const uint256 &hash) =0;
1010     virtual void SetBestChain(const CBlockLocator &locator) =0;
1011     virtual void UpdatedTransaction(const uint256 &hash) =0;
1012     virtual void Inventory(const uint256 &hash) =0;
1013     virtual void ResendWalletTransactions() =0;
1014     friend void ::RegisterWallet(CWalletInterface*);
1015     friend void ::UnregisterWallet(CWalletInterface*);
1016     friend void ::UnregisterAllWallets();
1017 };
1018
1019 #endif // BITCOIN_MAIN_H
This page took 0.07842 seconds and 4 git commands to generate.