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"
14 #include "serialize.h"
20 #include <unordered_map>
26 * - VARINT((coinbase ? 1 : 0) | (height << 1))
27 * - the non-spent CTxOut (via CTxOutCompressor)
32 //! unspent transaction output
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
) {}
52 Coin() : fCoinBase(false), nHeight(0) { }
54 bool IsCoinBase() const {
58 template<typename Stream
>
59 void Serialize(Stream
&s
) const {
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
) {
69 ::Unserialize(s
, VARINT(code
));
72 ::Unserialize(s
, REF(CTxOutCompressor(out
)));
75 bool IsSpent() const {
79 size_t DynamicMemoryUsage() const {
80 return memusage::DynamicUsage(out
.scriptPubKey
);
84 class SaltedOutpointHasher
88 const uint64_t k0
, k1
;
91 SaltedOutpointHasher();
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.
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
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
; }
144 /** Abstract view on the open txout dataset. */
148 /** Retrieve the Coin (unspent transaction output) for a given outpoint.
149 * Returns true only when an unspent coin was found, which is returned in coin.
150 * When false is returned, coin's value is unspecified.
152 virtual bool GetCoin(const COutPoint
&outpoint
, Coin
&coin
) const;
154 //! Just check whether a given outpoint is unspent.
155 virtual bool HaveCoin(const COutPoint
&outpoint
) const;
157 //! Retrieve the block hash whose state this CCoinsView currently represents
158 virtual uint256
GetBestBlock() const;
160 //! Do a bulk modification (multiple Coin changes + BestBlock change).
161 //! The passed mapCoins can be modified.
162 virtual bool BatchWrite(CCoinsMap
&mapCoins
, const uint256
&hashBlock
);
164 //! Get a cursor to iterate over the whole state
165 virtual CCoinsViewCursor
*Cursor() const;
167 //! As we use CCoinsViews polymorphically, have a virtual destructor
168 virtual ~CCoinsView() {}
170 //! Estimate database size (0 if not implemented)
171 virtual size_t EstimateSize() const { return 0; }
175 /** CCoinsView backed by another CCoinsView */
176 class CCoinsViewBacked
: public CCoinsView
182 CCoinsViewBacked(CCoinsView
*viewIn
);
183 bool GetCoin(const COutPoint
&outpoint
, Coin
&coin
) const override
;
184 bool HaveCoin(const COutPoint
&outpoint
) const override
;
185 uint256
GetBestBlock() const override
;
186 void SetBackend(CCoinsView
&viewIn
);
187 bool BatchWrite(CCoinsMap
&mapCoins
, const uint256
&hashBlock
) override
;
188 CCoinsViewCursor
*Cursor() const override
;
189 size_t EstimateSize() const override
;
193 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
194 class CCoinsViewCache
: public CCoinsViewBacked
198 * Make mutable so that we can "fill the cache" even from Get-methods
199 * declared as "const".
201 mutable uint256 hashBlock
;
202 mutable CCoinsMap cacheCoins
;
204 /* Cached dynamic memory usage for the inner Coin objects. */
205 mutable size_t cachedCoinsUsage
;
208 CCoinsViewCache(CCoinsView
*baseIn
);
210 // Standard CCoinsView methods
211 bool GetCoin(const COutPoint
&outpoint
, Coin
&coin
) const override
;
212 bool HaveCoin(const COutPoint
&outpoint
) const override
;
213 uint256
GetBestBlock() const override
;
214 void SetBestBlock(const uint256
&hashBlock
);
215 bool BatchWrite(CCoinsMap
&mapCoins
, const uint256
&hashBlock
) override
;
216 CCoinsViewCursor
* Cursor() const override
{
217 throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
221 * Check if we have the given utxo already loaded in this cache.
222 * The semantics are the same as HaveCoin(), but no calls to
223 * the backing CCoinsView are made.
225 bool HaveCoinInCache(const COutPoint
&outpoint
) const;
228 * Return a reference to Coin in the cache, or a pruned one if not found. This is
229 * more efficient than GetCoin.
231 * Generally, do not hold the reference returned for more than a short scope.
232 * While the current implementation allows for modifications to the contents
233 * of the cache while holding the reference, this behavior should not be relied
234 * on! To be safe, best to not hold the returned reference through any other
235 * calls to this cache.
237 const Coin
& AccessCoin(const COutPoint
&output
) const;
240 * Add a coin. Set potential_overwrite to true if a non-pruned version may
243 void AddCoin(const COutPoint
& outpoint
, Coin
&& coin
, bool potential_overwrite
);
246 * Spend a coin. Pass moveto in order to get the deleted data.
247 * If no unspent output exists for the passed outpoint, this call
250 bool SpendCoin(const COutPoint
&outpoint
, Coin
* moveto
= nullptr);
253 * Push the modifications applied to this cache to its base.
254 * Failure to call this method before destruction will cause the changes to be forgotten.
255 * If false is returned, the state of this cache (and its backing view) will be undefined.
260 * Removes the UTXO with the given outpoint from the cache, if it is
263 void Uncache(const COutPoint
&outpoint
);
265 //! Calculate the size of the cache (in number of transaction outputs)
266 unsigned int GetCacheSize() const;
268 //! Calculate the size of the cache (in bytes)
269 size_t DynamicMemoryUsage() const;
272 * Amount of bitcoins coming in to a transaction
273 * Note that lightweight clients may not know anything besides the hash of previous transactions,
274 * so may not be able to calculate this.
276 * @param[in] tx transaction for which we are checking input total
277 * @return Sum of value of all inputs (scriptSigs)
279 CAmount
GetValueIn(const CTransaction
& tx
) const;
281 //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
282 bool HaveInputs(const CTransaction
& tx
) const;
285 CCoinsMap::iterator
FetchCoin(const COutPoint
&outpoint
) const;
288 * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
290 CCoinsViewCache(const CCoinsViewCache
&);
293 //! Utility function to add all of a transaction's outputs to a cache.
294 // It assumes that overwrites are only possible for coinbase transactions,
295 // TODO: pass in a boolean to limit these possible overwrites to known
296 // (pre-BIP34) cases.
297 void AddCoins(CCoinsViewCache
& cache
, const CTransaction
& tx
, int nHeight
);
299 //! Utility function to find any unspent output with a given txid.
300 const Coin
& AccessByTxid(const CCoinsViewCache
& cache
, const uint256
& txid
);
302 #endif // BITCOIN_COINS_H