Bitcoin Core  31.0.0
P2P Digital Currency
chain.h
Go to the documentation of this file.
1 // Copyright (c) 2018-present The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #ifndef BITCOIN_INTERFACES_CHAIN_H
6 #define BITCOIN_INTERFACES_CHAIN_H
7 
8 #include <blockfilter.h>
9 #include <common/settings.h>
10 #include <kernel/chain.h> // IWYU pragma: export
11 #include <node/types.h>
12 #include <primitives/transaction.h>
13 #include <util/result.h>
14 
15 #include <cstddef>
16 #include <cstdint>
17 #include <functional>
18 #include <map>
19 #include <memory>
20 #include <optional>
21 #include <string>
22 #include <vector>
23 
24 class ArgsManager;
25 class CBlock;
26 class CBlockUndo;
27 class CFeeRate;
28 class CRPCCommand;
29 class CScheduler;
30 class Coin;
31 class uint256;
32 enum class MemPoolRemovalReason;
33 enum class RBFTransactionState;
34 struct bilingual_str;
35 struct CBlockLocator;
36 struct FeeCalculation;
37 namespace kernel {
38 struct ChainstateRole;
39 } // namespace kernel
40 namespace node {
41 struct NodeContext;
42 } // namespace node
43 
44 namespace interfaces {
45 
46 class Handler;
47 class Wallet;
48 
53 {
54 public:
55  FoundBlock& hash(uint256& hash) { m_hash = &hash; return *this; }
56  FoundBlock& height(int& height) { m_height = &height; return *this; }
57  FoundBlock& time(int64_t& time) { m_time = &time; return *this; }
58  FoundBlock& maxTime(int64_t& max_time) { m_max_time = &max_time; return *this; }
59  FoundBlock& mtpTime(int64_t& mtp_time) { m_mtp_time = &mtp_time; return *this; }
61  FoundBlock& inActiveChain(bool& in_active_chain) { m_in_active_chain = &in_active_chain; return *this; }
65  FoundBlock& nextBlock(const FoundBlock& next_block) { m_next_block = &next_block; return *this; }
68  FoundBlock& data(CBlock& data) { m_data = &data; return *this; }
69 
70  uint256* m_hash = nullptr;
71  int* m_height = nullptr;
72  int64_t* m_time = nullptr;
73  int64_t* m_max_time = nullptr;
74  int64_t* m_mtp_time = nullptr;
75  bool* m_in_active_chain = nullptr;
77  const FoundBlock* m_next_block = nullptr;
78  CBlock* m_data = nullptr;
79  mutable bool found = false;
80 };
81 
86 enum class SettingsAction {
87  WRITE,
89 };
90 
91 using SettingsUpdate = std::function<std::optional<interfaces::SettingsAction>(common::SettingsValue&)>;
92 
117 class Chain
118 {
119 public:
120  virtual ~Chain() = default;
121 
125  virtual std::optional<int> getHeight() = 0;
126 
128  virtual uint256 getBlockHash(int height) = 0;
129 
132  virtual bool haveBlockOnDisk(int height) = 0;
133 
137  virtual std::optional<int> findLocatorFork(const CBlockLocator& locator) = 0;
138 
140  virtual bool hasBlockFilterIndex(BlockFilterType filter_type) = 0;
141 
144  virtual std::optional<bool> blockFilterMatchesAny(BlockFilterType filter_type, const uint256& block_hash, const GCSFilter::ElementSet& filter_set) = 0;
145 
148  virtual bool findBlock(const uint256& hash, const FoundBlock& block={}) = 0;
149 
154  virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block={}) = 0;
155 
158  virtual bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out={}) = 0;
159 
162  virtual bool findAncestorByHash(const uint256& block_hash,
163  const uint256& ancestor_hash,
164  const FoundBlock& ancestor_out={}) = 0;
165 
168  virtual bool findCommonAncestor(const uint256& block_hash1,
169  const uint256& block_hash2,
170  const FoundBlock& ancestor_out={},
171  const FoundBlock& block1_out={},
172  const FoundBlock& block2_out={}) = 0;
173 
177  virtual void findCoins(std::map<COutPoint, Coin>& coins) = 0;
178 
181  virtual double guessVerificationProgress(const uint256& block_hash) = 0;
182 
186  virtual bool hasBlocks(const uint256& block_hash, int min_height = 0, std::optional<int> max_height = {}) = 0;
187 
189  virtual RBFTransactionState isRBFOptIn(const CTransaction& tx) = 0;
190 
192  virtual bool isInMempool(const Txid& txid) = 0;
193 
195  virtual bool hasDescendantsInMempool(const Txid& txid) = 0;
196 
206  virtual bool broadcastTransaction(const CTransactionRef& tx,
207  const CAmount& max_tx_fee,
208  node::TxBroadcast broadcast_method,
209  std::string& err_string) = 0;
210 
212  virtual void getTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) = 0;
213 
215  // feerate, including bumping its ancestors. For example, if the target feerate is 10sat/vbyte
216  // and this outpoint refers to a mempool transaction at 3sat/vbyte, the bump fee includes the
217  // cost to bump the mempool transaction to 10sat/vbyte (i.e. 7 * mempooltx.vsize). If that
218  // transaction also has, say, an unconfirmed parent with a feerate of 1sat/vbyte, the bump fee
219  // includes the cost to bump the parent (i.e. 9 * parentmempooltx.vsize).
220  //
221  // If the outpoint comes from an unconfirmed transaction that is already above the target
222  // feerate or bumped by its descendant(s) already, it does not need to be bumped. Its bump fee
223  // is 0. Likewise, if any of the transaction's ancestors are already bumped by a transaction
224  // in our mempool, they are not included in the transaction's bump fee.
225  //
226  // Also supported is bump-fee calculation in the case of replacements. If an outpoint
227  // conflicts with another transaction in the mempool, it is assumed that the goal is to replace
228  // that transaction. As such, the calculation will exclude the to-be-replaced transaction, but
229  // will include the fee-bumping cost. If bump fees of descendants of the to-be-replaced
230  // transaction are requested, the value will be 0. Fee-related RBF rules are not included as
231  // they are logically distinct.
232  //
233  // Any outpoints that are otherwise unavailable from the mempool (e.g. UTXOs from confirmed
234  // transactions or transactions not yet broadcast by the wallet) are given a bump fee of 0.
235  //
236  // If multiple outpoints come from the same transaction (which would be very rare because
237  // it means that one transaction has multiple change outputs or paid the same wallet using multiple
238  // outputs in the same transaction) or have shared ancestry, the bump fees are calculated
239  // independently, i.e. as if only one of them is spent. This may result in double-fee-bumping. This
240  // caveat can be rectified per use of the sister-function CalculateCombinedBumpFee(…).
241  virtual std::map<COutPoint, CAmount> calculateIndividualBumpFees(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) = 0;
242 
244  // as in CalculateIndividualBumpFees(…).
245  // Unlike CalculateIndividualBumpFees(…), this does not return individual
246  // bump fees per outpoint, but a single bump fee for the shared ancestry.
247  // The combined bump fee may be used to correct overestimation due to
248  // shared ancestry by multiple UTXOs after coin selection.
249  virtual std::optional<CAmount> calculateCombinedBumpFee(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) = 0;
250 
254  virtual void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) = 0;
255 
257  virtual util::Result<void> checkChainLimits(const CTransactionRef& tx) = 0;
258 
260  virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc = nullptr) = 0;
261 
263  virtual unsigned int estimateMaxBlocks() = 0;
264 
266  virtual CFeeRate mempoolMinFee() = 0;
267 
269  virtual CFeeRate relayMinFee() = 0;
270 
272  virtual CFeeRate relayIncrementalFee() = 0;
273 
275  virtual CFeeRate relayDustFee() = 0;
276 
278  virtual bool havePruned() = 0;
279 
281  virtual std::optional<int> getPruneHeight() = 0;
282 
284  virtual bool isReadyToBroadcast() = 0;
285 
287  virtual bool isInitialBlockDownload() = 0;
288 
290  virtual bool shutdownRequested() = 0;
291 
293  virtual void initMessage(const std::string& message) = 0;
294 
296  virtual void initWarning(const bilingual_str& message) = 0;
297 
299  virtual void initError(const bilingual_str& message) = 0;
300 
302  virtual void showProgress(const std::string& title, int progress, bool resume_possible) = 0;
303 
306  {
307  public:
308  virtual ~Notifications() = default;
309  virtual void transactionAddedToMempool(const CTransactionRef& tx) {}
311  virtual void blockConnected(const kernel::ChainstateRole& role, const BlockInfo& block) {}
312  virtual void blockDisconnected(const BlockInfo& block) {}
313  virtual void updatedBlockTip() {}
314  virtual void chainStateFlushed(const kernel::ChainstateRole& role, const CBlockLocator& locator) {}
315  };
316 
319  {
321  bool connect_undo_data = false;
323  bool disconnect_data = false;
325  bool disconnect_undo_data = false;
326  };
327 
332  virtual std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) = 0;
333 
336  virtual void waitForNotificationsIfTipChanged(const uint256& old_tip) = 0;
337 
339  virtual void waitForNotifications() = 0;
340 
343  virtual std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) = 0;
344 
346  virtual bool rpcEnableDeprecated(const std::string& method) = 0;
347 
349  virtual common::SettingsValue getSetting(const std::string& arg) = 0;
350 
352  virtual std::vector<common::SettingsValue> getSettingsList(const std::string& arg) = 0;
353 
355  virtual common::SettingsValue getRwSetting(const std::string& name) = 0;
356 
362  virtual bool updateRwSetting(const std::string& name, const SettingsUpdate& update_function) = 0;
363 
368  virtual bool overwriteRwSetting(const std::string& name, common::SettingsValue value, SettingsAction action = SettingsAction::WRITE) = 0;
369 
373  virtual bool deleteRwSettings(const std::string& name, SettingsAction action = SettingsAction::WRITE) = 0;
374 
383  virtual void requestMempoolTransactions(Notifications& notifications) = 0;
384 
388  virtual bool hasAssumedValidChain() = 0;
389 
392  virtual node::NodeContext* context() { return nullptr; }
393 };
394 
398 {
399 public:
400  virtual ~ChainClient() = default;
401 
403  virtual void registerRpcs() = 0;
404 
406  virtual bool verify() = 0;
407 
409  virtual bool load() = 0;
410 
412  virtual void start(CScheduler& scheduler) = 0;
413 
415  virtual void stop() = 0;
416 
418  virtual void setMockTime(int64_t time) = 0;
419 
421  virtual void schedulerMockForward(std::chrono::seconds delta_seconds) = 0;
422 };
423 
425 std::unique_ptr<Chain> MakeChain(node::NodeContext& node);
426 
427 } // namespace interfaces
428 
429 #endif // BITCOIN_INTERFACES_CHAIN_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:52
virtual bool deleteRwSettings(const std::string &name, SettingsAction action=SettingsAction::WRITE)=0
Delete a given setting in <datadir>/settings.json.
virtual bool findCommonAncestor(const uint256 &block_hash1, const uint256 &block_hash2, const FoundBlock &ancestor_out={}, const FoundBlock &block1_out={}, const FoundBlock &block2_out={})=0
Find most recent common ancestor between two blocks and optionally return block information.
FoundBlock & locator(CBlockLocator &locator)
Return locator if block is in the active chain.
Definition: chain.h:63
virtual void findCoins(std::map< COutPoint, Coin > &coins)=0
Look up unspent output information.
virtual void getPackageLimits(unsigned int &limit_ancestor_count, unsigned int &limit_descendant_count)=0
Get the node&#39;s package limits.
TxBroadcast
How to broadcast a local transaction.
Definition: types.h:165
virtual std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
virtual ~Notifications()=default
virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock &block={})=0
Find first block in the chain with timestamp >= the given time and height >= than the given height...
virtual void getTransactionAncestry(const Txid &txid, size_t &ancestors, size_t &cluster_count, size_t *ancestorsize=nullptr, CAmount *ancestorfees=nullptr)=0
Calculate mempool ancestor and cluster counts for the given transaction.
virtual void blockConnected(const kernel::ChainstateRole &role, const BlockInfo &block)
Definition: chain.h:311
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:116
virtual std::unique_ptr< Handler > handleNotifications(std::shared_ptr< Notifications > notifications)=0
Register handler for notifications.
virtual void registerRpcs()=0
Register rpcs.
virtual void transactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason)
Definition: chain.h:310
A UTXO entry.
Definition: coins.h:34
Bilingual messages:
Definition: translation.h:24
Definition: block.h:73
virtual uint256 getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
virtual CFeeRate mempoolMinFee()=0
Mempool minimum fee.
virtual common::SettingsValue getSetting(const std::string &arg)=0
Get settings value.
int64_t * m_max_time
Definition: chain.h:73
virtual CFeeRate relayDustFee()=0
Relay dust fee setting (-dustrelayfee), reflecting lowest rate it&#39;s economical to spend...
virtual bool hasBlockFilterIndex(BlockFilterType filter_type)=0
Returns whether a block filter index is available.
virtual std::vector< common::SettingsValue > getSettingsList(const std::string &arg)=0
Get list of settings values.
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
Information about chainstate that notifications are sent from.
Definition: types.h:18
virtual bool isInitialBlockDownload()=0
Check if in IBD.
virtual std::optional< int > getPruneHeight()=0
Get the current prune height.
virtual void stop()=0
Shut down client.
virtual void updatedBlockTip()
Definition: chain.h:313
bool disconnect_undo_data
Include undo data with block disconnected notifications.
Definition: chain.h:325
bool connect_undo_data
Include undo data with block connected notifications.
Definition: chain.h:321
virtual double guessVerificationProgress(const uint256 &block_hash)=0
Estimate fraction of total transactions verified if blocks up to the specified block hash are verifie...
virtual bool load()=0
Load saved state.
int64_t * m_mtp_time
Definition: chain.h:74
CBlockLocator * m_locator
Definition: chain.h:76
virtual bool hasDescendantsInMempool(const Txid &txid)=0
Check if transaction has descendants in mempool.
RBFTransactionState
The rbf state of unconfirmed transactions.
Definition: rbf.h:29
uint256 * m_hash
Definition: chain.h:70
virtual void transactionAddedToMempool(const CTransactionRef &tx)
Definition: chain.h:309
virtual ~ChainClient()=default
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
virtual std::optional< int > findLocatorFork(const CBlockLocator &locator)=0
Return height of the highest block on chain in common with the locator, which will either be the orig...
FoundBlock & data(CBlock &data)
Read block data from disk.
Definition: chain.h:68
BlockFilterType
Definition: blockfilter.h:93
Block data sent with blockConnected, blockDisconnected notifications.
Definition: chain.h:19
NodeContext struct containing references to chain state and connection state.
Definition: context.h:56
virtual void chainStateFlushed(const kernel::ChainstateRole &role, const CBlockLocator &locator)
Definition: chain.h:314
virtual void setMockTime(int64_t time)=0
Set mock time.
virtual bool hasAssumedValidChain()=0
Return true if an assumed-valid snapshot is in use.
virtual void schedulerMockForward(std::chrono::seconds delta_seconds)=0
Mock the scheduler to fast forward in time.
std::function< std::optional< interfaces::SettingsAction >(common::SettingsValue &)> SettingsUpdate
Definition: chain.h:91
SettingsAction
The action to be taken after updating a settings value.
Definition: chain.h:86
virtual bool findAncestorByHeight(const uint256 &block_hash, int ancestor_height, const FoundBlock &ancestor_out={})=0
Find ancestor of block at specified height and optionally return ancestor information.
virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation *calc=nullptr)=0
Estimate smart fee.
CBlock * m_data
Definition: chain.h:78
const char * name
Definition: rest.cpp:48
virtual bool updateRwSetting(const std::string &name, const SettingsUpdate &update_function)=0
Updates a setting in <datadir>/settings.json.
Options specifying which chain notifications are required.
Definition: chain.h:318
virtual bool overwriteRwSetting(const std::string &name, common::SettingsValue value, SettingsAction action=SettingsAction::WRITE)=0
Replace a setting in <datadir>/settings.json with a new value.
Chain notifications.
Definition: chain.h:305
const FoundBlock * m_next_block
Definition: chain.h:77
FoundBlock & maxTime(int64_t &max_time)
Definition: chain.h:58
virtual std::unique_ptr< Handler > handleRpc(const CRPCCommand &command)=0
Register handler for RPC.
virtual void start(CScheduler &scheduler)=0
Start client execution and provide a scheduler.
virtual bool findBlock(const uint256 &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
virtual bool broadcastTransaction(const CTransactionRef &tx, const CAmount &max_tx_fee, node::TxBroadcast broadcast_method, std::string &err_string)=0
Process a local transaction, optionally adding it to the mempool and optionally broadcasting it to th...
virtual void waitForNotificationsIfTipChanged(const uint256 &old_tip)=0
Wait for pending notifications to be processed unless block hash points to the current chain tip...
virtual void requestMempoolTransactions(Notifications &notifications)=0
Synchronously send transactionAddedToMempool notifications about all current mempool transactions to ...
virtual std::optional< CAmount > calculateCombinedBumpFee(const std::vector< COutPoint > &outpoints, const CFeeRate &target_feerate)=0
Calculate the combined bump fee for an input set per the same strategy.
virtual bool verify()=0
Check for errors before loading.
std::unordered_set< Element, ByteVectorHash > ElementSet
Definition: blockfilter.h:33
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
Definition: messages.h:21
virtual bool isInMempool(const Txid &txid)=0
Check if transaction is in mempool.
virtual ~Chain()=default
virtual node::NodeContext * context()
Get internal node context.
Definition: chain.h:392
bool disconnect_data
Include block data with block disconnected notifications.
Definition: chain.h:323
256-bit opaque blob.
Definition: uint256.h:195
virtual bool isReadyToBroadcast()=0
Check if the node is ready to broadcast transactions.
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
const auto command
virtual bool findAncestorByHash(const uint256 &block_hash, const uint256 &ancestor_hash, const FoundBlock &ancestor_out={})=0
Return whether block descends from a specified ancestor, and optionally return ancestor information...
Interface to let node manage chain clients (wallets, or maybe tools for monitoring and analysis in th...
Definition: chain.h:397
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:117
virtual void blockDisconnected(const BlockInfo &block)
Definition: chain.h:312
Undo information for a CBlock.
Definition: undo.h:62
int64_t * m_time
Definition: chain.h:72
virtual void initMessage(const std::string &message)=0
Send init message.
virtual std::map< COutPoint, CAmount > calculateIndividualBumpFees(const std::vector< COutPoint > &outpoints, const CFeeRate &target_feerate)=0
For each outpoint, calculate the fee-bumping cost to spend this outpoint at the specified.
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac...
Definition: feerate.h:31
FoundBlock & hash(uint256 &hash)
Definition: chain.h:55
virtual RBFTransactionState isRBFOptIn(const CTransaction &tx)=0
Check if transaction is RBF opt in.
bool * m_in_active_chain
Definition: chain.h:75
virtual bool hasBlocks(const uint256 &block_hash, int min_height=0, std::optional< int > max_height={})=0
Return true if data is available for all blocks in the specified range of blocks. ...
virtual void showProgress(const std::string &title, int progress, bool resume_possible)=0
Send progress indicator.
virtual unsigned int estimateMaxBlocks()=0
Fee estimator max target.
virtual bool shutdownRequested()=0
Check if shutdown requested.
FoundBlock & inActiveChain(bool &in_active_chain)
Return whether block is in the active (most-work) chain.
Definition: chain.h:61
FoundBlock & height(int &height)
Definition: chain.h:56
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:280
FoundBlock & mtpTime(int64_t &mtp_time)
Definition: chain.h:59
virtual util::Result< void > checkChainLimits(const CTransactionRef &tx)=0
Check if transaction will pass the mempool&#39;s chain limits.
Simple class for background tasks that should be run periodically or once "after a while"...
Definition: scheduler.h:39
is a home for public enum and struct type definitions that are used internally by node code...
virtual bool rpcEnableDeprecated(const std::string &method)=0
Check if deprecated RPC is enabled.
virtual common::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
virtual void initError(const bilingual_str &message)=0
Send init error.
virtual CFeeRate relayIncrementalFee()=0
Relay incremental fee setting (-incrementalrelayfee), reflecting cost of relay.
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee and -incrementalrelayfee settings).
virtual void waitForNotifications()=0
Wait for all pending notifications up to this point to be processed.
FoundBlock & nextBlock(const FoundBlock &next_block)
Return next block in the active chain if current block is in the active chain.
Definition: chain.h:65
FoundBlock & time(int64_t &time)
Definition: chain.h:57
virtual bool havePruned()=0
Check if any block has been pruned.
virtual std::optional< bool > blockFilterMatchesAny(BlockFilterType filter_type, const uint256 &block_hash, const GCSFilter::ElementSet &filter_set)=0
Returns whether any of the elements match the block via a BIP 157 block filter or std::nullopt if the...