7 #ifndef ANONCOIN_MAIN_H
8 #define ANONCOIN_MAIN_H
10 #if defined(HAVE_CONFIG_H)
39 static const unsigned int MAX_BLOCK_SIZE = 1000000;
41 static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 750000;
42 static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
44 static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 17000;
46 static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
48 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
50 static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
52 static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS = 750;
54 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000;
56 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000;
58 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000;
60 static const int COINBASE_MATURITY = 100;
62 static const unsigned int LOCKTIME_THRESHOLD = 500000000;
64 static const int MAX_SCRIPTCHECK_THREADS = 16;
66 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
68 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 128;
72 static const unsigned int BLOCK_DOWNLOAD_TIMEOUT = 120;
75 static const int64_t DUST_SOFT_LIMIT = 100000;
78 static const int fHaveUPnP =
true;
80 static const int fHaveUPnP =
false;
84 static const unsigned char REJECT_MALFORMED = 0x01;
85 static const unsigned char REJECT_INVALID = 0x10;
86 static const unsigned char REJECT_OBSOLETE = 0x11;
87 static const unsigned char REJECT_DUPLICATE = 0x12;
88 static const unsigned char REJECT_NONSTANDARD = 0x40;
89 static const unsigned char REJECT_DUST = 0x41;
90 static const unsigned char REJECT_INSUFFICIENTFEE = 0x42;
91 static const unsigned char REJECT_CHECKPOINT = 0x43;
110 static const uint64_t nMinDiskSpace = 52428800;
157 bool VerifyDB(
int nCheckLevel,
int nCheckDepth);
197 bool* pfMissingInputs,
bool fRejectInsaneFee=
false);
241 bool IsNull()
const {
return (nFile == -1); }
313 return dPriority > COIN * 576 / 250;
321 std::vector<CScriptCheck> *pvChecks = NULL);
351 return error(
"CBlockUndo::WriteToDisk : OpenUndoFile failed");
358 long fileOutPos = ftell(fileout);
360 return error(
"CBlockUndo::WriteToDisk : ftell failed");
361 pos.
nPos = (
unsigned int)fileOutPos;
368 fileout << hasher.GetHash();
383 return error(
"CBlockUndo::ReadFromDisk : OpenBlockFile failed");
389 filein >> hashChecksum;
391 catch (std::exception &e) {
392 return error(
"%s : Deserialize or I/O error - %s", __func__, e.what());
399 if (hashChecksum != hasher.GetHash())
400 return error(
"CBlockUndo::ReadFromDisk : Checksum mismatch");
421 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
422 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
428 std::swap(ptxTo, check.
ptxTo);
429 std::swap(nIn, check.
nIn);
430 std::swap(nFlags, check.
nFlags);
464 fMerkleVerified =
false;
478 int SetMerkleBranch(
const CBlock* pblock=NULL);
546 return (nTransactions+(1 << height)-1) >> height;
550 uint256 CalcHash(
int height,
unsigned int pos,
const std::vector<uint256> &vTxid);
553 void TraverseAndBuild(
int height,
unsigned int pos,
const std::vector<uint256> &vTxid,
const std::vector<bool> &vMatch);
557 uint256 TraverseAndExtract(
int height,
unsigned int pos,
unsigned int &nBitsUsed,
unsigned int &nHashUsed, std::vector<uint256> &vMatch);
565 std::vector<unsigned char> vBytes;
569 us.
vBits.resize(vBytes.size() * 8);
570 for (
unsigned int p = 0; p < us.
vBits.size(); p++)
571 us.
vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
574 vBytes.resize((vBits.size()+7)/8);
575 for (
unsigned int p = 0; p < vBits.size(); p++)
576 vBytes[p / 8] |= vBits[p] << (p % 8);
582 CPartialMerkleTree(
const std::vector<uint256> &vTxid,
const std::vector<bool> &vMatch);
658 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());
662 void AddBlock(
unsigned int nHeightIn, uint64_t nTimeIn) {
663 if (nBlocks==0 || nHeightFirst > nHeightIn)
664 nHeightFirst = nHeightIn;
665 if (nBlocks==0 || nTimeFirst > nTimeIn)
666 nTimeFirst = nTimeIn;
668 if (nHeightIn > nHeightLast)
669 nHeightLast = nHeightIn;
670 if (nTimeIn > nTimeLast)
822 return (int64_t)
nTime;
831 return (
CBigNum(1)<<256) / (bnTarget+1);
853 std::sort(pbegin, pend);
854 return pbegin[(pend - pbegin)/2];
864 unsigned int nRequired,
unsigned int nToCheck);
868 return strprintf(
"CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
935 std::string str =
"CDiskBlockIndex(";
937 str +=
strprintf(
"\n hashBlock=%s, hashPrev=%s)",
963 bool DoS(
int level,
bool ret =
false,
964 unsigned char chRejectCodeIn=0, std::string strRejectReasonIn=
"",
965 bool corruptionIn=
false) {
966 chRejectCode = chRejectCodeIn;
967 strRejectReason = strRejectReasonIn;
968 corruptionPossible = corruptionIn;
976 unsigned char _chRejectCode=0, std::string _strRejectReason=
"") {
977 return DoS(0, ret, _chRejectCode, _strRejectReason);
979 bool Error(std::string strRejectReasonIn=
"") {
981 strRejectReason = strRejectReasonIn;
985 bool Abort(
const std::string &msg) {
1020 return vChain.size() > 0 ? vChain[0] : NULL;
1025 return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
1030 if (nHeight < 0 || nHeight >= (
int)vChain.size())
1032 return vChain[nHeight];
1043 return (*
this)[pindex->
nHeight] == pindex;
1049 return (*
this)[pindex->
nHeight + 1];
1056 return vChain.size() - 1;
1124 virtual void EraseFromWallet(
const uint256 &hash) =0;
1126 virtual void UpdatedTransaction(
const uint256 &hash) =0;
1127 virtual void Inventory(
const uint256 &hash) =0;
1128 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.
CDiskBlockPos GetBlockPos() const
bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true)
CBigNum GetBlockWork() const
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)
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
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...
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...
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.
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)
Data structure that represents a partial merkle tree.
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)
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.
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.
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.
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
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).
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)
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.
IMPLEMENT_SERIALIZE(READWRITE(vtxundo);) bool WriteToDisk(CDiskBlockPos &pos
const CTransaction * ptxTo
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
std::vector< int64_t > vTxSigOps
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.
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.
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.
std::vector< int > vHeightInFlight
CCoinsView that adds a memory cache for transactions to another CCoinsView.
int64_t GetBlockTime() const
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.
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