Convert COrphanTx to keep a CTransactionRef
[bitcoinplatinum.git] / src / coins.h
blobdd6ef6cc3a9a172668ff0bb2410b593a82c1d2c8
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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).
274 CCoinsCacheEntry() : coins(), flags(0) {}
277 typedef boost::unordered_map<uint256, CCoinsCacheEntry, SaltedTxidHasher> CCoinsMap;
279 /** Cursor for iterating over CoinsView state */
280 class CCoinsViewCursor
282 public:
283 CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
284 virtual ~CCoinsViewCursor();
286 virtual bool GetKey(uint256 &key) const = 0;
287 virtual bool GetValue(CCoins &coins) const = 0;
288 /* Don't care about GetKeySize here */
289 virtual unsigned int GetValueSize() const = 0;
291 virtual bool Valid() const = 0;
292 virtual void Next() = 0;
294 //! Get best block at the time this cursor was created
295 const uint256 &GetBestBlock() const { return hashBlock; }
296 private:
297 uint256 hashBlock;
300 /** Abstract view on the open txout dataset. */
301 class CCoinsView
303 public:
304 //! Retrieve the CCoins (unspent transaction outputs) for a given txid
305 virtual bool GetCoins(const uint256 &txid, CCoins &coins) const;
307 //! Just check whether we have data for a given txid.
308 //! This may (but cannot always) return true for fully spent transactions
309 virtual bool HaveCoins(const uint256 &txid) const;
311 //! Retrieve the block hash whose state this CCoinsView currently represents
312 virtual uint256 GetBestBlock() const;
314 //! Do a bulk modification (multiple CCoins changes + BestBlock change).
315 //! The passed mapCoins can be modified.
316 virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
318 //! Get a cursor to iterate over the whole state
319 virtual CCoinsViewCursor *Cursor() const;
321 //! As we use CCoinsViews polymorphically, have a virtual destructor
322 virtual ~CCoinsView() {}
326 /** CCoinsView backed by another CCoinsView */
327 class CCoinsViewBacked : public CCoinsView
329 protected:
330 CCoinsView *base;
332 public:
333 CCoinsViewBacked(CCoinsView *viewIn);
334 bool GetCoins(const uint256 &txid, CCoins &coins) const;
335 bool HaveCoins(const uint256 &txid) const;
336 uint256 GetBestBlock() const;
337 void SetBackend(CCoinsView &viewIn);
338 bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
339 CCoinsViewCursor *Cursor() const;
343 class CCoinsViewCache;
345 /**
346 * A reference to a mutable cache entry. Encapsulating it allows us to run
347 * cleanup code after the modification is finished, and keeping track of
348 * concurrent modifications.
350 class CCoinsModifier
352 private:
353 CCoinsViewCache& cache;
354 CCoinsMap::iterator it;
355 size_t cachedCoinUsage; // Cached memory usage of the CCoins object before modification
356 CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage);
358 public:
359 CCoins* operator->() { return &it->second.coins; }
360 CCoins& operator*() { return it->second.coins; }
361 ~CCoinsModifier();
362 friend class CCoinsViewCache;
365 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
366 class CCoinsViewCache : public CCoinsViewBacked
368 protected:
369 /* Whether this cache has an active modifier. */
370 bool hasModifier;
374 * Make mutable so that we can "fill the cache" even from Get-methods
375 * declared as "const".
377 mutable uint256 hashBlock;
378 mutable CCoinsMap cacheCoins;
380 /* Cached dynamic memory usage for the inner CCoins objects. */
381 mutable size_t cachedCoinsUsage;
383 public:
384 CCoinsViewCache(CCoinsView *baseIn);
385 ~CCoinsViewCache();
387 // Standard CCoinsView methods
388 bool GetCoins(const uint256 &txid, CCoins &coins) const;
389 bool HaveCoins(const uint256 &txid) const;
390 uint256 GetBestBlock() const;
391 void SetBestBlock(const uint256 &hashBlock);
392 bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
395 * Check if we have the given tx already loaded in this cache.
396 * The semantics are the same as HaveCoins(), but no calls to
397 * the backing CCoinsView are made.
399 bool HaveCoinsInCache(const uint256 &txid) const;
402 * Return a pointer to CCoins in the cache, or NULL if not found. This is
403 * more efficient than GetCoins. Modifications to other cache entries are
404 * allowed while accessing the returned pointer.
406 const CCoins* AccessCoins(const uint256 &txid) const;
409 * Return a modifiable reference to a CCoins. If no entry with the given
410 * txid exists, a new one is created. Simultaneous modifications are not
411 * allowed.
413 CCoinsModifier ModifyCoins(const uint256 &txid);
416 * Return a modifiable reference to a CCoins. Assumes that no entry with the given
417 * txid exists and creates a new one. This saves a database access in the case where
418 * the coins were to be wiped out by FromTx anyway. This should not be called with
419 * the 2 historical coinbase duplicate pairs because the new coins are marked fresh, and
420 * in the event the duplicate coinbase was spent before a flush, the now pruned coins
421 * would not properly overwrite the first coinbase of the pair. Simultaneous modifications
422 * are not allowed.
424 CCoinsModifier ModifyNewCoins(const uint256 &txid, bool coinbase);
427 * Push the modifications applied to this cache to its base.
428 * Failure to call this method before destruction will cause the changes to be forgotten.
429 * If false is returned, the state of this cache (and its backing view) will be undefined.
431 bool Flush();
434 * Removes the transaction with the given hash from the cache, if it is
435 * not modified.
437 void Uncache(const uint256 &txid);
439 //! Calculate the size of the cache (in number of transactions)
440 unsigned int GetCacheSize() const;
442 //! Calculate the size of the cache (in bytes)
443 size_t DynamicMemoryUsage() const;
445 /**
446 * Amount of bitcoins coming in to a transaction
447 * Note that lightweight clients may not know anything besides the hash of previous transactions,
448 * so may not be able to calculate this.
450 * @param[in] tx transaction for which we are checking input total
451 * @return Sum of value of all inputs (scriptSigs)
453 CAmount GetValueIn(const CTransaction& tx) const;
455 //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
456 bool HaveInputs(const CTransaction& tx) const;
459 * Return priority of tx at height nHeight. Also calculate the sum of the values of the inputs
460 * that are already in the chain. These are the inputs that will age and increase priority as
461 * new blocks are added to the chain.
463 double GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const;
465 const CTxOut &GetOutputFor(const CTxIn& input) const;
467 friend class CCoinsModifier;
469 private:
470 CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const;
473 * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
475 CCoinsViewCache(const CCoinsViewCache &);
478 #endif // BITCOIN_COINS_H