6 #ifndef FABCOIN_VALIDATION_H 7 #define FABCOIN_VALIDATION_H 9 #if defined(HAVE_CONFIG_H) 33 #include <boost/unordered_map.hpp> 34 #include <boost/filesystem/path.hpp> 49 using valtype = std::vector<unsigned char>;
50 using ExtractFascTX = std::pair<std::vector<FascTransaction>, std::vector<EthTransactionParams>>;
71 static const uint64_t MINIMUM_GAS_LIMIT = 10000;
72 static const uint64_t MEMPOOL_MIN_GAS_LIMIT = 22000;
74 static const bool DEFAULT_WHITELISTRELAY =
true;
76 static const bool DEFAULT_WHITELISTFORCERELAY =
true;
78 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 1000;
83 static const CAmount DEFAULT_TRANSACTION_MAXFEE = 1 * COIN;
86 static const CAmount HIGH_TX_FEE_PER_KB = 1 * COIN;
89 static const CAmount HIGH_MAX_TX_FEE = 100 * HIGH_TX_FEE_PER_KB;
91 static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25;
93 static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101;
95 static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
97 static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
99 static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
101 static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
103 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000;
105 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000;
107 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000;
110 static const int MAX_SCRIPTCHECK_THREADS = 16;
112 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
114 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
116 static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
119 static const unsigned int MAX_HEADERS_RESULTS = 2000;
122 static const int MAX_CMPCTBLOCK_DEPTH = 5;
124 static const int MAX_BLOCKTXN_DEPTH = 10;
129 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
131 static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
133 static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
135 static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
137 static const unsigned int AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL = 24 * 60 * 60;
139 static const unsigned int AVG_ADDRESS_BROADCAST_INTERVAL = 30;
142 static const unsigned int INVENTORY_BROADCAST_INTERVAL = 5;
145 static const unsigned int INVENTORY_BROADCAST_MAX = 7 * INVENTORY_BROADCAST_INTERVAL;
147 static const unsigned int AVG_FEEFILTER_BROADCAST_INTERVAL = 10 * 60;
149 static const unsigned int MAX_FEEFILTER_CHANGE_DELAY = 5 * 60;
151 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_BASE = 1000000;
153 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 500000;
156 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
158 static const int64_t MAX_FEE_ESTIMATION_TIP_AGE = 3 * 60 * 60;
161 static const bool DEFAULT_PERMIT_BAREMULTISIG =
true;
162 static const bool DEFAULT_CHECKPOINTS_ENABLED =
true;
163 static const bool DEFAULT_TXINDEX =
false;
164 static const bool DEFAULT_LOGEVENTS =
false;
165 static const unsigned int DEFAULT_BANSCORE_THRESHOLD = 100;
167 static const bool DEFAULT_PERSIST_MEMPOOL =
true;
169 static const bool DEFAULT_ENABLE_REPLACEMENT =
true;
171 static const bool DEFAULT_FEEFILTER =
true;
174 static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
177 static const int MAX_UNCONNECTING_HEADERS = 10;
179 static const bool DEFAULT_PEERBLOOMFILTERS =
true;
182 static const int DEFAULT_STOPATHEIGHT = 0;
183 static const uint64_t DEFAULT_GAS_LIMIT_OP_CREATE=2500000;
184 static const uint64_t DEFAULT_GAS_LIMIT_OP_SEND=250000;
185 static const CAmount DEFAULT_GAS_PRICE=0.00000040*COIN;
186 static const CAmount MAX_RPC_GAS_PRICE=0.00000100*COIN;
187 static const size_t MAX_CONTRACT_VOUTS = 1000;
198 typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher>
BlockMap;
233 static const uint64_t nMinDiskSpace = 52428800;
243 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
245 static const signed int DEFAULT_CHECKBLOCKS = 6;
246 static const unsigned int DEFAULT_CHECKLEVEL = 3;
256 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
278 bool ProcessNewBlock(
const CChainParams& chainparams,
const std::shared_ptr<const CBlock> pblock,
bool fForceProcessing,
bool* fNewBlock);
323 std::string
GetWarnings(
const std::string& strFor);
357 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced =
nullptr,
358 bool fOverrideMempoolLimit =
false,
const CAmount nAbsurdFee = 0,
bool rawTx =
false);
362 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced = NULL,
363 bool fOverrideMempoolLimit =
false,
const CAmount nAbsurdFee = 0,
bool rawTx =
false);
388 template<
typename Stream>
392 template<
typename Stream>
417 template<
typename Stream>
422 template<
typename Stream>
558 scriptPubKey(scriptPubKeyIn), amount(amountIn),
559 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(
SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
583 template <
typename Block>
672 static const unsigned int REJECT_INTERNAL = 0x100;
674 static const unsigned int REJECT_HIGHFEE = 0x100;
676 static const unsigned int REJECT_ALREADY_KNOWN = 0x101;
678 static const unsigned int REJECT_CONFLICT = 0x102;
696 bool CheckMinGasPrice(std::vector<EthTransactionParams>& etps,
const uint64_t& minGasPrice);
701 const dev::h256& oldHashStateRoot,
const std::vector<FascTransaction>& transactions);
714 this->gasPrice != etp.
gasPrice || this->code != etp.
code ||
722 uint64_t usedGas = 0;
738 bool receiveStack(
const CScript& scriptPubKey);
756 ByteCodeExec(
const CBlock& _block, std::vector<FascTransaction> _txs,
const uint64_t _blockGasLimit) : txs(_txs), block(_block), blockGasLimit(_blockGasLimit) {}
762 std::vector<ResultExecute>&
getResult(){
return result; }
770 std::vector<FascTransaction>
txs;
780 #endif // FABCOIN_VALIDATION_H CCoinsViewDB * pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
std::pair< std::vector< FascTransaction >, std::vector< EthTransactionParams >> ExtractFascTX
CHeightTxIndexIteratorKey()
void EnforceContractVoutLimit(ByteCodeExecResult &bcer, ByteCodeExecResult &bcerOut, const dev::h256 &oldHashFascRoot, const dev::h256 &oldHashStateRoot, const std::vector< FascTransaction > &transactions)
std::vector< ResultExecute > & getResult()
bool error(const char *fmt, const Args &...args)
bool operator!=(EthTransactionParams etp)
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, int flags)
Compute total signature operation cost of a transaction.
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download...
boost::condition_variable CConditionVariable
Just a typedef for boost::condition_variable, can be wrapped later if desired.
bool CheckTxInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp=nullptr)
Import blocks from an external file.
enum ScriptError_t ScriptError
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
void PruneOneBlockFile(const int fileNumber)
Mark one block file as pruned.
CConditionVariable cvBlockChange
bool CheckIndexProof(const CBlockIndex &block, const Consensus::Params &consensusParams)
void swap(dev::eth::Watch &_a, dev::eth::Watch &_b)
void swap(CScriptCheck &check)
const uint64_t blockGasLimit
std::vector< ResultExecute > result
An in-memory indexed chain of blocks.
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
void DumpMempool()
Dump the mempool to disk.
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
bool CheckSenderScript(const CCoinsViewCache &view, const CTransaction &tx)
bool CheckBlock(const CBlock &block, CValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW=true, bool fCheckMerkleRoot=true)
Functions for validating blocks and updating the block tree.
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time...
bool ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
CBlockPolicyEstimator feeEstimator
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
bool PreciousBlock(CValidationState &state, const CChainParams ¶ms, CBlockIndex *pindex)
Mark a block as precious and reorganize.
std::vector< valtype > stack
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
bool CheckTransactionTimestamp(const CTransaction &tx, const uint32_t &nTimeBlock, CBlockTreeDB &txdb)
Check if coinstake transaction timestamp is bigger than the previous.
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, CValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=nullptr, CBlockHeader *first_invalid=nullptr)
Process incoming block headers.
ScriptError GetScriptError() const
CChainParams defines various tweakable parameters of a given instance of the Fabcoin system...
std::shared_ptr< dev::eth::SealEngineFace > globalSealEngine
bool LoadMempool()
Load the mempool from disk.
std::shared_ptr< const CTransaction > CTransactionRef
uint64_t GetCheapHash() const
A cheap hash function that just returns 64 bits from the result, it can be used when the contents are...
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock=std::shared_ptr< const CBlock >())
Find the best known block, and make it the tip of the block chain.
bool CheckReward(const CBlock &block, CValidationState &state, int nHeight, const Consensus::Params &consensusParams, CAmount nFees, CAmount gasRefunds, const std::vector< CTxOut > &vouts)
BIP9Stats VersionBitsTipStatistics(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the numerical statistics for the BIP9 state for a given deployment at the current tip...
bool CheckFinalTx(const CTransaction &tx, int flags=-1)
Check if transaction will be final in the next block to be created.
void Serialize(Stream &s) const
int64_t FutureDrift(uint32_t nTime)
int64_t CAmount
Amount in lius (Can be negative)
CHeightTxIndexIteratorKey(unsigned int _height)
ByteCodeExec(const CBlock &_block, std::vector< FascTransaction > _txs, const uint64_t _blockGasLimit)
bool SignBlock(std::shared_ptr< CBlock > pblock, CWallet &wallet, const CAmount &nTotalFees, uint32_t nTime)
bool TestBlockValidity(CValidationState &state, const CChainParams &chainparams, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW=true, bool fCheckMerkleRoot=true)
Check a block is completely valid from start to finish (only works on top of our current best block...
bool InvalidateBlock(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex)
Mark a block as invalid.
opcodetype
Script opcodes.
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness nonce).
void swap(prevector< N, T, Size, Diff > &other)
Access to the block database (blocks/index/)
std::vector< ResultExecute > CallContract(const dev::Address &addrContract, std::vector< unsigned char > opcode, const dev::Address &sender=dev::Address(), uint64_t gasLimit=0)
const std::vector< CTransactionRef > * blockTransactions
bool ReadBlockFromDisk(Block &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
Abstract view on the open txout dataset.
bool CheckCanonicalBlockSignature(const std::shared_ptr< const CBlock > pblock)
bool fHavePruned
Pruning-related variables and constants.
void InitScriptExecutionCache()
Initializes the script-execution cache.
We want to be able to estimate feerates that are needed on tx's to be included in a certain number of...
CHeightTxIndexKey(unsigned int _height, dev::h160 _address)
fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
bool SequenceLocks(const CTransaction &tx, int flags, std::vector< int > *prevHeights, const CBlockIndex &block)
Check if transaction is final per BIP 68 sequence numbers and can be included in a block...
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
bool AcceptToMemoryPoolWithTime(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, int64_t nAcceptTime, std::list< CTransactionRef > *plTxnReplaced=NULL, bool fOverrideMempoolLimit=false, const CAmount nAbsurdFee=0, bool rawTx=false)
(try to) add transaction to memory pool with a specified acceptance time
bool LoadBlockIndex(const CChainParams &chainparams)
Load the block tree and coins database from disk, initializing state if we're running with -reindex...
size_t operator()(const uint256 &hash) const
Fixed-size raw-byte array container type, with an API optimised for storing hashes.
size_t GetSerializeSize(int nType, int nVersion) const
dev::Address receiveAddress
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
bool TestLockPointValidity(const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain. ...
std::string GetWarnings(const std::string &strFor)
Format a string that describes several potential problems detected by the core.
ThresholdState VersionBitsTipState(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
std::atomic_bool fImporting
void ser_writedata32be(Stream &s, uint32_t obj)
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u256
Parameters that influence chain consensus.
An outpoint - a combination of a transaction hash and an index n into its vout.
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
bool CheckInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &view, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData &txdata, std::vector< CScriptCheck > *pvChecks=NULL)
Check whether all inputs of this transaction are valid (no double spends, scripts & sigs...
bool ReplayBlocks(const CChainParams ¶ms, CCoinsView *view)
Replay blocks that aren't fully applied to the database.
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Determine what nVersion a new block should use.
bool GetTransaction(const uint256 &hash, CTransactionRef &tx, const Consensus::Params ¶ms, uint256 &hashBlock, bool fAllowSlow=false)
Retrieve a transaction (from memory pool, or from disk, if possible)
256-bit unsigned big integer.
bool InitBlockIndex(const CChainParams &chainparams)
Initialize a new block tree database + block data on disk.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
Closure representing one script verification Note that this stores references to the spending transac...
bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints *lp=nullptr, bool useExistingLockPoints=false)
Check if transaction will be BIP 68 final in the next block to be created.
StorageResults * pstorageresult
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
bool RewindBlockIndex(const CChainParams ¶ms)
When there are blocks in the active chain with missing data, rewind the chainstate and remove them fr...
Capture information about block/transaction validation.
FascTxConverter(CTransaction tx, CCoinsViewCache *v=NULL, const std::vector< CTransactionRef > *blockTxs=NULL)
const CTransaction * ptxTo
uint64_t nLastBlockWeight
CScriptCheck(const CScript &scriptPubKeyIn, const CAmount amountIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly=false)
Open a block file (blk?????.dat)
Template mixin that adds -Wthread-safety locking annotations to a subset of the mutex API...
void Unserialize(Stream &s)
PlatformStyle::TableColorType type
CWaitableCriticalSection csBestBlock
bool ReadFromDisk(CBlockHeader &block, unsigned int nFile, unsigned int nBlockPos)
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms)
Check whether witness commitments are required for block.
The block chain is a tree shaped structure starting with the genesis block at the root...
Serialized script, used inside transaction inputs and outputs.
CCoinsView backed by the coin database (chainstate/)
CAmount maxTxFee
Absolute maximum transaction fee (in liu) used by wallet and mempool (rejects high fee in sendrawtran...
size_t GetSerializeSize(int nType, int nVersion) const
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
bool CheckDiskSpace(uint64_t nAdditionalBytes=0)
Check whether enough disk space is available for an incoming block.
uint32_t ser_readdata32be(Stream &s)
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
const CCoinsViewCache * view
void PruneAndFlush()
Prune block files and flush state to disk.
Fee rate in liu per kilobyte: CAmount / kB.
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
void ThreadScriptCheck()
Run an instance of the script checking thread.
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
std::unique_ptr< FascState > globalState
Global state.
std::vector< FascTransaction > txs
A mutable version of CTransaction.
std::vector< unsigned char > valtype
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
double GuessVerificationProgress(const ChainTxData &data, CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
std::vector< CTxOut > refundOutputs
The basic transaction that is broadcasted on the network and contained in blocks. ...
void Unserialize(Stream &s)
std::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
bool fPruneMode
True if we're running in -prune mode.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
int GetSpendHeight(const CCoinsViewCache &inputs)
Return the spend height, which is one more than the inputs.GetBestBlock().
int VersionBitsTipStateSinceHeight(const Consensus::Params ¶ms, Consensus::DeploymentPos pos)
Get the block height at which the BIP9 deployment switched into the state for the block building on t...
const std::string strMessageMagic
bool FlushStateToDisk()
Flush all state, indexes and buffers to disk.
void Serialize(Stream &s) const
bool GetBlockPublicKey(const CBlock &block, std::vector< unsigned char > &vchPubKey)
bool CheckTransaction(const CTransaction &tx, CValidationState &state, bool fCheckDuplicateInputs)
Transaction validation functions.
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
VersionBitsCache versionbitscache
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
void writeVMlog(const std::vector< ResultExecute > &res, const CTransaction &tx=CTransaction(), const CBlock &block=CBlock())
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
bool CheckMinGasPrice(std::vector< EthTransactionParams > &etps, const uint64_t &minGasPrice)
void UnloadBlockIndex()
Unload database information.
bool IsConfirmedInNPrevBlocks(const CDiskTxPos &txindex, const CBlockIndex *pindexFrom, int nMaxDepth, int &nActualDepth)
Check if the transaction is confirmed in N previous blocks.
bool LoadChainTip(const CChainParams &chainparams)
Update the chain tip based on database information.
bool ContextualCheckBlockHeader(const CBlockHeader &block, CValidationState &state, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev, int64_t nAdjustedTime)
Context-dependent validity checks.
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced=nullptr, bool fOverrideMempoolLimit=false, const CAmount nAbsurdFee=0, bool rawTx=false)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
std::vector< CTransaction > valueTransfers
PrecomputedTransactionData * txdata