Master Core  v0.0.9 - 2abfd2849db8ba7a83957c64eb976b406713c123
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
main.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #ifndef BITCOIN_MAIN_H
7 #define BITCOIN_MAIN_H
8 
9 #if defined(HAVE_CONFIG_H)
10 #include "bitcoin-config.h"
11 #endif
12 
13 #include "bignum.h"
14 #include "chainparams.h"
15 #include "coins.h"
16 #include "core.h"
17 #include "net.h"
18 #include "script.h"
19 #include "sync.h"
20 #include "txmempool.h"
21 #include "uint256.h"
22 
23 #include <algorithm>
24 #include <exception>
25 #include <map>
26 #include <set>
27 #include <stdint.h>
28 #include <string>
29 #include <utility>
30 #include <vector>
31 
32 class CBlockIndex;
33 class CBloomFilter;
34 class CInv;
35 
37 static const unsigned int MAX_BLOCK_SIZE = 1000000;
39 static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 750000;
40 static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
42 static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 50000;
44 static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
46 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
48 static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
50 static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS = 750;
52 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
54 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
56 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
58 static const int COINBASE_MATURITY = 100;
60 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
62 static const int MAX_SCRIPTCHECK_THREADS = 16;
64 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
66 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 128;
68 static const unsigned int BLOCK_DOWNLOAD_TIMEOUT = 60;
69 
70 #ifdef USE_UPNP
71 static const int fHaveUPnP = true;
72 #else
73 static const int fHaveUPnP = false;
74 #endif
75 
77 static const unsigned char REJECT_MALFORMED = 0x01;
78 static const unsigned char REJECT_INVALID = 0x10;
79 static const unsigned char REJECT_OBSOLETE = 0x11;
80 static const unsigned char REJECT_DUPLICATE = 0x12;
81 static const unsigned char REJECT_NONSTANDARD = 0x40;
82 static const unsigned char REJECT_DUST = 0x41;
83 static const unsigned char REJECT_INSUFFICIENTFEE = 0x42;
84 static const unsigned char REJECT_CHECKPOINT = 0x43;
85 
86 
87 extern CScript COINBASE_FLAGS;
89 extern CTxMemPool mempool;
90 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
91 extern uint64_t nLastBlockTx;
92 extern uint64_t nLastBlockSize;
93 extern const std::string strMessageMagic;
94 extern int64_t nTimeBestReceived;
95 extern bool fImporting;
96 extern bool fReindex;
97 extern bool fBenchmark;
98 extern int nScriptCheckThreads;
99 extern bool fTxIndex;
100 extern unsigned int nCoinCacheSize;
101 
102 // Minimum disk space required - used in CheckDiskSpace()
103 static const uint64_t nMinDiskSpace = 52428800;
104 
105 
106 class CCoinsDB;
107 class CBlockTreeDB;
108 struct CDiskBlockPos;
109 class CTxUndo;
110 class CScriptCheck;
111 class CValidationState;
112 class CWalletInterface;
113 struct CNodeStateStats;
114 
115 struct CBlockTemplate;
116 
118 void RegisterWallet(CWalletInterface* pwalletIn);
120 void UnregisterWallet(CWalletInterface* pwalletIn);
122 void UnregisterAllWallets();
124 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL);
125 
127 void RegisterNodeSignals(CNodeSignals& nodeSignals);
129 void UnregisterNodeSignals(CNodeSignals& nodeSignals);
130 
131 void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd);
132 
134 bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
136 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
138 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
140 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
142 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
144 bool InitBlockIndex();
146 bool LoadBlockIndex();
148 void UnloadBlockIndex();
150 bool VerifyDB(int nCheckLevel, int nCheckDepth);
152 void PrintBlockTree();
154 bool ProcessMessages(CNode* pfrom);
156 bool SendMessages(CNode* pto, bool fSendTrickle);
158 void ThreadScriptCheck();
160 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
162 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime);
166 std::string GetWarnings(std::string strFor);
168 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
171 int64_t GetBlockValue(int nHeight, int64_t nFees);
172 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock);
173 
174 void UpdateTime(CBlockHeader& block, const CBlockIndex* pindexPrev);
175 
179 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
181 bool AbortNode(const std::string &msg);
183 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats);
185 void Misbehaving(NodeId nodeid, int howmuch);
186 
187 
189 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
190  bool* pfMissingInputs, bool fRejectInsaneFee=false);
191 
192 
193 
194 
195 
196 
197 
198 
201 };
202 
204 {
205  int nFile;
206  unsigned int nPos;
207 
209  READWRITE(VARINT(nFile));
210  READWRITE(VARINT(nPos));
211  )
212 
213  CDiskBlockPos() {
214  SetNull();
215  }
216 
217  CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
218  nFile = nFileIn;
219  nPos = nPosIn;
220  }
221 
222  friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
223  return (a.nFile == b.nFile && a.nPos == b.nPos);
224  }
225 
226  friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
227  return !(a == b);
228  }
229 
230  void SetNull() { nFile = -1; nPos = 0; }
231  bool IsNull() const { return (nFile == -1); }
232 };
233 
234 struct CDiskTxPos : public CDiskBlockPos
235 {
236  unsigned int nTxOffset; // after header
237 
239  READWRITE(*(CDiskBlockPos*)this);
240  READWRITE(VARINT(nTxOffset));
241  )
242 
243  CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
244  }
245 
247  SetNull();
248  }
249 
250  void SetNull() {
252  nTxOffset = 0;
253  }
254 };
255 
256 
257 
259 {
262 };
263 
264 int64_t GetMinFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree, enum GetMinFee_mode mode);
265 
266 //
267 // Check transaction inputs, and make sure any
268 // pay-to-script-hash transactions are evaluating IsStandard scripts
269 //
270 // Why bother? To avoid denial-of-service attacks; an attacker
271 // can submit a standard HASH... OP_EQUAL transaction,
272 // which will get accepted into blocks. The redemption
273 // script can be anything; an attacker could use a very
274 // expensive-to-check-upon-redemption script like:
275 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
276 //
277 
282 bool AreInputsStandard(const CTransaction& tx, CCoinsViewCache& mapInputs);
283 
288 unsigned int GetLegacySigOpCount(const CTransaction& tx);
289 
296 unsigned int GetP2SHSigOpCount(const CTransaction& tx, CCoinsViewCache& mapInputs);
297 
298 
299 inline bool AllowFree(double dPriority)
300 {
301  // Large (in bytes) low-priority (new, small-coin) transactions
302  // need a fee.
303  return dPriority > COIN * 144 / 250;
304 }
305 
306 // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
307 // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
308 // instead of being performed inline.
309 bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true,
310  unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC,
311  std::vector<CScriptCheck> *pvChecks = NULL);
312 
313 // Apply the effects of this transaction on the UTXO set represented by view
314 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash);
315 
316 // Context-independent validity checks
317 bool CheckTransaction(const CTransaction& tx, CValidationState& state);
318 
322 bool IsStandardTx(const CTransaction& tx, std::string& reason);
323 
324 bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0);
325 
328 {
329 public:
330  std::vector<CTxUndo> vtxundo; // for all but the coinbase
331 
333  READWRITE(vtxundo);
334  )
335 
336  bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
337  {
338  // Open history file to append
340  if (!fileout)
341  return error("CBlockUndo::WriteToDisk : OpenUndoFile failed");
342 
343  // Write index header
344  unsigned int nSize = fileout.GetSerializeSize(*this);
345  fileout << FLATDATA(Params().MessageStart()) << nSize;
346 
347  // Write undo data
348  long fileOutPos = ftell(fileout);
349  if (fileOutPos < 0)
350  return error("CBlockUndo::WriteToDisk : ftell failed");
351  pos.nPos = (unsigned int)fileOutPos;
352  fileout << *this;
353 
354  // calculate & write checksum
356  hasher << hashBlock;
357  hasher << *this;
358  fileout << hasher.GetHash();
359 
360  // Flush stdio buffers and commit to disk before returning
361  fflush(fileout);
362  if (!IsInitialBlockDownload())
363  FileCommit(fileout);
364 
365  return true;
366  }
367 
368  bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
369  {
370  // Open history file to read
371  CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
372  if (!filein)
373  return error("CBlockUndo::ReadFromDisk : OpenBlockFile failed");
374 
375  // Read block
376  uint256 hashChecksum;
377  try {
378  filein >> *this;
379  filein >> hashChecksum;
380  }
381  catch (std::exception &e) {
382  return error("%s : Deserialize or I/O error - %s", __func__, e.what());
383  }
384 
385  // Verify checksum
387  hasher << hashBlock;
388  hasher << *this;
389  if (hashChecksum != hasher.GetHash())
390  return error("CBlockUndo::ReadFromDisk : Checksum mismatch");
391 
392  return true;
393  }
394 };
395 
396 
400 {
401 private:
404  unsigned int nIn;
405  unsigned int nFlags;
407 
408 public:
410  CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
411  scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
412  ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
413 
414  bool operator()() const;
415 
416  void swap(CScriptCheck &check) {
417  scriptPubKey.swap(check.scriptPubKey);
418  std::swap(ptxTo, check.ptxTo);
419  std::swap(nIn, check.nIn);
420  std::swap(nFlags, check.nFlags);
421  std::swap(nHashType, check.nHashType);
422  }
423 };
424 
426 class CMerkleTx : public CTransaction
427 {
428 private:
429  int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const;
430 
431 public:
433  std::vector<uint256> vMerkleBranch;
434  int nIndex;
435 
436  // memory only
437  mutable bool fMerkleVerified;
438 
439 
441  {
442  Init();
443  }
444 
445  CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
446  {
447  Init();
448  }
449 
450  void Init()
451  {
452  hashBlock = 0;
453  nIndex = -1;
454  fMerkleVerified = false;
455  }
456 
457 
459  (
460  nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
461  nVersion = this->nVersion;
462  READWRITE(hashBlock);
463  READWRITE(vMerkleBranch);
464  READWRITE(nIndex);
465  )
466 
467 
468  int SetMerkleBranch(const CBlock* pblock=NULL);
469 
470  // Return depth of transaction in blockchain:
471  // -1 : not in blockchain, and not in memory pool (conflicted transaction)
472  // 0 : in memory pool, waiting to be included in a block
473  // >=1 : this many blocks deep in the main chain
474  int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
475  int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
476  bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
477  int GetBlocksToMaturity() const;
478  bool AcceptToMemoryPool(bool fLimitFree=true);
479 };
480 
481 
482 
483 
484 
520 {
521 protected:
522  // the total number of transactions in the block
523  unsigned int nTransactions;
524 
525  // node-is-parent-of-matched-txid bits
526  std::vector<bool> vBits;
527 
528  // txids and internal hashes
529  std::vector<uint256> vHash;
530 
531  // flag set when encountering invalid data
532  bool fBad;
533 
534  // helper function to efficiently calculate the number of nodes at given height in the merkle tree
535  unsigned int CalcTreeWidth(int height) {
536  return (nTransactions+(1 << height)-1) >> height;
537  }
538 
539  // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
540  uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
541 
542  // recursive function that traverses tree nodes, storing the data as bits and hashes
543  void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
544 
545  // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
546  // it returns the hash of the respective node.
547  uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
548 
549 public:
550 
551  // serialization implementation
553  READWRITE(nTransactions);
554  READWRITE(vHash);
555  std::vector<unsigned char> vBytes;
556  if (fRead) {
557  READWRITE(vBytes);
558  CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
559  us.vBits.resize(vBytes.size() * 8);
560  for (unsigned int p = 0; p < us.vBits.size(); p++)
561  us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
562  us.fBad = false;
563  } else {
564  vBytes.resize((vBits.size()+7)/8);
565  for (unsigned int p = 0; p < vBits.size(); p++)
566  vBytes[p / 8] |= vBits[p] << (p % 8);
567  READWRITE(vBytes);
568  }
569  )
570 
571  // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
572  CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
573 
575 
576  // extract the matching txid's represented by this partial merkle tree.
577  // returns the merkle root, or 0 in case of failure
578  uint256 ExtractMatches(std::vector<uint256> &vMatch);
579 };
580 
581 
582 
584 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos);
585 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos);
586 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex);
587 
588 
595 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
596 
597 // Apply the effects of this block (with given index) on the UTXO set represented by coins
598 bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
599 
600 // Add this block to the block index, and if necessary, switch the active block chain to this
601 bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos);
602 
603 // Context-independent validity checks
604 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
605 
606 // Store block on disk
607 // if dbp is provided, the file is known to already reside on disk
608 bool AcceptBlock(CBlock& block, CValidationState& state, CDiskBlockPos* dbp = NULL);
609 
610 
611 
613 {
614 public:
615  unsigned int nBlocks; // number of blocks stored in file
616  unsigned int nSize; // number of used bytes of block file
617  unsigned int nUndoSize; // number of used bytes in the undo file
618  unsigned int nHeightFirst; // lowest height of block in file
619  unsigned int nHeightLast; // highest height of block in file
620  uint64_t nTimeFirst; // earliest time of block in file
621  uint64_t nTimeLast; // latest time of block in file
622 
624  READWRITE(VARINT(nBlocks));
625  READWRITE(VARINT(nSize));
626  READWRITE(VARINT(nUndoSize));
627  READWRITE(VARINT(nHeightFirst));
628  READWRITE(VARINT(nHeightLast));
629  READWRITE(VARINT(nTimeFirst));
630  READWRITE(VARINT(nTimeLast));
631  )
632 
633  void SetNull() {
634  nBlocks = 0;
635  nSize = 0;
636  nUndoSize = 0;
637  nHeightFirst = 0;
638  nHeightLast = 0;
639  nTimeFirst = 0;
640  nTimeLast = 0;
641  }
642 
644  SetNull();
645  }
646 
647  std::string ToString() const {
648  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());
649  }
650 
651  // update statistics (does not update nSize)
652  void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) {
653  if (nBlocks==0 || nHeightFirst > nHeightIn)
654  nHeightFirst = nHeightIn;
655  if (nBlocks==0 || nTimeFirst > nTimeIn)
656  nTimeFirst = nTimeIn;
657  nBlocks++;
658  if (nHeightIn > nHeightLast)
659  nHeightLast = nHeightIn;
660  if (nTimeIn > nTimeLast)
661  nTimeLast = nTimeIn;
662  }
663 };
664 
667  BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
668  BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
669  BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
670  BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
671  BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
673 
674  BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
675  BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
677 
678  BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
679  BLOCK_FAILED_CHILD = 64, // descends from failed block
681 };
682 
689 {
690 public:
691  // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
693 
694  // pointer to the index of the predecessor of this block
696 
697  // height of the entry in the chain. The genesis block has height 0
698  int nHeight;
699 
700  // Which # file this block is stored in (blk?????.dat)
701  int nFile;
702 
703  // Byte offset within blk?????.dat where this block's data is stored
704  unsigned int nDataPos;
705 
706  // Byte offset within rev?????.dat where this block's undo data is stored
707  unsigned int nUndoPos;
708 
709  // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
711 
712  // Number of transactions in this block.
713  // Note: in a potential headers-first mode, this number cannot be relied upon
714  unsigned int nTx;
715 
716  // (memory only) Number of transactions in the chain up to and including this block
717  unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
718 
719  // Verification status of this block. See enum BlockStatus
720  unsigned int nStatus;
721 
722  // block header
723  int nVersion;
725  unsigned int nTime;
726  unsigned int nBits;
727  unsigned int nNonce;
728 
729  // (memory only) Sequencial id assigned to distinguish order in which blocks are received.
730  uint32_t nSequenceId;
731 
733  {
734  phashBlock = NULL;
735  pprev = NULL;
736  nHeight = 0;
737  nFile = 0;
738  nDataPos = 0;
739  nUndoPos = 0;
740  nChainWork = 0;
741  nTx = 0;
742  nChainTx = 0;
743  nStatus = 0;
744  nSequenceId = 0;
745 
746  nVersion = 0;
747  hashMerkleRoot = 0;
748  nTime = 0;
749  nBits = 0;
750  nNonce = 0;
751  }
752 
754  {
755  phashBlock = NULL;
756  pprev = NULL;
757  nHeight = 0;
758  nFile = 0;
759  nDataPos = 0;
760  nUndoPos = 0;
761  nChainWork = 0;
762  nTx = 0;
763  nChainTx = 0;
764  nStatus = 0;
765  nSequenceId = 0;
766 
767  nVersion = block.nVersion;
768  hashMerkleRoot = block.hashMerkleRoot;
769  nTime = block.nTime;
770  nBits = block.nBits;
771  nNonce = block.nNonce;
772  }
773 
775  CDiskBlockPos ret;
776  if (nStatus & BLOCK_HAVE_DATA) {
777  ret.nFile = nFile;
778  ret.nPos = nDataPos;
779  }
780  return ret;
781  }
782 
784  CDiskBlockPos ret;
785  if (nStatus & BLOCK_HAVE_UNDO) {
786  ret.nFile = nFile;
787  ret.nPos = nUndoPos;
788  }
789  return ret;
790  }
791 
793  {
794  CBlockHeader block;
795  block.nVersion = nVersion;
796  if (pprev)
797  block.hashPrevBlock = pprev->GetBlockHash();
799  block.nTime = nTime;
800  block.nBits = nBits;
801  block.nNonce = nNonce;
802  return block;
803  }
804 
806  {
807  return *phashBlock;
808  }
809 
810  int64_t GetBlockTime() const
811  {
812  return (int64_t)nTime;
813  }
814 
816  {
817  CBigNum bnTarget;
818  bnTarget.SetCompact(nBits);
819  if (bnTarget <= 0)
820  return 0;
821  return (CBigNum(1)<<256) / (bnTarget+1);
822  }
823 
824  bool CheckIndex() const
825  {
826  return CheckProofOfWork(GetBlockHash(), nBits);
827  }
828 
829  enum { nMedianTimeSpan=11 };
830 
831  int64_t GetMedianTimePast() const
832  {
833  int64_t pmedian[nMedianTimeSpan];
834  int64_t* pbegin = &pmedian[nMedianTimeSpan];
835  int64_t* pend = &pmedian[nMedianTimeSpan];
836 
837  const CBlockIndex* pindex = this;
838  for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
839  *(--pbegin) = pindex->GetBlockTime();
840 
841  std::sort(pbegin, pend);
842  return pbegin[(pend - pbegin)/2];
843  }
844 
845  int64_t GetMedianTime() const;
846 
851  static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
852  unsigned int nRequired, unsigned int nToCheck);
853 
854  std::string ToString() const
855  {
856  return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
857  pprev, nHeight,
858  hashMerkleRoot.ToString().c_str(),
859  GetBlockHash().ToString().c_str());
860  }
861 
862  void print() const
863  {
864  LogPrintf("%s\n", ToString().c_str());
865  }
866 };
867 
868 
869 
872 {
873 public:
875 
877  hashPrev = 0;
878  }
879 
880  explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
881  hashPrev = (pprev ? pprev->GetBlockHash() : 0);
882  }
883 
885  (
886  if (!(nType & SER_GETHASH))
888 
891  READWRITE(VARINT(nTx));
893  READWRITE(VARINT(nFile));
894  if (nStatus & BLOCK_HAVE_DATA)
896  if (nStatus & BLOCK_HAVE_UNDO)
898 
899  // block header
900  READWRITE(this->nVersion);
901  READWRITE(hashPrev);
903  READWRITE(nTime);
904  READWRITE(nBits);
905  READWRITE(nNonce);
906  )
907 
908  uint256 GetBlockHash() const
909  {
910  CBlockHeader block;
911  block.nVersion = nVersion;
912  block.hashPrevBlock = hashPrev;
914  block.nTime = nTime;
915  block.nBits = nBits;
916  block.nNonce = nNonce;
917  return block.GetHash();
918  }
919 
920 
921  std::string ToString() const
922  {
923  std::string str = "CDiskBlockIndex(";
924  str += CBlockIndex::ToString();
925  str += strprintf("\n hashBlock=%s, hashPrev=%s)",
926  GetBlockHash().ToString().c_str(),
927  hashPrev.ToString().c_str());
928  return str;
929  }
930 
931  void print() const
932  {
933  LogPrintf("%s\n", ToString().c_str());
934  }
935 };
936 
939 private:
940  enum mode_state {
941  MODE_VALID, // everything ok
942  MODE_INVALID, // network rule violation (DoS value may be set)
943  MODE_ERROR, // run-time error
944  } mode;
945  int nDoS;
946  std::string strRejectReason;
947  unsigned char chRejectCode;
949 public:
950  CValidationState() : mode(MODE_VALID), nDoS(0), corruptionPossible(false) {}
951  bool DoS(int level, bool ret = false,
952  unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="",
953  bool corruptionIn=false) {
954  chRejectCode = chRejectCodeIn;
955  strRejectReason = strRejectReasonIn;
956  corruptionPossible = corruptionIn;
957  if (mode == MODE_ERROR)
958  return ret;
959  nDoS += level;
960  mode = MODE_INVALID;
961  return ret;
962  }
963  bool Invalid(bool ret = false,
964  unsigned char _chRejectCode=0, std::string _strRejectReason="") {
965  return DoS(0, ret, _chRejectCode, _strRejectReason);
966  }
967  bool Error(std::string strRejectReasonIn="") {
968  if (mode == MODE_VALID)
969  strRejectReason = strRejectReasonIn;
970  mode = MODE_ERROR;
971  return false;
972  }
973  bool Abort(const std::string &msg) {
974  AbortNode(msg);
975  return Error(msg);
976  }
977  bool IsValid() const {
978  return mode == MODE_VALID;
979  }
980  bool IsInvalid() const {
981  return mode == MODE_INVALID;
982  }
983  bool IsError() const {
984  return mode == MODE_ERROR;
985  }
986  bool IsInvalid(int &nDoSOut) const {
987  if (IsInvalid()) {
988  nDoSOut = nDoS;
989  return true;
990  }
991  return false;
992  }
993  bool CorruptionPossible() const {
994  return corruptionPossible;
995  }
996  unsigned char GetRejectCode() const { return chRejectCode; }
997  std::string GetRejectReason() const { return strRejectReason; }
998 };
999 
1001 class CChain {
1002 private:
1003  std::vector<CBlockIndex*> vChain;
1004 
1005 public:
1008  return vChain.size() > 0 ? vChain[0] : NULL;
1009  }
1010 
1012  CBlockIndex *Tip() const {
1013  return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
1014  }
1015 
1017  CBlockIndex *operator[](int nHeight) const {
1018  if (nHeight < 0 || nHeight >= (int)vChain.size())
1019  return NULL;
1020  return vChain[nHeight];
1021  }
1022 
1024  friend bool operator==(const CChain &a, const CChain &b) {
1025  return a.vChain.size() == b.vChain.size() &&
1026  a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
1027  }
1028 
1030  bool Contains(const CBlockIndex *pindex) const {
1031  return (*this)[pindex->nHeight] == pindex;
1032  }
1033 
1035  CBlockIndex *Next(const CBlockIndex *pindex) const {
1036  if (Contains(pindex))
1037  return (*this)[pindex->nHeight + 1];
1038  else
1039  return NULL;
1040  }
1041 
1043  int Height() const {
1044  return vChain.size() - 1;
1045  }
1046 
1048  CBlockIndex *SetTip(CBlockIndex *pindex);
1049 
1051  CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const;
1052 
1054  CBlockIndex *FindFork(const CBlockLocator &locator) const;
1055 };
1056 
1058 extern CChain chainActive;
1059 
1061 extern CChain chainMostWork;
1062 
1064 extern CCoinsViewCache *pcoinsTip;
1065 
1067 extern CBlockTreeDB *pblocktree;
1068 
1070 {
1072  std::vector<int64_t> vTxFees;
1073  std::vector<int64_t> vTxSigOps;
1074 };
1075 
1076 
1077 
1078 
1079 
1080 
1085 {
1086 public:
1087  // Public only for unit testing
1090 
1091 public:
1092  // Public only for unit testing and relay testing
1093  // (not relayed)
1094  std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
1095 
1096  // Create from a CBlock, filtering transactions according to filter
1097  // Note that this will call IsRelevantAndUpdate on the filter for each transaction,
1098  // thus the filter will likely be modified.
1099  CMerkleBlock(const CBlock& block, CBloomFilter& filter);
1100 
1102  (
1103  READWRITE(header);
1104  READWRITE(txn);
1105  )
1106 };
1107 
1108 
1110 protected:
1111  virtual void SyncTransaction(const uint256 &hash, const CTransaction &tx, const CBlock *pblock) =0;
1112  virtual void EraseFromWallet(const uint256 &hash) =0;
1113  virtual void SetBestChain(const CBlockLocator &locator) =0;
1114  virtual void UpdatedTransaction(const uint256 &hash) =0;
1115  virtual void Inventory(const uint256 &hash) =0;
1116  virtual void ResendWalletTransactions() =0;
1119  friend void ::UnregisterAllWallets();
1120 };
1121 
1122 #endif
uint64_t nLastBlockSize
Definition: miner.cpp:81
std::map< uint256, CBlockIndex * > mapBlockIndex
Definition: main.cpp:47
#define VARINT(obj)
Definition: serialize.h:310
bool AcceptBlock(CBlock &block, CValidationState &state, CDiskBlockPos *dbp=NULL)
Definition: main.cpp:2405
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: main.cpp:1325
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: main.h:52
CDiskBlockPos GetBlockPos() const
Definition: main.h:774
unsigned int nTxOffsetIn
Definition: main.h:243
int nVersion
Definition: core.h:189
CBlockHeader header
Definition: main.h:1088
bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true)
Definition: main.cpp:2339
CBigNum GetBlockWork() const
Definition: main.h:815
static const unsigned int DEFAULT_BLOCK_MIN_SIZE
Definition: main.h:40
void TraverseAndBuild(int height, unsigned int pos, const std::vector< uint256 > &vTxid, const std::vector< bool > &vMatch)
Definition: main.cpp:2695
void UnregisterWallet(CWalletInterface *pwalletIn)
Unregister a wallet from core.
Definition: main.cpp:169
std::vector< CBlockIndex * > vChain
Definition: main.h:1003
CDiskBlockPos(int nFileIn, unsigned int nPosIn)
Definition: main.h:217
bool AddToBlockIndex(CBlock &block, CValidationState &state, const CDiskBlockPos &pos)
Definition: main.cpp:2186
unsigned int nTxOffset
Definition: main.h:236
int nVersion
Definition: core.h:349
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
Definition: main.cpp:1341
unsigned int SerReadWrite(Stream &s, const T &obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
Definition: serialize.h:797
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule) ...
Definition: main.h:58
CChain chainActive
The currently-connected chain of blocks.
Definition: main.cpp:48
IMPLEMENT_SERIALIZE(READWRITE(VARINT(nFile));READWRITE(VARINT(nPos));) CDiskBlockPos()
Definition: main.h:208
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: core.h:459
CScript COINBASE_FLAGS
Definition: main.cpp:80
CBlockIndex * pprev
Definition: main.h:695
#define READWRITE(obj)
Definition: serialize.h:92
int64_t GetBlockValue(int nHeight, int64_t nFees)
Definition: main.cpp:1218
int nMisbehavior
Definition: main.h:200
bool LoadExternalBlockFile(FILE *fileIn, CDiskBlockPos *dbp=NULL)
Import blocks from an external file.
Definition: main.cpp:3118
bool IsError() const
Definition: main.h:983
void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
Definition: main.h:652
void FileCommit(FILE *fileout)
Definition: util.cpp:1092
void swap(CScriptCheck &check)
Definition: main.h:416
unsigned int nTransactions
Definition: main.h:523
Definition: core.h:396
CScriptCheck()
Definition: main.h:409
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER
Number of blocks that can be requested at any given time from a single peer.
Definition: main.h:66
CScriptCheck(const CCoins &txFromIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn)
Definition: main.h:410
An in-memory indexed chain of blocks.
Definition: main.h:1001
GetMinFee_mode
Definition: main.h:258
CBlockIndex * operator[](int nHeight) const
Returns the index entry at a particular height in this chain, or NULL if no such height exists...
Definition: main.h:1017
static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE
Default for -blockprioritysize, maximum space for zero/low-fee transactions.
Definition: main.h:42
unsigned int nFlags
Definition: main.h:405
unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
Calculate the minimum amount of work a received block needs, without knowing its direct parent...
Definition: main.cpp:1241
int nIndex
Definition: main.h:434
inv message data
Definition: protocol.h:105
CBlockIndex()
Definition: main.h:732
int GetDepthInMainChainINTERNAL(CBlockIndex *&pindexRet) const
Definition: main.cpp:997
enum CValidationState::mode_state mode
uint256 hashBlock
Definition: main.h:432
bool CorruptionPossible() const
Definition: main.h:993
void PrintBlockTree()
Print the loaded block tree.
Definition: main.cpp:3049
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:42
static const int CLIENT_VERSION
Definition: version.h:15
std::string ToString() const
Definition: main.h:854
unsigned char chRejectCode
Definition: main.h:947
std::vector< int64_t > vTxFees
Definition: main.h:1072
CScript scriptPubKey
Definition: main.h:402
bool IsStandardTx(const CTransaction &tx, std::string &reason)
Check for standard transaction types.
Definition: main.cpp:507
static const unsigned char REJECT_CHECKPOINT
Definition: main.h:84
IMPLEMENT_SERIALIZE(READWRITE(*(CDiskBlockPos *) this);READWRITE(VARINT(nTxOffset));) CDiskTxPos(const CDiskBlockPos &blockIn
unsigned int nSize
Definition: main.h:616
friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b)
Definition: main.h:222
const uint256 &hashBlock CAutoFile fileout
Definition: main.h:339
#define strprintf
Definition: util.h:116
#define IMPLEMENT_SERIALIZE(statements)
Definition: serialize.h:54
static const unsigned char REJECT_OBSOLETE
Definition: main.h:79
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: main.h:54
bool fMerkleVerified
Definition: main.h:437
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Definition: main.h:56
Data structure that represents a partial merkle tree.
Definition: main.h:519
static const unsigned int BLOCK_DOWNLOAD_TIMEOUT
Timeout in seconds before considering a block download peer unresponsive.
Definition: main.h:68
int nFile
Definition: main.h:701
CTxMemPool mempool
Definition: main.cpp:45
pruned version of CTransaction: only retains metadata and unspent transaction outputs ...
Definition: coins.h:68
bool fReindex
Definition: main.cpp:53
const std::string strMessageMagic
Definition: main.cpp:82
unsigned int GetSerializeSize(const T &obj)
Definition: serialize.h:1227
unsigned int nCoinCacheSize
Definition: main.cpp:56
bool AllowFree(double dPriority)
Definition: main.h:299
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: util.cpp:1429
bool corruptionPossible
Definition: main.h:948
bool ConnectBlock(CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false)
Definition: main.cpp:1758
uint256 nChainWork
Definition: main.h:710
CBlockIndex(CBlockHeader &block)
Definition: main.h:753
CDiskBlockIndex(CBlockIndex *pindex)
Definition: main.h:880
unsigned int nHeightLast
Definition: main.h:619
#define FLATDATA(obj)
Definition: serialize.h:309
void Init()
Definition: main.h:450
static const unsigned int DEFAULT_BLOCK_MAX_SIZE
Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will cr...
Definition: main.h:39
unsigned int nChainTx
Definition: main.h:717
bool VerifySignature(const CCoins &txFrom, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
Verify a signature.
Definition: main.cpp:1544
unsigned int nUndoSize
Definition: main.h:617
std::string GetWarnings(std::string strFor)
Format a string that describes several potential problems detected by the core.
Definition: main.cpp:3204
int64_t GetMinFee(const CTransaction &tx, unsigned int nBytes, bool fAllowFree, enum GetMinFee_mode mode)
Definition: main.cpp:817
bool CheckIndex() const
Definition: main.h:824
bool InitBlockIndex()
Initialize a new block tree database + block data on disk.
Definition: main.cpp:3014
bool Invalid(bool ret=false, unsigned char _chRejectCode=0, std::string _strRejectReason="")
Definition: main.h:963
int GetDepthInMainChain() const
Definition: main.h:475
void UpdateCoins(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash)
Definition: main.cpp:1518
friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b)
Definition: main.h:226
uint64_t nLastBlockTx
Definition: miner.cpp:80
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
Return a CBlockLocator that refers to a block in this chain (by default the tip). ...
Definition: main.cpp:372
int nHashType
Definition: main.h:406
bool operator()() const
Definition: main.cpp:1537
int GetBlocksToMaturity() const
Definition: main.cpp:1033
CBigNum & SetCompact(unsigned int nCompact)
Definition: bignum.h:295
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: main.h:1012
std::vector< uint256 > vHash
Definition: main.h:529
int Height() const
Return the maximal height in the chain.
Definition: main.h:1043
bool IsInMainChain() const
Definition: main.h:476
Used to relay blocks as header + vector to filtered nodes.
Definition: main.h:1084
static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS
Default for -maxorphanblocks, maximum number of orphan blocks kept in memory.
Definition: main.h:50
unsigned int nTime
Definition: main.h:725
unsigned int CalcTreeWidth(int height)
Definition: main.h:535
#define LogPrintf(...)
Definition: util.h:117
uint64_t nTimeFirst
Definition: main.h:620
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly=false)
Open a block file (blk?????.dat)
Definition: main.cpp:2840
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
Definition: main.cpp:2848
static const unsigned int MAX_BLOCK_SIGOPS
The maximum allowed number of signature check operations in a block (network rule) ...
Definition: main.h:46
unsigned int nStatus
Definition: main.h:720
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or NULL if the given index is not found or is the tip...
Definition: main.h:1035
void SyncWithWallets(const uint256 &hash, const CTransaction &tx, const CBlock *pblock=NULL)
Push an updated transaction to all registered wallets.
Definition: main.cpp:187
Access to the block database (blocks/index/)
Definition: txdb.h:46
CBlockHeader GetBlockHeader() const
Definition: main.h:792
uint256 hashMerkleRoot
Definition: core.h:351
void print() const
Definition: main.h:862
unsigned int nDataPos
Definition: main.h:704
void RegisterWallet(CWalletInterface *pwalletIn)
Register a wallet to receive updates from core.
Definition: main.cpp:160
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: main.cpp:414
IMPLEMENT_SERIALIZE(READWRITE(VARINT(nBlocks));READWRITE(VARINT(nSize));READWRITE(VARINT(nUndoSize));READWRITE(VARINT(nHeightFirst));READWRITE(VARINT(nHeightLast));READWRITE(VARINT(nTimeFirst));READWRITE(VARINT(nTimeLast));) void SetNull()
Definition: main.h:623
bool ProcessBlock(CValidationState &state, CNode *pfrom, CBlock *pblock, CDiskBlockPos *dbp=NULL)
Process an incoming block.
Definition: main.cpp:2542
bool VerifyDB(int nCheckLevel, int nCheckDepth)
Verify consistency of the block and coin databases.
Definition: main.cpp:2923
CBlockFileInfo()
Definition: main.h:643
uint256 hashPrevBlock
Definition: core.h:350
static bool error(const char *format)
Definition: util.h:148
bool DoS(int level, bool ret=false, unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="", bool corruptionIn=false)
Definition: main.h:951
int64_t GetMedianTime() const
Definition: main.cpp:2517
C++ wrapper for BIGNUM (OpenSSL bignum)
Definition: bignum.h:57
bool CheckInputs(const CTransaction &tx, CValidationState &state, CCoinsViewCache &view, bool fScriptChecks=true, unsigned int flags=SCRIPT_VERIFY_P2SH|SCRIPT_VERIFY_STRICTENC, std::vector< CScriptCheck > *pvChecks=NULL)
Definition: main.cpp:1549
bool IsFinalTx(const CTransaction &tx, int nBlockHeight=0, int64_t nBlockTime=0)
Definition: main.cpp:594
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
Definition: main.cpp:677
std::vector< uint256 > vMerkleBranch
Definition: main.h:433
unsigned int nBits
Definition: main.h:726
CDiskBlockIndex()
Definition: main.h:876
static const unsigned int MAX_BLOCK_SIZE
The maximum allowed size for a serialized block, in bytes (network rule)
Definition: main.h:37
bool AcceptToMemoryPool(bool fLimitFree=true)
Definition: main.cpp:1041
uint256 hashMerkleRoot
Definition: main.h:724
int nScriptCheckThreads
Definition: main.cpp:51
friend bool operator==(const CChain &a, const CChain &b)
Compare two chains efficiently.
Definition: main.h:1024
bool Error(std::string strRejectReasonIn="")
Definition: main.h:967
unsigned int nNonce
Definition: core.h:354
unsigned int nHeightFirst
Definition: main.h:618
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector< uint256 > &vMatch)
Definition: main.cpp:2713
Used to marshal pointers into hashes for db storage.
Definition: main.h:871
bool IsValid() const
Definition: main.h:977
bool CheckDiskSpace(uint64_t nAdditionalBytes=0)
Check whether enough disk space is available for an incoming block.
Definition: main.cpp:2806
void print() const
Definition: main.h:931
CPartialMerkleTree txn
Definition: main.h:1089
bool IsNull() const
Definition: main.h:231
bool Abort(const std::string &msg)
Definition: main.h:973
std::string ToString() const
Definition: main.h:921
void ThreadScriptCheck()
Run an instance of the script checking thread.
Definition: main.cpp:1753
unsigned int nPos
Definition: main.h:206
CChain chainMostWork
The currently best known chain of headers (some of which may be invalid).
Definition: main.cpp:49
static const unsigned char REJECT_MALFORMED
"reject" message codes
Definition: main.h:77
void UnloadBlockIndex()
Unload database information.
Definition: main.cpp:2997
void UpdateTime(CBlockHeader &block, const CBlockIndex *pindexPrev)
Definition: main.cpp:1499
bool IsInvalid(int &nDoSOut) const
Definition: main.h:986
bool WriteBlockToDisk(CBlock &block, CDiskBlockPos &pos)
Functions for disk access for blocks.
Definition: main.cpp:1119
Closure representing one script verification Note that this stores references to the spending transac...
Definition: main.h:399
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow=false)
Retrieve a transaction (from memory pool, or from disk, if possible)
Definition: main.cpp:1049
bool IsInvalid() const
Definition: main.h:980
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos)
Definition: main.cpp:1145
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: main.h:64
int nVersion
Definition: main.h:723
std::vector< bool > vBits
Definition: main.h:526
std::string GetRejectReason() const
Definition: main.h:997
bool LoadBlockIndex()
Load the block tree and coins database from disk.
Definition: main.cpp:3005
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: main.cpp:413
unsigned char GetRejectCode() const
Definition: main.h:996
CValidationState()
Definition: main.h:950
unsigned int nUndoPos
Definition: main.h:707
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or NULL if none.
Definition: main.h:1007
CMerkleTx(const CTransaction &txIn)
Definition: main.h:445
Capture information about block/transaction validation.
Definition: main.h:938
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of script-checking threads allowed.
Definition: main.h:62
256-bit unsigned integer
Definition: uint256.h:531
IMPLEMENT_SERIALIZE(READWRITE(vtxundo);) bool WriteToDisk(CDiskBlockPos &pos
uint256 hashPrev
Definition: main.h:874
static const unsigned char REJECT_INVALID
Definition: main.h:78
const CTransaction * ptxTo
Definition: main.h:403
static const int64_t COIN
Definition: util.h:38
uint256 ExtractMatches(std::vector< uint256 > &vMatch)
Definition: main.cpp:2759
unsigned int nTime
Definition: core.h:352
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool *pfMissingInputs, bool fRejectInsaneFee=false)
(try to) add transaction to memory pool
Definition: main.cpp:852
uint256 GetHash() const
Definition: core.cpp:215
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
Definition: main.cpp:327
void UnregisterAllWallets()
Unregister all wallets from core.
Definition: main.cpp:178
void RegisterNodeSignals(CNodeSignals &nodeSignals)
Register with a network node to receive its signals.
Definition: main.cpp:336
void PushGetBlocks(CNode *pnode, CBlockIndex *pindexBegin, uint256 hashEnd)
Definition: main.cpp:2530
IMPLEMENT_SERIALIZE(nSerSize+=SerReadWrite(s,*(CTransaction *) this, nType, nVersion, ser_action);nVersion=this->nVersion;READWRITE(hashBlock);READWRITE(vMerkleBranch);READWRITE(nIndex);) int SetMerkleBranch(const CBlock *pblock
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
Definition: main.h:1094
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: main.h:688
const CChainParams & Params()
Return the currently selected parameters.
Undo information for a CBlock.
Definition: main.h:327
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:401
Undo information for a CTransaction.
Definition: core.h:325
std::string ToString() const
Definition: uint256.h:340
static const int PROTOCOL_VERSION
Definition: version.h:29
std::vector< int64_t > vTxSigOps
Definition: main.h:1073
static const unsigned char REJECT_INSUFFICIENTFEE
Definition: main.h:83
static const unsigned char REJECT_NONSTANDARD
Definition: main.h:81
CBlockIndex * FindFork(const CBlockLocator &locator) const
Find the last common block between this chain and a locator.
Definition: main.cpp:399
bool AreInputsStandard(const CTransaction &tx, CCoinsViewCache &mapInputs)
Check for standard transaction types.
Definition: main.cpp:623
static const unsigned int LOCKTIME_THRESHOLD
Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timest...
Definition: main.h:60
int NodeId
Definition: net.h:61
void SetNull()
Definition: main.h:230
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: main.h:1030
bool DisconnectBlock(CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean=NULL)
Functions for validating blocks and updating the block tree.
Definition: main.cpp:1638
bool ActivateBestChain(CValidationState &state)
Find the best known block, and make it the tip of the block chain.
Definition: main.cpp:2138
CBlockIndex * SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
Definition: main.cpp:359
CMerkleBlock(const CBlock &block, CBloomFilter &filter)
Definition: main.cpp:2645
unsigned int nBlocks
Definition: main.h:615
bool fImporting
Definition: main.cpp:52
unsigned int GetP2SHSigOpCount(const CTransaction &tx, CCoinsViewCache &mapInputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
Definition: main.cpp:691
std::string ToString() const
Definition: main.h:647
bool ProcessMessages(CNode *pfrom)
Process protocol messages received from a given node.
Definition: main.cpp:4114
BlockStatus
Definition: main.h:665
static const unsigned int MAX_STANDARD_TX_SIZE
The maximum size for transactions we're willing to relay/mine.
Definition: main.h:44
CBlock block
Definition: main.h:1071
unsigned int nIn
Definition: main.h:404
uint64_t nTimeLast
Definition: main.h:621
uint32_t nSequenceId
Definition: main.h:730
int64_t nTimeBestReceived
Definition: main.cpp:50
bool CheckTransaction(const CTransaction &tx, CValidationState &state)
Definition: main.cpp:760
CMerkleTx()
Definition: main.h:440
CDiskBlockPos GetUndoPos() const
Definition: main.h:783
FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly=false)
Open an undo file (rev?????.dat)
Definition: main.cpp:2844
std::string strRejectReason
Definition: main.h:946
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: core.h:183
int nHeight
Definition: main.h:698
Information about a peer.
Definition: net.h:193
bool SendMessages(CNode *pto, bool fSendTrickle)
Send queued protocol messages to be sent to a give node.
Definition: main.cpp:4235
static const unsigned char REJECT_DUPLICATE
Definition: main.h:80
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:308
unsigned int nBits
Definition: core.h:353
int64_t GetBlockTime() const
Definition: main.h:810
static const int fHaveUPnP
Definition: main.h:73
void SetNull()
Definition: main.h:250
CCriticalSection cs_main
Definition: main.cpp:43
static const unsigned char REJECT_DUST
Definition: main.h:82
std::vector< CTxUndo > vtxundo
Definition: main.h:330
int nFile
Definition: main.h:205
CDiskTxPos()
Definition: main.h:246
int64_t GetMedianTimePast() const
Definition: main.h:831
void Misbehaving(NodeId nodeid, int howmuch)
Increase a node's misbehavior score.
Definition: main.cpp:1441
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock)
Definition: main.cpp:1263
unsigned int nNonce
Definition: main.h:727
unsigned int nTx
Definition: main.h:714
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: core.h:344
Definition: main.h:261
RAII wrapper for FILE*.
Definition: serialize.h:1145
bool AbortNode(const std::string &msg)
Abort with a message.
Definition: main.cpp:2798
bool fBenchmark
Definition: main.cpp:54
IMPLEMENT_SERIALIZE(if(!(nType &SER_GETHASH)) READWRITE(VARINT(nVersion));READWRITE(VARINT(nHeight));READWRITE(VARINT(nStatus));READWRITE(VARINT(nTx));if(nStatus &(BLOCK_HAVE_DATA|BLOCK_HAVE_UNDO)) READWRITE(VARINT(nFile));if(nStatus &BLOCK_HAVE_DATA) READWRITE(VARINT(nDataPos));if(nStatus &BLOCK_HAVE_UNDO) READWRITE(VARINT(nUndoPos));READWRITE(this->nVersion);READWRITE(hashPrev);READWRITE(hashMerkleRoot);READWRITE(nTime);READWRITE(nBits);READWRITE(nNonce);) uint256 GetBlockHash() const
Definition: main.h:885
bool fTxIndex
Definition: main.cpp:55
uint256 GetBlockHash() const
Definition: main.h:805
A transaction with a merkle branch linking it to the block chain.
Definition: main.h:426
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
Definition: main.h:48
void UnregisterNodeSignals(CNodeSignals &nodeSignals)
Unregister a network node.
Definition: main.cpp:345
uint256 CalcHash(int height, unsigned int pos, const std::vector< uint256 > &vTxid)
Definition: main.cpp:2678
static bool IsSuperMajority(int minVersion, const CBlockIndex *pstart, unsigned int nRequired, unsigned int nToCheck)
Returns true if there are nRequired or more blocks of minVersion or above in the last nToCheck blocks...
Definition: main.cpp:2505
const uint256 * phashBlock
Definition: main.h:692
static const uint64_t nMinDiskSpace
Definition: main.h:103