9 #if defined(HAVE_CONFIG_H)
73 static const int fHaveUPnP =
false;
150 bool VerifyDB(
int nCheckLevel,
int nCheckDepth);
190 bool* pfMissingInputs,
bool fRejectInsaneFee=
false);
231 bool IsNull()
const {
return (nFile == -1); }
303 return dPriority >
COIN * 144 / 250;
311 std::vector<CScriptCheck> *pvChecks = NULL);
341 return error(
"CBlockUndo::WriteToDisk : OpenUndoFile failed");
348 long fileOutPos = ftell(fileout);
350 return error(
"CBlockUndo::WriteToDisk : ftell failed");
351 pos.
nPos = (
unsigned int)fileOutPos;
358 fileout << hasher.GetHash();
373 return error(
"CBlockUndo::ReadFromDisk : OpenBlockFile failed");
379 filein >> hashChecksum;
381 catch (std::exception &e) {
382 return error(
"%s : Deserialize or I/O error - %s", __func__, e.what());
389 if (hashChecksum != hasher.GetHash())
390 return error(
"CBlockUndo::ReadFromDisk : Checksum mismatch");
411 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
412 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
418 std::swap(ptxTo, check.
ptxTo);
419 std::swap(nIn, check.
nIn);
420 std::swap(nFlags, check.
nFlags);
454 fMerkleVerified =
false;
468 int SetMerkleBranch(
const CBlock* pblock=NULL);
536 return (nTransactions+(1 << height)-1) >> height;
540 uint256 CalcHash(
int height,
unsigned int pos,
const std::vector<uint256> &vTxid);
543 void TraverseAndBuild(
int height,
unsigned int pos,
const std::vector<uint256> &vTxid,
const std::vector<bool> &vMatch);
547 uint256 TraverseAndExtract(
int height,
unsigned int pos,
unsigned int &nBitsUsed,
unsigned int &nHashUsed, std::vector<uint256> &vMatch);
555 std::vector<unsigned char> vBytes;
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;
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);
572 CPartialMerkleTree(
const std::vector<uint256> &vTxid,
const std::vector<bool> &vMatch);
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());
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;
658 if (nHeightIn > nHeightLast)
659 nHeightLast = nHeightIn;
660 if (nTimeIn > nTimeLast)
812 return (int64_t)
nTime;
821 return (
CBigNum(1)<<256) / (bnTarget+1);
841 std::sort(pbegin, pend);
842 return pbegin[(pend - pbegin)/2];
852 unsigned int nRequired,
unsigned int nToCheck);
856 return strprintf(
"CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
923 std::string str =
"CDiskBlockIndex(";
925 str +=
strprintf(
"\n hashBlock=%s, hashPrev=%s)",
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;
964 unsigned char _chRejectCode=0, std::string _strRejectReason=
"") {
965 return DoS(0, ret, _chRejectCode, _strRejectReason);
967 bool Error(std::string strRejectReasonIn=
"") {
969 strRejectReason = strRejectReasonIn;
973 bool Abort(
const std::string &msg) {
1008 return vChain.size() > 0 ? vChain[0] : NULL;
1013 return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
1018 if (nHeight < 0 || nHeight >= (
int)vChain.size())
1020 return vChain[nHeight];
1031 return (*
this)[pindex->
nHeight] == pindex;
1037 return (*
this)[pindex->
nHeight + 1];
1044 return vChain.size() - 1;
1112 virtual void EraseFromWallet(
const uint256 &hash) =0;
1114 virtual void UpdatedTransaction(
const uint256 &hash) =0;
1115 virtual void Inventory(
const uint256 &hash) =0;
1116 virtual void ResendWalletTransactions() =0;
std::map< uint256, CBlockIndex * > mapBlockIndex
bool AcceptBlock(CBlock &block, CValidationState &state, CDiskBlockPos *dbp=NULL)
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
CDiskBlockPos GetBlockPos() const
bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true)
CBigNum GetBlockWork() const
static const unsigned int DEFAULT_BLOCK_MIN_SIZE
void TraverseAndBuild(int height, unsigned int pos, const std::vector< uint256 > &vTxid, const std::vector< bool > &vMatch)
void UnregisterWallet(CWalletInterface *pwalletIn)
Unregister a wallet from core.
std::vector< CBlockIndex * > vChain
CDiskBlockPos(int nFileIn, unsigned int nPosIn)
bool AddToBlockIndex(CBlock &block, CValidationState &state, const CDiskBlockPos &pos)
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
unsigned int SerReadWrite(Stream &s, const T &obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule) ...
CChain chainActive
The currently-connected chain of blocks.
IMPLEMENT_SERIALIZE(READWRITE(VARINT(nFile));READWRITE(VARINT(nPos));) CDiskBlockPos()
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
int64_t GetBlockValue(int nHeight, int64_t nFees)
bool LoadExternalBlockFile(FILE *fileIn, CDiskBlockPos *dbp=NULL)
Import blocks from an external file.
void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
void FileCommit(FILE *fileout)
void swap(CScriptCheck &check)
unsigned int nTransactions
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER
Number of blocks that can be requested at any given time from a single peer.
CScriptCheck(const CCoins &txFromIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn)
An in-memory indexed chain of blocks.
CBlockIndex * operator[](int nHeight) const
Returns the index entry at a particular height in this chain, or NULL if no such height exists...
static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE
Default for -blockprioritysize, maximum space for zero/low-fee transactions.
unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
Calculate the minimum amount of work a received block needs, without knowing its direct parent...
int GetDepthInMainChainINTERNAL(CBlockIndex *&pindexRet) const
enum CValidationState::mode_state mode
bool CorruptionPossible() const
void PrintBlockTree()
Print the loaded block tree.
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
static const int CLIENT_VERSION
std::string ToString() const
unsigned char chRejectCode
std::vector< int64_t > vTxFees
bool IsStandardTx(const CTransaction &tx, std::string &reason)
Check for standard transaction types.
static const unsigned char REJECT_CHECKPOINT
IMPLEMENT_SERIALIZE(READWRITE(*(CDiskBlockPos *) this);READWRITE(VARINT(nTxOffset));) CDiskTxPos(const CDiskBlockPos &blockIn
friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b)
const uint256 &hashBlock CAutoFile fileout
#define IMPLEMENT_SERIALIZE(statements)
static const unsigned char REJECT_OBSOLETE
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Data structure that represents a partial merkle tree.
static const unsigned int BLOCK_DOWNLOAD_TIMEOUT
Timeout in seconds before considering a block download peer unresponsive.
pruned version of CTransaction: only retains metadata and unspent transaction outputs ...
const std::string strMessageMagic
unsigned int GetSerializeSize(const T &obj)
unsigned int nCoinCacheSize
bool AllowFree(double dPriority)
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
bool ConnectBlock(CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false)
CBlockIndex(CBlockHeader &block)
CDiskBlockIndex(CBlockIndex *pindex)
static const unsigned int DEFAULT_BLOCK_MAX_SIZE
Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will cr...
bool VerifySignature(const CCoins &txFrom, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
Verify a signature.
std::string GetWarnings(std::string strFor)
Format a string that describes several potential problems detected by the core.
int64_t GetMinFee(const CTransaction &tx, unsigned int nBytes, bool fAllowFree, enum GetMinFee_mode mode)
bool InitBlockIndex()
Initialize a new block tree database + block data on disk.
bool Invalid(bool ret=false, unsigned char _chRejectCode=0, std::string _strRejectReason="")
int GetDepthInMainChain() const
void UpdateCoins(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash)
friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b)
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
Return a CBlockLocator that refers to a block in this chain (by default the tip). ...
int GetBlocksToMaturity() const
CBigNum & SetCompact(unsigned int nCompact)
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
std::vector< uint256 > vHash
int Height() const
Return the maximal height in the chain.
bool IsInMainChain() const
Used to relay blocks as header + vector to filtered nodes.
static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS
Default for -maxorphanblocks, maximum number of orphan blocks kept in memory.
unsigned int CalcTreeWidth(int height)
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly=false)
Open a block file (blk?????.dat)
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
static const unsigned int MAX_BLOCK_SIGOPS
The maximum allowed number of signature check operations in a block (network rule) ...
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...
void SyncWithWallets(const uint256 &hash, const CTransaction &tx, const CBlock *pblock=NULL)
Push an updated transaction to all registered wallets.
Access to the block database (blocks/index/)
CBlockHeader GetBlockHeader() const
void RegisterWallet(CWalletInterface *pwalletIn)
Register a wallet to receive updates from core.
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
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()
bool ProcessBlock(CValidationState &state, CNode *pfrom, CBlock *pblock, CDiskBlockPos *dbp=NULL)
Process an incoming block.
bool VerifyDB(int nCheckLevel, int nCheckDepth)
Verify consistency of the block and coin databases.
static bool error(const char *format)
bool DoS(int level, bool ret=false, unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="", bool corruptionIn=false)
int64_t GetMedianTime() const
C++ wrapper for BIGNUM (OpenSSL bignum)
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)
bool IsFinalTx(const CTransaction &tx, int nBlockHeight=0, int64_t nBlockTime=0)
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
std::vector< uint256 > vMerkleBranch
static const unsigned int MAX_BLOCK_SIZE
The maximum allowed size for a serialized block, in bytes (network rule)
bool AcceptToMemoryPool(bool fLimitFree=true)
friend bool operator==(const CChain &a, const CChain &b)
Compare two chains efficiently.
bool Error(std::string strRejectReasonIn="")
unsigned int nHeightFirst
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector< uint256 > &vMatch)
Used to marshal pointers into hashes for db storage.
bool CheckDiskSpace(uint64_t nAdditionalBytes=0)
Check whether enough disk space is available for an incoming block.
bool Abort(const std::string &msg)
std::string ToString() const
void ThreadScriptCheck()
Run an instance of the script checking thread.
CChain chainMostWork
The currently best known chain of headers (some of which may be invalid).
static const unsigned char REJECT_MALFORMED
"reject" message codes
void UnloadBlockIndex()
Unload database information.
void UpdateTime(CBlockHeader &block, const CBlockIndex *pindexPrev)
bool IsInvalid(int &nDoSOut) const
bool WriteBlockToDisk(CBlock &block, CDiskBlockPos &pos)
Functions for disk access for blocks.
Closure representing one script verification Note that this stores references to the spending transac...
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow=false)
Retrieve a transaction (from memory pool, or from disk, if possible)
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos)
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
std::vector< bool > vBits
std::string GetRejectReason() const
bool LoadBlockIndex()
Load the block tree and coins database from disk.
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
unsigned char GetRejectCode() const
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or NULL if none.
CMerkleTx(const CTransaction &txIn)
Capture information about block/transaction validation.
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of script-checking threads allowed.
IMPLEMENT_SERIALIZE(READWRITE(vtxundo);) bool WriteToDisk(CDiskBlockPos &pos
static const unsigned char REJECT_INVALID
const CTransaction * ptxTo
static const int64_t COIN
uint256 ExtractMatches(std::vector< uint256 > &vMatch)
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool *pfMissingInputs, bool fRejectInsaneFee=false)
(try to) add transaction to memory pool
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
void UnregisterAllWallets()
Unregister all wallets from core.
void RegisterNodeSignals(CNodeSignals &nodeSignals)
Register with a network node to receive its signals.
void PushGetBlocks(CNode *pnode, CBlockIndex *pindexBegin, uint256 hashEnd)
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
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
Undo information for a CBlock.
Serialized script, used inside transaction inputs and outputs.
Undo information for a CTransaction.
std::string ToString() const
static const int PROTOCOL_VERSION
std::vector< int64_t > vTxSigOps
static const unsigned char REJECT_INSUFFICIENTFEE
static const unsigned char REJECT_NONSTANDARD
CBlockIndex * FindFork(const CBlockLocator &locator) const
Find the last common block between this chain and a locator.
bool AreInputsStandard(const CTransaction &tx, CCoinsViewCache &mapInputs)
Check for standard transaction types.
static const unsigned int LOCKTIME_THRESHOLD
Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timest...
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
bool DisconnectBlock(CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean=NULL)
Functions for validating blocks and updating the block tree.
bool ActivateBestChain(CValidationState &state)
Find the best known block, and make it the tip of the block chain.
CBlockIndex * SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
CMerkleBlock(const CBlock &block, CBloomFilter &filter)
unsigned int GetP2SHSigOpCount(const CTransaction &tx, CCoinsViewCache &mapInputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
std::string ToString() const
bool ProcessMessages(CNode *pfrom)
Process protocol messages received from a given node.
static const unsigned int MAX_STANDARD_TX_SIZE
The maximum size for transactions we're willing to relay/mine.
int64_t nTimeBestReceived
bool CheckTransaction(const CTransaction &tx, CValidationState &state)
CDiskBlockPos GetUndoPos() const
FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly=false)
Open an undo file (rev?????.dat)
std::string strRejectReason
The basic transaction that is broadcasted on the network and contained in blocks. ...
Information about a peer.
bool SendMessages(CNode *pto, bool fSendTrickle)
Send queued protocol messages to be sent to a give node.
static const unsigned char REJECT_DUPLICATE
CCoinsView that adds a memory cache for transactions to another CCoinsView.
int64_t GetBlockTime() const
static const int fHaveUPnP
static const unsigned char REJECT_DUST
std::vector< CTxUndo > vtxundo
int64_t GetMedianTimePast() const
void Misbehaving(NodeId nodeid, int howmuch)
Increase a node's misbehavior score.
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock)
bool AbortNode(const std::string &msg)
Abort with a message.
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
uint256 GetBlockHash() const
A transaction with a merkle branch linking it to the block chain.
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
void UnregisterNodeSignals(CNodeSignals &nodeSignals)
Unregister a network node.
uint256 CalcHash(int height, unsigned int pos, const std::vector< uint256 > &vTxid)
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...
const uint256 * phashBlock
static const uint64_t nMinDiskSpace