]> Git Repo - VerusCoin.git/blame - src/main.h
Merge pull request #2336 from petertodd/invalid-opcode-coverage
[VerusCoin.git] / src / main.h
CommitLineData
0a61b0df 1// Copyright (c) 2009-2010 Satoshi Nakamoto
88216419 2// Copyright (c) 2009-2012 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.
223b6f1b
WL
5#ifndef BITCOIN_MAIN_H
6#define BITCOIN_MAIN_H
7
8#include "bignum.h"
7f3ccb59 9#include "sync.h"
223b6f1b 10#include "net.h"
223b6f1b
WL
11#include "script.h"
12
13#include <list>
0a61b0df 14
9eace6b1 15class CWallet;
0a61b0df 16class CBlock;
17class CBlockIndex;
0a61b0df 18class CKeyItem;
64c7ee7e 19class CReserveKey;
0a61b0df 20
40c2614e
JL
21class CAddress;
22class CInv;
40c2614e 23class CNode;
40c2614e 24
40c5e409 25struct CBlockIndexWorkComparator;
857c61df 26
9d6633ac 27/** The maximum allowed size for a serialized block, in bytes (network rule) */
0a61b0df 28static const unsigned int MAX_BLOCK_SIZE = 1000000;
9d6633ac 29/** The maximum size for mined blocks */
3df62878 30static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
69e07747 31/** The maximum size for transactions we're willing to relay/mine */
41e1a0d7 32static const unsigned int MAX_STANDARD_TX_SIZE = MAX_BLOCK_SIZE_GEN/5;
9d6633ac 33/** The maximum allowed number of signature check operations in a block (network rule) */
7bd9c3a3 34static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
9d6633ac 35/** The maximum number of orphan transactions kept in memory */
7bd9c3a3 36static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
9d6633ac 37/** The maximum number of entries in an 'inv' protocol message */
05a85b2b 38static const unsigned int MAX_INV_SZ = 50000;
9d6633ac 39/** The maximum size of a blk?????.dat file (since 0.8) */
5382bcf8 40static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
9d6633ac 41/** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
bba89aa8 42static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
9d6633ac 43/** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
bba89aa8 44static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
9d6633ac 45/** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
450cbb09 46static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
9d6633ac 47/** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
bde280b9 48static const int64 MIN_TX_FEE = 50000;
9d6633ac 49/** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
bde280b9 50static const int64 MIN_RELAY_TX_FEE = 10000;
9d6633ac 51/** No amount larger than this (in satoshi) is valid */
bde280b9
WL
52static const int64 MAX_MONEY = 21000000 * COIN;
53inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
9d6633ac 54/** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
0a61b0df 55static const int COINBASE_MATURITY = 100;
9d6633ac 56/** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
f621326c 57static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
f9cae832
PW
58/** Maximum number of script-checking threads allowed */
59static const int MAX_SCRIPTCHECK_THREADS = 16;
8bb5edc1
MC
60#ifdef USE_UPNP
61static const int fHaveUPnP = true;
62#else
63static const int fHaveUPnP = false;
64#endif
0a61b0df 65
66
7bf8b7c2 67extern CScript COINBASE_FLAGS;
52a3d263
FV
68
69
0a61b0df 70
71
72
73
74extern CCriticalSection cs_main;
223b6f1b 75extern std::map<uint256, CBlockIndex*> mapBlockIndex;
857c61df 76extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
5cbf7532 77extern uint256 hashGenesisBlock;
0a61b0df 78extern CBlockIndex* pindexGenesisBlock;
79extern int nBestHeight;
80extern CBigNum bnBestChainWork;
81extern CBigNum bnBestInvalidWork;
82extern uint256 hashBestChain;
83extern CBlockIndex* pindexBest;
84extern unsigned int nTransactionsUpdated;
340f0876
LD
85extern uint64 nLastBlockTx;
86extern uint64 nLastBlockSize;
2bc4fd60 87extern const std::string strMessageMagic;
0a61b0df 88extern double dHashesPerSec;
bde280b9
WL
89extern int64 nHPSTimerStart;
90extern int64 nTimeBestReceived;
64c7ee7e
PW
91extern CCriticalSection cs_setpwalletRegistered;
92extern std::set<CWallet*> setpwalletRegistered;
1d740055 93extern unsigned char pchMessageStart[4];
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
101// Settings
bde280b9 102extern int64 nTransactionFee;
0a61b0df 103
966ae00f
PK
104// Minimum disk space required - used in CheckDiskSpace()
105static const uint64 nMinDiskSpace = 52428800;
0a61b0df 106
107
1512d5ce 108class CReserveKey;
450cbb09 109class CCoinsDB;
d979e6e3 110class CBlockTreeDB;
15ebd486 111struct CDiskBlockPos;
450cbb09
PW
112class CCoins;
113class CTxUndo;
114class CCoinsView;
13c51f20 115class CCoinsViewCache;
f9cae832 116class CScriptCheck;
ef3988ca 117class CValidationState;
0a61b0df 118
03cac0bb
FV
119struct CBlockTemplate;
120
160b028b 121/** Register a wallet to receive updates from core */
64c7ee7e 122void RegisterWallet(CWallet* pwalletIn);
160b028b 123/** Unregister a wallet from core */
64c7ee7e 124void UnregisterWallet(CWallet* pwalletIn);
160b028b 125/** Push an updated transaction to all registered wallets */
64dd46fd 126void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
160b028b 127/** Process an incoming block */
ef3988ca 128bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
160b028b 129/** Check whether enough disk space is available for an incoming block */
ec95a809 130bool CheckDiskSpace(uint64 nAdditionalBytes = 0);
160b028b 131/** Open a block file (blk?????.dat) */
5382bcf8 132FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
160b028b 133/** Open an undo file (rev?????.dat) */
5382bcf8 134FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
160b028b 135/** Import blocks from an external file */
7fea4846 136bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
38603761
PW
137/** Initialize a new block tree database + block data on disk */
138bool InitBlockIndex();
160b028b 139/** Load the block tree and coins database from disk */
7fea4846 140bool LoadBlockIndex();
f7f3a96b
PW
141/** Unload database information */
142void UnloadBlockIndex();
1f355b66
PW
143/** Verify consistency of the block and coin databases */
144bool VerifyDB();
160b028b 145/** Print the loaded block tree */
0a61b0df 146void PrintBlockTree();
160b028b 147/** Find a block by height in the currently-connected chain */
1be06419 148CBlockIndex* FindBlockByHeight(int nHeight);
160b028b 149/** Process protocol messages received from a given node */
0a61b0df 150bool ProcessMessages(CNode* pfrom);
160b028b 151/** Send queued protocol messages to be sent to a give node */
0a61b0df 152bool SendMessages(CNode* pto, bool fSendTrickle);
160b028b 153/** Run the importer thread, which deals with reindexing, loading bootstrap.dat, and whatever is passed to -loadblock */
66b02c93 154void ThreadImport(void *parg);
f9cae832
PW
155/** Run an instance of the script checking thread */
156void ThreadScriptCheck(void* parg);
157/** Stop the script checking threads */
158void ThreadScriptCheckQuit();
160b028b 159/** Run the miner threads */
64c7ee7e 160void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
160b028b 161/** Generate a new block, without valid proof-of-work */
03cac0bb 162CBlockTemplate* CreateNewBlock(CReserveKey& reservekey);
160b028b 163/** Modify the extranonce in a block */
83f4cd15 164void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
160b028b 165/** Do mining precalculation */
776d0f34 166void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
160b028b 167/** Check mined block */
64c7ee7e 168bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
160b028b 169/** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
0a61b0df 170bool CheckProofOfWork(uint256 hash, unsigned int nBits);
160b028b 171/** Calculate the minimum amount of work a received block needs, without knowing its direct parent */
bde280b9 172unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
160b028b 173/** Get the number of active peers */
d33cc2b5 174int GetNumBlocksOfPeers();
f0bf5fb2 175/** Check whether we are doing an initial block download (synchronizing from disk or network) */
0a61b0df 176bool IsInitialBlockDownload();
160b028b 177/** Format a string that describes several potential problems detected by the core */
223b6f1b 178std::string GetWarnings(std::string strFor);
160b028b 179/** Retrieve a transaction (from memory pool, or from disk, if possible) */
450cbb09 180bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
160b028b 181/** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */
ef3988ca 182bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew);
160b028b 183/** Find the best known block, and make it the tip of the block chain */
ef3988ca 184bool ConnectBestBlock(CValidationState &state);
160b028b 185/** Create a new block index entry for a given block hash */
2d8a4829 186CBlockIndex * InsertBlockIndex(uint256 hash);
f1136200
PW
187/** Verify a signature */
188bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
7851033d
PW
189/** Abort with a message */
190bool AbortNode(const std::string &msg);
857c61df 191
0a61b0df 192
193
194
195
196
197
198
199
200
201
f3a84c3a
LD
202static inline std::string BlockHashStr(const uint256& hash)
203{
c34a3269 204 return hash.ToString();
f3a84c3a
LD
205}
206
64c7ee7e
PW
207bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
208
2d1fa42e 209struct CDiskBlockPos
630fd8dc 210{
5382bcf8
PW
211 int nFile;
212 unsigned int nPos;
630fd8dc 213
5382bcf8
PW
214 IMPLEMENT_SERIALIZE(
215 READWRITE(VARINT(nFile));
216 READWRITE(VARINT(nPos));
217 )
630fd8dc 218
a8a4b967
PK
219 CDiskBlockPos() {
220 SetNull();
221 }
222
223 CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
224 nFile = nFileIn;
225 nPos = nPosIn;
226 }
227
630fd8dc 228 friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
5382bcf8 229 return (a.nFile == b.nFile && a.nPos == b.nPos);
630fd8dc
PW
230 }
231
232 friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
233 return !(a == b);
234 }
235
5382bcf8
PW
236 void SetNull() { nFile = -1; nPos = 0; }
237 bool IsNull() const { return (nFile == -1); }
630fd8dc
PW
238};
239
2d1fa42e
PW
240struct CDiskTxPos : public CDiskBlockPos
241{
242 unsigned int nTxOffset; // after header
243
244 IMPLEMENT_SERIALIZE(
245 READWRITE(*(CDiskBlockPos*)this);
246 READWRITE(VARINT(nTxOffset));
247 )
248
249 CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
250 }
251
252 CDiskTxPos() {
253 SetNull();
254 }
0a61b0df 255
2d1fa42e
PW
256 void SetNull() {
257 CDiskBlockPos::SetNull();
258 nTxOffset = 0;
259 }
260};
0a61b0df 261
262
6b8de05d 263/** An inpoint - a combination of a transaction and an index n into its vin */
0a61b0df 264class CInPoint
265{
266public:
267 CTransaction* ptx;
268 unsigned int n;
269
270 CInPoint() { SetNull(); }
271 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
24de9226
JG
272 void SetNull() { ptx = NULL; n = (unsigned int) -1; }
273 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
0a61b0df 274};
275
276
277
6b8de05d 278/** An outpoint - a combination of a transaction hash and an index n into its vout */
0a61b0df 279class COutPoint
280{
281public:
282 uint256 hash;
283 unsigned int n;
284
285 COutPoint() { SetNull(); }
286 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
287 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
24de9226
JG
288 void SetNull() { hash = 0; n = (unsigned int) -1; }
289 bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
0a61b0df 290
291 friend bool operator<(const COutPoint& a, const COutPoint& b)
292 {
293 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
294 }
295
296 friend bool operator==(const COutPoint& a, const COutPoint& b)
297 {
298 return (a.hash == b.hash && a.n == b.n);
299 }
300
301 friend bool operator!=(const COutPoint& a, const COutPoint& b)
302 {
303 return !(a == b);
304 }
305
223b6f1b 306 std::string ToString() const
0a61b0df 307 {
463a1cab 308 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
0a61b0df 309 }
310
311 void print() const
312 {
313 printf("%s\n", ToString().c_str());
314 }
315};
316
317
318
319
6b8de05d
PW
320/** An input of a transaction. It contains the location of the previous
321 * transaction's output that it claims and a signature that matches the
322 * output's public key.
323 */
0a61b0df 324class CTxIn
325{
326public:
327 COutPoint prevout;
328 CScript scriptSig;
329 unsigned int nSequence;
330
331 CTxIn()
332 {
26ce92b3 333 nSequence = std::numeric_limits<unsigned int>::max();
0a61b0df 334 }
335
26ce92b3 336 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
0a61b0df 337 {
338 prevout = prevoutIn;
339 scriptSig = scriptSigIn;
340 nSequence = nSequenceIn;
341 }
342
26ce92b3 343 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
0a61b0df 344 {
345 prevout = COutPoint(hashPrevTx, nOut);
346 scriptSig = scriptSigIn;
347 nSequence = nSequenceIn;
348 }
349
350 IMPLEMENT_SERIALIZE
351 (
352 READWRITE(prevout);
353 READWRITE(scriptSig);
354 READWRITE(nSequence);
355 )
356
357 bool IsFinal() const
358 {
26ce92b3 359 return (nSequence == std::numeric_limits<unsigned int>::max());
0a61b0df 360 }
361
362 friend bool operator==(const CTxIn& a, const CTxIn& b)
363 {
364 return (a.prevout == b.prevout &&
365 a.scriptSig == b.scriptSig &&
366 a.nSequence == b.nSequence);
367 }
368
369 friend bool operator!=(const CTxIn& a, const CTxIn& b)
370 {
371 return !(a == b);
372 }
373
223b6f1b 374 std::string ToString() const
0a61b0df 375 {
223b6f1b 376 std::string str;
52d3a481 377 str += "CTxIn(";
0a61b0df 378 str += prevout.ToString();
379 if (prevout.IsNull())
f1e1fb4b 380 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
0a61b0df 381 else
382 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
26ce92b3 383 if (nSequence != std::numeric_limits<unsigned int>::max())
0a61b0df 384 str += strprintf(", nSequence=%u", nSequence);
385 str += ")";
386 return str;
387 }
388
389 void print() const
390 {
391 printf("%s\n", ToString().c_str());
392 }
0a61b0df 393};
394
395
396
397
6b8de05d
PW
398/** An output of a transaction. It contains the public key that the next input
399 * must be able to sign with to claim it.
400 */
0a61b0df 401class CTxOut
402{
403public:
bde280b9 404 int64 nValue;
0a61b0df 405 CScript scriptPubKey;
406
407 CTxOut()
408 {
409 SetNull();
410 }
411
bde280b9 412 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
0a61b0df 413 {
414 nValue = nValueIn;
415 scriptPubKey = scriptPubKeyIn;
416 }
417
418 IMPLEMENT_SERIALIZE
419 (
420 READWRITE(nValue);
421 READWRITE(scriptPubKey);
422 )
423
424 void SetNull()
425 {
426 nValue = -1;
427 scriptPubKey.clear();
428 }
429
10fd8604 430 bool IsNull() const
0a61b0df 431 {
432 return (nValue == -1);
433 }
434
435 uint256 GetHash() const
436 {
437 return SerializeHash(*this);
438 }
439
0a61b0df 440 friend bool operator==(const CTxOut& a, const CTxOut& b)
441 {
442 return (a.nValue == b.nValue &&
443 a.scriptPubKey == b.scriptPubKey);
444 }
445
446 friend bool operator!=(const CTxOut& a, const CTxOut& b)
447 {
448 return !(a == b);
449 }
450
223b6f1b 451 std::string ToString() const
0a61b0df 452 {
453 if (scriptPubKey.size() < 6)
454 return "CTxOut(error)";
10384941 455 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
0a61b0df 456 }
457
458 void print() const
459 {
460 printf("%s\n", ToString().c_str());
461 }
462};
463
464
465
dbbf1d4a
LD
466enum GetMinFee_mode
467{
468 GMF_BLOCK,
469 GMF_RELAY,
470 GMF_SEND,
471};
472
6b8de05d 473/** The basic transaction that is broadcasted on the network and contained in
ec95a809 474 * blocks. A transaction can contain multiple inputs and outputs.
6b8de05d 475 */
0a61b0df 476class CTransaction
477{
478public:
dae3e10a 479 static const int CURRENT_VERSION=1;
0a61b0df 480 int nVersion;
223b6f1b
WL
481 std::vector<CTxIn> vin;
482 std::vector<CTxOut> vout;
0a61b0df 483 unsigned int nLockTime;
484
0a61b0df 485 CTransaction()
486 {
487 SetNull();
488 }
489
490 IMPLEMENT_SERIALIZE
491 (
492 READWRITE(this->nVersion);
493 nVersion = this->nVersion;
494 READWRITE(vin);
495 READWRITE(vout);
496 READWRITE(nLockTime);
497 )
498
499 void SetNull()
500 {
dae3e10a 501 nVersion = CTransaction::CURRENT_VERSION;
0a61b0df 502 vin.clear();
503 vout.clear();
504 nLockTime = 0;
505 }
506
507 bool IsNull() const
508 {
509 return (vin.empty() && vout.empty());
510 }
511
512 uint256 GetHash() const
513 {
514 return SerializeHash(*this);
515 }
516
bde280b9 517 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
0a61b0df 518 {
519 // Time based nLockTime implemented in 0.1.6
520 if (nLockTime == 0)
521 return true;
522 if (nBlockHeight == 0)
523 nBlockHeight = nBestHeight;
524 if (nBlockTime == 0)
525 nBlockTime = GetAdjustedTime();
1d8c7a95 526 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
0a61b0df 527 return true;
223b6f1b 528 BOOST_FOREACH(const CTxIn& txin, vin)
0a61b0df 529 if (!txin.IsFinal())
530 return false;
531 return true;
532 }
533
534 bool IsNewerThan(const CTransaction& old) const
535 {
536 if (vin.size() != old.vin.size())
537 return false;
c376ac35 538 for (unsigned int i = 0; i < vin.size(); i++)
0a61b0df 539 if (vin[i].prevout != old.vin[i].prevout)
540 return false;
541
542 bool fNewer = false;
26ce92b3 543 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
c376ac35 544 for (unsigned int i = 0; i < vin.size(); i++)
0a61b0df 545 {
546 if (vin[i].nSequence != old.vin[i].nSequence)
547 {
548 if (vin[i].nSequence <= nLowest)
549 {
550 fNewer = false;
551 nLowest = vin[i].nSequence;
552 }
553 if (old.vin[i].nSequence < nLowest)
554 {
555 fNewer = true;
556 nLowest = old.vin[i].nSequence;
557 }
558 }
559 }
560 return fNewer;
561 }
562
563 bool IsCoinBase() const
564 {
565 return (vin.size() == 1 && vin[0].prevout.IsNull());
566 }
567
8d7849b6
GA
568 /** Check for standard transaction types
569 @return True if all outputs (scriptPubKeys) use only standard transaction forms
570 */
e679ec96 571 bool IsStandard() const;
922e8e29 572
8d7849b6
GA
573 /** Check for standard transaction types
574 @param[in] mapInputs Map of previous transactions that have outputs we're spending
575 @return True if all inputs (scriptSigs) use only standard transaction forms
8d7849b6 576 */
13c51f20 577 bool AreInputsStandard(CCoinsViewCache& mapInputs) const;
8d7849b6
GA
578
579 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
580 @return number of sigops this transaction's outputs will produce when spent
8d7849b6 581 */
7bd9c3a3 582 unsigned int GetLegacySigOpCount() const;
a206a239 583
137d0685 584 /** Count ECDSA signature operations in pay-to-script-hash inputs.
8d7849b6
GA
585
586 @param[in] mapInputs Map of previous transactions that have outputs we're spending
587 @return maximum number of sigops required to validate this transaction's inputs
8d7849b6 588 */
13c51f20 589 unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const;
8d7849b6
GA
590
591 /** Amount of bitcoins spent by this transaction.
592 @return sum of all outputs (note: does not include fees)
593 */
bde280b9 594 int64 GetValueOut() const
0a61b0df 595 {
bde280b9 596 int64 nValueOut = 0;
223b6f1b 597 BOOST_FOREACH(const CTxOut& txout, vout)
0a61b0df 598 {
599 nValueOut += txout.nValue;
600 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
223b6f1b 601 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
0a61b0df 602 }
603 return nValueOut;
604 }
605
8d7849b6
GA
606 /** Amount of bitcoins coming in to this transaction
607 Note that lightweight clients may not know anything besides the hash of previous transactions,
608 so may not be able to calculate this.
609
610 @param[in] mapInputs Map of previous transactions that have outputs we're spending
611 @return Sum of value of all inputs (scriptSigs)
8d7849b6 612 */
13c51f20 613 int64 GetValueIn(CCoinsViewCache& mapInputs) const;
8d7849b6 614
395c1f44
GA
615 static bool AllowFree(double dPriority)
616 {
617 // Large (in bytes) low-priority (new, small-coin) transactions
618 // need a fee.
619 return dPriority > COIN * 144 / 250;
620 }
621
76970091 622 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const;
0a61b0df 623
0a61b0df 624 friend bool operator==(const CTransaction& a, const CTransaction& b)
625 {
626 return (a.nVersion == b.nVersion &&
627 a.vin == b.vin &&
628 a.vout == b.vout &&
629 a.nLockTime == b.nLockTime);
630 }
631
632 friend bool operator!=(const CTransaction& a, const CTransaction& b)
633 {
634 return !(a == b);
635 }
636
637
223b6f1b 638 std::string ToString() const
0a61b0df 639 {
223b6f1b 640 std::string str;
d210f4f5 641 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
b22c8842 642 GetHash().ToString().substr(0,10).c_str(),
0a61b0df 643 nVersion,
644 vin.size(),
645 vout.size(),
646 nLockTime);
c376ac35 647 for (unsigned int i = 0; i < vin.size(); i++)
0a61b0df 648 str += " " + vin[i].ToString() + "\n";
c376ac35 649 for (unsigned int i = 0; i < vout.size(); i++)
0a61b0df 650 str += " " + vout[i].ToString() + "\n";
651 return str;
652 }
653
654 void print() const
655 {
656 printf("%s", ToString().c_str());
657 }
658
659
450cbb09 660 // Check whether all prevouts of this transaction are present in the UTXO set represented by view
13c51f20 661 bool HaveInputs(CCoinsViewCache &view) const;
8d7849b6 662
450cbb09 663 // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
f9cae832
PW
664 // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
665 // instead of being performed inline.
ef3988ca 666 bool CheckInputs(CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true,
f9cae832
PW
667 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC,
668 std::vector<CScriptCheck> *pvChecks = NULL) const;
450cbb09
PW
669
670 // Apply the effects of this transaction on the UTXO set represented by view
ef3988ca 671 bool UpdateCoins(CValidationState &state, CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash) const;
450cbb09
PW
672
673 // Context-independent validity checks
ef3988ca 674 bool CheckTransaction(CValidationState &state) const;
450cbb09
PW
675
676 // Try to accept this transaction into the memory pool
ef3988ca 677 bool AcceptToMemoryPool(CValidationState &state, bool fCheckInputs=true, bool fLimitFree = true, bool* pfMissingInputs=NULL);
8d7849b6 678
0a61b0df 679protected:
13c51f20 680 static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs);
0a61b0df 681};
682
69fc8047
PW
683/** wrapper for CTxOut that provides a more compact serialization */
684class CTxOutCompressor
685{
686private:
687 CTxOut &txout;
0fa593d0 688
69fc8047 689public:
0fa593d0
PW
690 static uint64 CompressAmount(uint64 nAmount);
691 static uint64 DecompressAmount(uint64 nAmount);
692
69fc8047
PW
693 CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
694
0fa593d0
PW
695 IMPLEMENT_SERIALIZE(({
696 if (!fRead) {
697 uint64 nVal = CompressAmount(txout.nValue);
698 READWRITE(VARINT(nVal));
699 } else {
700 uint64 nVal = 0;
701 READWRITE(VARINT(nVal));
702 txout.nValue = DecompressAmount(nVal);
703 }
69fc8047
PW
704 CScriptCompressor cscript(REF(txout.scriptPubKey));
705 READWRITE(cscript);
0fa593d0 706 });)
69fc8047 707};
0a61b0df 708
44ac1c0f
PW
709/** Undo information for a CTxIn
710 *
711 * Contains the prevout's CTxOut being spent, and if this was the
712 * last output of the affected transaction, its metadata as well
713 * (coinbase or not, height, transaction version)
714 */
715class CTxInUndo
716{
717public:
718 CTxOut txout; // the txout data before being spent
719 bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
720 unsigned int nHeight; // if the outpoint was the last unspent: its height
721 int nVersion; // if the outpoint was the last unspent: its version
722
723 CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
724 CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
725
726 unsigned int GetSerializeSize(int nType, int nVersion) const {
727 return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
728 (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
729 ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
730 }
731
732 template<typename Stream>
733 void Serialize(Stream &s, int nType, int nVersion) const {
734 ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
735 if (nHeight > 0)
736 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
737 ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
738 }
739
740 template<typename Stream>
741 void Unserialize(Stream &s, int nType, int nVersion) {
742 unsigned int nCode = 0;
743 ::Unserialize(s, VARINT(nCode), nType, nVersion);
744 nHeight = nCode / 2;
745 fCoinBase = nCode & 1;
746 if (nHeight > 0)
747 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
748 ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
749 }
750};
751
752/** Undo information for a CTransaction */
753class CTxUndo
754{
755public:
450cbb09 756 // undo information for all txins
44ac1c0f
PW
757 std::vector<CTxInUndo> vprevout;
758
759 IMPLEMENT_SERIALIZE(
760 READWRITE(vprevout);
761 )
762};
763
8adf48dc
PW
764/** Undo information for a CBlock */
765class CBlockUndo
766{
767public:
450cbb09 768 std::vector<CTxUndo> vtxundo; // for all but the coinbase
8adf48dc
PW
769
770 IMPLEMENT_SERIALIZE(
771 READWRITE(vtxundo);
772 )
5382bcf8 773
8539361e 774 bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
5382bcf8
PW
775 {
776 // Open history file to append
777 CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
778 if (!fileout)
779 return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
780
781 // Write index header
782 unsigned int nSize = fileout.GetSerializeSize(*this);
783 fileout << FLATDATA(pchMessageStart) << nSize;
784
785 // Write undo data
786 long fileOutPos = ftell(fileout);
787 if (fileOutPos < 0)
13e5cce4 788 return error("CBlockUndo::WriteToDisk() : ftell failed");
5382bcf8
PW
789 pos.nPos = (unsigned int)fileOutPos;
790 fileout << *this;
791
8539361e
PW
792 // calculate & write checksum
793 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
794 hasher << hashBlock;
795 hasher << *this;
796 fileout << hasher.GetHash();
797
5382bcf8
PW
798 // Flush stdio buffers and commit to disk before returning
799 fflush(fileout);
450cbb09 800 if (!IsInitialBlockDownload())
5382bcf8
PW
801 FileCommit(fileout);
802
803 return true;
804 }
8539361e
PW
805
806 bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
807 {
808 // Open history file to read
809 CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
810 if (!filein)
811 return error("CBlockUndo::ReadFromDisk() : OpenBlockFile failed");
812
813 // Read block
814 uint256 hashChecksum;
815 try {
816 filein >> *this;
d0809a19 817 filein >> hashChecksum;
8539361e
PW
818 }
819 catch (std::exception &e) {
820 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
821 }
822
8539361e
PW
823 // Verify checksum
824 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
825 hasher << hashBlock;
826 hasher << *this;
827 if (hashChecksum != hasher.GetHash())
828 return error("CBlockUndo::ReadFromDisk() : checksum mismatch");
829
830 return true;
831 }
8adf48dc
PW
832};
833
10fd8604
PW
834/** pruned version of CTransaction: only retains metadata and unspent transaction outputs
835 *
836 * Serialized format:
837 * - VARINT(nVersion)
838 * - VARINT(nCode)
839 * - unspentness bitvector, for vout[2] and further; least significant byte first
840 * - the non-spent CTxOuts (via CTxOutCompressor)
841 * - VARINT(nHeight)
842 *
843 * The nCode value consists of:
844 * - bit 1: IsCoinBase()
845 * - bit 2: vout[0] is not spent
846 * - bit 4: vout[1] is not spent
847 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
848 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
849 * least one non-spent output).
850 *
851 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
852 * <><><--------------------------------------------><---->
853 * | \ | /
854 * version code vout[1] height
855 *
856 * - version = 1
857 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
858 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
859 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
860 * * 8358: compact amount representation for 60000000000 (600 BTC)
861 * * 00: special txout type pay-to-pubkey-hash
862 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
863 * - height = 203998
864 *
865 *
866 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
867 * <><><--><--------------------------------------------------><----------------------------------------------><---->
868 * / \ \ | | /
869 * version code unspentness vout[4] vout[16] height
870 *
871 * - version = 1
872 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
873 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
874 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
875 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
876 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
877 * * 00: special txout type pay-to-pubkey-hash
878 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
879 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
880 * * bbd123: compact amount representation for 110397 (0.001 BTC)
881 * * 00: special txout type pay-to-pubkey-hash
882 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
883 * - height = 120891
884 */
885class CCoins
886{
887public:
888 // whether transaction is a coinbase
889 bool fCoinBase;
890
891 // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
892 std::vector<CTxOut> vout;
893
729b1806 894 // at which height this transaction was included in the active block chain
10fd8604
PW
895 int nHeight;
896
897 // version of the CTransaction; accesses to this value should probably check for nHeight as well,
898 // as new tx version will probably only be introduced at certain heights
899 int nVersion;
900
901 // construct a CCoins from a CTransaction, at a given height
902 CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { }
903
904 // empty constructor
905 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
906
907 // remove spent outputs at the end of vout
908 void Cleanup() {
909 while (vout.size() > 0 && vout.back().IsNull())
910 vout.pop_back();
f369d02c
PW
911 if (vout.empty())
912 std::vector<CTxOut>().swap(vout);
913 }
914
915 void swap(CCoins &to) {
916 std::swap(to.fCoinBase, fCoinBase);
917 to.vout.swap(vout);
918 std::swap(to.nHeight, nHeight);
919 std::swap(to.nVersion, nVersion);
10fd8604
PW
920 }
921
922 // equality test
923 friend bool operator==(const CCoins &a, const CCoins &b) {
729b1806 924 return a.fCoinBase == b.fCoinBase &&
10fd8604
PW
925 a.nHeight == b.nHeight &&
926 a.nVersion == b.nVersion &&
927 a.vout == b.vout;
928 }
929 friend bool operator!=(const CCoins &a, const CCoins &b) {
930 return !(a == b);
931 }
932
933 // calculate number of bytes for the bitmask, and its number of non-zero bytes
934 // each bit in the bitmask represents the availability of one output, but the
935 // availabilities of the first two outputs are encoded separately
936 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
937 unsigned int nLastUsedByte = 0;
938 for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
939 bool fZero = true;
940 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
941 if (!vout[2+b*8+i].IsNull()) {
942 fZero = false;
943 continue;
944 }
945 }
946 if (!fZero) {
947 nLastUsedByte = b + 1;
948 nNonzeroBytes++;
949 }
950 }
951 nBytes += nLastUsedByte;
952 }
953
954 bool IsCoinBase() const {
955 return fCoinBase;
956 }
957
958 unsigned int GetSerializeSize(int nType, int nVersion) const {
959 unsigned int nSize = 0;
960 unsigned int nMaskSize = 0, nMaskCode = 0;
961 CalcMaskSize(nMaskSize, nMaskCode);
962 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
963 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
964 assert(fFirst || fSecond || nMaskCode);
965 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
966 // version
967 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
968 // size of header code
969 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
970 // spentness bitmask
971 nSize += nMaskSize;
972 // txouts themself
973 for (unsigned int i = 0; i < vout.size(); i++)
974 if (!vout[i].IsNull())
975 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
976 // height
977 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
978 return nSize;
979 }
980
981 template<typename Stream>
982 void Serialize(Stream &s, int nType, int nVersion) const {
983 unsigned int nMaskSize = 0, nMaskCode = 0;
984 CalcMaskSize(nMaskSize, nMaskCode);
985 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
986 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
987 assert(fFirst || fSecond || nMaskCode);
988 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
989 // version
990 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
991 // header code
992 ::Serialize(s, VARINT(nCode), nType, nVersion);
993 // spentness bitmask
994 for (unsigned int b = 0; b<nMaskSize; b++) {
995 unsigned char chAvail = 0;
996 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
997 if (!vout[2+b*8+i].IsNull())
998 chAvail |= (1 << i);
999 ::Serialize(s, chAvail, nType, nVersion);
1000 }
1001 // txouts themself
1002 for (unsigned int i = 0; i < vout.size(); i++) {
1003 if (!vout[i].IsNull())
1004 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
1005 }
1006 // coinbase height
1007 ::Serialize(s, VARINT(nHeight), nType, nVersion);
1008 }
1009
1010 template<typename Stream>
1011 void Unserialize(Stream &s, int nType, int nVersion) {
1012 unsigned int nCode = 0;
1013 // version
1014 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
1015 // header code
1016 ::Unserialize(s, VARINT(nCode), nType, nVersion);
1017 fCoinBase = nCode & 1;
1018 std::vector<bool> vAvail(2, false);
1019 vAvail[0] = nCode & 2;
1020 vAvail[1] = nCode & 4;
1021 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
1022 // spentness bitmask
1023 while (nMaskCode > 0) {
1024 unsigned char chAvail = 0;
1025 ::Unserialize(s, chAvail, nType, nVersion);
1026 for (unsigned int p = 0; p < 8; p++) {
1027 bool f = (chAvail & (1 << p)) != 0;
1028 vAvail.push_back(f);
1029 }
1030 if (chAvail != 0)
1031 nMaskCode--;
1032 }
1033 // txouts themself
1034 vout.assign(vAvail.size(), CTxOut());
1035 for (unsigned int i = 0; i < vAvail.size(); i++) {
1036 if (vAvail[i])
1037 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
1038 }
1039 // coinbase height
1040 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
1041 Cleanup();
1042 }
1043
44ac1c0f
PW
1044 // mark an outpoint spent, and construct undo information
1045 bool Spend(const COutPoint &out, CTxInUndo &undo) {
10fd8604
PW
1046 if (out.n >= vout.size())
1047 return false;
1048 if (vout[out.n].IsNull())
1049 return false;
44ac1c0f 1050 undo = CTxInUndo(vout[out.n]);
10fd8604
PW
1051 vout[out.n].SetNull();
1052 Cleanup();
44ac1c0f
PW
1053 if (vout.size() == 0) {
1054 undo.nHeight = nHeight;
1055 undo.fCoinBase = fCoinBase;
1056 undo.nVersion = this->nVersion;
1057 }
10fd8604
PW
1058 return true;
1059 }
1060
1061 // mark a vout spent
1062 bool Spend(int nPos) {
44ac1c0f 1063 CTxInUndo undo;
10fd8604 1064 COutPoint out(0, nPos);
44ac1c0f 1065 return Spend(out, undo);
10fd8604
PW
1066 }
1067
1068 // check whether a particular output is still available
1069 bool IsAvailable(unsigned int nPos) const {
1070 return (nPos < vout.size() && !vout[nPos].IsNull());
1071 }
1072
1073 // check whether the entire CCoins is spent
1074 // note that only !IsPruned() CCoins can be serialized
1075 bool IsPruned() const {
1076 BOOST_FOREACH(const CTxOut &out, vout)
1077 if (!out.IsNull())
1078 return false;
1079 return true;
1080 }
1081};
0a61b0df 1082
2800ce73
PW
1083/** Closure representing one script verification
1084 * Note that this stores references to the spending transaction */
1085class CScriptCheck
1086{
1087private:
1088 CScript scriptPubKey;
1089 const CTransaction *ptxTo;
1090 unsigned int nIn;
1091 unsigned int nFlags;
1092 int nHashType;
0a61b0df 1093
2800ce73
PW
1094public:
1095 CScriptCheck() {}
1096 CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
1097 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
1098 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
1099
1100 bool operator()() const;
1101
1102 void swap(CScriptCheck &check) {
1103 scriptPubKey.swap(check.scriptPubKey);
1104 std::swap(ptxTo, check.ptxTo);
1105 std::swap(nIn, check.nIn);
1106 std::swap(nFlags, check.nFlags);
1107 std::swap(nHashType, check.nHashType);
1108 }
1109};
0a61b0df 1110
6b8de05d 1111/** A transaction with a merkle branch linking it to the block chain. */
0a61b0df 1112class CMerkleTx : public CTransaction
1113{
1114public:
1115 uint256 hashBlock;
223b6f1b 1116 std::vector<uint256> vMerkleBranch;
0a61b0df 1117 int nIndex;
1118
1119 // memory only
cdcc319c 1120 mutable bool fMerkleVerified;
0a61b0df 1121
1122
1123 CMerkleTx()
1124 {
1125 Init();
1126 }
1127
1128 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
1129 {
1130 Init();
1131 }
1132
1133 void Init()
1134 {
1135 hashBlock = 0;
1136 nIndex = -1;
1137 fMerkleVerified = false;
0a61b0df 1138 }
1139
335e878b 1140
0a61b0df 1141 IMPLEMENT_SERIALIZE
1142 (
1143 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
1144 nVersion = this->nVersion;
1145 READWRITE(hashBlock);
1146 READWRITE(vMerkleBranch);
1147 READWRITE(nIndex);
1148 )
1149
0a61b0df 1150
1151 int SetMerkleBranch(const CBlock* pblock=NULL);
30ab2c9c
PW
1152 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
1153 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
0a61b0df 1154 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
1155 int GetBlocksToMaturity() const;
ce99358f 1156 bool AcceptToMemoryPool(bool fCheckInputs=true, bool fLimitFree=true);
0a61b0df 1157};
1158
1159
1160
1161
0a61b0df 1162
4bedfa92
PW
1163/** Data structure that represents a partial merkle tree.
1164 *
1165 * It respresents a subset of the txid's of a known block, in a way that
1166 * allows recovery of the list of txid's and the merkle root, in an
1167 * authenticated way.
1168 *
1169 * The encoding works as follows: we traverse the tree in depth-first order,
1170 * storing a bit for each traversed node, signifying whether the node is the
1171 * parent of at least one matched leaf txid (or a matched txid itself). In
1172 * case we are at the leaf level, or this bit is 0, its merkle node hash is
1173 * stored, and its children are not explorer further. Otherwise, no hash is
1174 * stored, but we recurse into both (or the only) child branch. During
1175 * decoding, the same depth-first traversal is performed, consuming bits and
1176 * hashes as they written during encoding.
1177 *
1178 * The serialization is fixed and provides a hard guarantee about the
1179 * encoded size:
1180 *
1181 * SIZE <= 10 + ceil(32.25*N)
1182 *
1183 * Where N represents the number of leaf nodes of the partial tree. N itself
1184 * is bounded by:
1185 *
1186 * N <= total_transactions
1187 * N <= 1 + matched_transactions*tree_height
1188 *
1189 * The serialization format:
1190 * - uint32 total_transactions (4 bytes)
1191 * - varint number of hashes (1-3 bytes)
1192 * - uint256[] hashes in depth-first order (<= 32*N bytes)
1193 * - varint number of bytes of flag bits (1-3 bytes)
1194 * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
1195 * The size constraints follow from this.
1196 */
1197class CPartialMerkleTree
1198{
1199protected:
1200 // the total number of transactions in the block
1201 unsigned int nTransactions;
1202
1203 // node-is-parent-of-matched-txid bits
1204 std::vector<bool> vBits;
1205
1206 // txids and internal hashes
1207 std::vector<uint256> vHash;
0a61b0df 1208
4bedfa92
PW
1209 // flag set when encountering invalid data
1210 bool fBad;
0a61b0df 1211
4bedfa92
PW
1212 // helper function to efficiently calculate the number of nodes at given height in the merkle tree
1213 unsigned int CalcTreeWidth(int height) {
1214 return (nTransactions+(1 << height)-1) >> height;
1215 }
1216
1217 // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
1218 uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
1219
1220 // recursive function that traverses tree nodes, storing the data as bits and hashes
1221 void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
1222
1223 // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
1224 // it returns the hash of the respective node.
1225 uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
1226
1227public:
0a61b0df 1228
4bedfa92
PW
1229 // serialization implementation
1230 IMPLEMENT_SERIALIZE(
1231 READWRITE(nTransactions);
1232 READWRITE(vHash);
1233 std::vector<unsigned char> vBytes;
1234 if (fRead) {
1235 READWRITE(vBytes);
1236 CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
1237 us.vBits.resize(vBytes.size() * 8);
1238 for (unsigned int p = 0; p < us.vBits.size(); p++)
1239 us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
1240 us.fBad = false;
1241 } else {
1242 vBytes.resize((vBits.size()+7)/8);
1243 for (unsigned int p = 0; p < vBits.size(); p++)
1244 vBytes[p / 8] |= vBits[p] << (p % 8);
1245 READWRITE(vBytes);
1246 }
1247 )
1248
1249 // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
1250 CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
0a61b0df 1251
4bedfa92 1252 CPartialMerkleTree();
0a61b0df 1253
4bedfa92
PW
1254 // extract the matching txid's represented by this partial merkle tree.
1255 // returns the merkle root, or 0 in case of failure
1256 uint256 ExtractMatches(std::vector<uint256> &vMatch);
1257};
0a61b0df 1258
1259
6b8de05d
PW
1260/** Nodes collect new transactions into a block, hash them into a hash tree,
1261 * and scan through nonce values to make the block's hash satisfy proof-of-work
1262 * requirements. When they solve the proof-of-work, they broadcast the block
1263 * to everyone and the block is added to the block chain. The first transaction
1264 * in the block is a special one that creates a new coin owned by the creator
1265 * of the block.
6b8de05d 1266 */
e754cf41 1267class CBlockHeader
0a61b0df 1268{
1269public:
1270 // header
de237cbf 1271 static const int CURRENT_VERSION=2;
0a61b0df 1272 int nVersion;
1273 uint256 hashPrevBlock;
1274 uint256 hashMerkleRoot;
1275 unsigned int nTime;
1276 unsigned int nBits;
1277 unsigned int nNonce;
1278
e754cf41 1279 CBlockHeader()
0a61b0df 1280 {
1281 SetNull();
1282 }
1283
1284 IMPLEMENT_SERIALIZE
1285 (
1286 READWRITE(this->nVersion);
1287 nVersion = this->nVersion;
1288 READWRITE(hashPrevBlock);
1289 READWRITE(hashMerkleRoot);
1290 READWRITE(nTime);
1291 READWRITE(nBits);
1292 READWRITE(nNonce);
0a61b0df 1293 )
1294
1295 void SetNull()
1296 {
e754cf41 1297 nVersion = CBlockHeader::CURRENT_VERSION;
0a61b0df 1298 hashPrevBlock = 0;
1299 hashMerkleRoot = 0;
1300 nTime = 0;
1301 nBits = 0;
1302 nNonce = 0;
0a61b0df 1303 }
1304
1305 bool IsNull() const
1306 {
1307 return (nBits == 0);
1308 }
1309
1310 uint256 GetHash() const
1311 {
1312 return Hash(BEGIN(nVersion), END(nNonce));
1313 }
1314
bde280b9 1315 int64 GetBlockTime() const
0a61b0df 1316 {
bde280b9 1317 return (int64)nTime;
0a61b0df 1318 }
1319
0f8cb5db 1320 void UpdateTime(const CBlockIndex* pindexPrev);
e754cf41
PW
1321};
1322
1323class CBlock : public CBlockHeader
1324{
1325public:
1326 // network and disk
1327 std::vector<CTransaction> vtx;
1328
1329 // memory only
1330 mutable std::vector<uint256> vMerkleTree;
f1e1fb4b 1331
e754cf41
PW
1332 CBlock()
1333 {
1334 SetNull();
1335 }
1336
1337 CBlock(const CBlockHeader &header)
1338 {
1339 SetNull();
1340 *((CBlockHeader*)this) = header;
1341 }
1342
1343 IMPLEMENT_SERIALIZE
1344 (
1345 READWRITE(*(CBlockHeader*)this);
1346 READWRITE(vtx);
1347 )
1348
1349 void SetNull()
1350 {
1351 CBlockHeader::SetNull();
1352 vtx.clear();
1353 vMerkleTree.clear();
e754cf41 1354 }
0a61b0df 1355
587f0f85
MC
1356 CBlockHeader GetBlockHeader() const
1357 {
1358 CBlockHeader block;
1359 block.nVersion = nVersion;
1360 block.hashPrevBlock = hashPrevBlock;
1361 block.hashMerkleRoot = hashMerkleRoot;
1362 block.nTime = nTime;
1363 block.nBits = nBits;
1364 block.nNonce = nNonce;
1365 return block;
1366 }
1367
0a61b0df 1368 uint256 BuildMerkleTree() const
1369 {
1370 vMerkleTree.clear();
223b6f1b 1371 BOOST_FOREACH(const CTransaction& tx, vtx)
0a61b0df 1372 vMerkleTree.push_back(tx.GetHash());
1373 int j = 0;
1374 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1375 {
1376 for (int i = 0; i < nSize; i += 2)
1377 {
223b6f1b 1378 int i2 = std::min(i+1, nSize-1);
0a61b0df 1379 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1380 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1381 }
1382 j += nSize;
1383 }
1384 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1385 }
1386
64dd46fd
PW
1387 const uint256 &GetTxHash(unsigned int nIndex) const {
1388 assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
1389 assert(nIndex < vtx.size());
1390 return vMerkleTree[nIndex];
1391 }
1392
223b6f1b 1393 std::vector<uint256> GetMerkleBranch(int nIndex) const
0a61b0df 1394 {
1395 if (vMerkleTree.empty())
1396 BuildMerkleTree();
223b6f1b 1397 std::vector<uint256> vMerkleBranch;
0a61b0df 1398 int j = 0;
1399 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1400 {
223b6f1b 1401 int i = std::min(nIndex^1, nSize-1);
0a61b0df 1402 vMerkleBranch.push_back(vMerkleTree[j+i]);
1403 nIndex >>= 1;
1404 j += nSize;
1405 }
1406 return vMerkleBranch;
1407 }
1408
223b6f1b 1409 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
0a61b0df 1410 {
1411 if (nIndex == -1)
1412 return 0;
223b6f1b 1413 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
0a61b0df 1414 {
1415 if (nIndex & 1)
1416 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1417 else
1418 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1419 nIndex >>= 1;
1420 }
1421 return hash;
1422 }
1423
630fd8dc 1424 bool WriteToDisk(CDiskBlockPos &pos)
0a61b0df 1425 {
1426 // Open history file to append
5382bcf8 1427 CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
0a61b0df 1428 if (!fileout)
5382bcf8
PW
1429 return error("CBlock::WriteToDisk() : OpenBlockFile failed");
1430
1431 // Write index header
1432 unsigned int nSize = fileout.GetSerializeSize(*this);
1433 fileout << FLATDATA(pchMessageStart) << nSize;
0a61b0df 1434
0a61b0df 1435 // Write block
5382bcf8
PW
1436 long fileOutPos = ftell(fileout);
1437 if (fileOutPos < 0)
1438 return error("CBlock::WriteToDisk() : ftell failed");
1439 pos.nPos = (unsigned int)fileOutPos;
0a61b0df 1440 fileout << *this;
1441
1442 // Flush stdio buffers and commit to disk before returning
1443 fflush(fileout);
450cbb09 1444 if (!IsInitialBlockDownload())
768e5d52 1445 FileCommit(fileout);
0a61b0df 1446
1447 return true;
1448 }
1449
e754cf41 1450 bool ReadFromDisk(const CDiskBlockPos &pos)
0a61b0df 1451 {
1452 SetNull();
1453
1454 // Open history file to read
5382bcf8 1455 CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
0a61b0df 1456 if (!filein)
1457 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
0a61b0df 1458
1459 // Read block
8fe791e4
JG
1460 try {
1461 filein >> *this;
1462 }
1463 catch (std::exception &e) {
1464 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1465 }
0a61b0df 1466
1467 // Check the header
1468 if (!CheckProofOfWork(GetHash(), nBits))
1469 return error("CBlock::ReadFromDisk() : errors in block header");
1470
1471 return true;
1472 }
1473
1474
1475
1476 void print() const
1477 {
d210f4f5 1478 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
f3a84c3a 1479 BlockHashStr(GetHash()).c_str(),
0a61b0df 1480 nVersion,
f3a84c3a 1481 BlockHashStr(hashPrevBlock).c_str(),
b22c8842 1482 hashMerkleRoot.ToString().substr(0,10).c_str(),
0a61b0df 1483 nTime, nBits, nNonce,
1484 vtx.size());
c376ac35 1485 for (unsigned int i = 0; i < vtx.size(); i++)
0a61b0df 1486 {
1487 printf(" ");
1488 vtx[i].print();
1489 }
1490 printf(" vMerkleTree: ");
c376ac35 1491 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
b22c8842 1492 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
0a61b0df 1493 printf("\n");
1494 }
1495
1496
2cbd71da
PW
1497 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1498 * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
1499 * will be true if no problems were found. Otherwise, the return value will be false in case
1500 * of problems. Note that in any case, coins may be modified. */
ef3988ca 1501 bool DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean = NULL);
450cbb09
PW
1502
1503 // Apply the effects of this block (with given index) on the UTXO set represented by coins
ef3988ca 1504 bool ConnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
450cbb09
PW
1505
1506 // Read a block from disk
e754cf41 1507 bool ReadFromDisk(const CBlockIndex* pindex);
450cbb09 1508
450cbb09 1509 // Add this block to the block index, and if necessary, switch the active block chain to this
ef3988ca 1510 bool AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos);
450cbb09
PW
1511
1512 // Context-independent validity checks
ef3988ca 1513 bool CheckBlock(CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
d68dcf74 1514
450cbb09 1515 // Store block on disk
7fea4846 1516 // if dbp is provided, the file is known to already reside on disk
ef3988ca 1517 bool AcceptBlock(CValidationState &state, CDiskBlockPos *dbp = NULL);
0a61b0df 1518};
1519
1520
1521
1522
1523
5382bcf8
PW
1524class CBlockFileInfo
1525{
1526public:
1527 unsigned int nBlocks; // number of blocks stored in file
1528 unsigned int nSize; // number of used bytes of block file
1529 unsigned int nUndoSize; // number of used bytes in the undo file
1530 unsigned int nHeightFirst; // lowest height of block in file
1531 unsigned int nHeightLast; // highest height of block in file
1532 uint64 nTimeFirst; // earliest time of block in file
1533 uint64 nTimeLast; // latest time of block in file
1534
1535 IMPLEMENT_SERIALIZE(
1536 READWRITE(VARINT(nBlocks));
1537 READWRITE(VARINT(nSize));
1538 READWRITE(VARINT(nUndoSize));
1539 READWRITE(VARINT(nHeightFirst));
1540 READWRITE(VARINT(nHeightLast));
1541 READWRITE(VARINT(nTimeFirst));
1542 READWRITE(VARINT(nTimeLast));
1543 )
1544
1545 void SetNull() {
1546 nBlocks = 0;
1547 nSize = 0;
1548 nUndoSize = 0;
1549 nHeightFirst = 0;
1550 nHeightLast = 0;
1551 nTimeFirst = 0;
1552 nTimeLast = 0;
1553 }
1554
1555 CBlockFileInfo() {
1556 SetNull();
1557 }
1558
1559 std::string ToString() const {
69e07747 1560 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
1561 }
1562
1563 // update statistics (does not update nSize)
1564 void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
1565 if (nBlocks==0 || nHeightFirst > nHeightIn)
1566 nHeightFirst = nHeightIn;
1567 if (nBlocks==0 || nTimeFirst > nTimeIn)
1568 nTimeFirst = nTimeIn;
1569 nBlocks++;
1570 if (nHeightIn > nHeightFirst)
1571 nHeightLast = nHeightIn;
1572 if (nTimeIn > nTimeLast)
1573 nTimeLast = nTimeIn;
1574 }
1575};
1576
1577extern CCriticalSection cs_LastBlockFile;
1578extern CBlockFileInfo infoLastBlockFile;
1579extern int nLastBlockFile;
0a61b0df 1580
857c61df
PW
1581enum BlockStatus {
1582 BLOCK_VALID_UNKNOWN = 0,
1583 BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
1584 BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
1585 BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
1586 BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
1587 BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
1588 BLOCK_VALID_MASK = 7,
1589
1590 BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
1591 BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
1592 BLOCK_HAVE_MASK = 24,
1593
1594 BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
1595 BLOCK_FAILED_CHILD = 64, // descends from failed block
1596 BLOCK_FAILED_MASK = 96
1597};
1598
6b8de05d
PW
1599/** The block chain is a tree shaped structure starting with the
1600 * genesis block at the root, with each block potentially having multiple
1601 * candidates to be the next block. pprev and pnext link a path through the
1602 * main/longest chain. A blockindex may have multiple pprev pointing back
1603 * to it, but pnext will only point forward to the longest branch, or will
1604 * be null if the block is not part of the longest chain.
1605 */
0a61b0df 1606class CBlockIndex
1607{
1608public:
857c61df 1609 // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
0a61b0df 1610 const uint256* phashBlock;
857c61df
PW
1611
1612 // pointer to the index of the predecessor of this block
0a61b0df 1613 CBlockIndex* pprev;
857c61df
PW
1614
1615 // (memory only) pointer to the index of the *active* successor of this block
0a61b0df 1616 CBlockIndex* pnext;
857c61df
PW
1617
1618 // height of the entry in the chain. The genesis block has height 0
0a61b0df 1619 int nHeight;
857c61df
PW
1620
1621 // Which # file this block is stored in (blk?????.dat)
1622 int nFile;
1623
1624 // Byte offset within blk?????.dat where this block's data is stored
1625 unsigned int nDataPos;
1626
1627 // Byte offset within rev?????.dat where this block's undo data is stored
5382bcf8 1628 unsigned int nUndoPos;
857c61df
PW
1629
1630 // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
0a61b0df 1631 CBigNum bnChainWork;
1632
857c61df
PW
1633 // Number of transactions in this block.
1634 // Note: in a potential headers-first mode, this number cannot be relied upon
1635 unsigned int nTx;
1636
1637 // (memory only) Number of transactions in the chain up to and including this block
1638 unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
1639
1640 // Verification status of this block. See enum BlockStatus
1641 unsigned int nStatus;
1642
0a61b0df 1643 // block header
1644 int nVersion;
1645 uint256 hashMerkleRoot;
1646 unsigned int nTime;
1647 unsigned int nBits;
1648 unsigned int nNonce;
1649
1650
1651 CBlockIndex()
1652 {
1653 phashBlock = NULL;
1654 pprev = NULL;
1655 pnext = NULL;
0a61b0df 1656 nHeight = 0;
857c61df
PW
1657 nFile = 0;
1658 nDataPos = 0;
450cbb09 1659 nUndoPos = 0;
0a61b0df 1660 bnChainWork = 0;
857c61df
PW
1661 nTx = 0;
1662 nChainTx = 0;
1663 nStatus = 0;
0a61b0df 1664
1665 nVersion = 0;
1666 hashMerkleRoot = 0;
1667 nTime = 0;
1668 nBits = 0;
1669 nNonce = 0;
1670 }
1671
e754cf41 1672 CBlockIndex(CBlockHeader& block)
0a61b0df 1673 {
1674 phashBlock = NULL;
1675 pprev = NULL;
1676 pnext = NULL;
0a61b0df 1677 nHeight = 0;
857c61df
PW
1678 nFile = 0;
1679 nDataPos = 0;
5382bcf8 1680 nUndoPos = 0;
0a61b0df 1681 bnChainWork = 0;
857c61df
PW
1682 nTx = 0;
1683 nChainTx = 0;
1684 nStatus = 0;
0a61b0df 1685
1686 nVersion = block.nVersion;
1687 hashMerkleRoot = block.hashMerkleRoot;
1688 nTime = block.nTime;
1689 nBits = block.nBits;
1690 nNonce = block.nNonce;
1691 }
1692
630fd8dc 1693 CDiskBlockPos GetBlockPos() const {
857c61df
PW
1694 CDiskBlockPos ret;
1695 if (nStatus & BLOCK_HAVE_DATA) {
1696 ret.nFile = nFile;
1697 ret.nPos = nDataPos;
a8a4b967 1698 }
857c61df 1699 return ret;
5382bcf8
PW
1700 }
1701
1702 CDiskBlockPos GetUndoPos() const {
857c61df
PW
1703 CDiskBlockPos ret;
1704 if (nStatus & BLOCK_HAVE_UNDO) {
1705 ret.nFile = nFile;
1706 ret.nPos = nUndoPos;
a8a4b967 1707 }
5382bcf8 1708 return ret;
630fd8dc
PW
1709 }
1710
e754cf41 1711 CBlockHeader GetBlockHeader() const
f03304a9 1712 {
e754cf41 1713 CBlockHeader block;
f03304a9 1714 block.nVersion = nVersion;
1715 if (pprev)
1716 block.hashPrevBlock = pprev->GetBlockHash();
1717 block.hashMerkleRoot = hashMerkleRoot;
1718 block.nTime = nTime;
1719 block.nBits = nBits;
1720 block.nNonce = nNonce;
1721 return block;
1722 }
1723
0a61b0df 1724 uint256 GetBlockHash() const
1725 {
1726 return *phashBlock;
1727 }
1728
bde280b9 1729 int64 GetBlockTime() const
0a61b0df 1730 {
bde280b9 1731 return (int64)nTime;
0a61b0df 1732 }
1733
1734 CBigNum GetBlockWork() const
1735 {
9b8eb4d6 1736 CBigNum bnTarget;
1737 bnTarget.SetCompact(nBits);
1738 if (bnTarget <= 0)
0a61b0df 1739 return 0;
9b8eb4d6 1740 return (CBigNum(1)<<256) / (bnTarget+1);
0a61b0df 1741 }
1742
1743 bool IsInMainChain() const
1744 {
1745 return (pnext || this == pindexBest);
1746 }
1747
1748 bool CheckIndex() const
1749 {
1750 return CheckProofOfWork(GetBlockHash(), nBits);
1751 }
1752
0a61b0df 1753 enum { nMedianTimeSpan=11 };
1754
bde280b9 1755 int64 GetMedianTimePast() const
0a61b0df 1756 {
bde280b9
WL
1757 int64 pmedian[nMedianTimeSpan];
1758 int64* pbegin = &pmedian[nMedianTimeSpan];
1759 int64* pend = &pmedian[nMedianTimeSpan];
0a61b0df 1760
1761 const CBlockIndex* pindex = this;
1762 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1763 *(--pbegin) = pindex->GetBlockTime();
1764
223b6f1b 1765 std::sort(pbegin, pend);
0a61b0df 1766 return pbegin[(pend - pbegin)/2];
1767 }
1768
bde280b9 1769 int64 GetMedianTime() const
0a61b0df 1770 {
1771 const CBlockIndex* pindex = this;
1772 for (int i = 0; i < nMedianTimeSpan/2; i++)
1773 {
1774 if (!pindex->pnext)
1775 return GetBlockTime();
1776 pindex = pindex->pnext;
1777 }
1778 return pindex->GetMedianTimePast();
1779 }
1780
de237cbf
GA
1781 /**
1782 * Returns true if there are nRequired or more blocks of minVersion or above
1783 * in the last nToCheck blocks, starting at pstart and going backwards.
1784 */
1785 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1786 unsigned int nRequired, unsigned int nToCheck);
0a61b0df 1787
223b6f1b 1788 std::string ToString() const
0a61b0df 1789 {
630fd8dc
PW
1790 return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
1791 pprev, pnext, nHeight,
b22c8842 1792 hashMerkleRoot.ToString().substr(0,10).c_str(),
f3a84c3a 1793 BlockHashStr(GetBlockHash()).c_str());
0a61b0df 1794 }
1795
1796 void print() const
1797 {
1798 printf("%s\n", ToString().c_str());
1799 }
1800};
1801
857c61df
PW
1802struct CBlockIndexWorkComparator
1803{
1804 bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
1805 if (pa->bnChainWork > pb->bnChainWork) return false;
1806 if (pa->bnChainWork < pb->bnChainWork) return true;
1807
1808 if (pa->GetBlockHash() < pb->GetBlockHash()) return false;
1809 if (pa->GetBlockHash() > pb->GetBlockHash()) return true;
1810
1811 return false; // identical blocks
1812 }
1813};
1814
0a61b0df 1815
1816
6b8de05d 1817/** Used to marshal pointers into hashes for db storage. */
0a61b0df 1818class CDiskBlockIndex : public CBlockIndex
1819{
1820public:
1821 uint256 hashPrev;
0a61b0df 1822
450cbb09 1823 CDiskBlockIndex() {
0a61b0df 1824 hashPrev = 0;
0a61b0df 1825 }
1826
450cbb09 1827 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
0a61b0df 1828 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
0a61b0df 1829 }
1830
1831 IMPLEMENT_SERIALIZE
1832 (
1833 if (!(nType & SER_GETHASH))
857c61df
PW
1834 READWRITE(VARINT(nVersion));
1835
1836 READWRITE(VARINT(nHeight));
1837 READWRITE(VARINT(nStatus));
1838 READWRITE(VARINT(nTx));
1839 if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
1840 READWRITE(VARINT(nFile));
1841 if (nStatus & BLOCK_HAVE_DATA)
1842 READWRITE(VARINT(nDataPos));
1843 if (nStatus & BLOCK_HAVE_UNDO)
1844 READWRITE(VARINT(nUndoPos));
0a61b0df 1845
1846 // block header
1847 READWRITE(this->nVersion);
1848 READWRITE(hashPrev);
1849 READWRITE(hashMerkleRoot);
1850 READWRITE(nTime);
1851 READWRITE(nBits);
1852 READWRITE(nNonce);
1853 )
1854
1855 uint256 GetBlockHash() const
1856 {
e754cf41 1857 CBlockHeader block;
0a61b0df 1858 block.nVersion = nVersion;
1859 block.hashPrevBlock = hashPrev;
1860 block.hashMerkleRoot = hashMerkleRoot;
1861 block.nTime = nTime;
1862 block.nBits = nBits;
1863 block.nNonce = nNonce;
1864 return block.GetHash();
1865 }
1866
1867
223b6f1b 1868 std::string ToString() const
0a61b0df 1869 {
223b6f1b 1870 std::string str = "CDiskBlockIndex(";
0a61b0df 1871 str += CBlockIndex::ToString();
450cbb09 1872 str += strprintf("\n hashBlock=%s, hashPrev=%s)",
0a61b0df 1873 GetBlockHash().ToString().c_str(),
f3a84c3a 1874 BlockHashStr(hashPrev).c_str());
0a61b0df 1875 return str;
1876 }
1877
1878 void print() const
1879 {
1880 printf("%s\n", ToString().c_str());
1881 }
1882};
1883
ef3988ca
PW
1884/** Capture information about block/transaction validation */
1885class CValidationState {
1886private:
1887 enum mode_state {
1888 MODE_VALID, // everything ok
1889 MODE_INVALID, // network rule violation (DoS value may be set)
1890 MODE_ERROR, // run-time error
1891 } mode;
1892 int nDoS;
1893public:
1894 CValidationState() : mode(MODE_VALID), nDoS(0) {}
1895 bool DoS(int level, bool ret = false) {
1896 if (mode == MODE_ERROR)
1897 return ret;
1898 nDoS += level;
1899 mode = MODE_INVALID;
1900 return ret;
1901 }
1902 bool Invalid(bool ret = false) {
1903 return DoS(0, ret);
1904 }
7851033d 1905 bool Error() {
ef3988ca 1906 mode = MODE_ERROR;
7851033d
PW
1907 return false;
1908 }
1909 bool Abort(const std::string &msg) {
1910 AbortNode(msg);
1911 return Error();
ef3988ca
PW
1912 }
1913 bool IsValid() {
1914 return mode == MODE_VALID;
1915 }
1916 bool IsInvalid() {
1917 return mode == MODE_INVALID;
1918 }
1919 bool IsError() {
1920 return mode == MODE_ERROR;
1921 }
1922 bool IsInvalid(int &nDoSOut) {
1923 if (IsInvalid()) {
1924 nDoSOut = nDoS;
1925 return true;
1926 }
1927 return false;
1928 }
1929};
0a61b0df 1930
1931
1932
1933
1934
1935
1936
6b8de05d
PW
1937/** Describes a place in the block chain to another node such that if the
1938 * other node doesn't have the same branch, it can find a recent common trunk.
1939 * The further back it is, the further before the fork it may be.
1940 */
0a61b0df 1941class CBlockLocator
1942{
1943protected:
223b6f1b 1944 std::vector<uint256> vHave;
0a61b0df 1945public:
1946
1947 CBlockLocator()
1948 {
1949 }
1950
1951 explicit CBlockLocator(const CBlockIndex* pindex)
1952 {
1953 Set(pindex);
1954 }
1955
1956 explicit CBlockLocator(uint256 hashBlock)
1957 {
223b6f1b 1958 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
0a61b0df 1959 if (mi != mapBlockIndex.end())
1960 Set((*mi).second);
1961 }
1962
30ab2c9c
PW
1963 CBlockLocator(const std::vector<uint256>& vHaveIn)
1964 {
1965 vHave = vHaveIn;
1966 }
1967
0a61b0df 1968 IMPLEMENT_SERIALIZE
1969 (
1970 if (!(nType & SER_GETHASH))
1971 READWRITE(nVersion);
1972 READWRITE(vHave);
1973 )
1974
f03304a9 1975 void SetNull()
1976 {
1977 vHave.clear();
1978 }
1979
1980 bool IsNull()
1981 {
1982 return vHave.empty();
1983 }
1984
0a61b0df 1985 void Set(const CBlockIndex* pindex)
1986 {
1987 vHave.clear();
1988 int nStep = 1;
1989 while (pindex)
1990 {
1991 vHave.push_back(pindex->GetBlockHash());
1992
1993 // Exponentially larger steps back
1994 for (int i = 0; pindex && i < nStep; i++)
1995 pindex = pindex->pprev;
1996 if (vHave.size() > 10)
1997 nStep *= 2;
1998 }
1999 vHave.push_back(hashGenesisBlock);
2000 }
2001
2002 int GetDistanceBack()
2003 {
2004 // Retrace how far back it was in the sender's branch
2005 int nDistance = 0;
2006 int nStep = 1;
223b6f1b 2007 BOOST_FOREACH(const uint256& hash, vHave)
0a61b0df 2008 {
223b6f1b 2009 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
0a61b0df 2010 if (mi != mapBlockIndex.end())
2011 {
2012 CBlockIndex* pindex = (*mi).second;
2013 if (pindex->IsInMainChain())
2014 return nDistance;
2015 }
2016 nDistance += nStep;
2017 if (nDistance > 10)
2018 nStep *= 2;
2019 }
2020 return nDistance;
2021 }
2022
2023 CBlockIndex* GetBlockIndex()
2024 {
2025 // Find the first block the caller has in the main chain
223b6f1b 2026 BOOST_FOREACH(const uint256& hash, vHave)
0a61b0df 2027 {
223b6f1b 2028 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
0a61b0df 2029 if (mi != mapBlockIndex.end())
2030 {
2031 CBlockIndex* pindex = (*mi).second;
2032 if (pindex->IsInMainChain())
2033 return pindex;
2034 }
2035 }
2036 return pindexGenesisBlock;
2037 }
2038
2039 uint256 GetBlockHash()
2040 {
2041 // Find the first block the caller has in the main chain
223b6f1b 2042 BOOST_FOREACH(const uint256& hash, vHave)
0a61b0df 2043 {
223b6f1b 2044 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
0a61b0df 2045 if (mi != mapBlockIndex.end())
2046 {
2047 CBlockIndex* pindex = (*mi).second;
2048 if (pindex->IsInMainChain())
2049 return hash;
2050 }
2051 }
2052 return hashGenesisBlock;
2053 }
2054
2055 int GetHeight()
2056 {
2057 CBlockIndex* pindex = GetBlockIndex();
2058 if (!pindex)
2059 return 0;
2060 return pindex->nHeight;
2061 }
2062};
2063
2064
2065
2066
2067
2068
e4ff4e68 2069
2070
235507ae
JG
2071class CTxMemPool
2072{
2073public:
2074 mutable CCriticalSection cs;
2075 std::map<uint256, CTransaction> mapTx;
2076 std::map<COutPoint, CInPoint> mapNextTx;
8e45ed66 2077
ef3988ca 2078 bool accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs);
f77654a0 2079 bool addUnchecked(const uint256& hash, CTransaction &tx);
231b3999
PW
2080 bool remove(const CTransaction &tx, bool fRecursive = false);
2081 bool removeConflicts(const CTransaction &tx);
639b61d7 2082 void clear();
25d5c195 2083 void queryHashes(std::vector<uint256>& vtxid);
450cbb09 2084 void pruneSpent(const uint256& hash, CCoins &coins);
8e45ed66
JG
2085
2086 unsigned long size()
2087 {
2088 LOCK(cs);
2089 return mapTx.size();
2090 }
ca4c4c53
JG
2091
2092 bool exists(uint256 hash)
2093 {
2094 return (mapTx.count(hash) != 0);
2095 }
2096
2097 CTransaction& lookup(uint256 hash)
2098 {
2099 return mapTx[hash];
2100 }
235507ae
JG
2101};
2102
8e45ed66
JG
2103extern CTxMemPool mempool;
2104
beeb5761
PW
2105struct CCoinsStats
2106{
2107 int nHeight;
2108 uint64 nTransactions;
2109 uint64 nTransactionOutputs;
2110 uint64 nSerializedSize;
2111
2112 CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0) {}
2113};
2114
450cbb09
PW
2115/** Abstract view on the open txout dataset. */
2116class CCoinsView
2117{
2118public:
2119 // Retrieve the CCoins (unspent transaction outputs) for a given txid
f369d02c 2120 virtual bool GetCoins(const uint256 &txid, CCoins &coins);
450cbb09
PW
2121
2122 // Modify the CCoins for a given txid
f369d02c 2123 virtual bool SetCoins(const uint256 &txid, const CCoins &coins);
450cbb09
PW
2124
2125 // Just check whether we have data for a given txid.
2126 // This may (but cannot always) return true for fully spent transactions
f369d02c 2127 virtual bool HaveCoins(const uint256 &txid);
450cbb09
PW
2128
2129 // Retrieve the block index whose state this CCoinsView currently represents
2130 virtual CBlockIndex *GetBestBlock();
2131
2132 // Modify the currently active block index
2133 virtual bool SetBestBlock(CBlockIndex *pindex);
c2ed184f
PW
2134
2135 // Do a bulk modification (multiple SetCoins + one SetBestBlock)
ae8bfd12 2136 virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
c2ed184f
PW
2137
2138 // Calculate statistics about the unspent transaction output set
beeb5761 2139 virtual bool GetStats(CCoinsStats &stats);
c9c7d482
PW
2140
2141 // As we use CCoinsViews polymorphically, have a virtual destructor
13e5cce4 2142 virtual ~CCoinsView() {}
450cbb09
PW
2143};
2144
2145/** CCoinsView backed by another CCoinsView */
2146class CCoinsViewBacked : public CCoinsView
2147{
2148protected:
2149 CCoinsView *base;
2150
2151public:
2152 CCoinsViewBacked(CCoinsView &viewIn);
f369d02c
PW
2153 bool GetCoins(const uint256 &txid, CCoins &coins);
2154 bool SetCoins(const uint256 &txid, const CCoins &coins);
2155 bool HaveCoins(const uint256 &txid);
450cbb09
PW
2156 CBlockIndex *GetBestBlock();
2157 bool SetBestBlock(CBlockIndex *pindex);
2158 void SetBackend(CCoinsView &viewIn);
ae8bfd12 2159 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
beeb5761 2160 bool GetStats(CCoinsStats &stats);
450cbb09
PW
2161};
2162
2163/** CCoinsView that adds a memory cache for transactions to another CCoinsView */
2164class CCoinsViewCache : public CCoinsViewBacked
2165{
2166protected:
2167 CBlockIndex *pindexTip;
2168 std::map<uint256,CCoins> cacheCoins;
2169
2170public:
2171 CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
c2ed184f
PW
2172
2173 // Standard CCoinsView methods
f369d02c
PW
2174 bool GetCoins(const uint256 &txid, CCoins &coins);
2175 bool SetCoins(const uint256 &txid, const CCoins &coins);
2176 bool HaveCoins(const uint256 &txid);
450cbb09
PW
2177 CBlockIndex *GetBestBlock();
2178 bool SetBestBlock(CBlockIndex *pindex);
ae8bfd12 2179 bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
c2ed184f
PW
2180
2181 // Return a modifiable reference to a CCoins. Check HaveCoins first.
2182 // Many methods explicitly require a CCoinsViewCache because of this method, to reduce
2183 // copying.
f369d02c 2184 CCoins &GetCoins(const uint256 &txid);
c2ed184f
PW
2185
2186 // Push the modifications applied to this cache to its base.
2187 // Failure to call this method before destruction will cause the changes to be forgotten.
450cbb09 2188 bool Flush();
c2ed184f
PW
2189
2190 // Calculate the size of the cache (in number of transactions)
ae8bfd12 2191 unsigned int GetCacheSize();
13c51f20
PW
2192
2193private:
f369d02c 2194 std::map<uint256,CCoins>::iterator FetchCoins(const uint256 &txid);
450cbb09
PW
2195};
2196
2197/** CCoinsView that brings transactions from a memorypool into view.
2198 It does not check for spendings by memory pool transactions. */
2199class CCoinsViewMemPool : public CCoinsViewBacked
2200{
2201protected:
2202 CTxMemPool &mempool;
2203
2204public:
2205 CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
f369d02c
PW
2206 bool GetCoins(const uint256 &txid, CCoins &coins);
2207 bool HaveCoins(const uint256 &txid);
450cbb09
PW
2208};
2209
d979e6e3 2210/** Global variable that points to the active CCoinsView (protected by cs_main) */
ae8bfd12
PW
2211extern CCoinsViewCache *pcoinsTip;
2212
d979e6e3
PW
2213/** Global variable that points to the active block tree (protected by cs_main) */
2214extern CBlockTreeDB *pblocktree;
2215
03cac0bb
FV
2216struct CBlockTemplate
2217{
2218 CBlock block;
2219 std::vector<int64_t> vTxFees;
2220 std::vector<int64_t> vTxSigOps;
2221};
2222
9fb106e7
MC
2223
2224
2225
2226
2227
2228/** Used to relay blocks as header + vector<merkle branch>
2229 * to filtered nodes.
2230 */
2231class CMerkleBlock
2232{
2233public:
21aaf255 2234 // Public only for unit testing
9fb106e7 2235 CBlockHeader header;
21aaf255 2236 CPartialMerkleTree txn;
9fb106e7 2237
21aaf255
MC
2238public:
2239 // Public only for unit testing and relay testing
2240 // (not relayed)
2241 std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
9fb106e7
MC
2242
2243 // Create from a CBlock, filtering transactions according to filter
2244 // Note that this will call IsRelevantAndUpdate on the filter for each transaction,
2245 // thus the filter will likely be modified.
2246 CMerkleBlock(const CBlock& block, CBloomFilter& filter);
2247
2248 IMPLEMENT_SERIALIZE
2249 (
2250 READWRITE(header);
21aaf255 2251 READWRITE(txn);
9fb106e7
MC
2252 )
2253};
2254
223b6f1b 2255#endif
This page took 0.455777 seconds and 4 git commands to generate.