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