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