2010-08-29 16:58:15 +00:00
|
|
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
2022-12-24 23:49:50 +00:00
|
|
|
// Copyright (c) 2009-2022 The Bitcoin Core developers
|
2014-12-01 09:39:44 +08:00
|
|
|
// Distributed under the MIT software license, see the accompanying
|
2012-05-18 22:02:28 +08:00
|
|
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
2013-04-13 00:13:08 -05:00
|
|
|
|
2016-12-01 16:06:41 -08:00
|
|
|
#ifndef BITCOIN_VALIDATION_H
|
|
|
|
#define BITCOIN_VALIDATION_H
|
2011-05-15 09:11:04 +02:00
|
|
|
|
2013-05-27 19:55:01 -04:00
|
|
|
#if defined(HAVE_CONFIG_H)
|
2017-11-10 13:57:53 +13:00
|
|
|
#include <config/bitcoin-config.h>
|
2013-05-27 19:55:01 -04:00
|
|
|
#endif
|
|
|
|
|
2021-08-04 21:04:44 +02:00
|
|
|
#include <arith_uint256.h>
|
2020-08-25 13:50:23 -04:00
|
|
|
#include <attributes.h>
|
2021-08-04 21:04:44 +02:00
|
|
|
#include <chain.h>
|
2022-01-18 21:34:16 +10:00
|
|
|
#include <chainparams.h>
|
2022-03-01 16:14:12 -05:00
|
|
|
#include <kernel/chainstatemanager_opts.h>
|
2021-09-11 10:29:00 +08:00
|
|
|
#include <consensus/amount.h>
|
2022-04-15 05:49:31 +10:00
|
|
|
#include <deploymentstatus.h>
|
2017-11-10 13:57:53 +13:00
|
|
|
#include <fs.h>
|
2022-09-15 10:45:07 +01:00
|
|
|
#include <kernel/cs_main.h> // IWYU pragma: export
|
2022-01-02 17:05:43 +01:00
|
|
|
#include <node/blockstorage.h>
|
2017-11-10 13:57:53 +13:00
|
|
|
#include <policy/feerate.h>
|
2021-04-05 10:12:58 -07:00
|
|
|
#include <policy/packages.h>
|
2022-06-07 23:16:25 +08:00
|
|
|
#include <policy/policy.h>
|
2017-11-10 13:57:53 +13:00
|
|
|
#include <script/script_error.h>
|
|
|
|
#include <sync.h>
|
2019-07-24 13:23:48 -04:00
|
|
|
#include <txdb.h>
|
2021-08-04 21:04:44 +02:00
|
|
|
#include <txmempool.h> // For CTxMemPool::cs
|
|
|
|
#include <uint256.h>
|
2021-01-19 05:29:40 -08:00
|
|
|
#include <util/check.h>
|
2019-09-17 17:02:56 -04:00
|
|
|
#include <util/hasher.h>
|
2021-04-18 15:41:08 +02:00
|
|
|
#include <util/translation.h>
|
2022-04-15 06:53:19 +10:00
|
|
|
#include <versionbits.h>
|
2011-05-15 09:11:04 +02:00
|
|
|
|
2019-03-19 12:09:27 -04:00
|
|
|
#include <atomic>
|
2013-04-13 00:13:08 -05:00
|
|
|
#include <map>
|
2018-04-02 18:31:40 +00:00
|
|
|
#include <memory>
|
2021-03-15 11:59:05 +08:00
|
|
|
#include <optional>
|
2013-04-13 00:13:08 -05:00
|
|
|
#include <set>
|
|
|
|
#include <stdint.h>
|
2020-05-30 21:52:47 +09:00
|
|
|
#include <string>
|
2021-04-02 20:38:28 +02:00
|
|
|
#include <thread>
|
2013-04-13 00:13:08 -05:00
|
|
|
#include <utility>
|
|
|
|
#include <vector>
|
2010-08-29 16:58:15 +00:00
|
|
|
|
2022-03-09 12:37:19 -05:00
|
|
|
class Chainstate;
|
2014-10-31 09:36:30 +01:00
|
|
|
class CBlockTreeDB;
|
2015-07-05 14:30:07 +02:00
|
|
|
class CTxMemPool;
|
2020-04-18 08:05:52 -04:00
|
|
|
class ChainstateManager;
|
2017-01-04 07:31:56 -08:00
|
|
|
struct ChainTxData;
|
2019-03-27 10:20:41 -04:00
|
|
|
struct DisconnectedBlockTransactions;
|
2016-09-02 11:43:06 +02:00
|
|
|
struct PrecomputedTransactionData;
|
2015-12-04 15:01:22 -05:00
|
|
|
struct LockPoints;
|
2019-04-25 11:09:29 -04:00
|
|
|
struct AssumeutxoData;
|
2021-11-12 10:06:00 -05:00
|
|
|
namespace node {
|
|
|
|
class SnapshotMetadata;
|
|
|
|
} // namespace node
|
2022-01-18 21:34:16 +10:00
|
|
|
namespace Consensus {
|
|
|
|
struct Params;
|
|
|
|
} // namespace Consensus
|
2011-05-14 16:20:30 -05:00
|
|
|
|
2019-11-02 17:14:38 -04:00
|
|
|
/** Maximum number of dedicated script-checking threads allowed */
|
|
|
|
static const int MAX_SCRIPTCHECK_THREADS = 15;
|
2014-02-18 12:48:16 +01:00
|
|
|
/** -par default (number of script-checking threads, 0 = auto) */
|
|
|
|
static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
|
2017-04-27 12:25:13 -07:00
|
|
|
/** Default for -stopatheight */
|
|
|
|
static const int DEFAULT_STOPATHEIGHT = 0;
|
2021-10-12 14:36:51 +13:00
|
|
|
/** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pruned. */
|
2019-11-05 14:33:38 -05:00
|
|
|
static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
|
|
|
|
static const signed int DEFAULT_CHECKBLOCKS = 6;
|
2022-02-15 11:27:39 +01:00
|
|
|
static constexpr int DEFAULT_CHECKLEVEL{3};
|
2019-11-05 14:33:38 -05:00
|
|
|
// Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
|
|
|
|
// At 1MB per block, 288 blocks = 288MB.
|
|
|
|
// Add 15% for Undo data = 331MB
|
|
|
|
// Add 20% for Orphan block rate = 397MB
|
|
|
|
// We want the low water mark after pruning to be at least 397 MB and since we prune in
|
|
|
|
// full block file chunks, we need the high water mark which triggers the prune to be
|
|
|
|
// one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
|
|
|
|
// Setting the target to >= 550 MiB will make it likely we can respect the target.
|
|
|
|
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
|
2017-04-27 12:25:13 -07:00
|
|
|
|
2020-03-04 20:05:42 +02:00
|
|
|
/** Current sync state passed to tip changed callbacks. */
|
|
|
|
enum class SynchronizationState {
|
|
|
|
INIT_REINDEX,
|
|
|
|
INIT_DOWNLOAD,
|
|
|
|
POST_INIT
|
|
|
|
};
|
|
|
|
|
2022-04-20 17:10:13 +10:00
|
|
|
extern GlobalMutex g_best_block_mutex;
|
2017-11-03 07:49:16 -04:00
|
|
|
extern std::condition_variable g_best_block_cv;
|
2021-09-15 15:46:29 -04:00
|
|
|
/** Used to notify getblocktemplate RPC of new tips. */
|
2018-04-03 21:53:07 -07:00
|
|
|
extern uint256 g_best_block;
|
2017-05-07 14:10:19 -04:00
|
|
|
|
2020-05-30 21:52:47 +09:00
|
|
|
/** Documentation for argument 'checklevel'. */
|
|
|
|
extern const std::vector<std::string> CHECKLEVEL_DOC;
|
Add block pruning functionality
This adds a -prune=N option to bitcoind, which if set to N>0 will enable block
file pruning. When pruning is enabled, block and undo files will be deleted to
try to keep total space used by those files to below the prune target (N, in
MB) specified by the user, subject to some constraints:
- The last 288 blocks on the main chain are always kept (MIN_BLOCKS_TO_KEEP),
- N must be at least 550MB (chosen as a value for the target that could
reasonably be met, with some assumptions about block sizes, orphan rates,
etc; see comment in main.h),
- No blocks are pruned until chainActive is at least 100,000 blocks long (on
mainnet; defined separately for mainnet, testnet, and regtest in chainparams
as nPruneAfterHeight).
This unsets NODE_NETWORK if pruning is enabled.
Also included is an RPC test for pruning (pruning.py).
Thanks to @rdponticelli for earlier work on this feature; this is based in
part off that work.
2015-02-23 14:27:44 -05:00
|
|
|
|
2020-08-21 09:24:05 +03:00
|
|
|
/** Run instances of script checking worker threads */
|
|
|
|
void StartScriptCheckWorkerThreads(int threads_num);
|
|
|
|
/** Stop all of the script checking worker threads */
|
|
|
|
void StopScriptCheckWorkerThreads();
|
2021-07-22 15:01:14 +02:00
|
|
|
|
2015-04-01 16:03:11 +02:00
|
|
|
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
|
2013-01-08 14:58:06 -08:00
|
|
|
|
2021-04-18 15:41:08 +02:00
|
|
|
bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage = bilingual_str{});
|
|
|
|
|
2017-01-04 07:09:02 -08:00
|
|
|
/** Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip). */
|
2017-04-25 21:31:08 -04:00
|
|
|
double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
|
2017-01-04 07:09:02 -08:00
|
|
|
|
2016-11-29 12:39:19 -05:00
|
|
|
/** Prune block files up to a given height */
|
2022-03-09 12:37:19 -05:00
|
|
|
void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight);
|
2012-08-19 00:33:01 +02:00
|
|
|
|
2021-01-19 05:29:40 -08:00
|
|
|
/**
|
|
|
|
* Validation result for a single transaction mempool acceptance.
|
|
|
|
*/
|
|
|
|
struct MempoolAcceptResult {
|
2021-05-20 21:22:35 +01:00
|
|
|
/** Used to indicate the results of mempool validation. */
|
2021-01-19 05:29:40 -08:00
|
|
|
enum class ResultType {
|
|
|
|
VALID, //!> Fully validated, valid.
|
|
|
|
INVALID, //!> Invalid.
|
2021-08-23 16:57:10 +01:00
|
|
|
MEMPOOL_ENTRY, //!> Valid, transaction was already in the mempool.
|
2021-12-17 14:06:16 +00:00
|
|
|
DIFFERENT_WITNESS, //!> Not validated. A same-txid-different-witness tx (see m_other_wtxid) already exists in the mempool and was not replaced.
|
2021-01-19 05:29:40 -08:00
|
|
|
};
|
2021-12-17 14:06:16 +00:00
|
|
|
/** Result type. Present in all MempoolAcceptResults. */
|
2021-02-11 06:23:04 -08:00
|
|
|
const ResultType m_result_type;
|
2021-12-17 14:06:16 +00:00
|
|
|
|
|
|
|
/** Contains information about why the transaction failed. */
|
2021-02-11 06:23:04 -08:00
|
|
|
const TxValidationState m_state;
|
2021-01-19 05:29:40 -08:00
|
|
|
|
2021-08-23 16:57:10 +01:00
|
|
|
// The following fields are only present when m_result_type = ResultType::VALID or MEMPOOL_ENTRY
|
2022-07-19 09:52:55 +01:00
|
|
|
/** Mempool transactions replaced by the tx. */
|
2021-02-11 06:23:04 -08:00
|
|
|
const std::optional<std::list<CTransactionRef>> m_replaced_transactions;
|
2021-09-02 13:09:11 +01:00
|
|
|
/** Virtual size as used by the mempool, calculated using serialized size and sigops. */
|
|
|
|
const std::optional<int64_t> m_vsize;
|
2021-02-11 06:23:04 -08:00
|
|
|
/** Raw base fees in satoshis. */
|
|
|
|
const std::optional<CAmount> m_base_fees;
|
2022-09-28 11:23:55 +01:00
|
|
|
/** The feerate at which this transaction was considered. This includes any fee delta added
|
|
|
|
* using prioritisetransaction (i.e. modified fees). If this transaction was submitted as a
|
|
|
|
* package, this is the package feerate, which may also include its descendants and/or
|
2022-12-09 13:13:49 +00:00
|
|
|
* ancestors (see m_wtxids_fee_calculations below).
|
|
|
|
* Only present when m_result_type = ResultType::VALID.
|
|
|
|
*/
|
2022-09-28 11:23:55 +01:00
|
|
|
const std::optional<CFeeRate> m_effective_feerate;
|
2022-12-09 13:13:49 +00:00
|
|
|
/** Contains the wtxids of the transactions used for fee-related checks. Includes this
|
|
|
|
* transaction's wtxid and may include others if this transaction was validated as part of a
|
|
|
|
* package. This is not necessarily equivalent to the list of transactions passed to
|
|
|
|
* ProcessNewPackage().
|
|
|
|
* Only present when m_result_type = ResultType::VALID. */
|
|
|
|
const std::optional<std::vector<uint256>> m_wtxids_fee_calculations;
|
2021-08-23 16:57:10 +01:00
|
|
|
|
2021-12-17 14:06:16 +00:00
|
|
|
// The following field is only present when m_result_type = ResultType::DIFFERENT_WITNESS
|
|
|
|
/** The wtxid of the transaction in the mempool which has the same txid but different witness. */
|
|
|
|
const std::optional<uint256> m_other_wtxid;
|
|
|
|
|
2021-05-20 21:22:35 +01:00
|
|
|
static MempoolAcceptResult Failure(TxValidationState state) {
|
|
|
|
return MempoolAcceptResult(state);
|
|
|
|
}
|
2021-01-19 05:29:40 -08:00
|
|
|
|
2022-09-28 11:23:55 +01:00
|
|
|
static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns,
|
|
|
|
int64_t vsize,
|
|
|
|
CAmount fees,
|
2022-12-09 13:13:49 +00:00
|
|
|
CFeeRate effective_feerate,
|
|
|
|
const std::vector<uint256>& wtxids_fee_calculations) {
|
|
|
|
return MempoolAcceptResult(std::move(replaced_txns), vsize, fees,
|
|
|
|
effective_feerate, wtxids_fee_calculations);
|
2021-05-20 21:22:35 +01:00
|
|
|
}
|
2021-01-19 05:29:40 -08:00
|
|
|
|
2021-08-23 16:57:10 +01:00
|
|
|
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees) {
|
|
|
|
return MempoolAcceptResult(vsize, fees);
|
|
|
|
}
|
|
|
|
|
2021-12-17 14:06:16 +00:00
|
|
|
static MempoolAcceptResult MempoolTxDifferentWitness(const uint256& other_wtxid) {
|
|
|
|
return MempoolAcceptResult(other_wtxid);
|
|
|
|
}
|
|
|
|
|
2021-05-20 21:22:35 +01:00
|
|
|
// Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct.
|
|
|
|
private:
|
2021-01-19 05:29:40 -08:00
|
|
|
/** Constructor for failure case */
|
|
|
|
explicit MempoolAcceptResult(TxValidationState state)
|
2021-03-15 11:59:05 +08:00
|
|
|
: m_result_type(ResultType::INVALID), m_state(state) {
|
2021-01-19 05:29:40 -08:00
|
|
|
Assume(!state.IsValid()); // Can be invalid or error
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Constructor for success case */
|
2022-09-28 11:23:55 +01:00
|
|
|
explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns,
|
|
|
|
int64_t vsize,
|
|
|
|
CAmount fees,
|
2022-12-09 13:13:49 +00:00
|
|
|
CFeeRate effective_feerate,
|
|
|
|
const std::vector<uint256>& wtxids_fee_calculations)
|
2021-02-11 06:23:04 -08:00
|
|
|
: m_result_type(ResultType::VALID),
|
2022-09-28 11:23:55 +01:00
|
|
|
m_replaced_transactions(std::move(replaced_txns)),
|
|
|
|
m_vsize{vsize},
|
|
|
|
m_base_fees(fees),
|
2022-12-09 13:13:49 +00:00
|
|
|
m_effective_feerate(effective_feerate),
|
|
|
|
m_wtxids_fee_calculations(wtxids_fee_calculations) {}
|
2021-08-23 16:57:10 +01:00
|
|
|
|
|
|
|
/** Constructor for already-in-mempool case. It wouldn't replace any transactions. */
|
|
|
|
explicit MempoolAcceptResult(int64_t vsize, CAmount fees)
|
|
|
|
: m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize}, m_base_fees(fees) {}
|
2021-12-17 14:06:16 +00:00
|
|
|
|
|
|
|
/** Constructor for witness-swapped case. */
|
|
|
|
explicit MempoolAcceptResult(const uint256& other_wtxid)
|
|
|
|
: m_result_type(ResultType::DIFFERENT_WITNESS), m_other_wtxid(other_wtxid) {}
|
2021-01-19 05:29:40 -08:00
|
|
|
};
|
|
|
|
|
2021-04-05 10:12:58 -07:00
|
|
|
/**
|
|
|
|
* Validation result for package mempool acceptance.
|
|
|
|
*/
|
|
|
|
struct PackageMempoolAcceptResult
|
|
|
|
{
|
|
|
|
const PackageValidationState m_state;
|
|
|
|
/**
|
2021-12-17 14:06:16 +00:00
|
|
|
* Map from wtxid to finished MempoolAcceptResults. The client is responsible
|
2021-04-05 10:12:58 -07:00
|
|
|
* for keeping track of the transaction objects themselves. If a result is not
|
2021-07-15 07:12:29 +01:00
|
|
|
* present, it means validation was unfinished for that transaction. If there
|
|
|
|
* was a package-wide error (see result in m_state), m_tx_results will be empty.
|
2021-04-05 10:12:58 -07:00
|
|
|
*/
|
|
|
|
std::map<const uint256, const MempoolAcceptResult> m_tx_results;
|
|
|
|
|
|
|
|
explicit PackageMempoolAcceptResult(PackageValidationState state,
|
|
|
|
std::map<const uint256, const MempoolAcceptResult>&& results)
|
|
|
|
: m_state{state}, m_tx_results(std::move(results)) {}
|
|
|
|
|
2021-07-20 13:26:26 +01:00
|
|
|
explicit PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate,
|
|
|
|
std::map<const uint256, const MempoolAcceptResult>&& results)
|
2022-09-28 14:31:20 +01:00
|
|
|
: m_state{state}, m_tx_results(std::move(results)) {}
|
2021-07-20 13:26:26 +01:00
|
|
|
|
2021-04-05 10:12:58 -07:00
|
|
|
/** Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult */
|
|
|
|
explicit PackageMempoolAcceptResult(const uint256& wtxid, const MempoolAcceptResult& result)
|
|
|
|
: m_tx_results{ {wtxid, result} } {}
|
|
|
|
};
|
|
|
|
|
2021-01-19 05:29:40 -08:00
|
|
|
/**
|
2021-11-03 22:23:38 -03:00
|
|
|
* Try to add a transaction to the mempool. This is an internal function and is exposed only for testing.
|
|
|
|
* Client code should use ChainstateManager::ProcessTransaction()
|
2021-09-27 17:47:21 +01:00
|
|
|
*
|
2021-11-03 22:23:38 -03:00
|
|
|
* @param[in] active_chainstate Reference to the active chainstate.
|
2021-09-27 17:47:21 +01:00
|
|
|
* @param[in] tx The transaction to submit for mempool acceptance.
|
2021-12-02 01:50:27 -03:00
|
|
|
* @param[in] accept_time The timestamp for adding the transaction to the mempool.
|
2021-11-03 22:23:38 -03:00
|
|
|
* It is also used to determine when the entry expires.
|
2021-09-27 17:47:21 +01:00
|
|
|
* @param[in] bypass_limits When true, don't enforce mempool fee and capacity limits.
|
|
|
|
* @param[in] test_accept When true, run validation checks but don't submit to mempool.
|
|
|
|
*
|
|
|
|
* @returns a MempoolAcceptResult indicating whether the transaction was accepted/rejected with reason.
|
2021-01-19 05:29:40 -08:00
|
|
|
*/
|
2022-03-09 12:37:19 -05:00
|
|
|
MempoolAcceptResult AcceptToMemoryPool(Chainstate& active_chainstate, const CTransactionRef& tx,
|
2021-11-03 22:23:38 -03:00
|
|
|
int64_t accept_time, bool bypass_limits, bool test_accept)
|
|
|
|
EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2010-08-29 16:58:15 +00:00
|
|
|
|
2021-04-05 10:12:58 -07:00
|
|
|
/**
|
2021-10-20 12:02:18 +01:00
|
|
|
* Validate (and maybe submit) a package to the mempool. See doc/policy/packages.md for full details
|
|
|
|
* on package validation rules.
|
2021-07-20 11:07:25 +01:00
|
|
|
* @param[in] test_accept When true, run validation checks but don't submit to mempool.
|
2021-04-05 10:12:58 -07:00
|
|
|
* @returns a PackageMempoolAcceptResult which includes a MempoolAcceptResult for each transaction.
|
2021-07-20 11:07:25 +01:00
|
|
|
* If a transaction fails, validation will exit early and some results may be missing. It is also
|
|
|
|
* possible for the package to be partially submitted.
|
2021-04-05 10:12:58 -07:00
|
|
|
*/
|
2022-03-09 12:37:19 -05:00
|
|
|
PackageMempoolAcceptResult ProcessNewPackage(Chainstate& active_chainstate, CTxMemPool& pool,
|
2021-04-05 10:12:58 -07:00
|
|
|
const Package& txns, bool test_accept)
|
|
|
|
EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2010-08-29 16:58:15 +00:00
|
|
|
|
2022-03-14 16:52:55 +01:00
|
|
|
/* Mempool validation helper functions */
|
2016-07-16 20:57:42 +02:00
|
|
|
|
2015-05-25 00:48:33 -04:00
|
|
|
/**
|
|
|
|
* Check if transaction will be final in the next block to be created.
|
|
|
|
*/
|
2022-07-22 14:28:18 +02:00
|
|
|
bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
Ultraprune
This switches bitcoin's transaction/block verification logic to use a
"coin database", which contains all unredeemed transaction output scripts,
amounts and heights.
The name ultraprune comes from the fact that instead of a full transaction
index, we only (need to) keep an index with unspent outputs. For now, the
blocks themselves are kept as usual, although they are only necessary for
serving, rescanning and reorganizing.
The basic datastructures are CCoins (representing the coins of a single
transaction), and CCoinsView (representing a state of the coins database).
There are several implementations for CCoinsView. A dummy, one backed by
the coins database (coins.dat), one backed by the memory pool, and one
that adds a cache on top of it. FetchInputs, ConnectInputs, ConnectBlock,
DisconnectBlock, ... now operate on a generic CCoinsView.
The block switching logic now builds a single cached CCoinsView with
changes to be committed to the database before any changes are made.
This means no uncommitted changes are ever read from the database, and
should ease the transition to another database layer which does not
support transactions (but does support atomic writes), like LevelDB.
For the getrawtransaction() RPC call, access to a txid-to-disk index
would be preferable. As this index is not necessary or even useful
for any other part of the implementation, it is not provided. Instead,
getrawtransaction() uses the coin database to find the block height,
and then scans that block to find the requested transaction. This is
slow, but should suffice for debug purposes.
2012-07-01 18:54:00 +02:00
|
|
|
|
2015-12-07 15:44:16 -05:00
|
|
|
/**
|
2021-02-11 09:36:20 -08:00
|
|
|
* Check if transaction will be BIP68 final in the next block to be created on top of tip.
|
|
|
|
* @param[in] tip Chain tip to check tx sequence locks against. For example,
|
|
|
|
* the tip of the current active chain.
|
2021-05-27 08:39:59 +01:00
|
|
|
* @param[in] coins_view Any CCoinsView that provides access to the relevant coins for
|
|
|
|
* checking sequence locks. For example, it can be a CCoinsViewCache
|
|
|
|
* that isn't connected to anything but contains all the relevant
|
|
|
|
* coins, or a CCoinsViewMemPool that is connected to the
|
|
|
|
* mempool and chainstate UTXO set. In the latter case, the caller is
|
|
|
|
* responsible for holding the appropriate locks to ensure that
|
|
|
|
* calls to GetCoin() return correct coins.
|
2021-02-11 09:36:20 -08:00
|
|
|
* Simulates calling SequenceLocks() with data from the tip passed in.
|
2015-12-04 15:01:22 -05:00
|
|
|
* Optionally stores in LockPoints the resulting height and time calculated and the hash
|
|
|
|
* of the block needed for calculation or skips the calculation and uses the LockPoints
|
|
|
|
* passed in for evaluation.
|
2022-01-11 15:53:50 +01:00
|
|
|
* The LockPoints should not be considered valid if CheckSequenceLocksAtTip returns false.
|
2015-12-07 15:44:16 -05:00
|
|
|
*/
|
2022-01-11 15:53:50 +01:00
|
|
|
bool CheckSequenceLocksAtTip(CBlockIndex* tip,
|
2021-02-11 09:36:20 -08:00
|
|
|
const CCoinsView& coins_view,
|
2021-02-08 14:12:12 -05:00
|
|
|
const CTransaction& tx,
|
|
|
|
LockPoints* lp = nullptr,
|
2021-02-11 09:36:20 -08:00
|
|
|
bool useExistingLockPoints = false);
|
2015-12-07 15:44:16 -05:00
|
|
|
|
|
|
|
/**
|
2014-12-01 09:39:44 +08:00
|
|
|
* Closure representing one script verification
|
2018-07-24 16:59:49 +01:00
|
|
|
* Note that this stores references to the spending transaction
|
2014-12-01 09:39:44 +08:00
|
|
|
*/
|
2012-12-01 22:30:06 +01:00
|
|
|
class CScriptCheck
|
|
|
|
{
|
|
|
|
private:
|
2017-09-22 14:27:03 +08:00
|
|
|
CTxOut m_tx_out;
|
2012-12-01 22:30:06 +01:00
|
|
|
const CTransaction *ptxTo;
|
|
|
|
unsigned int nIn;
|
|
|
|
unsigned int nFlags;
|
2014-09-14 04:48:32 +02:00
|
|
|
bool cacheStore;
|
2014-11-29 16:01:37 +01:00
|
|
|
ScriptError error;
|
2016-08-26 18:38:20 +02:00
|
|
|
PrecomputedTransactionData *txdata;
|
2010-08-29 16:58:15 +00:00
|
|
|
|
2012-12-01 22:30:06 +01:00
|
|
|
public:
|
2017-07-30 17:32:39 +08:00
|
|
|
CScriptCheck(): ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
|
|
|
|
CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
|
2017-09-22 14:27:03 +08:00
|
|
|
m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
|
2012-12-01 22:30:06 +01:00
|
|
|
|
2014-11-29 16:01:37 +01:00
|
|
|
bool operator()();
|
2012-12-01 22:30:06 +01:00
|
|
|
|
2022-04-28 20:20:30 +02:00
|
|
|
void swap(CScriptCheck& check) noexcept
|
|
|
|
{
|
2012-12-01 22:30:06 +01:00
|
|
|
std::swap(ptxTo, check.ptxTo);
|
2017-09-22 14:27:03 +08:00
|
|
|
std::swap(m_tx_out, check.m_tx_out);
|
2012-12-01 22:30:06 +01:00
|
|
|
std::swap(nIn, check.nIn);
|
|
|
|
std::swap(nFlags, check.nFlags);
|
2014-09-14 04:48:32 +02:00
|
|
|
std::swap(cacheStore, check.cacheStore);
|
2014-11-29 16:01:37 +01:00
|
|
|
std::swap(error, check.error);
|
2016-08-26 18:38:20 +02:00
|
|
|
std::swap(txdata, check.txdata);
|
2012-12-01 22:30:06 +01:00
|
|
|
}
|
2014-11-29 16:01:37 +01:00
|
|
|
|
|
|
|
ScriptError GetScriptError() const { return error; }
|
2012-12-01 22:30:06 +01:00
|
|
|
};
|
2010-08-29 16:58:15 +00:00
|
|
|
|
Cache full script execution results in addition to signatures
This adds a new CuckooCache in validation, caching whether all of a
transaction's scripts were valid with a given set of script flags.
Unlike previous attempts at caching an entire transaction's
validity, which have nearly universally introduced consensus
failures, this only caches the validity of a transaction's
scriptSigs. As these are pure functions of the transaction and
data it commits to, this should be much safer.
This is somewhat duplicative with the sigcache, as entries in the
new cache will also have several entries in the sigcache. However,
the sigcache is kept both as ATMP relies on it and because it
prevents malleability-based DoS attacks on the new higher-level
cache. Instead, the -sigcachesize option is re-used - cutting the
sigcache size in half and using the newly freed memory for the
script execution cache.
Transactions which match the script execution cache never even have
entries in the script check thread's workqueue created.
Note that the cache is indexed only on the script execution flags
and the transaction's witness hash. While this is sufficient to
make the CScriptCheck() calls pure functions, this introduces
dependancies on the mempool calculating things such as the
PrecomputedTransactionData object, filling the CCoinsViewCache, etc
in the exact same way as ConnectBlock. I belive this is a reasonable
assumption, but should be noted carefully.
In a rather naive benchmark (reindex-chainstate up to block 284k
with cuckoocache always returning true for contains(),
-assumevalid=0 and a very large dbcache), this connected blocks
~1.7x faster.
2017-04-11 16:46:39 -04:00
|
|
|
/** Initializes the script-execution cache */
|
2022-07-01 00:08:14 -04:00
|
|
|
[[nodiscard]] bool InitScriptExecutionCache(size_t max_size_bytes);
|
Cache full script execution results in addition to signatures
This adds a new CuckooCache in validation, caching whether all of a
transaction's scripts were valid with a given set of script flags.
Unlike previous attempts at caching an entire transaction's
validity, which have nearly universally introduced consensus
failures, this only caches the validity of a transaction's
scriptSigs. As these are pure functions of the transaction and
data it commits to, this should be much safer.
This is somewhat duplicative with the sigcache, as entries in the
new cache will also have several entries in the sigcache. However,
the sigcache is kept both as ATMP relies on it and because it
prevents malleability-based DoS attacks on the new higher-level
cache. Instead, the -sigcachesize option is re-used - cutting the
sigcache size in half and using the newly freed memory for the
script execution cache.
Transactions which match the script execution cache never even have
entries in the script check thread's workqueue created.
Note that the cache is indexed only on the script execution flags
and the transaction's witness hash. While this is sufficient to
make the CScriptCheck() calls pure functions, this introduces
dependancies on the mempool calculating things such as the
PrecomputedTransactionData object, filling the CCoinsViewCache, etc
in the exact same way as ConnectBlock. I belive this is a reasonable
assumption, but should be noted carefully.
In a rather naive benchmark (reindex-chainstate up to block 284k
with cuckoocache always returning true for contains(),
-assumevalid=0 and a very large dbcache), this connected blocks
~1.7x faster.
2017-04-11 16:46:39 -04:00
|
|
|
|
2013-06-23 18:32:58 -07:00
|
|
|
/** Functions for validating blocks and updating the block tree */
|
|
|
|
|
2014-12-01 09:39:44 +08:00
|
|
|
/** Context-independent validity checks */
|
2019-10-24 11:35:42 -04:00
|
|
|
bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
|
2013-06-23 19:14:11 -07:00
|
|
|
|
2018-06-04 18:25:13 -04:00
|
|
|
/** Check a block is completely valid from start to finish (only works on top of our current best block) */
|
2021-01-20 14:27:27 -05:00
|
|
|
bool TestBlockValidity(BlockValidationState& state,
|
|
|
|
const CChainParams& chainparams,
|
2022-03-09 12:37:19 -05:00
|
|
|
Chainstate& chainstate,
|
2021-01-20 14:27:27 -05:00
|
|
|
const CBlock& block,
|
|
|
|
CBlockIndex* pindexPrev,
|
2022-08-05 15:12:58 +02:00
|
|
|
const std::function<NodeClock::time_point()>& adjusted_time_callback,
|
2021-01-20 14:27:27 -05:00
|
|
|
bool fCheckPOW = true,
|
|
|
|
bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2014-10-20 02:10:03 +00:00
|
|
|
|
2022-02-09 09:38:52 -05:00
|
|
|
/** Check with the proof of work on each blockheader matches the value in nBits */
|
|
|
|
bool HasValidProofOfWork(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams);
|
|
|
|
|
|
|
|
/** Return the sum of the work on a given set of headers */
|
|
|
|
arith_uint256 CalculateHeadersWork(const std::vector<CBlockHeader>& headers);
|
|
|
|
|
2014-05-23 18:04:09 +02:00
|
|
|
/** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
|
|
|
|
class CVerifyDB {
|
|
|
|
public:
|
|
|
|
CVerifyDB();
|
|
|
|
~CVerifyDB();
|
2021-04-13 09:57:20 -04:00
|
|
|
bool VerifyDB(
|
2022-03-09 12:37:19 -05:00
|
|
|
Chainstate& chainstate,
|
2021-09-20 14:02:07 -04:00
|
|
|
const Consensus::Params& consensus_params,
|
2021-04-13 10:05:28 -04:00
|
|
|
CCoinsView& coinsview,
|
2021-04-13 09:57:20 -04:00
|
|
|
int nCheckLevel,
|
|
|
|
int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2014-05-23 18:04:09 +02:00
|
|
|
};
|
|
|
|
|
2019-03-27 10:20:41 -04:00
|
|
|
enum DisconnectResult
|
|
|
|
{
|
|
|
|
DISCONNECT_OK, // All good.
|
|
|
|
DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
|
|
|
|
DISCONNECT_FAILED // Something else went wrong.
|
|
|
|
};
|
|
|
|
|
|
|
|
class ConnectTrace;
|
|
|
|
|
2022-03-09 12:37:19 -05:00
|
|
|
/** @see Chainstate::FlushStateToDisk */
|
2019-03-27 12:07:52 -04:00
|
|
|
enum class FlushStateMode {
|
|
|
|
NONE,
|
|
|
|
IF_NEEDED,
|
|
|
|
PERIODIC,
|
|
|
|
ALWAYS
|
|
|
|
};
|
|
|
|
|
2019-07-24 13:23:48 -04:00
|
|
|
/**
|
|
|
|
* A convenience class for constructing the CCoinsView* hierarchy used
|
|
|
|
* to facilitate access to the UTXO set.
|
|
|
|
*
|
|
|
|
* This class consists of an arrangement of layered CCoinsView objects,
|
|
|
|
* preferring to store and retrieve coins in memory via `m_cacheview` but
|
|
|
|
* ultimately falling back on cache misses to the canonical store of UTXOs on
|
|
|
|
* disk, `m_dbview`.
|
|
|
|
*/
|
|
|
|
class CoinsViews {
|
|
|
|
|
|
|
|
public:
|
|
|
|
//! The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
|
|
|
|
//! All unspent coins reside in this store.
|
2019-07-24 13:39:42 -04:00
|
|
|
CCoinsViewDB m_dbview GUARDED_BY(cs_main);
|
2019-07-24 13:23:48 -04:00
|
|
|
|
|
|
|
//! This view wraps access to the leveldb instance and handles read errors gracefully.
|
2019-07-24 13:39:42 -04:00
|
|
|
CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main);
|
2019-07-24 13:23:48 -04:00
|
|
|
|
|
|
|
//! This is the top layer of the cache hierarchy - it keeps as many coins in memory as
|
|
|
|
//! can fit per the dbcache setting.
|
2019-07-24 13:39:42 -04:00
|
|
|
std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
|
2019-07-24 13:23:48 -04:00
|
|
|
|
|
|
|
//! This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it
|
|
|
|
//! *does not* create a CCoinsViewCache instance by default. This is done separately because the
|
|
|
|
//! presence of the cache has implications on whether or not we're allowed to flush the cache's
|
|
|
|
//! state to disk, which should not be done until the health of the database is verified.
|
|
|
|
//!
|
|
|
|
//! All arguments forwarded onto CCoinsViewDB.
|
2022-03-03 14:40:18 -05:00
|
|
|
CoinsViews(fs::path ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe);
|
2019-07-24 13:23:48 -04:00
|
|
|
|
|
|
|
//! Initialize the CCoinsViewCache member.
|
2019-07-24 13:39:42 -04:00
|
|
|
void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
2019-07-24 13:23:48 -04:00
|
|
|
};
|
2019-07-24 11:45:04 -04:00
|
|
|
|
2019-04-16 16:40:40 -04:00
|
|
|
enum class CoinsCacheSizeState
|
|
|
|
{
|
|
|
|
//! The coins cache is in immediate need of a flush.
|
|
|
|
CRITICAL = 2,
|
|
|
|
//! The cache is at >= 90% capacity.
|
|
|
|
LARGE = 1,
|
|
|
|
OK = 0
|
|
|
|
};
|
|
|
|
|
2019-03-27 17:07:32 -04:00
|
|
|
/**
|
2022-03-09 12:37:19 -05:00
|
|
|
* Chainstate stores and provides an API to update our local knowledge of the
|
2019-03-27 17:07:32 -04:00
|
|
|
* current best chain.
|
2019-03-27 10:20:41 -04:00
|
|
|
*
|
|
|
|
* Eventually, the API here is targeted at being exposed externally as a
|
|
|
|
* consumable libconsensus library, so any functions added must only call
|
|
|
|
* other class member functions, pure functions in other parts of the consensus
|
|
|
|
* library, callbacks via the validation interface, or read/write-to-disk
|
|
|
|
* functions (eventually this will also be via callbacks).
|
2019-03-27 17:07:32 -04:00
|
|
|
*
|
|
|
|
* Anything that is contingent on the current tip of the chain is stored here,
|
|
|
|
* whereas block information and metadata independent of the current tip is
|
2021-04-28 09:16:48 +02:00
|
|
|
* kept in `BlockManager`.
|
2019-03-27 10:20:41 -04:00
|
|
|
*/
|
2022-03-09 12:37:19 -05:00
|
|
|
class Chainstate
|
2020-11-06 15:03:51 +01:00
|
|
|
{
|
|
|
|
protected:
|
2019-03-27 10:20:41 -04:00
|
|
|
/**
|
|
|
|
* Every received block is assigned a unique and increasing identifier, so we
|
|
|
|
* know which one to give priority in case of a fork.
|
|
|
|
*/
|
|
|
|
/** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
|
2021-08-28 11:51:36 +02:00
|
|
|
int32_t nBlockSequenceId GUARDED_BY(::cs_main) = 1;
|
2019-03-27 10:20:41 -04:00
|
|
|
/** Decreasing counter (used by subsequent preciousblock calls). */
|
|
|
|
int32_t nBlockReverseSequenceId = -1;
|
|
|
|
/** chainwork for the last block that preciousblock has been applied to. */
|
|
|
|
arith_uint256 nLastPreciousChainwork = 0;
|
|
|
|
|
|
|
|
/**
|
2022-01-19 14:45:49 -03:00
|
|
|
* The ChainState Mutex
|
|
|
|
* A lock that must be held when modifying this ChainState - held in ActivateBestChain() and
|
|
|
|
* InvalidateBlock()
|
2019-03-27 10:20:41 -04:00
|
|
|
*/
|
2022-01-19 14:45:49 -03:00
|
|
|
Mutex m_chainstate_mutex;
|
2019-03-27 10:20:41 -04:00
|
|
|
|
2019-03-27 12:21:50 -04:00
|
|
|
/**
|
|
|
|
* Whether this chainstate is undergoing initial block download.
|
|
|
|
*
|
|
|
|
* Mutable because we need to be able to mark IsInitialBlockDownload()
|
|
|
|
* const, which latches this for caching purposes.
|
|
|
|
*/
|
|
|
|
mutable std::atomic<bool> m_cached_finished_ibd{false};
|
|
|
|
|
2021-07-06 17:05:25 -04:00
|
|
|
//! Optional mempool that is kept in sync with the chain.
|
|
|
|
//! Only the active chainstate has a mempool.
|
|
|
|
CTxMemPool* m_mempool;
|
2020-07-28 07:40:49 +02:00
|
|
|
|
2019-07-24 13:23:48 -04:00
|
|
|
//! Manages the UTXO set, which is a reflection of the contents of `m_chain`.
|
|
|
|
std::unique_ptr<CoinsViews> m_coins_views;
|
|
|
|
|
2022-02-02 14:40:47 -05:00
|
|
|
//! This toggle exists for use when doing background validation for UTXO
|
|
|
|
//! snapshots.
|
|
|
|
//!
|
|
|
|
//! In the expected case, it is set once the background validation chain reaches the
|
|
|
|
//! same height as the base of the snapshot and its UTXO set is found to hash to
|
|
|
|
//! the expected assumeutxo value. It signals that we should no longer connect
|
|
|
|
//! blocks to the background chainstate. When set on the background validation
|
|
|
|
//! chainstate, it signifies that we have fully validated the snapshot chainstate.
|
|
|
|
//!
|
|
|
|
//! In the unlikely case that the snapshot chainstate is found to be invalid, this
|
|
|
|
//! is set to true on the snapshot chainstate.
|
|
|
|
bool m_disabled GUARDED_BY(::cs_main) {false};
|
|
|
|
|
2019-03-27 10:20:41 -04:00
|
|
|
public:
|
2020-09-02 16:05:54 -04:00
|
|
|
//! Reference to a BlockManager instance which itself is shared across all
|
2022-03-09 12:37:19 -05:00
|
|
|
//! Chainstate instances.
|
2021-11-12 10:06:00 -05:00
|
|
|
node::BlockManager& m_blockman;
|
2020-09-02 16:05:54 -04:00
|
|
|
|
2021-06-12 10:52:40 -04:00
|
|
|
//! The chainstate manager that owns this chainstate. The reference is
|
|
|
|
//! necessary so that this instance can check whether it is the active
|
|
|
|
//! chainstate within deeply nested method calls.
|
|
|
|
ChainstateManager& m_chainman;
|
|
|
|
|
2022-03-09 12:37:19 -05:00
|
|
|
explicit Chainstate(
|
2021-07-06 17:05:25 -04:00
|
|
|
CTxMemPool* mempool,
|
2021-11-12 10:06:00 -05:00
|
|
|
node::BlockManager& blockman,
|
2021-06-12 10:52:40 -04:00
|
|
|
ChainstateManager& chainman,
|
2021-07-06 17:05:25 -04:00
|
|
|
std::optional<uint256> from_snapshot_blockhash = std::nullopt);
|
2019-07-24 13:23:48 -04:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Initialize the CoinsViews UTXO set database management data structures. The in-memory
|
|
|
|
* cache is initialized separately.
|
|
|
|
*
|
|
|
|
* All parameters forwarded to CoinsViews.
|
|
|
|
*/
|
|
|
|
void InitCoinsDB(
|
|
|
|
size_t cache_size_bytes,
|
|
|
|
bool in_memory,
|
|
|
|
bool should_wipe,
|
2022-03-03 14:40:18 -05:00
|
|
|
fs::path leveldb_name = "chainstate");
|
2019-07-24 13:23:48 -04:00
|
|
|
|
|
|
|
//! Initialize the in-memory coins cache (to be done after the health of the on-disk database
|
|
|
|
//! is verified).
|
2019-09-16 15:01:12 -04:00
|
|
|
void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
2019-07-24 13:23:48 -04:00
|
|
|
|
|
|
|
//! @returns whether or not the CoinsViews object has been fully initialized and we can
|
|
|
|
//! safely flush this object to disk.
|
2022-01-27 12:37:50 +01:00
|
|
|
bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
|
|
|
|
{
|
|
|
|
AssertLockHeld(::cs_main);
|
2019-07-24 13:23:48 -04:00
|
|
|
return m_coins_views && m_coins_views->m_cacheview;
|
|
|
|
}
|
2019-03-27 17:07:32 -04:00
|
|
|
|
2019-03-27 10:20:41 -04:00
|
|
|
//! The current chain of blockheaders we consult and build on.
|
|
|
|
//! @see CChain, CBlockIndex.
|
|
|
|
CChain m_chain;
|
2019-07-24 13:23:48 -04:00
|
|
|
|
2019-12-11 16:41:40 -05:00
|
|
|
/**
|
|
|
|
* The blockhash which is the base of the snapshot this chainstate was created from.
|
|
|
|
*
|
2021-04-03 17:26:39 +02:00
|
|
|
* std::nullopt if this chainstate was not created from a snapshot.
|
2019-12-11 16:41:40 -05:00
|
|
|
*/
|
2021-04-03 17:26:39 +02:00
|
|
|
const std::optional<uint256> m_from_snapshot_blockhash;
|
2019-12-11 16:41:40 -05:00
|
|
|
|
2021-10-28 16:07:46 -04:00
|
|
|
//! Return true if this chainstate relies on blocks that are assumed-valid. In
|
|
|
|
//! practice this means it was created based on a UTXO snapshot.
|
|
|
|
bool reliesOnAssumedValid() { return m_from_snapshot_blockhash.has_value(); }
|
|
|
|
|
2019-03-27 17:07:32 -04:00
|
|
|
/**
|
2021-07-21 14:13:33 -04:00
|
|
|
* The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for
|
|
|
|
* itself and all ancestors) *or* BLOCK_ASSUMED_VALID (if using background
|
|
|
|
* chainstates) and as good as our current tip or better. Entries may be failed,
|
|
|
|
* though, and pruning nodes may be missing the data for the block.
|
2019-03-27 17:07:32 -04:00
|
|
|
*/
|
2021-11-12 10:06:00 -05:00
|
|
|
std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates;
|
2019-03-27 10:20:41 -04:00
|
|
|
|
2019-07-24 11:45:04 -04:00
|
|
|
//! @returns A reference to the in-memory cache of the UTXO set.
|
2022-01-27 12:37:50 +01:00
|
|
|
CCoinsViewCache& CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
|
2019-07-24 11:45:04 -04:00
|
|
|
{
|
2022-01-27 12:37:50 +01:00
|
|
|
AssertLockHeld(::cs_main);
|
2019-07-24 13:23:48 -04:00
|
|
|
assert(m_coins_views->m_cacheview);
|
|
|
|
return *m_coins_views->m_cacheview.get();
|
|
|
|
}
|
|
|
|
|
|
|
|
//! @returns A reference to the on-disk UTXO set database.
|
2022-01-27 12:37:50 +01:00
|
|
|
CCoinsViewDB& CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
|
2019-07-24 13:23:48 -04:00
|
|
|
{
|
2022-01-27 12:37:50 +01:00
|
|
|
AssertLockHeld(::cs_main);
|
2019-07-24 13:23:48 -04:00
|
|
|
return m_coins_views->m_dbview;
|
2019-07-24 11:45:04 -04:00
|
|
|
}
|
|
|
|
|
2021-12-02 01:50:27 -03:00
|
|
|
//! @returns A pointer to the mempool.
|
|
|
|
CTxMemPool* GetMempool()
|
|
|
|
{
|
|
|
|
return m_mempool;
|
|
|
|
}
|
|
|
|
|
2019-07-24 13:23:48 -04:00
|
|
|
//! @returns A reference to a wrapped view of the in-memory UTXO set that
|
|
|
|
//! handles disk read errors gracefully.
|
2022-01-27 12:37:50 +01:00
|
|
|
CCoinsViewErrorCatcher& CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
|
2019-07-24 13:23:48 -04:00
|
|
|
{
|
2022-01-27 12:37:50 +01:00
|
|
|
AssertLockHeld(::cs_main);
|
2019-07-24 13:23:48 -04:00
|
|
|
return m_coins_views->m_catcherview;
|
|
|
|
}
|
|
|
|
|
|
|
|
//! Destructs all objects related to accessing the UTXO set.
|
|
|
|
void ResetCoinsViews() { m_coins_views.reset(); }
|
|
|
|
|
2019-09-16 15:01:12 -04:00
|
|
|
//! The cache size of the on-disk coins view.
|
|
|
|
size_t m_coinsdb_cache_size_bytes{0};
|
|
|
|
|
|
|
|
//! The cache size of the in-memory coins view.
|
|
|
|
size_t m_coinstip_cache_size_bytes{0};
|
|
|
|
|
|
|
|
//! Resize the CoinsViews caches dynamically and flush state to disk.
|
|
|
|
//! @returns true unless an error occurred during the flush.
|
|
|
|
bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
|
|
|
|
EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
|
|
|
|
2020-07-26 23:43:01 +03:00
|
|
|
/**
|
|
|
|
* Import blocks from an external file
|
|
|
|
*
|
|
|
|
* During reindexing, this function is called for each block file (datadir/blocks/blk?????.dat).
|
|
|
|
* It reads all blocks contained in the given file and attempts to process them (add them to the
|
|
|
|
* block index). The blocks may be out of order within each file and across files. Often this
|
|
|
|
* function reads a block but finds that its parent hasn't been read yet, so the block can't be
|
|
|
|
* processed yet. The function will add an entry to the blocks_with_unknown_parent map (which is
|
|
|
|
* passed as an argument), so that when the block's parent is later read and processed, this
|
|
|
|
* function can re-read the child block from disk and process it.
|
|
|
|
*
|
|
|
|
* Because a block's parent may be in a later file, not just later in the same file, the
|
|
|
|
* blocks_with_unknown_parent map must be passed in and out with each call. It's a multimap,
|
|
|
|
* rather than just a map, because multiple blocks may have the same parent (when chain splits
|
|
|
|
* or stale blocks exist). It maps from parent-hash to child-disk-position.
|
|
|
|
*
|
|
|
|
* This function can also be used to read blocks from user-specified block files using the
|
|
|
|
* -loadblock= option. There's no unknown-parent tracking, so the last two arguments are omitted.
|
|
|
|
*
|
|
|
|
*
|
|
|
|
* @param[in] fileIn FILE handle to file containing blocks to read
|
|
|
|
* @param[in] dbp (optional) Disk block position (only for reindex)
|
|
|
|
* @param[in,out] blocks_with_unknown_parent (optional) Map of disk positions for blocks with
|
|
|
|
* unknown parent, key is parent block hash
|
|
|
|
* (only used for reindex)
|
|
|
|
* */
|
|
|
|
void LoadExternalBlockFile(
|
|
|
|
FILE* fileIn,
|
|
|
|
FlatFilePos* dbp = nullptr,
|
|
|
|
std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr)
|
2022-02-02 09:08:00 +01:00
|
|
|
EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex);
|
2020-08-25 17:17:22 -04:00
|
|
|
|
2019-03-27 12:07:52 -04:00
|
|
|
/**
|
|
|
|
* Update the on-disk chain state.
|
|
|
|
* The caches and indexes are flushed depending on the mode we're called with
|
|
|
|
* if they're too large, if it's been a while since the last write,
|
|
|
|
* or always and in all cases if we're in prune mode and are deleting files.
|
|
|
|
*
|
|
|
|
* If FlushStateMode::NONE is used, then FlushStateToDisk(...) won't do anything
|
|
|
|
* besides checking if we need to prune.
|
2019-08-29 12:42:00 -04:00
|
|
|
*
|
|
|
|
* @returns true unless a system error occurred
|
2019-03-27 12:07:52 -04:00
|
|
|
*/
|
|
|
|
bool FlushStateToDisk(
|
2021-04-27 22:54:53 +02:00
|
|
|
BlockValidationState& state,
|
2019-03-27 12:07:52 -04:00
|
|
|
FlushStateMode mode,
|
|
|
|
int nManualPruneHeight = 0);
|
|
|
|
|
|
|
|
//! Unconditionally flush all changes to disk.
|
|
|
|
void ForceFlushStateToDisk();
|
|
|
|
|
|
|
|
//! Prune blockfiles from the disk if necessary and then flush chainstate changes
|
|
|
|
//! if we pruned.
|
|
|
|
void PruneAndFlush();
|
|
|
|
|
2019-09-10 15:50:16 +03:00
|
|
|
/**
|
2021-01-20 14:28:48 -05:00
|
|
|
* Find the best known block, and make it the tip of the block chain. The
|
|
|
|
* result is either failure or an activated best chain. pblock is either
|
|
|
|
* nullptr or a pointer to a block that is already loaded (to avoid loading
|
|
|
|
* it again from disk).
|
2019-09-10 15:50:16 +03:00
|
|
|
*
|
|
|
|
* ActivateBestChain is split into steps (see ActivateBestChainStep) so that
|
|
|
|
* we avoid holding cs_main for an extended period of time; the length of this
|
|
|
|
* call may be quite long during reindexing or a substantial reorg.
|
|
|
|
*
|
2019-03-29 14:09:00 -04:00
|
|
|
* May not be called with cs_main held. May not be called in a
|
|
|
|
* validationinterface callback.
|
|
|
|
*
|
2019-09-10 15:50:16 +03:00
|
|
|
* @returns true unless a system error occurred
|
|
|
|
*/
|
2019-03-29 14:09:00 -04:00
|
|
|
bool ActivateBestChain(
|
2019-10-24 11:35:42 -04:00
|
|
|
BlockValidationState& state,
|
2022-02-02 09:08:00 +01:00
|
|
|
std::shared_ptr<const CBlock> pblock = nullptr)
|
|
|
|
EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
|
|
|
|
LOCKS_EXCLUDED(::cs_main);
|
2019-03-27 10:20:41 -04:00
|
|
|
|
2022-08-02 16:48:57 -04:00
|
|
|
bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2019-03-27 10:20:41 -04:00
|
|
|
|
|
|
|
// Block (dis)connection on a given view:
|
2021-12-03 10:34:07 -05:00
|
|
|
DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
|
|
|
|
EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
2019-10-24 11:35:42 -04:00
|
|
|
bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
|
2021-04-27 22:54:53 +02:00
|
|
|
CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2019-03-27 10:20:41 -04:00
|
|
|
|
2019-07-24 13:23:48 -04:00
|
|
|
// Apply the effects of a block disconnection on the UTXO set.
|
2021-07-06 17:05:25 -04:00
|
|
|
bool DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
|
2019-03-27 10:20:41 -04:00
|
|
|
|
|
|
|
// Manual block validity manipulation:
|
2020-09-15 15:10:57 -04:00
|
|
|
/** Mark a block as precious and reorganize.
|
|
|
|
*
|
|
|
|
* May not be called in a validationinterface callback.
|
|
|
|
*/
|
2022-02-02 09:08:00 +01:00
|
|
|
bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
|
|
|
|
EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
|
|
|
|
LOCKS_EXCLUDED(::cs_main);
|
|
|
|
|
2020-09-15 15:10:57 -04:00
|
|
|
/** Mark a block as invalid. */
|
2022-02-02 09:08:00 +01:00
|
|
|
bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
|
|
|
|
EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
|
|
|
|
LOCKS_EXCLUDED(::cs_main);
|
|
|
|
|
2020-09-15 15:10:57 -04:00
|
|
|
/** Remove invalidity status from a block and its descendants. */
|
2019-03-27 10:20:41 -04:00
|
|
|
void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
|
|
|
|
2019-03-29 16:43:59 -04:00
|
|
|
/** Replay blocks that aren't fully applied to the database. */
|
2021-04-27 22:54:53 +02:00
|
|
|
bool ReplayBlocks();
|
2021-01-24 15:14:15 -08:00
|
|
|
|
|
|
|
/** Whether the chain state needs to be redownloaded due to lack of witness data */
|
2021-04-27 22:54:53 +02:00
|
|
|
[[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2021-03-08 15:48:42 -05:00
|
|
|
/** Ensures we have a genesis block in the block tree, possibly writing one to disk. */
|
2021-04-27 22:54:53 +02:00
|
|
|
bool LoadGenesisBlock();
|
2019-03-27 10:20:41 -04:00
|
|
|
|
|
|
|
void PruneBlockIndexCandidates();
|
|
|
|
|
2021-08-28 11:51:36 +02:00
|
|
|
void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
2019-03-27 10:20:41 -04:00
|
|
|
|
2019-03-27 12:21:50 -04:00
|
|
|
/** Check whether we are doing an initial block download (synchronizing from disk or network) */
|
|
|
|
bool IsInitialBlockDownload() const;
|
|
|
|
|
2021-11-23 18:07:00 +01:00
|
|
|
/** Find the last common block of this chain and a locator. */
|
2022-03-02 15:42:57 +10:00
|
|
|
const CBlockIndex* FindForkInGlobalIndex(const CBlockLocator& locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2021-11-23 18:07:00 +01:00
|
|
|
|
2019-03-27 10:20:41 -04:00
|
|
|
/**
|
|
|
|
* Make various assertions about the state of the block index.
|
|
|
|
*
|
2022-07-26 12:59:48 +02:00
|
|
|
* By default this only executes fully when using the Regtest chain; see: m_options.check_block_index.
|
2019-03-27 10:20:41 -04:00
|
|
|
*/
|
2021-04-27 22:54:53 +02:00
|
|
|
void CheckBlockIndex();
|
2020-07-19 09:07:54 +02:00
|
|
|
|
|
|
|
/** Load the persisted mempool from disk */
|
2022-07-12 21:42:00 -04:00
|
|
|
void LoadMempool(const fs::path& load_path, fsbridge::FopenFn mockable_fopen_function = fsbridge::fopen);
|
2019-03-27 10:20:41 -04:00
|
|
|
|
2019-03-29 14:09:55 -04:00
|
|
|
/** Update the chain tip based on database information, i.e. CoinsTip()'s best block. */
|
2021-04-27 22:54:53 +02:00
|
|
|
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2019-03-29 14:09:55 -04:00
|
|
|
|
2019-04-16 16:40:40 -04:00
|
|
|
//! Dictates whether we need to flush the cache to disk or not.
|
|
|
|
//!
|
|
|
|
//! @return the state of the size of the coins cache.
|
2021-07-09 09:24:27 -04:00
|
|
|
CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
2019-04-16 16:40:40 -04:00
|
|
|
|
|
|
|
CoinsCacheSizeState GetCoinsCacheSizeState(
|
|
|
|
size_t max_coins_cache_size_bytes,
|
|
|
|
size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
|
|
|
|
2019-12-12 10:20:44 -05:00
|
|
|
std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
|
|
|
|
2019-03-27 17:07:32 -04:00
|
|
|
private:
|
2021-07-06 17:05:25 -04:00
|
|
|
bool ActivateBestChainStep(BlockValidationState& state, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
|
|
|
|
bool ConnectTip(BlockValidationState& state, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions& disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
|
2019-03-27 17:07:32 -04:00
|
|
|
|
2021-04-27 22:54:53 +02:00
|
|
|
void InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2019-03-27 10:20:41 -04:00
|
|
|
CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2021-04-27 22:54:53 +02:00
|
|
|
void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2019-03-27 10:20:41 -04:00
|
|
|
|
2021-04-27 22:54:53 +02:00
|
|
|
bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2019-03-27 10:20:41 -04:00
|
|
|
|
2020-10-05 15:14:35 -04:00
|
|
|
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
|
|
|
void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
|
|
|
|
2021-07-06 17:05:25 -04:00
|
|
|
//! Indirection necessary to make lock annotations work with an optional mempool.
|
|
|
|
RecursiveMutex* MempoolMutex() const LOCK_RETURNED(m_mempool->cs)
|
|
|
|
{
|
|
|
|
return m_mempool ? &m_mempool->cs : nullptr;
|
|
|
|
}
|
|
|
|
|
2021-07-09 13:06:19 -04:00
|
|
|
/**
|
|
|
|
* Make mempool consistent after a reorg, by re-adding or recursively erasing
|
|
|
|
* disconnected block transactions from the mempool, and also removing any
|
|
|
|
* other transactions from the mempool that are no longer valid given the new
|
|
|
|
* tip/height.
|
|
|
|
*
|
|
|
|
* Note: we assume that disconnectpool only contains transactions that are NOT
|
|
|
|
* confirmed in the current chain nor already in the mempool (otherwise,
|
|
|
|
* in-mempool descendants of such transactions would be removed).
|
|
|
|
*
|
|
|
|
* Passing fAddToMempool=false will skip trying to add the transactions back,
|
|
|
|
* and instead just erase from the mempool as needed.
|
|
|
|
*/
|
|
|
|
void MaybeUpdateMempoolForReorg(
|
|
|
|
DisconnectedBlockTransactions& disconnectpool,
|
|
|
|
bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
|
|
|
|
|
2021-07-09 09:34:39 -04:00
|
|
|
/** Check warning conditions and do some notifications on new chain tip set. */
|
|
|
|
void UpdateTip(const CBlockIndex* pindexNew)
|
|
|
|
EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
|
|
|
|
2022-11-16 16:51:53 +01:00
|
|
|
std::chrono::microseconds m_last_write{0};
|
|
|
|
std::chrono::microseconds m_last_flush{0};
|
|
|
|
|
2019-12-12 10:20:44 -05:00
|
|
|
friend ChainstateManager;
|
2019-03-27 10:20:41 -04:00
|
|
|
};
|
|
|
|
|
2019-12-12 10:20:44 -05:00
|
|
|
/**
|
|
|
|
* Provides an interface for creating and interacting with one or two
|
|
|
|
* chainstates: an IBD chainstate generated by downloading blocks, and
|
|
|
|
* an optional snapshot chainstate loaded from a UTXO snapshot. Managed
|
|
|
|
* chainstates can be maintained at different heights simultaneously.
|
|
|
|
*
|
|
|
|
* This class provides abstractions that allow the retrieval of the current
|
|
|
|
* most-work chainstate ("Active") as well as chainstates which may be in
|
|
|
|
* background use to validate UTXO snapshots.
|
|
|
|
*
|
|
|
|
* Definitions:
|
|
|
|
*
|
|
|
|
* *IBD chainstate*: a chainstate whose current state has been "fully"
|
|
|
|
* validated by the initial block download process.
|
|
|
|
*
|
|
|
|
* *Snapshot chainstate*: a chainstate populated by loading in an
|
|
|
|
* assumeutxo UTXO snapshot.
|
|
|
|
*
|
|
|
|
* *Active chainstate*: the chainstate containing the current most-work
|
|
|
|
* chain. Consulted by most parts of the system (net_processing,
|
|
|
|
* wallet) as a reflection of the current chain and UTXO set.
|
|
|
|
* This may either be an IBD chainstate or a snapshot chainstate.
|
|
|
|
*
|
|
|
|
* *Background IBD chainstate*: an IBD chainstate for which the
|
|
|
|
* IBD process is happening in the background while use of the
|
|
|
|
* active (snapshot) chainstate allows the rest of the system to function.
|
|
|
|
*/
|
|
|
|
class ChainstateManager
|
|
|
|
{
|
|
|
|
private:
|
|
|
|
//! The chainstate used under normal operation (i.e. "regular" IBD) or, if
|
|
|
|
//! a snapshot is in use, for background validation.
|
|
|
|
//!
|
|
|
|
//! Its contents (including on-disk data) will be deleted *upon shutdown*
|
|
|
|
//! after background validation of the snapshot has completed. We do not
|
|
|
|
//! free the chainstate contents immediately after it finishes validation
|
|
|
|
//! to cautiously avoid a case where some other part of the system is still
|
|
|
|
//! using this pointer (e.g. net_processing).
|
2020-01-29 09:57:56 -05:00
|
|
|
//!
|
|
|
|
//! Once this pointer is set to a corresponding chainstate, it will not
|
2021-02-11 22:02:44 -06:00
|
|
|
//! be reset until init.cpp:Shutdown().
|
2020-01-29 09:57:56 -05:00
|
|
|
//!
|
|
|
|
//! This is especially important when, e.g., calling ActivateBestChain()
|
|
|
|
//! on all chainstates because we are not able to hold ::cs_main going into
|
|
|
|
//! that call.
|
2022-03-09 12:37:19 -05:00
|
|
|
std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
|
2019-12-12 10:20:44 -05:00
|
|
|
|
|
|
|
//! A chainstate initialized on the basis of a UTXO snapshot. If this is
|
|
|
|
//! non-null, it is always our active chainstate.
|
2020-01-29 09:57:56 -05:00
|
|
|
//!
|
|
|
|
//! Once this pointer is set to a corresponding chainstate, it will not
|
2021-02-11 22:02:44 -06:00
|
|
|
//! be reset until init.cpp:Shutdown().
|
2020-01-29 09:57:56 -05:00
|
|
|
//!
|
|
|
|
//! This is especially important when, e.g., calling ActivateBestChain()
|
|
|
|
//! on all chainstates because we are not able to hold ::cs_main going into
|
|
|
|
//! that call.
|
2022-03-09 12:37:19 -05:00
|
|
|
std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
|
2019-12-12 10:20:44 -05:00
|
|
|
|
|
|
|
//! Points to either the ibd or snapshot chainstate; indicates our
|
|
|
|
//! most-work chain.
|
2020-01-29 09:57:56 -05:00
|
|
|
//!
|
|
|
|
//! Once this pointer is set to a corresponding chainstate, it will not
|
2021-02-11 22:02:44 -06:00
|
|
|
//! be reset until init.cpp:Shutdown().
|
2020-01-29 09:57:56 -05:00
|
|
|
//!
|
|
|
|
//! This is especially important when, e.g., calling ActivateBestChain()
|
|
|
|
//! on all chainstates because we are not able to hold ::cs_main going into
|
|
|
|
//! that call.
|
2022-03-09 12:37:19 -05:00
|
|
|
Chainstate* m_active_chainstate GUARDED_BY(::cs_main) {nullptr};
|
2019-12-12 10:20:44 -05:00
|
|
|
|
2022-04-15 07:47:20 +10:00
|
|
|
CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr};
|
2021-11-23 19:49:48 +01:00
|
|
|
|
2020-08-25 13:50:23 -04:00
|
|
|
//! Internal helper for ActivateSnapshot().
|
|
|
|
[[nodiscard]] bool PopulateAndValidateSnapshot(
|
2022-03-09 12:37:19 -05:00
|
|
|
Chainstate& snapshot_chainstate,
|
2022-06-06 17:22:59 +02:00
|
|
|
AutoFile& coins_file,
|
2021-11-12 10:06:00 -05:00
|
|
|
const node::SnapshotMetadata& metadata);
|
2020-08-25 13:50:23 -04:00
|
|
|
|
2021-11-23 20:05:07 +01:00
|
|
|
/**
|
|
|
|
* If a block header hasn't already been seen, call CheckBlockHeader on it, ensure
|
|
|
|
* that it doesn't descend from an invalid block, and then add it to m_block_index.
|
2022-08-02 16:48:57 -04:00
|
|
|
* Caller must set min_pow_checked=true in order to add a new header to the
|
|
|
|
* block index (permanent memory storage), indicating that the header is
|
|
|
|
* known to be part of a sufficiently high-work chain (anti-dos check).
|
2021-11-23 20:05:07 +01:00
|
|
|
*/
|
|
|
|
bool AcceptBlockHeader(
|
|
|
|
const CBlockHeader& block,
|
|
|
|
BlockValidationState& state,
|
2022-08-02 16:48:57 -04:00
|
|
|
CBlockIndex** ppindex,
|
|
|
|
bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2022-03-09 12:37:19 -05:00
|
|
|
friend Chainstate;
|
2021-11-23 20:05:07 +01:00
|
|
|
|
2022-08-12 17:29:52 -04:00
|
|
|
/** Most recent headers presync progress update, for rate-limiting. */
|
|
|
|
std::chrono::time_point<std::chrono::steady_clock> m_last_presync_update GUARDED_BY(::cs_main) {};
|
|
|
|
|
2021-10-28 16:59:18 -04:00
|
|
|
//! Returns nullptr if no snapshot has been loaded.
|
|
|
|
const CBlockIndex* GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
|
|
|
|
|
|
|
//! Return the height of the base block of the snapshot in use, if one exists, else
|
|
|
|
//! nullopt.
|
|
|
|
std::optional<int> GetSnapshotBaseHeight() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
|
|
|
|
2022-02-02 14:40:47 -05:00
|
|
|
//! Return true if a chainstate is considered usable.
|
|
|
|
//!
|
|
|
|
//! This is false when a background validation chainstate has completed its
|
|
|
|
//! validation of an assumed-valid chainstate, or when a snapshot
|
|
|
|
//! chainstate has been found to be invalid.
|
|
|
|
bool IsUsable(const Chainstate* const cs) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
|
|
|
|
return cs && !cs->m_disabled;
|
|
|
|
}
|
|
|
|
|
2019-12-12 10:20:44 -05:00
|
|
|
public:
|
2022-07-13 14:15:11 -04:00
|
|
|
using Options = kernel::ChainstateManagerOpts;
|
2022-03-01 16:14:12 -05:00
|
|
|
|
2022-07-20 22:00:11 +02:00
|
|
|
explicit ChainstateManager(Options options);
|
2022-01-18 21:34:16 +10:00
|
|
|
|
2022-08-22 13:19:15 -04:00
|
|
|
const CChainParams& GetParams() const { return m_options.chainparams; }
|
|
|
|
const Consensus::Params& GetConsensus() const { return m_options.chainparams.GetConsensus(); }
|
2022-07-26 12:59:48 +02:00
|
|
|
bool ShouldCheckBlockIndex() const { return *Assert(m_options.check_block_index); }
|
2022-07-21 11:13:13 +02:00
|
|
|
const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); }
|
2022-07-20 22:00:11 +02:00
|
|
|
const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); }
|
2022-01-18 21:34:16 +10:00
|
|
|
|
2022-07-12 17:45:49 +02:00
|
|
|
/**
|
|
|
|
* Alias for ::cs_main.
|
|
|
|
* Should be used in new code to make it easier to make ::cs_main a member
|
|
|
|
* of this class.
|
|
|
|
* Generally, methods of this class should be annotated to require this
|
|
|
|
* mutex. This will make calling code more verbose, but also help to:
|
|
|
|
* - Clarify that the method will acquire a mutex that heavily affects
|
|
|
|
* overall performance.
|
|
|
|
* - Force call sites to think how long they need to acquire the mutex to
|
|
|
|
* get consistent results.
|
|
|
|
*/
|
|
|
|
RecursiveMutex& GetMutex() const LOCK_RETURNED(::cs_main) { return ::cs_main; }
|
|
|
|
|
2022-08-22 13:19:15 -04:00
|
|
|
const Options m_options;
|
2021-04-02 20:38:28 +02:00
|
|
|
std::thread m_load_block;
|
2019-12-12 10:48:28 -05:00
|
|
|
//! A single BlockManager instance is shared across each constructed
|
|
|
|
//! chainstate to avoid duplicating block metadata.
|
2022-01-10 15:26:13 -05:00
|
|
|
node::BlockManager m_blockman;
|
2019-12-12 10:48:28 -05:00
|
|
|
|
2021-11-23 19:44:38 +01:00
|
|
|
/**
|
|
|
|
* In order to efficiently track invalidity of headers, we keep the set of
|
|
|
|
* blocks which we tried to connect and found to be invalid here (ie which
|
|
|
|
* were set to BLOCK_FAILED_VALID since the last restart). We can then
|
|
|
|
* walk this set and check if a new header is a descendant of something in
|
|
|
|
* this set, preventing us from having to walk m_block_index when we try
|
|
|
|
* to connect a bad block and fail.
|
|
|
|
*
|
|
|
|
* While this is more complicated than marking everything which descends
|
|
|
|
* from an invalid block as invalid at the time we discover it to be
|
|
|
|
* invalid, doing so would require walking all of m_block_index to find all
|
|
|
|
* descendants. Since this case should be very rare, keeping track of all
|
|
|
|
* BLOCK_FAILED_VALID blocks in a set should be just fine and work just as
|
|
|
|
* well.
|
|
|
|
*
|
|
|
|
* Because we already walk m_block_index in height-order at startup, we go
|
|
|
|
* ahead and mark descendants of invalid blocks as FAILED_CHILD at that time,
|
|
|
|
* instead of putting things in this set.
|
|
|
|
*/
|
|
|
|
std::set<CBlockIndex*> m_failed_blocks;
|
|
|
|
|
2020-12-24 16:18:46 -05:00
|
|
|
/** Best header we've seen so far (used for getheaders queries' starting points). */
|
2022-03-18 12:35:52 -04:00
|
|
|
CBlockIndex* m_best_header = nullptr;
|
2020-12-24 16:18:46 -05:00
|
|
|
|
2019-09-16 13:37:29 -04:00
|
|
|
//! The total number of bytes available for us to use across all in-memory
|
|
|
|
//! coins caches. This will be split somehow across chainstates.
|
|
|
|
int64_t m_total_coinstip_cache{0};
|
|
|
|
//
|
|
|
|
//! The total number of bytes available for us to use across all leveldb
|
|
|
|
//! coins databases. This will be split somehow across chainstates.
|
|
|
|
int64_t m_total_coinsdb_cache{0};
|
|
|
|
|
2022-04-20 17:40:01 -04:00
|
|
|
//! Instantiate a new chainstate.
|
2019-12-12 10:20:44 -05:00
|
|
|
//!
|
2020-07-28 07:40:49 +02:00
|
|
|
//! @param[in] mempool The mempool to pass to the chainstate
|
|
|
|
// constructor
|
2022-04-20 17:40:01 -04:00
|
|
|
Chainstate& InitializeChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
2019-12-12 10:20:44 -05:00
|
|
|
|
|
|
|
//! Get all chainstates currently being used.
|
2022-03-09 12:37:19 -05:00
|
|
|
std::vector<Chainstate*> GetAll();
|
2019-12-12 10:20:44 -05:00
|
|
|
|
2020-08-25 13:50:23 -04:00
|
|
|
//! Construct and activate a Chainstate on the basis of UTXO snapshot data.
|
|
|
|
//!
|
|
|
|
//! Steps:
|
|
|
|
//!
|
2022-03-09 12:37:19 -05:00
|
|
|
//! - Initialize an unused Chainstate.
|
2020-08-25 13:50:23 -04:00
|
|
|
//! - Load its `CoinsViews` contents from `coins_file`.
|
|
|
|
//! - Verify that the hash of the resulting coinsdb matches the expected hash
|
|
|
|
//! per assumeutxo chain parameters.
|
|
|
|
//! - Wait for our headers chain to include the base block of the snapshot.
|
|
|
|
//! - "Fast forward" the tip of the new chainstate to the base of the snapshot,
|
|
|
|
//! faking nTx* block index data along the way.
|
|
|
|
//! - Move the new chainstate to `m_snapshot_chainstate` and make it our
|
|
|
|
//! ChainstateActive().
|
|
|
|
[[nodiscard]] bool ActivateSnapshot(
|
2022-06-06 17:22:59 +02:00
|
|
|
AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory);
|
2020-08-25 13:50:23 -04:00
|
|
|
|
2019-12-12 10:20:44 -05:00
|
|
|
//! The most-work chain.
|
2022-03-09 12:37:19 -05:00
|
|
|
Chainstate& ActiveChainstate() const;
|
2022-05-06 16:58:53 +02:00
|
|
|
CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; }
|
|
|
|
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); }
|
|
|
|
CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); }
|
2019-12-12 10:20:44 -05:00
|
|
|
|
2021-11-12 10:06:00 -05:00
|
|
|
node::BlockMap& BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
|
2019-12-12 10:48:28 -05:00
|
|
|
{
|
2022-01-27 12:37:50 +01:00
|
|
|
AssertLockHeld(::cs_main);
|
2019-12-12 10:48:28 -05:00
|
|
|
return m_blockman.m_block_index;
|
|
|
|
}
|
|
|
|
|
2022-04-15 06:53:19 +10:00
|
|
|
/**
|
|
|
|
* Track versionbit status
|
|
|
|
*/
|
|
|
|
mutable VersionBitsCache m_versionbitscache;
|
|
|
|
|
2021-04-13 10:49:54 -04:00
|
|
|
//! @returns true if a snapshot-based chainstate is in use. Also implies
|
|
|
|
//! that a background validation chainstate is also in use.
|
2019-12-12 10:20:44 -05:00
|
|
|
bool IsSnapshotActive() const;
|
|
|
|
|
2021-03-15 10:41:30 +08:00
|
|
|
std::optional<uint256> SnapshotBlockhash() const;
|
2019-12-12 10:20:44 -05:00
|
|
|
|
|
|
|
//! Is there a snapshot in use and has it been fully validated?
|
2022-02-02 14:40:47 -05:00
|
|
|
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
|
|
|
|
{
|
|
|
|
return m_snapshot_chainstate && m_ibd_chainstate && m_ibd_chainstate->m_disabled;
|
|
|
|
}
|
2019-12-12 10:20:44 -05:00
|
|
|
|
2020-04-18 09:55:57 -04:00
|
|
|
/**
|
|
|
|
* Process an incoming block. This only returns after the best known valid
|
|
|
|
* block is made active. Note that it does not, however, guarantee that the
|
|
|
|
* specific block passed to it has been checked for validity!
|
|
|
|
*
|
2021-05-31 13:54:58 +08:00
|
|
|
* If you want to *possibly* get feedback on whether block is valid, you must
|
2020-04-18 09:55:57 -04:00
|
|
|
* install a CValidationInterface (see validationinterface.h) - this will have
|
|
|
|
* its BlockChecked method called whenever *any* block completes validation.
|
|
|
|
*
|
2021-05-31 13:54:58 +08:00
|
|
|
* Note that we guarantee that either the proof-of-work is valid on block, or
|
2020-04-18 09:55:57 -04:00
|
|
|
* (and possibly also) BlockChecked will have been called.
|
|
|
|
*
|
2021-05-31 13:54:58 +08:00
|
|
|
* May not be called in a validationinterface callback.
|
2020-04-18 09:55:57 -04:00
|
|
|
*
|
2021-05-31 13:54:58 +08:00
|
|
|
* @param[in] block The block we want to process.
|
|
|
|
* @param[in] force_processing Process this block even if unrequested; used for non-network block sources.
|
2022-08-02 16:48:57 -04:00
|
|
|
* @param[in] min_pow_checked True if proof-of-work anti-DoS checks have
|
|
|
|
* been done by caller for headers chain
|
|
|
|
* (note: only affects headers acceptance; if
|
|
|
|
* block header is already present in block
|
|
|
|
* index then this parameter has no effect)
|
2021-05-31 13:54:58 +08:00
|
|
|
* @param[out] new_block A boolean which is set to indicate if the block was first received via this call
|
2020-04-18 09:55:57 -04:00
|
|
|
* @returns If the block was processed, independently of block validity
|
|
|
|
*/
|
2022-08-02 16:48:57 -04:00
|
|
|
bool ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block) LOCKS_EXCLUDED(cs_main);
|
2020-04-18 09:55:57 -04:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Process incoming block headers.
|
|
|
|
*
|
|
|
|
* May not be called in a
|
|
|
|
* validationinterface callback.
|
|
|
|
*
|
|
|
|
* @param[in] block The block headers themselves
|
2022-08-02 16:48:57 -04:00
|
|
|
* @param[in] min_pow_checked True if proof-of-work anti-DoS checks have been done by caller for headers chain
|
2020-04-18 09:55:57 -04:00
|
|
|
* @param[out] state This may be set to an Error state if any error occurred processing them
|
|
|
|
* @param[out] ppindex If set, the pointer will be set to point to the last new block index object for the given headers
|
|
|
|
*/
|
2022-08-02 16:48:57 -04:00
|
|
|
bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
|
2020-04-18 09:55:57 -04:00
|
|
|
|
2021-09-27 16:55:42 +01:00
|
|
|
/**
|
|
|
|
* Try to add a transaction to the memory pool.
|
|
|
|
*
|
|
|
|
* @param[in] tx The transaction to submit for mempool acceptance.
|
|
|
|
* @param[in] test_accept When true, run validation checks but don't submit to mempool.
|
|
|
|
*/
|
|
|
|
[[nodiscard]] MempoolAcceptResult ProcessTransaction(const CTransactionRef& tx, bool test_accept=false)
|
|
|
|
EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
|
|
|
|
2020-04-18 08:27:46 -04:00
|
|
|
//! Load the block tree and coins database from disk, initializing state if we're running with -reindex
|
2021-04-27 22:54:53 +02:00
|
|
|
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
|
2020-04-18 08:27:46 -04:00
|
|
|
|
2019-09-16 13:37:29 -04:00
|
|
|
//! Check to see if caches are out of balance and if so, call
|
|
|
|
//! ResizeCoinsCaches() as needed.
|
|
|
|
void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
qt/test: Reset chainman in ~ChainstateManager instead
There are some mutable, global state variables that are currently reset
by UnloadBlockIndex such as pindexBestHeader which should be cleaned up
whenever the ChainstateManager is unloaded/reset/destructed/etc.
Not cleaning them up leads to bugs like a use-after-free that happens
like so:
1. At the end of a test, ChainstateManager is destructed, which also
destructs BlockManager, which calls BlockManager::Unload to free all
CBlockIndexes in its BlockMap
2. Since pindexBestHeader is not cleaned up, it now points to an invalid
location
3. Another test starts to init, and calls LoadGenesisBlock, which calls
AddToBlockIndex, which compares the genesis block with an invalid
location
4. Cute puppies perish by the hundreds
Previously, for normal codepaths (e.g. bitcoind), we relied on the fact
that our program will be unloaded by the operating system which
effectively resets these variables. The one exception is in QT tests,
where these variables had to be manually reset.
Since now ChainstateManager is no longer a global, we can just put this
logic in its destructor to make sure that callers are always correct.
Over time, we should probably move these mutable global state variables
into ChainstateManager or CChainState so it's easier to reason about
their lifecycles.
2020-10-06 17:35:53 -04:00
|
|
|
|
2022-01-19 04:10:26 +10:00
|
|
|
/** Update uncommitted block structures (currently: only the witness reserved value). This is safe for submitted blocks. */
|
|
|
|
void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const;
|
|
|
|
|
|
|
|
/** Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). */
|
|
|
|
std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const;
|
|
|
|
|
2022-08-12 17:29:52 -04:00
|
|
|
/** This is used by net_processing to report pre-synchronization progress of headers, as
|
|
|
|
* headers are not yet fed to validation during that time, but validation is (for now)
|
|
|
|
* responsible for logging and signalling through NotifyHeaderTip, so it needs this
|
|
|
|
* information. */
|
|
|
|
void ReportHeadersPresync(const arith_uint256& work, int64_t height, int64_t timestamp);
|
|
|
|
|
2022-04-20 17:40:01 -04:00
|
|
|
//! When starting up, search the datadir for a chainstate based on a UTXO
|
|
|
|
//! snapshot that is in the process of being validated.
|
|
|
|
bool DetectSnapshotChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
|
|
|
|
2022-07-21 12:56:47 -04:00
|
|
|
void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
|
|
|
|
2022-04-20 17:40:01 -04:00
|
|
|
//! Switch the active chainstate to one based on a UTXO snapshot that was loaded
|
|
|
|
//! previously.
|
|
|
|
Chainstate& ActivateExistingSnapshot(CTxMemPool* mempool, uint256 base_blockhash)
|
|
|
|
EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
|
|
|
|
|
2022-01-11 14:49:28 -05:00
|
|
|
~ChainstateManager();
|
2019-12-12 10:20:44 -05:00
|
|
|
};
|
|
|
|
|
2022-04-15 05:49:31 +10:00
|
|
|
/** Deployment* info via ChainstateManager */
|
|
|
|
template<typename DEP>
|
|
|
|
bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep)
|
|
|
|
{
|
2022-04-15 06:53:19 +10:00
|
|
|
return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
|
2022-04-15 05:49:31 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
template<typename DEP>
|
|
|
|
bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep)
|
|
|
|
{
|
2022-04-15 06:53:19 +10:00
|
|
|
return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
|
2022-04-15 05:49:31 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
template<typename DEP>
|
|
|
|
bool DeploymentEnabled(const ChainstateManager& chainman, DEP dep)
|
|
|
|
{
|
|
|
|
return DeploymentEnabled(chainman.GetConsensus(), dep);
|
|
|
|
}
|
|
|
|
|
2019-04-25 11:09:29 -04:00
|
|
|
/**
|
|
|
|
* Return the expected assumeutxo value for a given height, if one exists.
|
|
|
|
*
|
2021-04-03 10:53:29 +08:00
|
|
|
* @param[in] height Get the assumeutxo value for this height.
|
2019-04-25 11:09:29 -04:00
|
|
|
*
|
|
|
|
* @returns empty if no assumeutxo configuration exists for the given height.
|
|
|
|
*/
|
|
|
|
const AssumeutxoData* ExpectedAssumeutxo(const int height, const CChainParams& params);
|
|
|
|
|
2020-12-24 00:11:40 +01:00
|
|
|
/** Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30) */
|
|
|
|
bool IsBIP30Repeat(const CBlockIndex& block_index);
|
|
|
|
|
|
|
|
/** Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30) */
|
|
|
|
bool IsBIP30Unspendable(const CBlockIndex& block_index);
|
|
|
|
|
2016-12-01 16:06:41 -08:00
|
|
|
#endif // BITCOIN_VALIDATION_H
|