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