]> Git Repo - VerusCoin.git/blob - src/chain.h
Make some global variables less-global (static)
[VerusCoin.git] / src / chain.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #ifndef BITCOIN_CHAIN_H
7 #define BITCOIN_CHAIN_H
8
9 #include "arith_uint256.h"
10 #include "primitives/block.h"
11 #include "pow.h"
12 #include "tinyformat.h"
13 #include "uint256.h"
14
15 #include <vector>
16
17 #include <boost/foreach.hpp>
18
19 struct CDiskBlockPos
20 {
21     int nFile;
22     unsigned int nPos;
23
24     ADD_SERIALIZE_METHODS;
25
26     template <typename Stream, typename Operation>
27     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
28         READWRITE(VARINT(nFile));
29         READWRITE(VARINT(nPos));
30     }
31
32     CDiskBlockPos() {
33         SetNull();
34     }
35
36     CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
37         nFile = nFileIn;
38         nPos = nPosIn;
39     }
40
41     friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
42         return (a.nFile == b.nFile && a.nPos == b.nPos);
43     }
44
45     friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
46         return !(a == b);
47     }
48
49     void SetNull() { nFile = -1; nPos = 0; }
50     bool IsNull() const { return (nFile == -1); }
51
52     std::string ToString() const
53     {
54         return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos);
55     }
56
57 };
58
59 enum BlockStatus: uint32_t {
60     //! Unused.
61     BLOCK_VALID_UNKNOWN      =    0,
62
63     //! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
64     BLOCK_VALID_HEADER       =    1,
65
66     //! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
67     //! are also at least TREE.
68     BLOCK_VALID_TREE         =    2,
69
70     /**
71      * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
72      * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
73      * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
74      */
75     BLOCK_VALID_TRANSACTIONS =    3,
76
77     //! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30.
78     //! Implies all parents are also at least CHAIN.
79     BLOCK_VALID_CHAIN        =    4,
80
81     //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
82     BLOCK_VALID_SCRIPTS      =    5,
83
84     //! All validity bits.
85     BLOCK_VALID_MASK         =   BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
86                                  BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
87
88     BLOCK_HAVE_DATA          =    8, //! full block available in blk*.dat
89     BLOCK_HAVE_UNDO          =   16, //! undo data available in rev*.dat
90     BLOCK_HAVE_MASK          =   BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
91
92     BLOCK_FAILED_VALID       =   32, //! stage after last reached validness failed
93     BLOCK_FAILED_CHILD       =   64, //! descends from failed block
94     BLOCK_FAILED_MASK        =   BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
95 };
96
97 /** The block chain is a tree shaped structure starting with the
98  * genesis block at the root, with each block potentially having multiple
99  * candidates to be the next block. A blockindex may have multiple pprev pointing
100  * to it, but at most one of them can be part of the currently active branch.
101  */
102 class CBlockIndex
103 {
104 public:
105     //! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
106     const uint256* phashBlock;
107
108     //! pointer to the index of the predecessor of this block
109     CBlockIndex* pprev;
110
111     //! pointer to the index of some further predecessor of this block
112     CBlockIndex* pskip;
113
114     //! height of the entry in the chain. The genesis block has height 0
115     int nHeight;
116
117     //! Which # file this block is stored in (blk?????.dat)
118     int nFile;
119
120     //! Byte offset within blk?????.dat where this block's data is stored
121     unsigned int nDataPos;
122
123     //! Byte offset within rev?????.dat where this block's undo data is stored
124     unsigned int nUndoPos;
125
126     //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
127     arith_uint256 nChainWork;
128
129     //! Number of transactions in this block.
130     //! Note: in a potential headers-first mode, this number cannot be relied upon
131     unsigned int nTx;
132
133     //! (memory only) Number of transactions in the chain up to and including this block.
134     //! This value will be non-zero only if and only if transactions for this block and all its parents are available.
135     //! Change to 64-bit type when necessary; won't happen before 2030
136     unsigned int nChainTx;
137
138     //! Verification status of this block. See enum BlockStatus
139     unsigned int nStatus;
140
141     //! The anchor for the tree state up to the start of this block
142     uint256 hashAnchor;
143
144     //! (memory only) The anchor for the tree state up to the end of this block
145     uint256 hashAnchorEnd;
146
147     //! block header
148     int nVersion;
149     uint256 hashMerkleRoot;
150     uint256 hashReserved;
151     unsigned int nTime;
152     unsigned int nBits;
153     uint256 nNonce;
154     std::vector<unsigned char> nSolution;
155
156     //! (memory only) Sequential id assigned to distinguish order in which blocks are received.
157     uint32_t nSequenceId;
158
159     void SetNull()
160     {
161         phashBlock = NULL;
162         pprev = NULL;
163         pskip = NULL;
164         nHeight = 0;
165         nFile = 0;
166         nDataPos = 0;
167         nUndoPos = 0;
168         nChainWork = arith_uint256();
169         nTx = 0;
170         nChainTx = 0;
171         nStatus = 0;
172         hashAnchor = uint256();
173         hashAnchorEnd = uint256();
174         nSequenceId = 0;
175
176         nVersion       = 0;
177         hashMerkleRoot = uint256();
178         hashReserved   = uint256();
179         nTime          = 0;
180         nBits          = 0;
181         nNonce         = uint256();
182         nSolution.clear();
183     }
184
185     CBlockIndex()
186     {
187         SetNull();
188     }
189
190     CBlockIndex(const CBlockHeader& block)
191     {
192         SetNull();
193
194         nVersion       = block.nVersion;
195         hashMerkleRoot = block.hashMerkleRoot;
196         hashReserved   = block.hashReserved;
197         nTime          = block.nTime;
198         nBits          = block.nBits;
199         nNonce         = block.nNonce;
200         nSolution      = block.nSolution;
201     }
202
203     CDiskBlockPos GetBlockPos() const {
204         CDiskBlockPos ret;
205         if (nStatus & BLOCK_HAVE_DATA) {
206             ret.nFile = nFile;
207             ret.nPos  = nDataPos;
208         }
209         return ret;
210     }
211
212     CDiskBlockPos GetUndoPos() const {
213         CDiskBlockPos ret;
214         if (nStatus & BLOCK_HAVE_UNDO) {
215             ret.nFile = nFile;
216             ret.nPos  = nUndoPos;
217         }
218         return ret;
219     }
220
221     CBlockHeader GetBlockHeader() const
222     {
223         CBlockHeader block;
224         block.nVersion       = nVersion;
225         if (pprev)
226             block.hashPrevBlock = pprev->GetBlockHash();
227         block.hashMerkleRoot = hashMerkleRoot;
228         block.hashReserved   = hashReserved;
229         block.nTime          = nTime;
230         block.nBits          = nBits;
231         block.nNonce         = nNonce;
232         block.nSolution      = nSolution;
233         return block;
234     }
235
236     uint256 GetBlockHash() const
237     {
238         return *phashBlock;
239     }
240
241     int64_t GetBlockTime() const
242     {
243         return (int64_t)nTime;
244     }
245
246     enum { nMedianTimeSpan=11 };
247
248     int64_t GetMedianTimePast() const
249     {
250         int64_t pmedian[nMedianTimeSpan];
251         int64_t* pbegin = &pmedian[nMedianTimeSpan];
252         int64_t* pend = &pmedian[nMedianTimeSpan];
253
254         const CBlockIndex* pindex = this;
255         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
256             *(--pbegin) = pindex->GetBlockTime();
257
258         std::sort(pbegin, pend);
259         return pbegin[(pend - pbegin)/2];
260     }
261
262     std::string ToString() const
263     {
264         return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
265             pprev, nHeight,
266             hashMerkleRoot.ToString(),
267             GetBlockHash().ToString());
268     }
269
270     //! Check whether this block index entry is valid up to the passed validity level.
271     bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const
272     {
273         assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
274         if (nStatus & BLOCK_FAILED_MASK)
275             return false;
276         return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
277     }
278
279     //! Raise the validity level of this block index entry.
280     //! Returns true if the validity was changed.
281     bool RaiseValidity(enum BlockStatus nUpTo)
282     {
283         assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
284         if (nStatus & BLOCK_FAILED_MASK)
285             return false;
286         if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
287             nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
288             return true;
289         }
290         return false;
291     }
292
293     //! Build the skiplist pointer for this entry.
294     void BuildSkip();
295
296     //! Efficiently find an ancestor of this block.
297     CBlockIndex* GetAncestor(int height);
298     const CBlockIndex* GetAncestor(int height) const;
299 };
300
301 /** Used to marshal pointers into hashes for db storage. */
302 class CDiskBlockIndex : public CBlockIndex
303 {
304 public:
305     uint256 hashPrev;
306
307     CDiskBlockIndex() {
308         hashPrev = uint256();
309     }
310
311     explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
312         hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
313     }
314
315     ADD_SERIALIZE_METHODS;
316
317     template <typename Stream, typename Operation>
318     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
319         if (!(nType & SER_GETHASH))
320             READWRITE(VARINT(nVersion));
321
322         READWRITE(VARINT(nHeight));
323         READWRITE(VARINT(nStatus));
324         READWRITE(VARINT(nTx));
325         if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
326             READWRITE(VARINT(nFile));
327         if (nStatus & BLOCK_HAVE_DATA)
328             READWRITE(VARINT(nDataPos));
329         if (nStatus & BLOCK_HAVE_UNDO)
330             READWRITE(VARINT(nUndoPos));
331         READWRITE(hashAnchor);
332
333         // block header
334         READWRITE(this->nVersion);
335         READWRITE(hashPrev);
336         READWRITE(hashMerkleRoot);
337         READWRITE(hashReserved);
338         READWRITE(nTime);
339         READWRITE(nBits);
340         READWRITE(nNonce);
341         READWRITE(nSolution);
342     }
343
344     uint256 GetBlockHash() const
345     {
346         CBlockHeader block;
347         block.nVersion        = nVersion;
348         block.hashPrevBlock   = hashPrev;
349         block.hashMerkleRoot  = hashMerkleRoot;
350         block.hashReserved    = hashReserved;
351         block.nTime           = nTime;
352         block.nBits           = nBits;
353         block.nNonce          = nNonce;
354         block.nSolution       = nSolution;
355         return block.GetHash();
356     }
357
358
359     std::string ToString() const
360     {
361         std::string str = "CDiskBlockIndex(";
362         str += CBlockIndex::ToString();
363         str += strprintf("\n                hashBlock=%s, hashPrev=%s)",
364             GetBlockHash().ToString(),
365             hashPrev.ToString());
366         return str;
367     }
368 };
369
370 /** An in-memory indexed chain of blocks. */
371 class CChain {
372 private:
373     std::vector<CBlockIndex*> vChain;
374
375 public:
376     /** Returns the index entry for the genesis block of this chain, or NULL if none. */
377     CBlockIndex *Genesis() const {
378         return vChain.size() > 0 ? vChain[0] : NULL;
379     }
380
381     /** Returns the index entry for the tip of this chain, or NULL if none. */
382     CBlockIndex *Tip() const {
383         return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
384     }
385
386     /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
387     CBlockIndex *operator[](int nHeight) const {
388         if (nHeight < 0 || nHeight >= (int)vChain.size())
389             return NULL;
390         return vChain[nHeight];
391     }
392
393     /** Compare two chains efficiently. */
394     friend bool operator==(const CChain &a, const CChain &b) {
395         return a.vChain.size() == b.vChain.size() &&
396                a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
397     }
398
399     /** Efficiently check whether a block is present in this chain. */
400     bool Contains(const CBlockIndex *pindex) const {
401         return (*this)[pindex->nHeight] == pindex;
402     }
403
404     /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
405     CBlockIndex *Next(const CBlockIndex *pindex) const {
406         if (Contains(pindex))
407             return (*this)[pindex->nHeight + 1];
408         else
409             return NULL;
410     }
411
412     /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
413     int Height() const {
414         return vChain.size() - 1;
415     }
416
417     /** Set/initialize a chain with a given tip. */
418     void SetTip(CBlockIndex *pindex);
419
420     /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
421     CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
422
423     /** Find the last common block between this chain and a block index entry. */
424     const CBlockIndex *FindFork(const CBlockIndex *pindex) const;
425 };
426
427 #endif // BITCOIN_CHAIN_H
This page took 0.076552 seconds and 4 git commands to generate.