Merge #10114: [tests] sync_with_ping should assert that ping hasn't timed out
[bitcoinplatinum.git] / src / coins.h
blob8ee49b33aeadd3effd80fe6f3e59a7b5dbc9b178
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"
11 #include "hash.h"
12 #include "memusage.h"
13 #include "serialize.h"
14 #include "uint256.h"
16 #include <assert.h>
17 #include <stdint.h>
19 #include <boost/foreach.hpp>
20 #include <boost/unordered_map.hpp>
22 /**
23 * Pruned version of CTransaction: only retains metadata and unspent transaction outputs
25 * Serialized format:
26 * - VARINT(nVersion)
27 * - VARINT(nCode)
28 * - unspentness bitvector, for vout[2] and further; least significant byte first
29 * - the non-spent CTxOuts (via CTxOutCompressor)
30 * - VARINT(nHeight)
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 * <><><--------------------------------------------><---->
42 * | \ | /
43 * version code vout[1] height
45 * - version = 1
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
52 * - height = 203998
55 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
56 * <><><--><--------------------------------------------------><----------------------------------------------><---->
57 * / \ \ | | /
58 * version code unspentness vout[4] vout[16] height
60 * - version = 1
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
72 * - height = 120891
74 class CCoins
76 public:
77 //! whether transaction is a coinbase
78 bool fCoinBase;
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
84 int nHeight;
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
88 int nVersion;
90 void FromTx(const CTransaction &tx, int nHeightIn) {
91 fCoinBase = tx.IsCoinBase();
92 vout = tx.vout;
93 nHeight = nHeightIn;
94 nVersion = tx.nVersion;
95 ClearUnspendable();
98 //! construct a CCoins from a CTransaction, at a given height
99 CCoins(const CTransaction &tx, int nHeightIn) {
100 FromTx(tx, nHeightIn);
103 void Clear() {
104 fCoinBase = false;
105 std::vector<CTxOut>().swap(vout);
106 nHeight = 0;
107 nVersion = 0;
110 //! empty constructor
111 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
113 //!remove spent outputs at the end of vout
114 void Cleanup() {
115 while (vout.size() > 0 && vout.back().IsNull())
116 vout.pop_back();
117 if (vout.empty())
118 std::vector<CTxOut>().swap(vout);
121 void ClearUnspendable() {
122 BOOST_FOREACH(CTxOut &txout, vout) {
123 if (txout.scriptPubKey.IsUnspendable())
124 txout.SetNull();
126 Cleanup();
129 void swap(CCoins &to) {
130 std::swap(to.fCoinBase, fCoinBase);
131 to.vout.swap(vout);
132 std::swap(to.nHeight, nHeight);
133 std::swap(to.nVersion, nVersion);
136 //! equality test
137 friend bool operator==(const CCoins &a, const CCoins &b) {
138 // Empty CCoins objects are always equal.
139 if (a.IsPruned() && b.IsPruned())
140 return true;
141 return a.fCoinBase == b.fCoinBase &&
142 a.nHeight == b.nHeight &&
143 a.nVersion == b.nVersion &&
144 a.vout == b.vout;
146 friend bool operator!=(const CCoins &a, const CCoins &b) {
147 return !(a == b);
150 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
152 bool IsCoinBase() const {
153 return fCoinBase;
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);
164 // version
165 ::Serialize(s, VARINT(this->nVersion));
166 // header code
167 ::Serialize(s, VARINT(nCode));
168 // spentness bitmask
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())
173 chAvail |= (1 << i);
174 ::Serialize(s, chAvail);
176 // txouts themself
177 for (unsigned int i = 0; i < vout.size(); i++) {
178 if (!vout[i].IsNull())
179 ::Serialize(s, CTxOutCompressor(REF(vout[i])));
181 // coinbase height
182 ::Serialize(s, VARINT(nHeight));
185 template<typename Stream>
186 void Unserialize(Stream &s) {
187 unsigned int nCode = 0;
188 // version
189 ::Unserialize(s, VARINT(this->nVersion));
190 // header code
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);
197 // spentness bitmask
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;
203 vAvail.push_back(f);
205 if (chAvail != 0)
206 nMaskCode--;
208 // txouts themself
209 vout.assign(vAvail.size(), CTxOut());
210 for (unsigned int i = 0; i < vAvail.size(); i++) {
211 if (vAvail[i])
212 ::Unserialize(s, REF(CTxOutCompressor(vout[i])));
214 // coinbase height
215 ::Unserialize(s, VARINT(nHeight));
216 Cleanup();
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)
231 if (!out.IsNull())
232 return false;
233 return true;
236 size_t DynamicMemoryUsage() const {
237 size_t ret = memusage::DynamicUsage(vout);
238 BOOST_FOREACH(const CTxOut &out, vout) {
239 ret += RecursiveDynamicUsage(out.scriptPubKey);
241 return ret;
245 class SaltedTxidHasher
247 private:
248 /** Salt */
249 const uint64_t k0, k1;
251 public:
252 SaltedTxidHasher();
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.
267 unsigned char flags;
269 enum Flags {
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
287 public:
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; }
300 private:
301 uint256 hashBlock;
304 /** Abstract view on the open txout dataset. */
305 class CCoinsView
307 public:
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
333 protected:
334 CCoinsView *base;
336 public:
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;
349 /**
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.
354 class CCoinsModifier
356 private:
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);
362 public:
363 CCoins* operator->() { return &it->second.coins; }
364 CCoins& operator*() { return it->second.coins; }
365 ~CCoinsModifier();
366 friend class CCoinsViewCache;
369 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
370 class CCoinsViewCache : public CCoinsViewBacked
372 protected:
373 /* Whether this cache has an active modifier. */
374 bool hasModifier;
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;
387 public:
388 CCoinsViewCache(CCoinsView *baseIn);
389 ~CCoinsViewCache();
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
415 * allowed.
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
426 * are not allowed.
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.
435 bool Flush();
438 * Removes the transaction with the given hash from the cache, if it is
439 * not modified.
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;
449 /**
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;
466 private:
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