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 <boost/foreach.hpp>
21 #include <unordered_map>
27 * - VARINT((coinbase ? 1 : 0) | (height << 1))
28 * - the non-spent CTxOut (via CTxOutCompressor)
33 //! unspent transaction output
36 //! whether containing transaction was a coinbase
37 unsigned int fCoinBase
: 1;
39 //! at which height this containing transaction was included in the active block chain
40 uint32_t nHeight
: 31;
42 //! construct a Coin from a CTxOut and height/coinbase information.
43 Coin(CTxOut
&& outIn
, int nHeightIn
, bool fCoinBaseIn
) : out(std::move(outIn
)), fCoinBase(fCoinBaseIn
), nHeight(nHeightIn
) {}
44 Coin(const CTxOut
& outIn
, int nHeightIn
, bool fCoinBaseIn
) : out(outIn
), fCoinBase(fCoinBaseIn
),nHeight(nHeightIn
) {}
53 Coin() : fCoinBase(false), nHeight(0) { }
55 bool IsCoinBase() const {
59 template<typename Stream
>
60 void Serialize(Stream
&s
) const {
62 uint32_t code
= nHeight
* 2 + fCoinBase
;
63 ::Serialize(s
, VARINT(code
));
64 ::Serialize(s
, CTxOutCompressor(REF(out
)));
67 template<typename Stream
>
68 void Unserialize(Stream
&s
) {
70 ::Unserialize(s
, VARINT(code
));
73 ::Unserialize(s
, REF(CTxOutCompressor(out
)));
76 bool IsPruned() const {
80 size_t DynamicMemoryUsage() const {
81 return memusage::DynamicUsage(out
.scriptPubKey
);
85 class SaltedOutpointHasher
89 const uint64_t k0
, k1
;
92 SaltedOutpointHasher();
95 * This *must* return size_t. With Boost 1.46 on 32-bit systems the
96 * unordered_map will behave unpredictably if the custom hasher returns a
97 * uint64_t, resulting in failures when syncing the chain (#4634).
99 size_t operator()(const COutPoint
& id
) const {
100 return SipHashUint256Extra(k0
, k1
, id
.hash
, id
.n
);
104 struct CCoinsCacheEntry
106 Coin coin
; // The actual cached data.
110 DIRTY
= (1 << 0), // This cache entry is potentially different from the version in the parent view.
111 FRESH
= (1 << 1), // The parent view does not have this entry (or it is pruned).
112 /* Note that FRESH is a performance optimization with which we can
113 * erase coins that are fully spent if we know we do not need to
114 * flush the changes to the parent cache. It is always safe to
115 * not mark FRESH if that condition is not guaranteed.
119 CCoinsCacheEntry() : flags(0) {}
120 explicit CCoinsCacheEntry(Coin
&& coin_
) : coin(std::move(coin_
)), flags(0) {}
123 typedef std::unordered_map
<COutPoint
, CCoinsCacheEntry
, SaltedOutpointHasher
> CCoinsMap
;
125 /** Cursor for iterating over CoinsView state */
126 class CCoinsViewCursor
129 CCoinsViewCursor(const uint256
&hashBlockIn
): hashBlock(hashBlockIn
) {}
130 virtual ~CCoinsViewCursor() {}
132 virtual bool GetKey(COutPoint
&key
) const = 0;
133 virtual bool GetValue(Coin
&coin
) const = 0;
134 virtual unsigned int GetValueSize() const = 0;
136 virtual bool Valid() const = 0;
137 virtual void Next() = 0;
139 //! Get best block at the time this cursor was created
140 const uint256
&GetBestBlock() const { return hashBlock
; }
145 /** Abstract view on the open txout dataset. */
149 //! Retrieve the Coin (unspent transaction output) for a given outpoint.
150 virtual bool GetCoins(const COutPoint
&outpoint
, Coin
&coin
) const;
152 //! Just check whether we have data for a given outpoint.
153 //! This may (but cannot always) return true for spent outputs.
154 virtual bool HaveCoins(const COutPoint
&outpoint
) const;
156 //! Retrieve the block hash whose state this CCoinsView currently represents
157 virtual uint256
GetBestBlock() const;
159 //! Do a bulk modification (multiple Coin changes + BestBlock change).
160 //! The passed mapCoins can be modified.
161 virtual bool BatchWrite(CCoinsMap
&mapCoins
, const uint256
&hashBlock
);
163 //! Get a cursor to iterate over the whole state
164 virtual CCoinsViewCursor
*Cursor() const;
166 //! As we use CCoinsViews polymorphically, have a virtual destructor
167 virtual ~CCoinsView() {}
169 //! Estimate database size (0 if not implemented)
170 virtual size_t EstimateSize() const { return 0; }
174 /** CCoinsView backed by another CCoinsView */
175 class CCoinsViewBacked
: public CCoinsView
181 CCoinsViewBacked(CCoinsView
*viewIn
);
182 bool GetCoins(const COutPoint
&outpoint
, Coin
&coin
) const override
;
183 bool HaveCoins(const COutPoint
&outpoint
) const override
;
184 uint256
GetBestBlock() const override
;
185 void SetBackend(CCoinsView
&viewIn
);
186 bool BatchWrite(CCoinsMap
&mapCoins
, const uint256
&hashBlock
) override
;
187 CCoinsViewCursor
*Cursor() const override
;
188 size_t EstimateSize() const override
;
192 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
193 class CCoinsViewCache
: public CCoinsViewBacked
197 * Make mutable so that we can "fill the cache" even from Get-methods
198 * declared as "const".
200 mutable uint256 hashBlock
;
201 mutable CCoinsMap cacheCoins
;
203 /* Cached dynamic memory usage for the inner Coin objects. */
204 mutable size_t cachedCoinsUsage
;
207 CCoinsViewCache(CCoinsView
*baseIn
);
209 // Standard CCoinsView methods
210 bool GetCoins(const COutPoint
&outpoint
, Coin
&coin
) const;
211 bool HaveCoins(const COutPoint
&outpoint
) const;
212 uint256
GetBestBlock() const;
213 void SetBestBlock(const uint256
&hashBlock
);
214 bool BatchWrite(CCoinsMap
&mapCoins
, const uint256
&hashBlock
);
217 * Check if we have the given utxo already loaded in this cache.
218 * The semantics are the same as HaveCoins(), but no calls to
219 * the backing CCoinsView are made.
221 bool HaveCoinsInCache(const COutPoint
&outpoint
) const;
224 * Return a reference to Coin in the cache, or a pruned one if not found. This is
225 * more efficient than GetCoins. Modifications to other cache entries are
226 * allowed while accessing the returned pointer.
228 const Coin
& AccessCoin(const COutPoint
&output
) const;
231 * Add a coin. Set potential_overwrite to true if a non-pruned version may
234 void AddCoin(const COutPoint
& outpoint
, Coin
&& coin
, bool potential_overwrite
);
237 * Spend a coin. Pass moveto in order to get the deleted data.
238 * If no unspent output exists for the passed outpoint, this call
241 void SpendCoin(const COutPoint
&outpoint
, Coin
* moveto
= nullptr);
244 * Push the modifications applied to this cache to its base.
245 * Failure to call this method before destruction will cause the changes to be forgotten.
246 * If false is returned, the state of this cache (and its backing view) will be undefined.
251 * Removes the UTXO with the given outpoint from the cache, if it is
254 void Uncache(const COutPoint
&outpoint
);
256 //! Calculate the size of the cache (in number of transaction outputs)
257 unsigned int GetCacheSize() const;
259 //! Calculate the size of the cache (in bytes)
260 size_t DynamicMemoryUsage() const;
263 * Amount of bitcoins coming in to a transaction
264 * Note that lightweight clients may not know anything besides the hash of previous transactions,
265 * so may not be able to calculate this.
267 * @param[in] tx transaction for which we are checking input total
268 * @return Sum of value of all inputs (scriptSigs)
270 CAmount
GetValueIn(const CTransaction
& tx
) const;
272 //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
273 bool HaveInputs(const CTransaction
& tx
) const;
276 CCoinsMap::iterator
FetchCoins(const COutPoint
&outpoint
) const;
279 * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
281 CCoinsViewCache(const CCoinsViewCache
&);
284 //! Utility function to add all of a transaction's outputs to a cache.
285 // It assumes that overwrites are only possible for coinbase transactions,
286 // TODO: pass in a boolean to limit these possible overwrites to known
287 // (pre-BIP34) cases.
288 void AddCoins(CCoinsViewCache
& cache
, const CTransaction
& tx
, int nHeight
);
290 //! Utility function to find any unspent output with a given txid.
291 const Coin
& AccessByTxid(const CCoinsViewCache
& cache
, const uint256
& txid
);
293 #endif // BITCOIN_COINS_H