]> Git Repo - VerusCoin.git/blame - src/main.h
Make CCoinsView use block hashes instead of indices
[VerusCoin.git] / src / main.h
CommitLineData
0a61b0df 1// Copyright (c) 2009-2010 Satoshi Nakamoto
db0e8ccd 2// Copyright (c) 2009-2013 The Bitcoin developers
0a61b0df 3// Distributed under the MIT/X11 software license, see the accompanying
3a25a2b9 4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
51ed9ec9 5
223b6f1b
WL
6#ifndef BITCOIN_MAIN_H
7#define BITCOIN_MAIN_H
8
35b8af92
CF
9#if defined(HAVE_CONFIG_H)
10#include "bitcoin-config.h"
11#endif
12
223b6f1b 13#include "bignum.h"
51ed9ec9
BD
14#include "chainparams.h"
15#include "core.h"
223b6f1b 16#include "net.h"
223b6f1b 17#include "script.h"
51ed9ec9
BD
18#include "sync.h"
19#include "txmempool.h"
20#include "uint256.h"
223b6f1b 21
51ed9ec9
BD
22#include <algorithm>
23#include <exception>
24#include <map>
25#include <set>
26#include <stdint.h>
27#include <string>
28#include <utility>
29#include <vector>
0a61b0df 30
0a61b0df 31class CBlockIndex;
51ed9ec9 32class CBloomFilter;
40c2614e 33class CInv;
40c2614e 34
9d6633ac 35/** The maximum allowed size for a serialized block, in bytes (network rule) */
0a61b0df 36static const unsigned int MAX_BLOCK_SIZE = 1000000;
9d6633ac 37/** The maximum size for mined blocks */
3df62878 38static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
69e07747 39/** The maximum size for transactions we're willing to relay/mine */
41e1a0d7 40static const unsigned int MAX_STANDARD_TX_SIZE = MAX_BLOCK_SIZE_GEN/5;
9d6633ac 41/** The maximum allowed number of signature check operations in a block (network rule) */
7bd9c3a3 42static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
9d6633ac 43/** The maximum number of orphan transactions kept in memory */
7bd9c3a3 44static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
9d6633ac 45/** The maximum size of a blk?????.dat file (since 0.8) */
5382bcf8 46static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
9d6633ac 47/** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
bba89aa8 48static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
9d6633ac 49/** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
bba89aa8 50static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
9d6633ac 51/** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
450cbb09 52static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
9d6633ac 53/** No amount larger than this (in satoshi) is valid */
51ed9ec9
BD
54static const int64_t MAX_MONEY = 21000000 * COIN;
55inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
9d6633ac 56/** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
0a61b0df 57static const int COINBASE_MATURITY = 100;
9d6633ac 58/** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
f621326c 59static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
f9cae832
PW
60/** Maximum number of script-checking threads allowed */
61static const int MAX_SCRIPTCHECK_THREADS = 16;
87cce04c
MC
62/** Default amount of block size reserved for high-priority transactions (in bytes) */
63static const int DEFAULT_BLOCK_PRIORITY_SIZE = 27000;
8bb5edc1
MC
64#ifdef USE_UPNP
65static const int fHaveUPnP = true;
66#else
67static const int fHaveUPnP = false;
68#endif
0a61b0df 69
70
7bf8b7c2 71extern CScript COINBASE_FLAGS;
52a3d263
FV
72
73
0a61b0df 74
75
76
77
78extern CCriticalSection cs_main;
319b1160 79extern CTxMemPool mempool;
223b6f1b 80extern std::map<uint256, CBlockIndex*> mapBlockIndex;
51ed9ec9
BD
81extern uint64_t nLastBlockTx;
82extern uint64_t nLastBlockSize;
2bc4fd60 83extern const std::string strMessageMagic;
51ed9ec9 84extern int64_t nTimeBestReceived;
66b02c93 85extern bool fImporting;
7fea4846 86extern bool fReindex;
8a28bb6d 87extern bool fBenchmark;
f9cae832 88extern int nScriptCheckThreads;
2d1fa42e 89extern bool fTxIndex;
1c83b0a3 90extern unsigned int nCoinCacheSize;
13c84b3b 91extern bool fHaveGUI;
0a61b0df 92
93// Settings
51ed9ec9 94extern int64_t nTransactionFee;
0a61b0df 95
966ae00f 96// Minimum disk space required - used in CheckDiskSpace()
51ed9ec9 97static const uint64_t nMinDiskSpace = 52428800;
0a61b0df 98
99
450cbb09 100class CCoinsDB;
d979e6e3 101class CBlockTreeDB;
15ebd486 102struct CDiskBlockPos;
450cbb09
PW
103class CTxUndo;
104class CCoinsView;
13c51f20 105class CCoinsViewCache;
f9cae832 106class CScriptCheck;
ef3988ca 107class CValidationState;
00588c3f 108class CWalletInterface;
0a61b0df 109
03cac0bb
FV
110struct CBlockTemplate;
111
160b028b 112/** Register a wallet to receive updates from core */
00588c3f 113void RegisterWallet(CWalletInterface* pwalletIn);
160b028b 114/** Unregister a wallet from core */
00588c3f 115void UnregisterWallet(CWalletInterface* pwalletIn);
e6fe8e77
EL
116/** Unregister all wallets from core */
117void UnregisterAllWallets();
160b028b 118/** Push an updated transaction to all registered wallets */
00588c3f 119void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL);
8926263d 120
501da250
EL
121/** Register with a network node to receive its signals */
122void RegisterNodeSignals(CNodeSignals& nodeSignals);
123/** Unregister a network node */
124void UnregisterNodeSignals(CNodeSignals& nodeSignals);
125
8926263d
EL
126void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd);
127
160b028b 128/** Process an incoming block */
ef3988ca 129bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
160b028b 130/** Check whether enough disk space is available for an incoming block */
51ed9ec9 131bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
160b028b 132/** Open a block file (blk?????.dat) */
5382bcf8 133FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
160b028b 134/** Open an undo file (rev?????.dat) */
5382bcf8 135FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
160b028b 136/** Import blocks from an external file */
7fea4846 137bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
38603761
PW
138/** Initialize a new block tree database + block data on disk */
139bool InitBlockIndex();
160b028b 140/** Load the block tree and coins database from disk */
7fea4846 141bool LoadBlockIndex();
f7f3a96b
PW
142/** Unload database information */
143void UnloadBlockIndex();
1f355b66 144/** Verify consistency of the block and coin databases */
168ba993 145bool VerifyDB(int nCheckLevel, int nCheckDepth);
160b028b 146/** Print the loaded block tree */
0a61b0df 147void PrintBlockTree();
160b028b 148/** Process protocol messages received from a given node */
0a61b0df 149bool ProcessMessages(CNode* pfrom);
160b028b 150/** Send queued protocol messages to be sent to a give node */
0a61b0df 151bool SendMessages(CNode* pto, bool fSendTrickle);
f9cae832 152/** Run an instance of the script checking thread */
21eb5ada 153void ThreadScriptCheck();
160b028b 154/** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
0a61b0df 155bool CheckProofOfWork(uint256 hash, unsigned int nBits);
160b028b 156/** Calculate the minimum amount of work a received block needs, without knowing its direct parent */
51ed9ec9 157unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime);
160b028b 158/** Get the number of active peers */
d33cc2b5 159int GetNumBlocksOfPeers();
f0bf5fb2 160/** Check whether we are doing an initial block download (synchronizing from disk or network) */
0a61b0df 161bool IsInitialBlockDownload();
160b028b 162/** Format a string that describes several potential problems detected by the core */
223b6f1b 163std::string GetWarnings(std::string strFor);
160b028b 164/** Retrieve a transaction (from memory pool, or from disk, if possible) */
450cbb09 165bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
160b028b 166/** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */
ef3988ca 167bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew);
160b028b 168/** Find the best known block, and make it the tip of the block chain */
ef3988ca 169bool ConnectBestBlock(CValidationState &state);
51ed9ec9 170int64_t GetBlockValue(int nHeight, int64_t nFees);
d247a5d1 171unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock);
aabdf9e8
EL
172
173void UpdateTime(CBlockHeader& block, const CBlockIndex* pindexPrev);
174
160b028b 175/** Create a new block index entry for a given block hash */
2d8a4829 176CBlockIndex * InsertBlockIndex(uint256 hash);
f1136200
PW
177/** Verify a signature */
178bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
7851033d
PW
179/** Abort with a message */
180bool AbortNode(const std::string &msg);
857c61df 181
319b1160
GA
182/** (try to) add transaction to memory pool **/
183bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
184 bool* pfMissingInputs, bool fRejectInsaneFee=false);
0a61b0df 185
186
187
188
189
190
191
192
2d1fa42e 193struct CDiskBlockPos
630fd8dc 194{
5382bcf8
PW
195 int nFile;
196 unsigned int nPos;
630fd8dc 197
5382bcf8
PW
198 IMPLEMENT_SERIALIZE(
199 READWRITE(VARINT(nFile));
200 READWRITE(VARINT(nPos));
201 )
630fd8dc 202
a8a4b967
PK
203 CDiskBlockPos() {
204 SetNull();
205 }
206
207 CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
208 nFile = nFileIn;
209 nPos = nPosIn;
210 }
211
630fd8dc 212 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
5382bcf8 213 return (a.nFile == b.nFile && a.nPos == b.nPos);
630fd8dc
PW
214 }
215
216 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
217 return !(a == b);
218 }
219
5382bcf8
PW
220 void SetNull() { nFile = -1; nPos = 0; }
221 bool IsNull() const { return (nFile == -1); }
630fd8dc
PW
222};
223
2d1fa42e
PW
224struct CDiskTxPos : public CDiskBlockPos
225{
226 unsigned int nTxOffset; // after header
227
228 IMPLEMENT_SERIALIZE(
229 READWRITE(*(CDiskBlockPos*)this);
230 READWRITE(VARINT(nTxOffset));
231 )
232
233 CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
234 }
235
236 CDiskTxPos() {
237 SetNull();
238 }
0a61b0df 239
2d1fa42e
PW
240 void SetNull() {
241 CDiskBlockPos::SetNull();
242 nTxOffset = 0;
243 }
244};
0a61b0df 245
246
0a61b0df 247
dbbf1d4a
LD
248enum GetMinFee_mode
249{
dbbf1d4a
LD
250 GMF_RELAY,
251 GMF_SEND,
252};
253
51ed9ec9 254int64_t GetMinFee(const CTransaction& tx, bool fAllowFree, enum GetMinFee_mode mode);
788536f1 255
05df3fc6
EL
256//
257// Check transaction inputs, and make sure any
258// pay-to-script-hash transactions are evaluating IsStandard scripts
259//
260// Why bother? To avoid denial-of-service attacks; an attacker
261// can submit a standard HASH... OP_EQUAL transaction,
262// which will get accepted into blocks. The redemption
263// script can be anything; an attacker could use a very
264// expensive-to-check-upon-redemption script like:
265// DUP CHECKSIG DROP ... repeated 100 times... OP_1
266//
922e8e29 267
8d7849b6 268 /** Check for standard transaction types
05df3fc6 269 @param[in] mapInputs Map of previous transactions that have outputs we're spending
8d7849b6 270 @return True if all inputs (scriptSigs) use only standard transaction forms
8d7849b6 271 */
05df3fc6 272bool AreInputsStandard(const CTransaction& tx, CCoinsViewCache& mapInputs);
8d7849b6 273
05df3fc6
EL
274/** Count ECDSA signature operations the old-fashioned (pre-0.6) way
275 @return number of sigops this transaction's outputs will produce when spent
276 @see CTransaction::FetchInputs
277*/
278unsigned int GetLegacySigOpCount(const CTransaction& tx);
a206a239 279
05df3fc6 280/** Count ECDSA signature operations in pay-to-script-hash inputs.
0a61b0df 281
05df3fc6
EL
282 @param[in] mapInputs Map of previous transactions that have outputs we're spending
283 @return maximum number of sigops required to validate this transaction's inputs
284 @see CTransaction::FetchInputs
285 */
286unsigned int GetP2SHSigOpCount(const CTransaction& tx, CCoinsViewCache& mapInputs);
0a61b0df 287
0a61b0df 288
05df3fc6
EL
289inline bool AllowFree(double dPriority)
290{
291 // Large (in bytes) low-priority (new, small-coin) transactions
292 // need a fee.
293 return dPriority > COIN * 144 / 250;
294}
0a61b0df 295
05df3fc6
EL
296// Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
297// This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
298// instead of being performed inline.
299bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true,
300 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC,
301 std::vector<CScriptCheck> *pvChecks = NULL);
0a61b0df 302
05df3fc6 303// Apply the effects of this transaction on the UTXO set represented by view
18946846 304void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash);
8d7849b6 305
05df3fc6
EL
306// Context-independent validity checks
307bool CheckTransaction(const CTransaction& tx, CValidationState& state);
450cbb09 308
05df3fc6
EL
309/** Check for standard transaction types
310 @return True if all outputs (scriptPubKeys) use only standard transaction forms
311*/
980bfe6e 312bool IsStandardTx(const CTransaction& tx, std::string& reason);
450cbb09 313
51ed9ec9 314bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0);
450cbb09 315
05df3fc6
EL
316/** Amount of bitcoins spent by the transaction.
317 @return sum of all outputs (note: does not include fees)
318 */
51ed9ec9 319int64_t GetValueOut(const CTransaction& tx);
8d7849b6 320
8adf48dc
PW
321/** Undo information for a CBlock */
322class CBlockUndo
323{
324public:
450cbb09 325 std::vector<CTxUndo> vtxundo; // for all but the coinbase
8adf48dc
PW
326
327 IMPLEMENT_SERIALIZE(
328 READWRITE(vtxundo);
329 )
5382bcf8 330
8539361e 331 bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
5382bcf8
PW
332 {
333 // Open history file to append
334 CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
335 if (!fileout)
336 return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
337
338 // Write index header
339 unsigned int nSize = fileout.GetSerializeSize(*this);
0e4b3175 340 fileout << FLATDATA(Params().MessageStart()) << nSize;
5382bcf8
PW
341
342 // Write undo data
343 long fileOutPos = ftell(fileout);
344 if (fileOutPos < 0)
13e5cce4 345 return error("CBlockUndo::WriteToDisk() : ftell failed");
5382bcf8
PW
346 pos.nPos = (unsigned int)fileOutPos;
347 fileout << *this;
348
8539361e
PW
349 // calculate & write checksum
350 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
351 hasher << hashBlock;
352 hasher << *this;
353 fileout << hasher.GetHash();
354
5382bcf8
PW
355 // Flush stdio buffers and commit to disk before returning
356 fflush(fileout);
450cbb09 357 if (!IsInitialBlockDownload())
5382bcf8
PW
358 FileCommit(fileout);
359
360 return true;
361 }
8539361e
PW
362
363 bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
364 {
365 // Open history file to read
366 CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
367 if (!filein)
368 return error("CBlockUndo::ReadFromDisk() : OpenBlockFile failed");
369
370 // Read block
371 uint256 hashChecksum;
372 try {
373 filein >> *this;
d0809a19 374 filein >> hashChecksum;
8539361e
PW
375 }
376 catch (std::exception &e) {
377 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
378 }
379
8539361e
PW
380 // Verify checksum
381 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
382 hasher << hashBlock;
383 hasher << *this;
384 if (hashChecksum != hasher.GetHash())
385 return error("CBlockUndo::ReadFromDisk() : checksum mismatch");
386
387 return true;
388 }
8adf48dc
PW
389};
390
0a61b0df 391
2800ce73
PW
392/** Closure representing one script verification
393 * Note that this stores references to the spending transaction */
394class CScriptCheck
395{
396private:
397 CScript scriptPubKey;
398 const CTransaction *ptxTo;
399 unsigned int nIn;
400 unsigned int nFlags;
401 int nHashType;
0a61b0df 402
2800ce73
PW
403public:
404 CScriptCheck() {}
405 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
406 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
407 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
408
409 bool operator()() const;
410
411 void swap(CScriptCheck &check) {
412 scriptPubKey.swap(check.scriptPubKey);
413 std::swap(ptxTo, check.ptxTo);
414 std::swap(nIn, check.nIn);
415 std::swap(nFlags, check.nFlags);
416 std::swap(nHashType, check.nHashType);
417 }
418};
0a61b0df 419
6b8de05d 420/** A transaction with a merkle branch linking it to the block chain. */
0a61b0df 421class CMerkleTx : public CTransaction
422{
423public:
424 uint256 hashBlock;
223b6f1b 425 std::vector<uint256> vMerkleBranch;
0a61b0df 426 int nIndex;
427
428 // memory only
cdcc319c 429 mutable bool fMerkleVerified;
0a61b0df 430
431
432 CMerkleTx()
433 {
434 Init();
435 }
436
437 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
438 {
439 Init();
440 }
441
442 void Init()
443 {
444 hashBlock = 0;
445 nIndex = -1;
446 fMerkleVerified = false;
0a61b0df 447 }
448
335e878b 449
0a61b0df 450 IMPLEMENT_SERIALIZE
451 (
452 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
453 nVersion = this->nVersion;
454 READWRITE(hashBlock);
455 READWRITE(vMerkleBranch);
456 READWRITE(nIndex);
457 )
458
0a61b0df 459
460 int SetMerkleBranch(const CBlock* pblock=NULL);
30ab2c9c
PW
461 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
462 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
0a61b0df 463 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
464 int GetBlocksToMaturity() const;
b1f15b21 465 bool AcceptToMemoryPool(bool fLimitFree=true);
0a61b0df 466};
467
468
469
470
0a61b0df 471
4bedfa92
PW
472/** Data structure that represents a partial merkle tree.
473 *
474 * It respresents a subset of the txid's of a known block, in a way that
475 * allows recovery of the list of txid's and the merkle root, in an
476 * authenticated way.
477 *
478 * The encoding works as follows: we traverse the tree in depth-first order,
479 * storing a bit for each traversed node, signifying whether the node is the
480 * parent of at least one matched leaf txid (or a matched txid itself). In
481 * case we are at the leaf level, or this bit is 0, its merkle node hash is
482 * stored, and its children are not explorer further. Otherwise, no hash is
483 * stored, but we recurse into both (or the only) child branch. During
484 * decoding, the same depth-first traversal is performed, consuming bits and
485 * hashes as they written during encoding.
486 *
487 * The serialization is fixed and provides a hard guarantee about the
488 * encoded size:
489 *
490 * SIZE <= 10 + ceil(32.25*N)
491 *
492 * Where N represents the number of leaf nodes of the partial tree. N itself
493 * is bounded by:
494 *
495 * N <= total_transactions
496 * N <= 1 + matched_transactions*tree_height
497 *
498 * The serialization format:
499 * - uint32 total_transactions (4 bytes)
500 * - varint number of hashes (1-3 bytes)
501 * - uint256[] hashes in depth-first order (<= 32*N bytes)
502 * - varint number of bytes of flag bits (1-3 bytes)
503 * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
504 * The size constraints follow from this.
505 */
506class CPartialMerkleTree
507{
508protected:
509 // the total number of transactions in the block
510 unsigned int nTransactions;
511
512 // node-is-parent-of-matched-txid bits
513 std::vector<bool> vBits;
514
515 // txids and internal hashes
516 std::vector<uint256> vHash;
0a61b0df 517
4bedfa92
PW
518 // flag set when encountering invalid data
519 bool fBad;
0a61b0df 520
4bedfa92
PW
521 // helper function to efficiently calculate the number of nodes at given height in the merkle tree
522 unsigned int CalcTreeWidth(int height) {
523 return (nTransactions+(1 << height)-1) >> height;
524 }
525
526 // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
527 uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
528
529 // recursive function that traverses tree nodes, storing the data as bits and hashes
530 void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
531
532 // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
533 // it returns the hash of the respective node.
534 uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
535
536public:
0a61b0df 537
4bedfa92
PW
538 // serialization implementation
539 IMPLEMENT_SERIALIZE(
540 READWRITE(nTransactions);
541 READWRITE(vHash);
542 std::vector<unsigned char> vBytes;
543 if (fRead) {
544 READWRITE(vBytes);
545 CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
546 us.vBits.resize(vBytes.size() * 8);
547 for (unsigned int p = 0; p < us.vBits.size(); p++)
548 us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
549 us.fBad = false;
550 } else {
551 vBytes.resize((vBits.size()+7)/8);
552 for (unsigned int p = 0; p < vBits.size(); p++)
553 vBytes[p / 8] |= vBits[p] << (p % 8);
554 READWRITE(vBytes);
555 }
556 )
557
558 // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
559 CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
0a61b0df 560
4bedfa92 561 CPartialMerkleTree();
0a61b0df 562
4bedfa92
PW
563 // extract the matching txid's represented by this partial merkle tree.
564 // returns the merkle root, or 0 in case of failure
565 uint256 ExtractMatches(std::vector<uint256> &vMatch);
566};
0a61b0df 567
568
0a61b0df 569
a6dba0fd 570/** Functions for disk access for blocks */
226f8219 571bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos);
80313994 572bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos);
7db120d5 573bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex);
0a61b0df 574
575
5c363ed6
EL
576/** Functions for validating blocks and updating the block tree */
577
578/** Undo the effects of this block (with given index) on the UTXO set represented by coins.
579 * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
580 * will be true if no problems were found. Otherwise, the return value will be false in case
581 * of problems. Note that in any case, coins may be modified. */
582bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
583
f3ae51dc
EL
584// Apply the effects of this block (with given index) on the UTXO set represented by coins
585bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
586
1959997a
EL
587// Add this block to the block index, and if necessary, switch the active block chain to this
588bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos);
f3ae51dc 589
38991ffa
EL
590// Context-independent validity checks
591bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
592
2a4d3464
EL
593// Store block on disk
594// if dbp is provided, the file is known to already reside on disk
595bool AcceptBlock(CBlock& block, CValidationState& state, CDiskBlockPos* dbp = NULL);
596
5c363ed6
EL
597
598
5382bcf8
PW
599class CBlockFileInfo
600{
601public:
602 unsigned int nBlocks; // number of blocks stored in file
603 unsigned int nSize; // number of used bytes of block file
604 unsigned int nUndoSize; // number of used bytes in the undo file
605 unsigned int nHeightFirst; // lowest height of block in file
606 unsigned int nHeightLast; // highest height of block in file
51ed9ec9
BD
607 uint64_t nTimeFirst; // earliest time of block in file
608 uint64_t nTimeLast; // latest time of block in file
5382bcf8
PW
609
610 IMPLEMENT_SERIALIZE(
611 READWRITE(VARINT(nBlocks));
612 READWRITE(VARINT(nSize));
613 READWRITE(VARINT(nUndoSize));
614 READWRITE(VARINT(nHeightFirst));
615 READWRITE(VARINT(nHeightLast));
616 READWRITE(VARINT(nTimeFirst));
617 READWRITE(VARINT(nTimeLast));
618 )
619
620 void SetNull() {
621 nBlocks = 0;
622 nSize = 0;
623 nUndoSize = 0;
624 nHeightFirst = 0;
625 nHeightLast = 0;
626 nTimeFirst = 0;
627 nTimeLast = 0;
628 }
629
630 CBlockFileInfo() {
631 SetNull();
632 }
633
634 std::string ToString() const {
69e07747 635 return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str());
5382bcf8
PW
636 }
637
638 // update statistics (does not update nSize)
51ed9ec9 639 void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
5382bcf8
PW
640 if (nBlocks==0 || nHeightFirst > nHeightIn)
641 nHeightFirst = nHeightIn;
642 if (nBlocks==0 || nTimeFirst > nTimeIn)
643 nTimeFirst = nTimeIn;
644 nBlocks++;
367c29d6 645 if (nHeightIn > nHeightLast)
5382bcf8
PW
646 nHeightLast = nHeightIn;
647 if (nTimeIn > nTimeLast)
648 nTimeLast = nTimeIn;
649 }
650};
651
857c61df
PW
652enum BlockStatus {
653 BLOCK_VALID_UNKNOWN = 0,
654 BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
655 BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
656 BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
657 BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
658 BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
659 BLOCK_VALID_MASK = 7,
660
661 BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
662 BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
663 BLOCK_HAVE_MASK = 24,
664
665 BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
666 BLOCK_FAILED_CHILD = 64, // descends from failed block
667 BLOCK_FAILED_MASK = 96
668};
669
6b8de05d
PW
670/** The block chain is a tree shaped structure starting with the
671 * genesis block at the root, with each block potentially having multiple
0fe8010a
PW
672 * candidates to be the next block. A blockindex may have multiple pprev pointing
673 * to it, but at most one of them can be part of the currently active branch.
6b8de05d 674 */
0a61b0df 675class CBlockIndex
676{
677public:
857c61df 678 // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
0a61b0df 679 const uint256* phashBlock;
857c61df
PW
680
681 // pointer to the index of the predecessor of this block
0a61b0df 682 CBlockIndex* pprev;
857c61df 683
857c61df 684 // height of the entry in the chain. The genesis block has height 0
0a61b0df 685 int nHeight;
857c61df
PW
686
687 // Which # file this block is stored in (blk?????.dat)
688 int nFile;
689
690 // Byte offset within blk?????.dat where this block's data is stored
691 unsigned int nDataPos;
692
693 // Byte offset within rev?????.dat where this block's undo data is stored
5382bcf8 694 unsigned int nUndoPos;
857c61df
PW
695
696 // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
1657c4bc 697 uint256 nChainWork;
0a61b0df 698
857c61df
PW
699 // Number of transactions in this block.
700 // Note: in a potential headers-first mode, this number cannot be relied upon
701 unsigned int nTx;
702
703 // (memory only) Number of transactions in the chain up to and including this block
704 unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
705
706 // Verification status of this block. See enum BlockStatus
707 unsigned int nStatus;
708
0a61b0df 709 // block header
710 int nVersion;
711 uint256 hashMerkleRoot;
712 unsigned int nTime;
713 unsigned int nBits;
714 unsigned int nNonce;
715
716
717 CBlockIndex()
718 {
719 phashBlock = NULL;
720 pprev = NULL;
0a61b0df 721 nHeight = 0;
857c61df
PW
722 nFile = 0;
723 nDataPos = 0;
450cbb09 724 nUndoPos = 0;
1657c4bc 725 nChainWork = 0;
857c61df
PW
726 nTx = 0;
727 nChainTx = 0;
728 nStatus = 0;
0a61b0df 729
730 nVersion = 0;
731 hashMerkleRoot = 0;
732 nTime = 0;
733 nBits = 0;
734 nNonce = 0;
735 }
736
e754cf41 737 CBlockIndex(CBlockHeader& block)
0a61b0df 738 {
739 phashBlock = NULL;
740 pprev = NULL;
0a61b0df 741 nHeight = 0;
857c61df
PW
742 nFile = 0;
743 nDataPos = 0;
5382bcf8 744 nUndoPos = 0;
1657c4bc 745 nChainWork = 0;
857c61df
PW
746 nTx = 0;
747 nChainTx = 0;
748 nStatus = 0;
0a61b0df 749
750 nVersion = block.nVersion;
751 hashMerkleRoot = block.hashMerkleRoot;
752 nTime = block.nTime;
753 nBits = block.nBits;
754 nNonce = block.nNonce;
755 }
756
630fd8dc 757 CDiskBlockPos GetBlockPos() const {
857c61df
PW
758 CDiskBlockPos ret;
759 if (nStatus & BLOCK_HAVE_DATA) {
760 ret.nFile = nFile;
761 ret.nPos = nDataPos;
a8a4b967 762 }
857c61df 763 return ret;
5382bcf8
PW
764 }
765
766 CDiskBlockPos GetUndoPos() const {
857c61df
PW
767 CDiskBlockPos ret;
768 if (nStatus & BLOCK_HAVE_UNDO) {
769 ret.nFile = nFile;
770 ret.nPos = nUndoPos;
a8a4b967 771 }
5382bcf8 772 return ret;
630fd8dc
PW
773 }
774
e754cf41 775 CBlockHeader GetBlockHeader() const
f03304a9 776 {
e754cf41 777 CBlockHeader block;
f03304a9 778 block.nVersion = nVersion;
779 if (pprev)
780 block.hashPrevBlock = pprev->GetBlockHash();
781 block.hashMerkleRoot = hashMerkleRoot;
782 block.nTime = nTime;
783 block.nBits = nBits;
784 block.nNonce = nNonce;
785 return block;
786 }
787
0a61b0df 788 uint256 GetBlockHash() const
789 {
790 return *phashBlock;
791 }
792
51ed9ec9 793 int64_t GetBlockTime() const
0a61b0df 794 {
51ed9ec9 795 return (int64_t)nTime;
0a61b0df 796 }
797
798 CBigNum GetBlockWork() const
799 {
9b8eb4d6 800 CBigNum bnTarget;
801 bnTarget.SetCompact(nBits);
802 if (bnTarget <= 0)
0a61b0df 803 return 0;
9b8eb4d6 804 return (CBigNum(1)<<256) / (bnTarget+1);
0a61b0df 805 }
806
0a61b0df 807 bool CheckIndex() const
808 {
809 return CheckProofOfWork(GetBlockHash(), nBits);
810 }
811
0a61b0df 812 enum { nMedianTimeSpan=11 };
813
51ed9ec9 814 int64_t GetMedianTimePast() const
0a61b0df 815 {
51ed9ec9
BD
816 int64_t pmedian[nMedianTimeSpan];
817 int64_t* pbegin = &pmedian[nMedianTimeSpan];
818 int64_t* pend = &pmedian[nMedianTimeSpan];
0a61b0df 819
820 const CBlockIndex* pindex = this;
821 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
822 *(--pbegin) = pindex->GetBlockTime();
823
223b6f1b 824 std::sort(pbegin, pend);
0a61b0df 825 return pbegin[(pend - pbegin)/2];
826 }
827
51ed9ec9 828 int64_t GetMedianTime() const;
0a61b0df 829
de237cbf
GA
830 /**
831 * Returns true if there are nRequired or more blocks of minVersion or above
832 * in the last nToCheck blocks, starting at pstart and going backwards.
833 */
834 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
835 unsigned int nRequired, unsigned int nToCheck);
0a61b0df 836
223b6f1b 837 std::string ToString() const
0a61b0df 838 {
4c6d41b8
PW
839 return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
840 pprev, nHeight,
1c06aa98
PW
841 hashMerkleRoot.ToString().c_str(),
842 GetBlockHash().ToString().c_str());
0a61b0df 843 }
844
845 void print() const
846 {
881a85a2 847 LogPrintf("%s\n", ToString().c_str());
0a61b0df 848 }
849};
850
851
852
6b8de05d 853/** Used to marshal pointers into hashes for db storage. */
0a61b0df 854class CDiskBlockIndex : public CBlockIndex
855{
856public:
857 uint256 hashPrev;
0a61b0df 858
450cbb09 859 CDiskBlockIndex() {
0a61b0df 860 hashPrev = 0;
0a61b0df 861 }
862
450cbb09 863 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
0a61b0df 864 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
0a61b0df 865 }
866
867 IMPLEMENT_SERIALIZE
868 (
869 if (!(nType & SER_GETHASH))
857c61df
PW
870 READWRITE(VARINT(nVersion));
871
872 READWRITE(VARINT(nHeight));
873 READWRITE(VARINT(nStatus));
874 READWRITE(VARINT(nTx));
875 if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
876 READWRITE(VARINT(nFile));
877 if (nStatus & BLOCK_HAVE_DATA)
878 READWRITE(VARINT(nDataPos));
879 if (nStatus & BLOCK_HAVE_UNDO)
880 READWRITE(VARINT(nUndoPos));
0a61b0df 881
882 // block header
883 READWRITE(this->nVersion);
884 READWRITE(hashPrev);
885 READWRITE(hashMerkleRoot);
886 READWRITE(nTime);
887 READWRITE(nBits);
888 READWRITE(nNonce);
889 )
890
891 uint256 GetBlockHash() const
892 {
e754cf41 893 CBlockHeader block;
0a61b0df 894 block.nVersion = nVersion;
895 block.hashPrevBlock = hashPrev;
896 block.hashMerkleRoot = hashMerkleRoot;
897 block.nTime = nTime;
898 block.nBits = nBits;
899 block.nNonce = nNonce;
900 return block.GetHash();
901 }
902
903
223b6f1b 904 std::string ToString() const
0a61b0df 905 {
223b6f1b 906 std::string str = "CDiskBlockIndex(";
0a61b0df 907 str += CBlockIndex::ToString();
450cbb09 908 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
0a61b0df 909 GetBlockHash().ToString().c_str(),
1c06aa98 910 hashPrev.ToString().c_str());
0a61b0df 911 return str;
912 }
913
914 void print() const
915 {
881a85a2 916 LogPrintf("%s\n", ToString().c_str());
0a61b0df 917 }
918};
919
ef3988ca
PW
920/** Capture information about block/transaction validation */
921class CValidationState {
922private:
923 enum mode_state {
924 MODE_VALID, // everything ok
925 MODE_INVALID, // network rule violation (DoS value may be set)
926 MODE_ERROR, // run-time error
927 } mode;
928 int nDoS;
b33b9a6f 929 bool corruptionPossible;
ef3988ca
PW
930public:
931 CValidationState() : mode(MODE_VALID), nDoS(0) {}
b33b9a6f 932 bool DoS(int level, bool ret = false, bool corruptionIn = false) {
ef3988ca
PW
933 if (mode == MODE_ERROR)
934 return ret;
935 nDoS += level;
936 mode = MODE_INVALID;
b33b9a6f 937 corruptionPossible = corruptionIn;
ef3988ca
PW
938 return ret;
939 }
940 bool Invalid(bool ret = false) {
941 return DoS(0, ret);
942 }
7851033d 943 bool Error() {
ef3988ca 944 mode = MODE_ERROR;
7851033d
PW
945 return false;
946 }
947 bool Abort(const std::string &msg) {
948 AbortNode(msg);
949 return Error();
ef3988ca
PW
950 }
951 bool IsValid() {
952 return mode == MODE_VALID;
953 }
954 bool IsInvalid() {
955 return mode == MODE_INVALID;
956 }
957 bool IsError() {
958 return mode == MODE_ERROR;
959 }
960 bool IsInvalid(int &nDoSOut) {
961 if (IsInvalid()) {
962 nDoSOut = nDoS;
963 return true;
964 }
965 return false;
966 }
b33b9a6f
MC
967 bool CorruptionPossible() {
968 return corruptionPossible;
969 }
ef3988ca 970};
0a61b0df 971
4c6d41b8
PW
972/** An in-memory indexed chain of blocks. */
973class CChain {
974private:
975 std::vector<CBlockIndex*> vChain;
0a61b0df 976
4c6d41b8
PW
977public:
978 /** Returns the index entry for the genesis block of this chain, or NULL if none. */
979 CBlockIndex *Genesis() const {
980 return vChain.size() > 0 ? vChain[0] : NULL;
981 }
0a61b0df 982
4c6d41b8
PW
983 /** Returns the index entry for the tip of this chain, or NULL if none. */
984 CBlockIndex *Tip() const {
985 return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
986 }
987
988 /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
989 CBlockIndex *operator[](int nHeight) const {
990 if (nHeight < 0 || nHeight >= (int)vChain.size())
991 return NULL;
992 return vChain[nHeight];
993 }
994
995 /** Compare two chains efficiently. */
996 friend bool operator==(const CChain &a, const CChain &b) {
997 return a.vChain.size() == b.vChain.size() &&
998 a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
999 }
1000
1001 /** Efficiently check whether a block is present in this chain. */
1002 bool Contains(const CBlockIndex *pindex) const {
1003 return (*this)[pindex->nHeight] == pindex;
1004 }
1005
1006 /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
1007 CBlockIndex *Next(const CBlockIndex *pindex) const {
1008 if (Contains(pindex))
1009 return (*this)[pindex->nHeight + 1];
1010 else
1011 return NULL;
1012 }
1013
1014 /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
1015 int Height() const {
1016 return vChain.size() - 1;
1017 }
1018
1019 /** Set/initialize a chain with a given tip. Returns the forking point. */
1020 CBlockIndex *SetTip(CBlockIndex *pindex);
e4daecda
PW
1021
1022 /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
1023 CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
1024
1025 /** Find the last common block between this chain and a locator. */
1026 CBlockIndex *FindFork(const CBlockLocator &locator) const;
4c6d41b8 1027};
0a61b0df 1028
4c6d41b8
PW
1029/** The currently-connected chain of blocks. */
1030extern CChain chainActive;
0a61b0df 1031
1032
1033
0a61b0df 1034
1035
1036
1037
beeb5761
PW
1038struct CCoinsStats
1039{
1040 int nHeight;
e31aa7c9 1041 uint256 hashBlock;
51ed9ec9
BD
1042 uint64_t nTransactions;
1043 uint64_t nTransactionOutputs;
1044 uint64_t nSerializedSize;
e31aa7c9 1045 uint256 hashSerialized;
51ed9ec9 1046 int64_t nTotalAmount;
beeb5761 1047
e31aa7c9 1048 CCoinsStats() : nHeight(0), hashBlock(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), hashSerialized(0), nTotalAmount(0) {}
beeb5761
PW
1049};
1050
450cbb09
PW
1051/** Abstract view on the open txout dataset. */
1052class CCoinsView
1053{
1054public:
1055 // Retrieve the CCoins (unspent transaction outputs) for a given txid
f369d02c 1056 virtual bool GetCoins(const uint256 &txid, CCoins &coins);
450cbb09
PW
1057
1058 // Modify the CCoins for a given txid
f369d02c 1059 virtual bool SetCoins(const uint256 &txid, const CCoins &coins);
450cbb09
PW
1060
1061 // Just check whether we have data for a given txid.
1062 // This may (but cannot always) return true for fully spent transactions
f369d02c 1063 virtual bool HaveCoins(const uint256 &txid);
450cbb09 1064
84674082
PW
1065 // Retrieve the block hash whose state this CCoinsView currently represents
1066 virtual uint256 GetBestBlock();
450cbb09 1067
84674082
PW
1068 // Modify the currently active block hash
1069 virtual bool SetBestBlock(const uint256 &hashBlock);
c2ed184f
PW
1070
1071 // Do a bulk modification (multiple SetCoins + one SetBestBlock)
84674082 1072 virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, const uint256 &hashBlock);
c2ed184f
PW
1073
1074 // Calculate statistics about the unspent transaction output set
beeb5761 1075 virtual bool GetStats(CCoinsStats &stats);
c9c7d482
PW
1076
1077 // As we use CCoinsViews polymorphically, have a virtual destructor
13e5cce4 1078 virtual ~CCoinsView() {}
450cbb09
PW
1079};
1080
1081/** CCoinsView backed by another CCoinsView */
1082class CCoinsViewBacked : public CCoinsView
1083{
1084protected:
1085 CCoinsView *base;
1086
1087public:
1088 CCoinsViewBacked(CCoinsView &viewIn);
f369d02c
PW
1089 bool GetCoins(const uint256 &txid, CCoins &coins);
1090 bool SetCoins(const uint256 &txid, const CCoins &coins);
1091 bool HaveCoins(const uint256 &txid);
84674082
PW
1092 uint256 GetBestBlock();
1093 bool SetBestBlock(const uint256 &hashBlock);
450cbb09 1094 void SetBackend(CCoinsView &viewIn);
84674082 1095 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, const uint256 &hashBlock);
beeb5761 1096 bool GetStats(CCoinsStats &stats);
450cbb09
PW
1097};
1098
1099/** CCoinsView that adds a memory cache for transactions to another CCoinsView */
1100class CCoinsViewCache : public CCoinsViewBacked
1101{
1102protected:
84674082 1103 uint256 hashBlock;
450cbb09
PW
1104 std::map<uint256,CCoins> cacheCoins;
1105
1106public:
1107 CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
c2ed184f
PW
1108
1109 // Standard CCoinsView methods
f369d02c
PW
1110 bool GetCoins(const uint256 &txid, CCoins &coins);
1111 bool SetCoins(const uint256 &txid, const CCoins &coins);
1112 bool HaveCoins(const uint256 &txid);
84674082
PW
1113 uint256 GetBestBlock();
1114 bool SetBestBlock(const uint256 &hashBlock);
1115 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, const uint256 &hashBlock);
c2ed184f
PW
1116
1117 // Return a modifiable reference to a CCoins. Check HaveCoins first.
1118 // Many methods explicitly require a CCoinsViewCache because of this method, to reduce
1119 // copying.
f369d02c 1120 CCoins &GetCoins(const uint256 &txid);
c2ed184f
PW
1121
1122 // Push the modifications applied to this cache to its base.
1123 // Failure to call this method before destruction will cause the changes to be forgotten.
450cbb09 1124 bool Flush();
c2ed184f
PW
1125
1126 // Calculate the size of the cache (in number of transactions)
ae8bfd12 1127 unsigned int GetCacheSize();
13c51f20 1128
05df3fc6
EL
1129 /** Amount of bitcoins coming in to a transaction
1130 Note that lightweight clients may not know anything besides the hash of previous transactions,
1131 so may not be able to calculate this.
1132
1133 @param[in] tx transaction for which we are checking input total
1134 @return Sum of value of all inputs (scriptSigs)
1135 @see CTransaction::FetchInputs
1136 */
51ed9ec9
BD
1137 int64_t GetValueIn(const CTransaction& tx);
1138
faaeae1e 1139
05df3fc6
EL
1140 // Check whether all prevouts of the transaction are present in the UTXO set represented by this view
1141 bool HaveInputs(const CTransaction& tx);
1142
1143 const CTxOut &GetOutputFor(const CTxIn& input);
1144
13c51f20 1145private:
f369d02c 1146 std::map<uint256,CCoins>::iterator FetchCoins(const uint256 &txid);
450cbb09
PW
1147};
1148
1149/** CCoinsView that brings transactions from a memorypool into view.
1150 It does not check for spendings by memory pool transactions. */
1151class CCoinsViewMemPool : public CCoinsViewBacked
1152{
1153protected:
1154 CTxMemPool &mempool;
1155
1156public:
1157 CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
f369d02c
PW
1158 bool GetCoins(const uint256 &txid, CCoins &coins);
1159 bool HaveCoins(const uint256 &txid);
450cbb09
PW
1160};
1161
d979e6e3 1162/** Global variable that points to the active CCoinsView (protected by cs_main) */
ae8bfd12
PW
1163extern CCoinsViewCache *pcoinsTip;
1164
d979e6e3
PW
1165/** Global variable that points to the active block tree (protected by cs_main) */
1166extern CBlockTreeDB *pblocktree;
1167
03cac0bb
FV
1168struct CBlockTemplate
1169{
1170 CBlock block;
1171 std::vector<int64_t> vTxFees;
1172 std::vector<int64_t> vTxSigOps;
1173};
1174
9fb106e7
MC
1175
1176
1177
1178
1179
1180/** Used to relay blocks as header + vector<merkle branch>
1181 * to filtered nodes.
1182 */
1183class CMerkleBlock
1184{
1185public:
21aaf255 1186 // Public only for unit testing
9fb106e7 1187 CBlockHeader header;
21aaf255 1188 CPartialMerkleTree txn;
9fb106e7 1189
21aaf255
MC
1190public:
1191 // Public only for unit testing and relay testing
1192 // (not relayed)
1193 std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
9fb106e7
MC
1194
1195 // Create from a CBlock, filtering transactions according to filter
1196 // Note that this will call IsRelevantAndUpdate on the filter for each transaction,
1197 // thus the filter will likely be modified.
1198 CMerkleBlock(const CBlock& block, CBloomFilter& filter);
1199
1200 IMPLEMENT_SERIALIZE
1201 (
1202 READWRITE(header);
21aaf255 1203 READWRITE(txn);
9fb106e7
MC
1204 )
1205};
1206
00588c3f
PW
1207
1208class CWalletInterface {
1209protected:
1210 virtual void SyncTransaction(const uint256 &hash, const CTransaction &tx, const CBlock *pblock) =0;
1211 virtual void EraseFromWallet(const uint256 &hash) =0;
1212 virtual void SetBestChain(const CBlockLocator &locator) =0;
1213 virtual void UpdatedTransaction(const uint256 &hash) =0;
1214 virtual void Inventory(const uint256 &hash) =0;
1215 virtual void ResendWalletTransactions() =0;
1216 friend void ::RegisterWallet(CWalletInterface*);
1217 friend void ::UnregisterWallet(CWalletInterface*);
1218 friend void ::UnregisterAllWallets();
1219};
1220
223b6f1b 1221#endif
This page took 0.358475 seconds and 4 git commands to generate.