]> Git Repo - VerusCoin.git/blob - src/coins.h
Add support for spending keys to the encrypted wallet.
[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 "memusage.h"
11 #include "serialize.h"
12 #include "uint256.h"
13
14 #include <assert.h>
15 #include <stdint.h>
16
17 #include <boost/foreach.hpp>
18 #include <boost/unordered_map.hpp>
19 #include "zcash/IncrementalMerkleTree.hpp"
20
21 /** 
22  * Pruned version of CTransaction: only retains metadata and unspent transaction outputs
23  *
24  * Serialized format:
25  * - VARINT(nVersion)
26  * - VARINT(nCode)
27  * - unspentness bitvector, for vout[2] and further; least significant byte first
28  * - the non-spent CTxOuts (via CTxOutCompressor)
29  * - VARINT(nHeight)
30  *
31  * The nCode value consists of:
32  * - bit 1: IsCoinBase()
33  * - bit 2: vout[0] is not spent
34  * - bit 4: vout[1] is not spent
35  * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
36  *   - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
37  *     least one non-spent output).
38  *
39  * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
40  *          <><><--------------------------------------------><---->
41  *          |  \                  |                             /
42  *    version   code             vout[1]                  height
43  *
44  *    - version = 1
45  *    - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
46  *    - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
47  *    - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
48  *               * 8358: compact amount representation for 60000000000 (600 BTC)
49  *               * 00: special txout type pay-to-pubkey-hash
50  *               * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
51  *    - height = 203998
52  *
53  *
54  * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
55  *          <><><--><--------------------------------------------------><----------------------------------------------><---->
56  *         /  \   \                     |                                                           |                     /
57  *  version  code  unspentness       vout[4]                                                     vout[16]           height
58  *
59  *  - version = 1
60  *  - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
61  *                2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
62  *  - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
63  *  - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
64  *             * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
65  *             * 00: special txout type pay-to-pubkey-hash
66  *             * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
67  *  - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
68  *              * bbd123: compact amount representation for 110397 (0.001 BTC)
69  *              * 00: special txout type pay-to-pubkey-hash
70  *              * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
71  *  - height = 120891
72  */
73 class CCoins
74 {
75 public:
76     //! whether transaction is a coinbase
77     bool fCoinBase;
78
79     //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
80     std::vector<CTxOut> vout;
81
82     //! at which height this transaction was included in the active block chain
83     int nHeight;
84
85     //! version of the CTransaction; accesses to this value should probably check for nHeight as well,
86     //! as new tx version will probably only be introduced at certain heights
87     int nVersion;
88
89     void FromTx(const CTransaction &tx, int nHeightIn) {
90         fCoinBase = tx.IsCoinBase();
91         vout = tx.vout;
92         nHeight = nHeightIn;
93         nVersion = tx.nVersion;
94         ClearUnspendable();
95     }
96
97     //! construct a CCoins from a CTransaction, at a given height
98     CCoins(const CTransaction &tx, int nHeightIn) {
99         FromTx(tx, nHeightIn);
100     }
101
102     void Clear() {
103         fCoinBase = false;
104         std::vector<CTxOut>().swap(vout);
105         nHeight = 0;
106         nVersion = 0;
107     }
108
109     //! empty constructor
110     CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
111
112     //!remove spent outputs at the end of vout
113     void Cleanup() {
114         while (vout.size() > 0 && vout.back().IsNull())
115             vout.pop_back();
116         if (vout.empty())
117             std::vector<CTxOut>().swap(vout);
118     }
119
120     void ClearUnspendable() {
121         BOOST_FOREACH(CTxOut &txout, vout) {
122             if (txout.scriptPubKey.IsUnspendable())
123                 txout.SetNull();
124         }
125         Cleanup();
126     }
127
128     void swap(CCoins &to) {
129         std::swap(to.fCoinBase, fCoinBase);
130         to.vout.swap(vout);
131         std::swap(to.nHeight, nHeight);
132         std::swap(to.nVersion, nVersion);
133     }
134
135     //! equality test
136     friend bool operator==(const CCoins &a, const CCoins &b) {
137          // Empty CCoins objects are always equal.
138          if (a.IsPruned() && b.IsPruned())
139              return true;
140          return a.fCoinBase == b.fCoinBase &&
141                 a.nHeight == b.nHeight &&
142                 a.nVersion == b.nVersion &&
143                 a.vout == b.vout;
144     }
145     friend bool operator!=(const CCoins &a, const CCoins &b) {
146         return !(a == b);
147     }
148
149     void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
150
151     bool IsCoinBase() const {
152         return fCoinBase;
153     }
154
155     unsigned int GetSerializeSize(int nType, int nVersion) const {
156         unsigned int nSize = 0;
157         unsigned int nMaskSize = 0, nMaskCode = 0;
158         CalcMaskSize(nMaskSize, nMaskCode);
159         bool fFirst = vout.size() > 0 && !vout[0].IsNull();
160         bool fSecond = vout.size() > 1 && !vout[1].IsNull();
161         assert(fFirst || fSecond || nMaskCode);
162         unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
163         // version
164         nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
165         // size of header code
166         nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
167         // spentness bitmask
168         nSize += nMaskSize;
169         // txouts themself
170         for (unsigned int i = 0; i < vout.size(); i++)
171             if (!vout[i].IsNull())
172                 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
173         // height
174         nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
175         return nSize;
176     }
177
178     template<typename Stream>
179     void Serialize(Stream &s, int nType, int nVersion) const {
180         unsigned int nMaskSize = 0, nMaskCode = 0;
181         CalcMaskSize(nMaskSize, nMaskCode);
182         bool fFirst = vout.size() > 0 && !vout[0].IsNull();
183         bool fSecond = vout.size() > 1 && !vout[1].IsNull();
184         assert(fFirst || fSecond || nMaskCode);
185         unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
186         // version
187         ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
188         // header code
189         ::Serialize(s, VARINT(nCode), nType, nVersion);
190         // spentness bitmask
191         for (unsigned int b = 0; b<nMaskSize; b++) {
192             unsigned char chAvail = 0;
193             for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
194                 if (!vout[2+b*8+i].IsNull())
195                     chAvail |= (1 << i);
196             ::Serialize(s, chAvail, nType, nVersion);
197         }
198         // txouts themself
199         for (unsigned int i = 0; i < vout.size(); i++) {
200             if (!vout[i].IsNull())
201                 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
202         }
203         // coinbase height
204         ::Serialize(s, VARINT(nHeight), nType, nVersion);
205     }
206
207     template<typename Stream>
208     void Unserialize(Stream &s, int nType, int nVersion) {
209         unsigned int nCode = 0;
210         // version
211         ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
212         // header code
213         ::Unserialize(s, VARINT(nCode), nType, nVersion);
214         fCoinBase = nCode & 1;
215         std::vector<bool> vAvail(2, false);
216         vAvail[0] = (nCode & 2) != 0;
217         vAvail[1] = (nCode & 4) != 0;
218         unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
219         // spentness bitmask
220         while (nMaskCode > 0) {
221             unsigned char chAvail = 0;
222             ::Unserialize(s, chAvail, nType, nVersion);
223             for (unsigned int p = 0; p < 8; p++) {
224                 bool f = (chAvail & (1 << p)) != 0;
225                 vAvail.push_back(f);
226             }
227             if (chAvail != 0)
228                 nMaskCode--;
229         }
230         // txouts themself
231         vout.assign(vAvail.size(), CTxOut());
232         for (unsigned int i = 0; i < vAvail.size(); i++) {
233             if (vAvail[i])
234                 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
235         }
236         // coinbase height
237         ::Unserialize(s, VARINT(nHeight), nType, nVersion);
238         Cleanup();
239     }
240
241     //! mark a vout spent
242     bool Spend(uint32_t nPos);
243
244     //! check whether a particular output is still available
245     bool IsAvailable(unsigned int nPos) const {
246         return (nPos < vout.size() && !vout[nPos].IsNull());
247     }
248
249     //! check whether the entire CCoins is spent
250     //! note that only !IsPruned() CCoins can be serialized
251     bool IsPruned() const {
252         BOOST_FOREACH(const CTxOut &out, vout)
253             if (!out.IsNull())
254                 return false;
255         return true;
256     }
257
258     size_t DynamicMemoryUsage() const {
259         size_t ret = memusage::DynamicUsage(vout);
260         BOOST_FOREACH(const CTxOut &out, vout) {
261             const std::vector<unsigned char> *script = &out.scriptPubKey;
262             ret += memusage::DynamicUsage(*script);
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.071312 seconds and 4 git commands to generate.