]> Git Repo - VerusCoin.git/blob - src/coins.h
Catch mined PoS lookalike blocks
[VerusCoin.git] / src / coins.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_COINS_H
7 #define BITCOIN_COINS_H
8
9 #define KOMODO_ENABLE_INTEREST //enabling this is a hardfork, activate with new RR method
10
11 #include "compressor.h"
12 #include "core_memusage.h"
13 #include "memusage.h"
14 #include "serialize.h"
15 #include "uint256.h"
16
17 #include <assert.h>
18 #include <stdint.h>
19
20 #include <boost/foreach.hpp>
21 #include <boost/unordered_map.hpp>
22 #include "zcash/IncrementalMerkleTree.hpp"
23
24 /** 
25  * Pruned version of CTransaction: only retains metadata and unspent transaction outputs
26  *
27  * Serialized format:
28  * - VARINT(nVersion)
29  * - VARINT(nCode)
30  * - unspentness bitvector, for vout[2] and further; least significant byte first
31  * - the non-spent CTxOuts (via CTxOutCompressor)
32  * - VARINT(nHeight)
33  *
34  * The nCode value consists of:
35  * - bit 1: IsCoinBase()
36  * - bit 2: vout[0] is not spent
37  * - bit 4: vout[1] is not spent
38  * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
39  *   - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
40  *     least one non-spent output).
41  *
42  * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
43  *          <><><--------------------------------------------><---->
44  *          |  \                  |                             /
45  *    version   code             vout[1]                  height
46  *
47  *    - version = 1
48  *    - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
49  *    - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
50  *    - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
51  *               * 8358: compact amount representation for 60000000000 (600 BTC)
52  *               * 00: special txout type pay-to-pubkey-hash
53  *               * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
54  *    - height = 203998
55  *
56  *
57  * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
58  *          <><><--><--------------------------------------------------><----------------------------------------------><---->
59  *         /  \   \                     |                                                           |                     /
60  *  version  code  unspentness       vout[4]                                                     vout[16]           height
61  *
62  *  - version = 1
63  *  - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
64  *                2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
65  *  - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
66  *  - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
67  *             * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
68  *             * 00: special txout type pay-to-pubkey-hash
69  *             * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
70  *  - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
71  *              * bbd123: compact amount representation for 110397 (0.001 BTC)
72  *              * 00: special txout type pay-to-pubkey-hash
73  *              * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
74  *  - height = 120891
75  */
76 class CCoins
77 {
78 public:
79     //! whether transaction is a coinbase
80     bool fCoinBase;
81
82     //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
83     std::vector<CTxOut> vout;
84
85     //! at which height this transaction was included in the active block chain
86     int nHeight;
87
88     //! version of the CTransaction; accesses to this value should probably check for nHeight as well,
89     //! as new tx version will probably only be introduced at certain heights
90     int nVersion;
91     //uint32_t nLockTime;
92
93     void FromTx(const CTransaction &tx, int nHeightIn) {
94         fCoinBase = tx.IsCoinBase();
95         vout = tx.vout;
96         nHeight = nHeightIn;
97         nVersion = tx.nVersion;
98         //nLockTime = tx.nLockTime;
99         ClearUnspendable();
100     }
101
102     //! construct a CCoins from a CTransaction, at a given height
103     CCoins(const CTransaction &tx, int nHeightIn) {
104         FromTx(tx, nHeightIn);
105     }
106
107     void Clear() {
108         fCoinBase = false;
109         std::vector<CTxOut>().swap(vout);
110         nHeight = 0;
111         nVersion = 0;
112     }
113
114     //! empty constructor
115     CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
116
117     //!remove spent outputs at the end of vout
118     void Cleanup() {
119         while (vout.size() > 0 && vout.back().IsNull())
120             vout.pop_back();
121         if (vout.empty())
122             std::vector<CTxOut>().swap(vout);
123     }
124
125     void ClearUnspendable() {
126         BOOST_FOREACH(CTxOut &txout, vout) {
127             if (txout.scriptPubKey.IsUnspendable())
128                 txout.SetNull();
129         }
130         Cleanup();
131     }
132
133     void swap(CCoins &to) {
134         std::swap(to.fCoinBase, fCoinBase);
135         to.vout.swap(vout);
136         std::swap(to.nHeight, nHeight);
137         std::swap(to.nVersion, nVersion);
138     }
139
140     //! equality test
141     friend bool operator==(const CCoins &a, const CCoins &b) {
142          // Empty CCoins objects are always equal.
143          if (a.IsPruned() && b.IsPruned())
144              return true;
145          return a.fCoinBase == b.fCoinBase &&
146                 a.nHeight == b.nHeight &&
147                 a.nVersion == b.nVersion &&
148                 a.vout == b.vout;
149     }
150     friend bool operator!=(const CCoins &a, const CCoins &b) {
151         return !(a == b);
152     }
153
154     void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
155
156     bool IsCoinBase() const {
157         return fCoinBase;
158     }
159
160     unsigned int GetSerializeSize(int nType, int nVersion) const {
161         unsigned int nSize = 0;
162         unsigned int nMaskSize = 0, nMaskCode = 0;
163         CalcMaskSize(nMaskSize, nMaskCode);
164         bool fFirst = vout.size() > 0 && !vout[0].IsNull();
165         bool fSecond = vout.size() > 1 && !vout[1].IsNull();
166         assert(fFirst || fSecond || nMaskCode);
167         unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
168         // version
169         nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
170         // size of header code
171         nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
172         // spentness bitmask
173         nSize += nMaskSize;
174         // txouts
175         for (unsigned int i = 0; i < vout.size(); i++)
176             if (!vout[i].IsNull())
177                 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
178         // height
179         nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
180         return nSize;
181     }
182
183     template<typename Stream>
184     void Serialize(Stream &s, int nType, int nVersion) const {
185         unsigned int nMaskSize = 0, nMaskCode = 0;
186         CalcMaskSize(nMaskSize, nMaskCode);
187         bool fFirst = vout.size() > 0 && !vout[0].IsNull();
188         bool fSecond = vout.size() > 1 && !vout[1].IsNull();
189         assert(fFirst || fSecond || nMaskCode);
190         unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
191         // version
192         ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
193         // header code
194         ::Serialize(s, VARINT(nCode), nType, nVersion);
195         // spentness bitmask
196         for (unsigned int b = 0; b<nMaskSize; b++) {
197             unsigned char chAvail = 0;
198             for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
199                 if (!vout[2+b*8+i].IsNull())
200                     chAvail |= (1 << i);
201             ::Serialize(s, chAvail, nType, nVersion);
202         }
203         // txouts themself
204         for (unsigned int i = 0; i < vout.size(); i++) {
205             if (!vout[i].IsNull())
206                 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
207         }
208         // coinbase height
209         ::Serialize(s, VARINT(nHeight), nType, nVersion);
210     }
211
212     template<typename Stream>
213     void Unserialize(Stream &s, int nType, int nVersion) {
214         unsigned int nCode = 0;
215         // version
216         ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
217         // header code
218         ::Unserialize(s, VARINT(nCode), nType, nVersion);
219         fCoinBase = nCode & 1;
220         std::vector<bool> vAvail(2, false);
221         vAvail[0] = (nCode & 2) != 0;
222         vAvail[1] = (nCode & 4) != 0;
223         unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
224         // spentness bitmask
225         while (nMaskCode > 0) {
226             unsigned char chAvail = 0;
227             ::Unserialize(s, chAvail, nType, nVersion);
228             for (unsigned int p = 0; p < 8; p++) {
229                 bool f = (chAvail & (1 << p)) != 0;
230                 vAvail.push_back(f);
231             }
232             if (chAvail != 0)
233                 nMaskCode--;
234         }
235         // txouts themself
236         vout.assign(vAvail.size(), CTxOut());
237         for (unsigned int i = 0; i < vAvail.size(); i++) {
238             if (vAvail[i])
239                 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
240         }
241         // coinbase height
242         ::Unserialize(s, VARINT(nHeight), nType, nVersion);
243         Cleanup();
244     }
245
246     //! mark a vout spent
247     bool Spend(uint32_t nPos);
248
249     //! check whether a particular output is still available
250     bool IsAvailable(unsigned int nPos) const {
251         return (nPos < vout.size() && !vout[nPos].IsNull());
252     }
253
254     //! check whether the entire CCoins is spent
255     //! note that only !IsPruned() CCoins can be serialized
256     bool IsPruned() const {
257         BOOST_FOREACH(const CTxOut &out, vout)
258             if (!out.IsNull())
259                 return false;
260         return true;
261     }
262
263     size_t DynamicMemoryUsage() const {
264         size_t ret = memusage::DynamicUsage(vout);
265         BOOST_FOREACH(const CTxOut &out, vout) {
266             ret += RecursiveDynamicUsage(out.scriptPubKey);
267         }
268         return ret;
269     }
270 };
271
272 class CCoinsKeyHasher
273 {
274 private:
275     uint256 salt;
276
277 public:
278     CCoinsKeyHasher();
279
280     /**
281      * This *must* return size_t. With Boost 1.46 on 32-bit systems the
282      * unordered_map will behave unpredictably if the custom hasher returns a
283      * uint64_t, resulting in failures when syncing the chain (#4634).
284      */
285     size_t operator()(const uint256& key) const {
286         return key.GetHash(salt);
287     }
288 };
289
290 struct CCoinsCacheEntry
291 {
292     CCoins coins; // The actual cached data.
293     unsigned char flags;
294
295     enum Flags {
296         DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
297         FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
298     };
299
300     CCoinsCacheEntry() : coins(), flags(0) {}
301 };
302
303 struct CAnchorsCacheEntry
304 {
305     bool entered; // This will be false if the anchor is removed from the cache
306     ZCIncrementalMerkleTree tree; // The tree itself
307     unsigned char flags;
308
309     enum Flags {
310         DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
311     };
312
313     CAnchorsCacheEntry() : entered(false), flags(0) {}
314 };
315
316 struct CNullifiersCacheEntry
317 {
318     bool entered; // If the nullifier is spent or not
319     unsigned char flags;
320
321     enum Flags {
322         DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
323     };
324
325     CNullifiersCacheEntry() : entered(false), flags(0) {}
326 };
327
328 typedef boost::unordered_map<uint256, CCoinsCacheEntry, CCoinsKeyHasher> CCoinsMap;
329 typedef boost::unordered_map<uint256, CAnchorsCacheEntry, CCoinsKeyHasher> CAnchorsMap;
330 typedef boost::unordered_map<uint256, CNullifiersCacheEntry, CCoinsKeyHasher> CNullifiersMap;
331
332 struct CCoinsStats
333 {
334     int nHeight;
335     uint256 hashBlock;
336     uint64_t nTransactions;
337     uint64_t nTransactionOutputs;
338     uint64_t nSerializedSize;
339     uint256 hashSerialized;
340     CAmount nTotalAmount;
341
342     CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), nTotalAmount(0) {}
343 };
344
345
346 /** Abstract view on the open txout dataset. */
347 class CCoinsView
348 {
349 public:
350     //! Retrieve the tree at a particular anchored root in the chain
351     virtual bool GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const;
352
353     //! Determine whether a nullifier is spent or not
354     virtual bool GetNullifier(const uint256 &nullifier) const;
355
356     //! Retrieve the CCoins (unspent transaction outputs) for a given txid
357     virtual bool GetCoins(const uint256 &txid, CCoins &coins) const;
358
359     //! Just check whether we have data for a given txid.
360     //! This may (but cannot always) return true for fully spent transactions
361     virtual bool HaveCoins(const uint256 &txid) const;
362
363     //! Retrieve the block hash whose state this CCoinsView currently represents
364     virtual uint256 GetBestBlock() const;
365
366     //! Get the current "tip" or the latest anchored tree root in the chain
367     virtual uint256 GetBestAnchor() const;
368
369     //! Do a bulk modification (multiple CCoins changes + BestBlock change).
370     //! The passed mapCoins can be modified.
371     virtual bool BatchWrite(CCoinsMap &mapCoins,
372                             const uint256 &hashBlock,
373                             const uint256 &hashAnchor,
374                             CAnchorsMap &mapAnchors,
375                             CNullifiersMap &mapNullifiers);
376
377     //! Calculate statistics about the unspent transaction output set
378     virtual bool GetStats(CCoinsStats &stats) const;
379
380     //! As we use CCoinsViews polymorphically, have a virtual destructor
381     virtual ~CCoinsView() {}
382 };
383
384
385 /** CCoinsView backed by another CCoinsView */
386 class CCoinsViewBacked : public CCoinsView
387 {
388 protected:
389     CCoinsView *base;
390
391 public:
392     CCoinsViewBacked(CCoinsView *viewIn);
393     bool GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const;
394     bool GetNullifier(const uint256 &nullifier) const;
395     bool GetCoins(const uint256 &txid, CCoins &coins) const;
396     bool HaveCoins(const uint256 &txid) const;
397     uint256 GetBestBlock() const;
398     uint256 GetBestAnchor() const;
399     void SetBackend(CCoinsView &viewIn);
400     bool BatchWrite(CCoinsMap &mapCoins,
401                     const uint256 &hashBlock,
402                     const uint256 &hashAnchor,
403                     CAnchorsMap &mapAnchors,
404                     CNullifiersMap &mapNullifiers);
405     bool GetStats(CCoinsStats &stats) const;
406 };
407
408
409 class CCoinsViewCache;
410
411 /** 
412  * A reference to a mutable cache entry. Encapsulating it allows us to run
413  *  cleanup code after the modification is finished, and keeping track of
414  *  concurrent modifications. 
415  */
416 class CCoinsModifier
417 {
418 private:
419     CCoinsViewCache& cache;
420     CCoinsMap::iterator it;
421     size_t cachedCoinUsage; // Cached memory usage of the CCoins object before modification
422     CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage);
423
424 public:
425     CCoins* operator->() { return &it->second.coins; }
426     CCoins& operator*() { return it->second.coins; }
427     ~CCoinsModifier();
428     friend class CCoinsViewCache;
429 };
430
431 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
432 class CCoinsViewCache : public CCoinsViewBacked
433 {
434 protected:
435     /* Whether this cache has an active modifier. */
436     bool hasModifier;
437
438
439     /**
440      * Make mutable so that we can "fill the cache" even from Get-methods
441      * declared as "const".  
442      */
443     mutable uint256 hashBlock;
444     mutable CCoinsMap cacheCoins;
445     mutable uint256 hashAnchor;
446     mutable CAnchorsMap cacheAnchors;
447     mutable CNullifiersMap cacheNullifiers;
448
449     /* Cached dynamic memory usage for the inner CCoins objects. */
450     mutable size_t cachedCoinsUsage;
451
452 public:
453     CCoinsViewCache(CCoinsView *baseIn);
454     ~CCoinsViewCache();
455
456     // Standard CCoinsView methods
457     bool GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const;
458     bool GetNullifier(const uint256 &nullifier) const;
459     bool GetCoins(const uint256 &txid, CCoins &coins) const;
460     bool HaveCoins(const uint256 &txid) const;
461     uint256 GetBestBlock() const;
462     uint256 GetBestAnchor() const;
463     void SetBestBlock(const uint256 &hashBlock);
464     bool BatchWrite(CCoinsMap &mapCoins,
465                     const uint256 &hashBlock,
466                     const uint256 &hashAnchor,
467                     CAnchorsMap &mapAnchors,
468                     CNullifiersMap &mapNullifiers);
469
470
471     // Adds the tree to mapAnchors and sets the current commitment
472     // root to this root.
473     void PushAnchor(const ZCIncrementalMerkleTree &tree);
474
475     // Removes the current commitment root from mapAnchors and sets
476     // the new current root.
477     void PopAnchor(const uint256 &rt);
478
479     // Marks a nullifier as spent or not.
480     void SetNullifier(const uint256 &nullifier, bool spent);
481
482     /**
483      * Return a pointer to CCoins in the cache, or NULL if not found. This is
484      * more efficient than GetCoins. Modifications to other cache entries are
485      * allowed while accessing the returned pointer.
486      */
487     const CCoins* AccessCoins(const uint256 &txid) const;
488
489     /**
490      * Return a modifiable reference to a CCoins. If no entry with the given
491      * txid exists, a new one is created. Simultaneous modifications are not
492      * allowed.
493      */
494     CCoinsModifier ModifyCoins(const uint256 &txid);
495
496     /**
497      * Push the modifications applied to this cache to its base.
498      * Failure to call this method before destruction will cause the changes to be forgotten.
499      * If false is returned, the state of this cache (and its backing view) will be undefined.
500      */
501     bool Flush();
502
503     //! Calculate the size of the cache (in number of transactions)
504     unsigned int GetCacheSize() const;
505
506     //! Calculate the size of the cache (in bytes)
507     size_t DynamicMemoryUsage() const;
508
509     /** 
510      * Amount of bitcoins coming in to a transaction
511      * Note that lightweight clients may not know anything besides the hash of previous transactions,
512      * so may not be able to calculate this.
513      *
514      * @param[in] tx    transaction for which we are checking input total
515      * @return  Sum of value of all inputs (scriptSigs)
516      */
517     CAmount GetValueIn(int32_t nHeight,int64_t *interestp,const CTransaction& tx,uint32_t prevblocktime) const;
518
519     //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
520     bool HaveInputs(const CTransaction& tx) const;
521
522     //! Check whether all joinsplit requirements (anchors/nullifiers) are satisfied
523     bool HaveJoinSplitRequirements(const CTransaction& tx) const;
524
525     //! Return priority of tx at height nHeight
526     double GetPriority(const CTransaction &tx, int nHeight) const;
527
528     const CTxOut &GetOutputFor(const CTxIn& input) const;
529     const CScript &GetSpendFor(const CTxIn& input) const;
530
531     friend class CCoinsModifier;
532
533 private:
534     CCoinsMap::iterator FetchCoins(const uint256 &txid);
535     CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const;
536
537     /**
538      * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
539      */
540     CCoinsViewCache(const CCoinsViewCache &);
541 };
542
543 #endif // BITCOIN_COINS_H
This page took 0.052759 seconds and 4 git commands to generate.