Add commenting around JSON error codes
[bitcoinplatinum.git] / src / coins.h
blobd921f5c2a5c79b75342b01b34ec83afa7da69b1d
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 /* Don't care about GetKeySize here */
294 virtual unsigned int GetValueSize() const = 0;
296 virtual bool Valid() const = 0;
297 virtual void Next() = 0;
299 //! Get best block at the time this cursor was created
300 const uint256 &GetBestBlock() const { return hashBlock; }
301 private:
302 uint256 hashBlock;
305 /** Abstract view on the open txout dataset. */
306 class CCoinsView
308 public:
309 //! Retrieve the CCoins (unspent transaction outputs) for a given txid
310 virtual bool GetCoins(const uint256 &txid, CCoins &coins) const;
312 //! Just check whether we have data for a given txid.
313 //! This may (but cannot always) return true for fully spent transactions
314 virtual bool HaveCoins(const uint256 &txid) const;
316 //! Retrieve the block hash whose state this CCoinsView currently represents
317 virtual uint256 GetBestBlock() const;
319 //! Do a bulk modification (multiple CCoins changes + BestBlock change).
320 //! The passed mapCoins can be modified.
321 virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
323 //! Get a cursor to iterate over the whole state
324 virtual CCoinsViewCursor *Cursor() const;
326 //! As we use CCoinsViews polymorphically, have a virtual destructor
327 virtual ~CCoinsView() {}
331 /** CCoinsView backed by another CCoinsView */
332 class CCoinsViewBacked : public CCoinsView
334 protected:
335 CCoinsView *base;
337 public:
338 CCoinsViewBacked(CCoinsView *viewIn);
339 bool GetCoins(const uint256 &txid, CCoins &coins) const;
340 bool HaveCoins(const uint256 &txid) const;
341 uint256 GetBestBlock() const;
342 void SetBackend(CCoinsView &viewIn);
343 bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
344 CCoinsViewCursor *Cursor() const;
348 class CCoinsViewCache;
350 /**
351 * A reference to a mutable cache entry. Encapsulating it allows us to run
352 * cleanup code after the modification is finished, and keeping track of
353 * concurrent modifications.
355 class CCoinsModifier
357 private:
358 CCoinsViewCache& cache;
359 CCoinsMap::iterator it;
360 size_t cachedCoinUsage; // Cached memory usage of the CCoins object before modification
361 CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage);
363 public:
364 CCoins* operator->() { return &it->second.coins; }
365 CCoins& operator*() { return it->second.coins; }
366 ~CCoinsModifier();
367 friend class CCoinsViewCache;
370 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
371 class CCoinsViewCache : public CCoinsViewBacked
373 protected:
374 /* Whether this cache has an active modifier. */
375 bool hasModifier;
379 * Make mutable so that we can "fill the cache" even from Get-methods
380 * declared as "const".
382 mutable uint256 hashBlock;
383 mutable CCoinsMap cacheCoins;
385 /* Cached dynamic memory usage for the inner CCoins objects. */
386 mutable size_t cachedCoinsUsage;
388 public:
389 CCoinsViewCache(CCoinsView *baseIn);
390 ~CCoinsViewCache();
392 // Standard CCoinsView methods
393 bool GetCoins(const uint256 &txid, CCoins &coins) const;
394 bool HaveCoins(const uint256 &txid) const;
395 uint256 GetBestBlock() const;
396 void SetBestBlock(const uint256 &hashBlock);
397 bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
400 * Check if we have the given tx already loaded in this cache.
401 * The semantics are the same as HaveCoins(), but no calls to
402 * the backing CCoinsView are made.
404 bool HaveCoinsInCache(const uint256 &txid) const;
407 * Return a pointer to CCoins in the cache, or NULL if not found. This is
408 * more efficient than GetCoins. Modifications to other cache entries are
409 * allowed while accessing the returned pointer.
411 const CCoins* AccessCoins(const uint256 &txid) const;
414 * Return a modifiable reference to a CCoins. If no entry with the given
415 * txid exists, a new one is created. Simultaneous modifications are not
416 * allowed.
418 CCoinsModifier ModifyCoins(const uint256 &txid);
421 * Return a modifiable reference to a CCoins. Assumes that no entry with the given
422 * txid exists and creates a new one. This saves a database access in the case where
423 * the coins were to be wiped out by FromTx anyway. This should not be called with
424 * the 2 historical coinbase duplicate pairs because the new coins are marked fresh, and
425 * in the event the duplicate coinbase was spent before a flush, the now pruned coins
426 * would not properly overwrite the first coinbase of the pair. Simultaneous modifications
427 * are not allowed.
429 CCoinsModifier ModifyNewCoins(const uint256 &txid, bool coinbase);
432 * Push the modifications applied to this cache to its base.
433 * Failure to call this method before destruction will cause the changes to be forgotten.
434 * If false is returned, the state of this cache (and its backing view) will be undefined.
436 bool Flush();
439 * Removes the transaction with the given hash from the cache, if it is
440 * not modified.
442 void Uncache(const uint256 &txid);
444 //! Calculate the size of the cache (in number of transactions)
445 unsigned int GetCacheSize() const;
447 //! Calculate the size of the cache (in bytes)
448 size_t DynamicMemoryUsage() const;
450 /**
451 * Amount of bitcoins coming in to a transaction
452 * Note that lightweight clients may not know anything besides the hash of previous transactions,
453 * so may not be able to calculate this.
455 * @param[in] tx transaction for which we are checking input total
456 * @return Sum of value of all inputs (scriptSigs)
458 CAmount GetValueIn(const CTransaction& tx) const;
460 //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
461 bool HaveInputs(const CTransaction& tx) const;
463 const CTxOut &GetOutputFor(const CTxIn& input) const;
465 friend class CCoinsModifier;
467 private:
468 CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const;
471 * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
473 CCoinsViewCache(const CCoinsViewCache &);
476 #endif // BITCOIN_COINS_H