Merge #10537: Few Minor per-utxo assert-semantics re-adds and tweak
[bitcoinplatinum.git] / src / coins.h
blob4774c9f6a6272017c7a8a9de6dacc967c765b382
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 <unordered_map>
22 /**
23 * A UTXO entry.
25 * Serialized format:
26 * - VARINT((coinbase ? 1 : 0) | (height << 1))
27 * - the non-spent CTxOut (via CTxOutCompressor)
29 class Coin
31 public:
32 //! unspent transaction output
33 CTxOut out;
35 //! whether containing transaction was a coinbase
36 unsigned int fCoinBase : 1;
38 //! at which height this containing transaction was included in the active block chain
39 uint32_t nHeight : 31;
41 //! construct a Coin from a CTxOut and height/coinbase information.
42 Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
43 Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
45 void Clear() {
46 out.SetNull();
47 fCoinBase = false;
48 nHeight = 0;
51 //! empty constructor
52 Coin() : fCoinBase(false), nHeight(0) { }
54 bool IsCoinBase() const {
55 return fCoinBase;
58 template<typename Stream>
59 void Serialize(Stream &s) const {
60 assert(!IsSpent());
61 uint32_t code = nHeight * 2 + fCoinBase;
62 ::Serialize(s, VARINT(code));
63 ::Serialize(s, CTxOutCompressor(REF(out)));
66 template<typename Stream>
67 void Unserialize(Stream &s) {
68 uint32_t code = 0;
69 ::Unserialize(s, VARINT(code));
70 nHeight = code >> 1;
71 fCoinBase = code & 1;
72 ::Unserialize(s, REF(CTxOutCompressor(out)));
75 bool IsSpent() const {
76 return out.IsNull();
79 size_t DynamicMemoryUsage() const {
80 return memusage::DynamicUsage(out.scriptPubKey);
84 class SaltedOutpointHasher
86 private:
87 /** Salt */
88 const uint64_t k0, k1;
90 public:
91 SaltedOutpointHasher();
93 /**
94 * This *must* return size_t. With Boost 1.46 on 32-bit systems the
95 * unordered_map will behave unpredictably if the custom hasher returns a
96 * uint64_t, resulting in failures when syncing the chain (#4634).
98 size_t operator()(const COutPoint& id) const {
99 return SipHashUint256Extra(k0, k1, id.hash, id.n);
103 struct CCoinsCacheEntry
105 Coin coin; // The actual cached data.
106 unsigned char flags;
108 enum Flags {
109 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
110 FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
111 /* Note that FRESH is a performance optimization with which we can
112 * erase coins that are fully spent if we know we do not need to
113 * flush the changes to the parent cache. It is always safe to
114 * not mark FRESH if that condition is not guaranteed.
118 CCoinsCacheEntry() : flags(0) {}
119 explicit CCoinsCacheEntry(Coin&& coin_) : coin(std::move(coin_)), flags(0) {}
122 typedef std::unordered_map<COutPoint, CCoinsCacheEntry, SaltedOutpointHasher> CCoinsMap;
124 /** Cursor for iterating over CoinsView state */
125 class CCoinsViewCursor
127 public:
128 CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
129 virtual ~CCoinsViewCursor() {}
131 virtual bool GetKey(COutPoint &key) const = 0;
132 virtual bool GetValue(Coin &coin) const = 0;
133 virtual unsigned int GetValueSize() const = 0;
135 virtual bool Valid() const = 0;
136 virtual void Next() = 0;
138 //! Get best block at the time this cursor was created
139 const uint256 &GetBestBlock() const { return hashBlock; }
140 private:
141 uint256 hashBlock;
144 /** Abstract view on the open txout dataset. */
145 class CCoinsView
147 public:
148 //! Retrieve the Coin (unspent transaction output) for a given outpoint.
149 virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
151 //! Just check whether we have data for a given outpoint.
152 //! This may (but cannot always) return true for spent outputs.
153 virtual bool HaveCoin(const COutPoint &outpoint) const;
155 //! Retrieve the block hash whose state this CCoinsView currently represents
156 virtual uint256 GetBestBlock() const;
158 //! Do a bulk modification (multiple Coin changes + BestBlock change).
159 //! The passed mapCoins can be modified.
160 virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
162 //! Get a cursor to iterate over the whole state
163 virtual CCoinsViewCursor *Cursor() const;
165 //! As we use CCoinsViews polymorphically, have a virtual destructor
166 virtual ~CCoinsView() {}
168 //! Estimate database size (0 if not implemented)
169 virtual size_t EstimateSize() const { return 0; }
173 /** CCoinsView backed by another CCoinsView */
174 class CCoinsViewBacked : public CCoinsView
176 protected:
177 CCoinsView *base;
179 public:
180 CCoinsViewBacked(CCoinsView *viewIn);
181 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
182 bool HaveCoin(const COutPoint &outpoint) const override;
183 uint256 GetBestBlock() const override;
184 void SetBackend(CCoinsView &viewIn);
185 bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
186 CCoinsViewCursor *Cursor() const override;
187 size_t EstimateSize() const override;
191 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
192 class CCoinsViewCache : public CCoinsViewBacked
194 protected:
196 * Make mutable so that we can "fill the cache" even from Get-methods
197 * declared as "const".
199 mutable uint256 hashBlock;
200 mutable CCoinsMap cacheCoins;
202 /* Cached dynamic memory usage for the inner Coin objects. */
203 mutable size_t cachedCoinsUsage;
205 public:
206 CCoinsViewCache(CCoinsView *baseIn);
208 // Standard CCoinsView methods
209 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
210 bool HaveCoin(const COutPoint &outpoint) const override;
211 uint256 GetBestBlock() const override;
212 void SetBestBlock(const uint256 &hashBlock);
213 bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
214 CCoinsViewCursor* Cursor() const override {
215 throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
219 * Check if we have the given utxo already loaded in this cache.
220 * The semantics are the same as HaveCoin(), but no calls to
221 * the backing CCoinsView are made.
223 bool HaveCoinInCache(const COutPoint &outpoint) const;
226 * Return a reference to Coin in the cache, or a pruned one if not found. This is
227 * more efficient than GetCoin.
229 * Generally, do not hold the reference returned for more than a short scope.
230 * While the current implementation allows for modifications to the contents
231 * of the cache while holding the reference, this behavior should not be relied
232 * on! To be safe, best to not hold the returned reference through any other
233 * calls to this cache.
235 const Coin& AccessCoin(const COutPoint &output) const;
238 * Add a coin. Set potential_overwrite to true if a non-pruned version may
239 * already exist.
241 void AddCoin(const COutPoint& outpoint, Coin&& coin, bool potential_overwrite);
244 * Spend a coin. Pass moveto in order to get the deleted data.
245 * If no unspent output exists for the passed outpoint, this call
246 * has no effect.
248 bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
251 * Push the modifications applied to this cache to its base.
252 * Failure to call this method before destruction will cause the changes to be forgotten.
253 * If false is returned, the state of this cache (and its backing view) will be undefined.
255 bool Flush();
258 * Removes the UTXO with the given outpoint from the cache, if it is
259 * not modified.
261 void Uncache(const COutPoint &outpoint);
263 //! Calculate the size of the cache (in number of transaction outputs)
264 unsigned int GetCacheSize() const;
266 //! Calculate the size of the cache (in bytes)
267 size_t DynamicMemoryUsage() const;
269 /**
270 * Amount of bitcoins coming in to a transaction
271 * Note that lightweight clients may not know anything besides the hash of previous transactions,
272 * so may not be able to calculate this.
274 * @param[in] tx transaction for which we are checking input total
275 * @return Sum of value of all inputs (scriptSigs)
277 CAmount GetValueIn(const CTransaction& tx) const;
279 //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
280 bool HaveInputs(const CTransaction& tx) const;
282 private:
283 CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
286 * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
288 CCoinsViewCache(const CCoinsViewCache &);
291 //! Utility function to add all of a transaction's outputs to a cache.
292 // It assumes that overwrites are only possible for coinbase transactions,
293 // TODO: pass in a boolean to limit these possible overwrites to known
294 // (pre-BIP34) cases.
295 void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight);
297 //! Utility function to find any unspent output with a given txid.
298 const Coin& AccessByTxid(const CCoinsViewCache& cache, const uint256& txid);
300 #endif // BITCOIN_COINS_H