Remove/ignore tx version in utxo and undo
[bitcoinplatinum.git] / src / coins.h
blob12cfd6bf6b47f6b5d16ce3d2df6dd477652f1841
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
6 #ifndef BITCOIN_COINS_H
7 #define BITCOIN_COINS_H
9 #include "primitives/transaction.h"
10 #include "compressor.h"
11 #include "core_memusage.h"
12 #include "hash.h"
13 #include "memusage.h"
14 #include "serialize.h"
15 #include "uint256.h"
17 #include <assert.h>
18 #include <stdint.h>
20 #include <boost/foreach.hpp>
21 #include <unordered_map>
23 /**
24 * Pruned version of CTransaction: only retains metadata and unspent transaction outputs
26 * Serialized format:
27 * - VARINT(nVersion)
28 * - VARINT(nCode)
29 * - unspentness bitvector, for vout[2] and further; least significant byte first
30 * - the non-spent CTxOuts (via CTxOutCompressor)
31 * - VARINT(nHeight)
33 * The nCode value consists of:
34 * - bit 0: IsCoinBase()
35 * - bit 1: vout[0] is not spent
36 * - bit 2: vout[1] is not spent
37 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
38 * - In case both bit 1 and bit 2 are unset, they encode N-1, as there must be at
39 * least one non-spent output).
41 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
42 * <><><--------------------------------------------><---->
43 * | \ | /
44 * version code vout[1] height
46 * - version = 1
47 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
48 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
49 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
50 * * 8358: compact amount representation for 60000000000 (600 BTC)
51 * * 00: special txout type pay-to-pubkey-hash
52 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
53 * - height = 203998
56 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
57 * <><><--><--------------------------------------------------><----------------------------------------------><---->
58 * / \ \ | | /
59 * version code unspentness vout[4] vout[16] height
61 * - version = 1
62 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
63 * 2 (1, +1 because both bit 1 and bit 2 are unset) non-zero bitvector bytes follow)
64 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
65 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
66 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
67 * * 00: special txout type pay-to-pubkey-hash
68 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
69 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
70 * * bbd123: compact amount representation for 110397 (0.001 BTC)
71 * * 00: special txout type pay-to-pubkey-hash
72 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
73 * - height = 120891
75 class CCoins
77 public:
78 //! whether transaction is a coinbase
79 bool fCoinBase;
81 //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
82 std::vector<CTxOut> vout;
84 //! at which height this transaction was included in the active block chain
85 int nHeight;
87 void FromTx(const CTransaction &tx, int nHeightIn) {
88 fCoinBase = tx.IsCoinBase();
89 vout = tx.vout;
90 nHeight = nHeightIn;
91 ClearUnspendable();
94 //! construct a CCoins from a CTransaction, at a given height
95 CCoins(const CTransaction &tx, int nHeightIn) {
96 FromTx(tx, nHeightIn);
99 void Clear() {
100 fCoinBase = false;
101 std::vector<CTxOut>().swap(vout);
102 nHeight = 0;
105 //! empty constructor
106 CCoins() : fCoinBase(false), vout(0), nHeight(0) { }
108 //!remove spent outputs at the end of vout
109 void Cleanup() {
110 while (vout.size() > 0 && vout.back().IsNull())
111 vout.pop_back();
112 if (vout.empty())
113 std::vector<CTxOut>().swap(vout);
116 void ClearUnspendable() {
117 BOOST_FOREACH(CTxOut &txout, vout) {
118 if (txout.scriptPubKey.IsUnspendable())
119 txout.SetNull();
121 Cleanup();
124 void swap(CCoins &to) {
125 std::swap(to.fCoinBase, fCoinBase);
126 to.vout.swap(vout);
127 std::swap(to.nHeight, nHeight);
130 //! equality test
131 friend bool operator==(const CCoins &a, const CCoins &b) {
132 // Empty CCoins objects are always equal.
133 if (a.IsPruned() && b.IsPruned())
134 return true;
135 return a.fCoinBase == b.fCoinBase &&
136 a.nHeight == b.nHeight &&
137 a.vout == b.vout;
139 friend bool operator!=(const CCoins &a, const CCoins &b) {
140 return !(a == b);
143 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
145 bool IsCoinBase() const {
146 return fCoinBase;
149 template<typename Stream>
150 void Serialize(Stream &s) const {
151 unsigned int nMaskSize = 0, nMaskCode = 0;
152 CalcMaskSize(nMaskSize, nMaskCode);
153 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
154 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
155 assert(fFirst || fSecond || nMaskCode);
156 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
157 // version
158 int nVersionDummy = 0;
159 ::Serialize(s, VARINT(nVersionDummy));
160 // header code
161 ::Serialize(s, VARINT(nCode));
162 // spentness bitmask
163 for (unsigned int b = 0; b<nMaskSize; b++) {
164 unsigned char chAvail = 0;
165 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
166 if (!vout[2+b*8+i].IsNull())
167 chAvail |= (1 << i);
168 ::Serialize(s, chAvail);
170 // txouts themself
171 for (unsigned int i = 0; i < vout.size(); i++) {
172 if (!vout[i].IsNull())
173 ::Serialize(s, CTxOutCompressor(REF(vout[i])));
175 // coinbase height
176 ::Serialize(s, VARINT(nHeight));
179 template<typename Stream>
180 void Unserialize(Stream &s) {
181 unsigned int nCode = 0;
182 // version
183 int nVersionDummy;
184 ::Unserialize(s, VARINT(nVersionDummy));
185 // header code
186 ::Unserialize(s, VARINT(nCode));
187 fCoinBase = nCode & 1;
188 std::vector<bool> vAvail(2, false);
189 vAvail[0] = (nCode & 2) != 0;
190 vAvail[1] = (nCode & 4) != 0;
191 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
192 // spentness bitmask
193 while (nMaskCode > 0) {
194 unsigned char chAvail = 0;
195 ::Unserialize(s, chAvail);
196 for (unsigned int p = 0; p < 8; p++) {
197 bool f = (chAvail & (1 << p)) != 0;
198 vAvail.push_back(f);
200 if (chAvail != 0)
201 nMaskCode--;
203 // txouts themself
204 vout.assign(vAvail.size(), CTxOut());
205 for (unsigned int i = 0; i < vAvail.size(); i++) {
206 if (vAvail[i])
207 ::Unserialize(s, REF(CTxOutCompressor(vout[i])));
209 // coinbase height
210 ::Unserialize(s, VARINT(nHeight));
211 Cleanup();
214 //! mark a vout spent
215 bool Spend(uint32_t nPos);
217 //! check whether a particular output is still available
218 bool IsAvailable(unsigned int nPos) const {
219 return (nPos < vout.size() && !vout[nPos].IsNull());
222 //! check whether the entire CCoins is spent
223 //! note that only !IsPruned() CCoins can be serialized
224 bool IsPruned() const {
225 BOOST_FOREACH(const CTxOut &out, vout)
226 if (!out.IsNull())
227 return false;
228 return true;
231 size_t DynamicMemoryUsage() const {
232 size_t ret = memusage::DynamicUsage(vout);
233 BOOST_FOREACH(const CTxOut &out, vout) {
234 ret += RecursiveDynamicUsage(out.scriptPubKey);
236 return ret;
240 class SaltedTxidHasher
242 private:
243 /** Salt */
244 const uint64_t k0, k1;
246 public:
247 SaltedTxidHasher();
250 * This *must* return size_t. With Boost 1.46 on 32-bit systems the
251 * unordered_map will behave unpredictably if the custom hasher returns a
252 * uint64_t, resulting in failures when syncing the chain (#4634).
254 size_t operator()(const uint256& txid) const {
255 return SipHashUint256(k0, k1, txid);
259 struct CCoinsCacheEntry
261 CCoins coins; // The actual cached data.
262 unsigned char flags;
264 enum Flags {
265 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
266 FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
267 /* Note that FRESH is a performance optimization with which we can
268 * erase coins that are fully spent if we know we do not need to
269 * flush the changes to the parent cache. It is always safe to
270 * not mark FRESH if that condition is not guaranteed.
274 CCoinsCacheEntry() : coins(), flags(0) {}
277 typedef std::unordered_map<uint256, CCoinsCacheEntry, SaltedTxidHasher> CCoinsMap;
279 /** Cursor for iterating over CoinsView state */
280 class CCoinsViewCursor
282 public:
283 CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
284 virtual ~CCoinsViewCursor();
286 virtual bool GetKey(uint256 &key) const = 0;
287 virtual bool GetValue(CCoins &coins) const = 0;
288 virtual unsigned int GetValueSize() const = 0;
290 virtual bool Valid() const = 0;
291 virtual void Next() = 0;
293 //! Get best block at the time this cursor was created
294 const uint256 &GetBestBlock() const { return hashBlock; }
295 private:
296 uint256 hashBlock;
299 /** Abstract view on the open txout dataset. */
300 class CCoinsView
302 public:
303 //! Retrieve the CCoins (unspent transaction outputs) for a given txid
304 virtual bool GetCoins(const uint256 &txid, CCoins &coins) const;
306 //! Just check whether we have data for a given txid.
307 //! This may (but cannot always) return true for fully spent transactions
308 virtual bool HaveCoins(const uint256 &txid) const;
310 //! Retrieve the block hash whose state this CCoinsView currently represents
311 virtual uint256 GetBestBlock() const;
313 //! Do a bulk modification (multiple CCoins changes + BestBlock change).
314 //! The passed mapCoins can be modified.
315 virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
317 //! Get a cursor to iterate over the whole state
318 virtual CCoinsViewCursor *Cursor() const;
320 //! As we use CCoinsViews polymorphically, have a virtual destructor
321 virtual ~CCoinsView() {}
325 /** CCoinsView backed by another CCoinsView */
326 class CCoinsViewBacked : public CCoinsView
328 protected:
329 CCoinsView *base;
331 public:
332 CCoinsViewBacked(CCoinsView *viewIn);
333 bool GetCoins(const uint256 &txid, CCoins &coins) const;
334 bool HaveCoins(const uint256 &txid) const;
335 uint256 GetBestBlock() const;
336 void SetBackend(CCoinsView &viewIn);
337 bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
338 CCoinsViewCursor *Cursor() const;
342 class CCoinsViewCache;
344 /**
345 * A reference to a mutable cache entry. Encapsulating it allows us to run
346 * cleanup code after the modification is finished, and keeping track of
347 * concurrent modifications.
349 class CCoinsModifier
351 private:
352 CCoinsViewCache& cache;
353 CCoinsMap::iterator it;
354 size_t cachedCoinUsage; // Cached memory usage of the CCoins object before modification
355 CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage);
357 public:
358 CCoins* operator->() { return &it->second.coins; }
359 CCoins& operator*() { return it->second.coins; }
360 ~CCoinsModifier();
361 friend class CCoinsViewCache;
364 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
365 class CCoinsViewCache : public CCoinsViewBacked
367 protected:
368 /* Whether this cache has an active modifier. */
369 bool hasModifier;
373 * Make mutable so that we can "fill the cache" even from Get-methods
374 * declared as "const".
376 mutable uint256 hashBlock;
377 mutable CCoinsMap cacheCoins;
379 /* Cached dynamic memory usage for the inner CCoins objects. */
380 mutable size_t cachedCoinsUsage;
382 public:
383 CCoinsViewCache(CCoinsView *baseIn);
384 ~CCoinsViewCache();
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);
394 * Check if we have the given tx already loaded in this cache.
395 * The semantics are the same as HaveCoins(), but no calls to
396 * the backing CCoinsView are made.
398 bool HaveCoinsInCache(const uint256 &txid) const;
401 * Return a pointer to CCoins in the cache, or NULL if not found. This is
402 * more efficient than GetCoins. Modifications to other cache entries are
403 * allowed while accessing the returned pointer.
405 const CCoins* AccessCoins(const uint256 &txid) const;
408 * Return a modifiable reference to a CCoins. If no entry with the given
409 * txid exists, a new one is created. Simultaneous modifications are not
410 * allowed.
412 CCoinsModifier ModifyCoins(const uint256 &txid);
415 * Return a modifiable reference to a CCoins. Assumes that no entry with the given
416 * txid exists and creates a new one. This saves a database access in the case where
417 * the coins were to be wiped out by FromTx anyway. This should not be called with
418 * the 2 historical coinbase duplicate pairs because the new coins are marked fresh, and
419 * in the event the duplicate coinbase was spent before a flush, the now pruned coins
420 * would not properly overwrite the first coinbase of the pair. Simultaneous modifications
421 * are not allowed.
423 CCoinsModifier ModifyNewCoins(const uint256 &txid, bool coinbase);
426 * Push the modifications applied to this cache to its base.
427 * Failure to call this method before destruction will cause the changes to be forgotten.
428 * If false is returned, the state of this cache (and its backing view) will be undefined.
430 bool Flush();
433 * Removes the transaction with the given hash from the cache, if it is
434 * not modified.
436 void Uncache(const uint256 &txid);
438 //! Calculate the size of the cache (in number of transactions)
439 unsigned int GetCacheSize() const;
441 //! Calculate the size of the cache (in bytes)
442 size_t DynamicMemoryUsage() const;
444 /**
445 * Amount of bitcoins coming in to a transaction
446 * Note that lightweight clients may not know anything besides the hash of previous transactions,
447 * so may not be able to calculate this.
449 * @param[in] tx transaction for which we are checking input total
450 * @return Sum of value of all inputs (scriptSigs)
452 CAmount GetValueIn(const CTransaction& tx) const;
454 //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
455 bool HaveInputs(const CTransaction& tx) const;
457 const CTxOut &GetOutputFor(const CTxIn& input) const;
459 friend class CCoinsModifier;
461 private:
462 CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const;
465 * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
467 CCoinsViewCache(const CCoinsViewCache &);
470 #endif // BITCOIN_COINS_H