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 "compressor.h"
10 #include "core_memusage.h"
13 #include "serialize.h"
19 #include <boost/foreach.hpp>
20 #include <boost/unordered_map.hpp>
23 * Pruned version of CTransaction: only retains metadata and unspent transaction outputs
28 * - unspentness bitvector, for vout[2] and further; least significant byte first
29 * - the non-spent CTxOuts (via CTxOutCompressor)
32 * The nCode value consists of:
33 * - bit 0: IsCoinBase()
34 * - bit 1: vout[0] is not spent
35 * - bit 2: vout[1] is not spent
36 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
37 * - In case both bit 1 and bit 2 are unset, they encode N-1, as there must be at
38 * least one non-spent output).
40 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
41 * <><><--------------------------------------------><---->
43 * version code vout[1] height
46 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
47 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
48 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
49 * * 8358: compact amount representation for 60000000000 (600 BTC)
50 * * 00: special txout type pay-to-pubkey-hash
51 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
55 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
56 * <><><--><--------------------------------------------------><----------------------------------------------><---->
58 * version code unspentness vout[4] vout[16] height
61 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
62 * 2 (1, +1 because both bit 1 and bit 2 are unset) non-zero bitvector bytes follow)
63 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
64 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
65 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
66 * * 00: special txout type pay-to-pubkey-hash
67 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
68 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
69 * * bbd123: compact amount representation for 110397 (0.001 BTC)
70 * * 00: special txout type pay-to-pubkey-hash
71 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
77 //! whether transaction is a coinbase
80 //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
81 std::vector
<CTxOut
> vout
;
83 //! at which height this transaction was included in the active block chain
86 //! version of the CTransaction; accesses to this value should probably check for nHeight as well,
87 //! as new tx version will probably only be introduced at certain heights
90 void FromTx(const CTransaction
&tx
, int nHeightIn
) {
91 fCoinBase
= tx
.IsCoinBase();
94 nVersion
= tx
.nVersion
;
98 //! construct a CCoins from a CTransaction, at a given height
99 CCoins(const CTransaction
&tx
, int nHeightIn
) {
100 FromTx(tx
, nHeightIn
);
105 std::vector
<CTxOut
>().swap(vout
);
110 //! empty constructor
111 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
113 //!remove spent outputs at the end of vout
115 while (vout
.size() > 0 && vout
.back().IsNull())
118 std::vector
<CTxOut
>().swap(vout
);
121 void ClearUnspendable() {
122 BOOST_FOREACH(CTxOut
&txout
, vout
) {
123 if (txout
.scriptPubKey
.IsUnspendable())
129 void swap(CCoins
&to
) {
130 std::swap(to
.fCoinBase
, fCoinBase
);
132 std::swap(to
.nHeight
, nHeight
);
133 std::swap(to
.nVersion
, nVersion
);
137 friend bool operator==(const CCoins
&a
, const CCoins
&b
) {
138 // Empty CCoins objects are always equal.
139 if (a
.IsPruned() && b
.IsPruned())
141 return a
.fCoinBase
== b
.fCoinBase
&&
142 a
.nHeight
== b
.nHeight
&&
143 a
.nVersion
== b
.nVersion
&&
146 friend bool operator!=(const CCoins
&a
, const CCoins
&b
) {
150 void CalcMaskSize(unsigned int &nBytes
, unsigned int &nNonzeroBytes
) const;
152 bool IsCoinBase() const {
156 template<typename Stream
>
157 void Serialize(Stream
&s
) const {
158 unsigned int nMaskSize
= 0, nMaskCode
= 0;
159 CalcMaskSize(nMaskSize
, nMaskCode
);
160 bool fFirst
= vout
.size() > 0 && !vout
[0].IsNull();
161 bool fSecond
= vout
.size() > 1 && !vout
[1].IsNull();
162 assert(fFirst
|| fSecond
|| nMaskCode
);
163 unsigned int nCode
= 8*(nMaskCode
- (fFirst
|| fSecond
? 0 : 1)) + (fCoinBase
? 1 : 0) + (fFirst
? 2 : 0) + (fSecond
? 4 : 0);
165 ::Serialize(s
, VARINT(this->nVersion
));
167 ::Serialize(s
, VARINT(nCode
));
169 for (unsigned int b
= 0; b
<nMaskSize
; b
++) {
170 unsigned char chAvail
= 0;
171 for (unsigned int i
= 0; i
< 8 && 2+b
*8+i
< vout
.size(); i
++)
172 if (!vout
[2+b
*8+i
].IsNull())
174 ::Serialize(s
, chAvail
);
177 for (unsigned int i
= 0; i
< vout
.size(); i
++) {
178 if (!vout
[i
].IsNull())
179 ::Serialize(s
, CTxOutCompressor(REF(vout
[i
])));
182 ::Serialize(s
, VARINT(nHeight
));
185 template<typename Stream
>
186 void Unserialize(Stream
&s
) {
187 unsigned int nCode
= 0;
189 ::Unserialize(s
, VARINT(this->nVersion
));
191 ::Unserialize(s
, VARINT(nCode
));
192 fCoinBase
= nCode
& 1;
193 std::vector
<bool> vAvail(2, false);
194 vAvail
[0] = (nCode
& 2) != 0;
195 vAvail
[1] = (nCode
& 4) != 0;
196 unsigned int nMaskCode
= (nCode
/ 8) + ((nCode
& 6) != 0 ? 0 : 1);
198 while (nMaskCode
> 0) {
199 unsigned char chAvail
= 0;
200 ::Unserialize(s
, chAvail
);
201 for (unsigned int p
= 0; p
< 8; p
++) {
202 bool f
= (chAvail
& (1 << p
)) != 0;
209 vout
.assign(vAvail
.size(), CTxOut());
210 for (unsigned int i
= 0; i
< vAvail
.size(); i
++) {
212 ::Unserialize(s
, REF(CTxOutCompressor(vout
[i
])));
215 ::Unserialize(s
, VARINT(nHeight
));
219 //! mark a vout spent
220 bool Spend(uint32_t nPos
);
222 //! check whether a particular output is still available
223 bool IsAvailable(unsigned int nPos
) const {
224 return (nPos
< vout
.size() && !vout
[nPos
].IsNull());
227 //! check whether the entire CCoins is spent
228 //! note that only !IsPruned() CCoins can be serialized
229 bool IsPruned() const {
230 BOOST_FOREACH(const CTxOut
&out
, vout
)
236 size_t DynamicMemoryUsage() const {
237 size_t ret
= memusage::DynamicUsage(vout
);
238 BOOST_FOREACH(const CTxOut
&out
, vout
) {
239 ret
+= RecursiveDynamicUsage(out
.scriptPubKey
);
245 class SaltedTxidHasher
249 const uint64_t k0
, k1
;
255 * This *must* return size_t. With Boost 1.46 on 32-bit systems the
256 * unordered_map will behave unpredictably if the custom hasher returns a
257 * uint64_t, resulting in failures when syncing the chain (#4634).
259 size_t operator()(const uint256
& txid
) const {
260 return SipHashUint256(k0
, k1
, txid
);
264 struct CCoinsCacheEntry
266 CCoins coins
; // The actual cached data.
270 DIRTY
= (1 << 0), // This cache entry is potentially different from the version in the parent view.
271 FRESH
= (1 << 1), // The parent view does not have this entry (or it is pruned).
272 /* Note that FRESH is a performance optimization with which we can
273 * erase coins that are fully spent if we know we do not need to
274 * flush the changes to the parent cache. It is always safe to
275 * not mark FRESH if that condition is not guaranteed.
279 CCoinsCacheEntry() : coins(), flags(0) {}
282 typedef boost::unordered_map
<uint256
, CCoinsCacheEntry
, SaltedTxidHasher
> CCoinsMap
;
284 /** Cursor for iterating over CoinsView state */
285 class CCoinsViewCursor
288 CCoinsViewCursor(const uint256
&hashBlockIn
): hashBlock(hashBlockIn
) {}
289 virtual ~CCoinsViewCursor();
291 virtual bool GetKey(uint256
&key
) const = 0;
292 virtual bool GetValue(CCoins
&coins
) const = 0;
293 virtual unsigned int GetValueSize() const = 0;
295 virtual bool Valid() const = 0;
296 virtual void Next() = 0;
298 //! Get best block at the time this cursor was created
299 const uint256
&GetBestBlock() const { return hashBlock
; }
304 /** Abstract view on the open txout dataset. */
308 //! Retrieve the CCoins (unspent transaction outputs) for a given txid
309 virtual bool GetCoins(const uint256
&txid
, CCoins
&coins
) const;
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;
315 //! Retrieve the block hash whose state this CCoinsView currently represents
316 virtual uint256
GetBestBlock() const;
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
);
322 //! Get a cursor to iterate over the whole state
323 virtual CCoinsViewCursor
*Cursor() const;
325 //! As we use CCoinsViews polymorphically, have a virtual destructor
326 virtual ~CCoinsView() {}
330 /** CCoinsView backed by another CCoinsView */
331 class CCoinsViewBacked
: public CCoinsView
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 CCoinsViewCursor
*Cursor() const;
347 class CCoinsViewCache
;
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.
357 CCoinsViewCache
& cache
;
358 CCoinsMap::iterator it
;
359 size_t cachedCoinUsage
; // Cached memory usage of the CCoins object before modification
360 CCoinsModifier(CCoinsViewCache
& cache_
, CCoinsMap::iterator it_
, size_t usage
);
363 CCoins
* operator->() { return &it
->second
.coins
; }
364 CCoins
& operator*() { return it
->second
.coins
; }
366 friend class CCoinsViewCache
;
369 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
370 class CCoinsViewCache
: public CCoinsViewBacked
373 /* Whether this cache has an active modifier. */
378 * Make mutable so that we can "fill the cache" even from Get-methods
379 * declared as "const".
381 mutable uint256 hashBlock
;
382 mutable CCoinsMap cacheCoins
;
384 /* Cached dynamic memory usage for the inner CCoins objects. */
385 mutable size_t cachedCoinsUsage
;
388 CCoinsViewCache(CCoinsView
*baseIn
);
391 // Standard CCoinsView methods
392 bool GetCoins(const uint256
&txid
, CCoins
&coins
) const;
393 bool HaveCoins(const uint256
&txid
) const;
394 uint256
GetBestBlock() const;
395 void SetBestBlock(const uint256
&hashBlock
);
396 bool BatchWrite(CCoinsMap
&mapCoins
, const uint256
&hashBlock
);
399 * Check if we have the given tx already loaded in this cache.
400 * The semantics are the same as HaveCoins(), but no calls to
401 * the backing CCoinsView are made.
403 bool HaveCoinsInCache(const uint256
&txid
) const;
406 * Return a pointer to CCoins in the cache, or NULL if not found. This is
407 * more efficient than GetCoins. Modifications to other cache entries are
408 * allowed while accessing the returned pointer.
410 const CCoins
* AccessCoins(const uint256
&txid
) const;
413 * Return a modifiable reference to a CCoins. If no entry with the given
414 * txid exists, a new one is created. Simultaneous modifications are not
417 CCoinsModifier
ModifyCoins(const uint256
&txid
);
420 * Return a modifiable reference to a CCoins. Assumes that no entry with the given
421 * txid exists and creates a new one. This saves a database access in the case where
422 * the coins were to be wiped out by FromTx anyway. This should not be called with
423 * the 2 historical coinbase duplicate pairs because the new coins are marked fresh, and
424 * in the event the duplicate coinbase was spent before a flush, the now pruned coins
425 * would not properly overwrite the first coinbase of the pair. Simultaneous modifications
428 CCoinsModifier
ModifyNewCoins(const uint256
&txid
, bool coinbase
);
431 * Push the modifications applied to this cache to its base.
432 * Failure to call this method before destruction will cause the changes to be forgotten.
433 * If false is returned, the state of this cache (and its backing view) will be undefined.
438 * Removes the transaction with the given hash from the cache, if it is
441 void Uncache(const uint256
&txid
);
443 //! Calculate the size of the cache (in number of transactions)
444 unsigned int GetCacheSize() const;
446 //! Calculate the size of the cache (in bytes)
447 size_t DynamicMemoryUsage() const;
450 * Amount of bitcoins coming in to a transaction
451 * Note that lightweight clients may not know anything besides the hash of previous transactions,
452 * so may not be able to calculate this.
454 * @param[in] tx transaction for which we are checking input total
455 * @return Sum of value of all inputs (scriptSigs)
457 CAmount
GetValueIn(const CTransaction
& tx
) const;
459 //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
460 bool HaveInputs(const CTransaction
& tx
) const;
462 const CTxOut
&GetOutputFor(const CTxIn
& input
) const;
464 friend class CCoinsModifier
;
467 CCoinsMap::const_iterator
FetchCoins(const uint256
&txid
) const;
470 * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
472 CCoinsViewCache(const CCoinsViewCache
&);
475 #endif // BITCOIN_COINS_H