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