1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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 "serialize.h"
16 #include <boost/foreach.hpp>
17 #include <boost/unordered_map.hpp>
20 * Pruned version of CTransaction: only retains metadata and unspent transaction outputs
25 * - unspentness bitvector, for vout[2] and further; least significant byte first
26 * - the non-spent CTxOuts (via CTxOutCompressor)
29 * The nCode value consists of:
30 * - bit 1: IsCoinBase()
31 * - bit 2: vout[0] is not spent
32 * - bit 4: vout[1] is not spent
33 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
34 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
35 * least one non-spent output).
37 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
38 * <><><--------------------------------------------><---->
40 * version code vout[1] height
43 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
44 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
45 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
46 * * 8358: compact amount representation for 60000000000 (600 BTC)
47 * * 00: special txout type pay-to-pubkey-hash
48 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
52 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
53 * <><><--><--------------------------------------------------><----------------------------------------------><---->
55 * version code unspentness vout[4] vout[16] height
58 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
59 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
60 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
61 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
62 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
63 * * 00: special txout type pay-to-pubkey-hash
64 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
65 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
66 * * bbd123: compact amount representation for 110397 (0.001 BTC)
67 * * 00: special txout type pay-to-pubkey-hash
68 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
74 //! whether transaction is a coinbase
77 //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
78 std::vector<CTxOut> vout;
80 //! at which height this transaction was included in the active block chain
83 //! version of the CTransaction; accesses to this value should probably check for nHeight as well,
84 //! as new tx version will probably only be introduced at certain heights
87 void FromTx(const CTransaction &tx, int nHeightIn) {
88 fCoinBase = tx.IsCoinBase();
91 nVersion = tx.nVersion;
95 //! construct a CCoins from a CTransaction, at a given height
96 CCoins(const CTransaction &tx, int nHeightIn) {
97 FromTx(tx, nHeightIn);
102 std::vector<CTxOut>().swap(vout);
107 //! empty constructor
108 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
110 //!remove spent outputs at the end of vout
112 while (vout.size() > 0 && vout.back().IsNull())
115 std::vector<CTxOut>().swap(vout);
118 void ClearUnspendable() {
119 BOOST_FOREACH(CTxOut &txout, vout) {
120 if (txout.scriptPubKey.IsUnspendable())
126 void swap(CCoins &to) {
127 std::swap(to.fCoinBase, fCoinBase);
129 std::swap(to.nHeight, nHeight);
130 std::swap(to.nVersion, nVersion);
134 friend bool operator==(const CCoins &a, const CCoins &b) {
135 // Empty CCoins objects are always equal.
136 if (a.IsPruned() && b.IsPruned())
138 return a.fCoinBase == b.fCoinBase &&
139 a.nHeight == b.nHeight &&
140 a.nVersion == b.nVersion &&
143 friend bool operator!=(const CCoins &a, const CCoins &b) {
147 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
149 bool IsCoinBase() const {
153 unsigned int GetSerializeSize(int nType, int nVersion) const {
154 unsigned int nSize = 0;
155 unsigned int nMaskSize = 0, nMaskCode = 0;
156 CalcMaskSize(nMaskSize, nMaskCode);
157 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
158 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
159 assert(fFirst || fSecond || nMaskCode);
160 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
162 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
163 // size of header code
164 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
168 for (unsigned int i = 0; i < vout.size(); i++)
169 if (!vout[i].IsNull())
170 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
172 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
176 template<typename Stream>
177 void Serialize(Stream &s, int nType, int nVersion) const {
178 unsigned int nMaskSize = 0, nMaskCode = 0;
179 CalcMaskSize(nMaskSize, nMaskCode);
180 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
181 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
182 assert(fFirst || fSecond || nMaskCode);
183 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
185 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
187 ::Serialize(s, VARINT(nCode), nType, nVersion);
189 for (unsigned int b = 0; b<nMaskSize; b++) {
190 unsigned char chAvail = 0;
191 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
192 if (!vout[2+b*8+i].IsNull())
194 ::Serialize(s, chAvail, nType, nVersion);
197 for (unsigned int i = 0; i < vout.size(); i++) {
198 if (!vout[i].IsNull())
199 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
202 ::Serialize(s, VARINT(nHeight), nType, nVersion);
205 template<typename Stream>
206 void Unserialize(Stream &s, int nType, int nVersion) {
207 unsigned int nCode = 0;
209 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
211 ::Unserialize(s, VARINT(nCode), nType, nVersion);
212 fCoinBase = nCode & 1;
213 std::vector<bool> vAvail(2, false);
214 vAvail[0] = (nCode & 2) != 0;
215 vAvail[1] = (nCode & 4) != 0;
216 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
218 while (nMaskCode > 0) {
219 unsigned char chAvail = 0;
220 ::Unserialize(s, chAvail, nType, nVersion);
221 for (unsigned int p = 0; p < 8; p++) {
222 bool f = (chAvail & (1 << p)) != 0;
229 vout.assign(vAvail.size(), CTxOut());
230 for (unsigned int i = 0; i < vAvail.size(); i++) {
232 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
235 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
239 //! mark a vout spent
240 bool Spend(uint32_t nPos);
242 //! check whether a particular output is still available
243 bool IsAvailable(unsigned int nPos) const {
244 return (nPos < vout.size() && !vout[nPos].IsNull());
247 //! check whether the entire CCoins is spent
248 //! note that only !IsPruned() CCoins can be serialized
249 bool IsPruned() const {
250 BOOST_FOREACH(const CTxOut &out, vout)
257 class CCoinsKeyHasher
266 * This *must* return size_t. With Boost 1.46 on 32-bit systems the
267 * unordered_map will behave unpredictably if the custom hasher returns a
268 * uint64_t, resulting in failures when syncing the chain (#4634).
270 size_t operator()(const uint256& key) const {
271 return key.GetHash(salt);
275 struct CCoinsCacheEntry
277 CCoins coins; // The actual cached data.
281 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
282 FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
285 CCoinsCacheEntry() : coins(), flags(0) {}
288 typedef boost::unordered_map<uint256, CCoinsCacheEntry, CCoinsKeyHasher> CCoinsMap;
294 uint64_t nTransactions;
295 uint64_t nTransactionOutputs;
296 uint64_t nSerializedSize;
297 uint256 hashSerialized;
298 CAmount nTotalAmount;
300 CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), nTotalAmount(0) {}
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 //! Calculate statistics about the unspent transaction output set
323 virtual bool GetStats(CCoinsStats &stats) 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 bool GetStats(CCoinsStats &stats) 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 CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_);
362 CCoins* operator->() { return &it->second.coins; }
363 CCoins& operator*() { return it->second.coins; }
365 friend class CCoinsViewCache;
368 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
369 class CCoinsViewCache : public CCoinsViewBacked
372 /* Whether this cache has an active modifier. */
376 * Make mutable so that we can "fill the cache" even from Get-methods
377 * declared as "const".
379 mutable uint256 hashBlock;
380 mutable CCoinsMap cacheCoins;
383 CCoinsViewCache(CCoinsView *baseIn);
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 * Return a pointer to CCoins in the cache, or NULL if not found. This is
395 * more efficient than GetCoins. Modifications to other cache entries are
396 * allowed while accessing the returned pointer.
398 const CCoins* AccessCoins(const uint256 &txid) const;
401 * Return a modifiable reference to a CCoins. If no entry with the given
402 * txid exists, a new one is created. Simultaneous modifications are not
405 CCoinsModifier ModifyCoins(const uint256 &txid);
408 * Push the modifications applied to this cache to its base.
409 * Failure to call this method before destruction will cause the changes to be forgotten.
410 * If false is returned, the state of this cache (and its backing view) will be undefined.
414 //! Calculate the size of the cache (in number of transactions)
415 unsigned int GetCacheSize() const;
418 * Amount of bitcoins coming in to a transaction
419 * Note that lightweight clients may not know anything besides the hash of previous transactions,
420 * so may not be able to calculate this.
422 * @param[in] tx transaction for which we are checking input total
423 * @return Sum of value of all inputs (scriptSigs)
425 CAmount GetValueIn(const CTransaction& tx) const;
427 //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
428 bool HaveInputs(const CTransaction& tx) const;
430 //! Return priority of tx at height nHeight
431 double GetPriority(const CTransaction &tx, int nHeight) const;
433 const CTxOut &GetOutputFor(const CTxIn& input) const;
435 friend class CCoinsModifier;
438 CCoinsMap::iterator FetchCoins(const uint256 &txid);
439 CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const;
442 * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
444 CCoinsViewCache(const CCoinsViewCache &);
447 #endif // BITCOIN_COINS_H