Bitcoin Core  27.99.0
P2P Digital Currency
chain.h
Go to the documentation of this file.
1 // Copyright (c) 2018-2022 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 <primitives/transaction.h> // For CTransactionRef
11 #include <util/result.h>
12 
13 #include <functional>
14 #include <memory>
15 #include <optional>
16 #include <stddef.h>
17 #include <stdint.h>
18 #include <string>
19 #include <vector>
20 
21 class ArgsManager;
22 class CBlock;
23 class CBlockUndo;
24 class CFeeRate;
25 class CRPCCommand;
26 class CScheduler;
27 class Coin;
28 class uint256;
29 enum class MemPoolRemovalReason;
30 enum class RBFTransactionState;
31 enum class ChainstateRole;
32 struct bilingual_str;
33 struct CBlockLocator;
34 struct FeeCalculation;
35 namespace node {
36 struct NodeContext;
37 } // namespace node
38 
39 namespace interfaces {
40 
41 class Handler;
42 class Wallet;
43 
45 struct BlockKey {
47  int height = -1;
48 };
49 
54 {
55 public:
56  FoundBlock& hash(uint256& hash) { m_hash = &hash; return *this; }
57  FoundBlock& height(int& height) { m_height = &height; return *this; }
58  FoundBlock& time(int64_t& time) { m_time = &time; return *this; }
59  FoundBlock& maxTime(int64_t& max_time) { m_max_time = &max_time; return *this; }
60  FoundBlock& mtpTime(int64_t& mtp_time) { m_mtp_time = &mtp_time; return *this; }
62  FoundBlock& inActiveChain(bool& in_active_chain) { m_in_active_chain = &in_active_chain; return *this; }
66  FoundBlock& nextBlock(const FoundBlock& next_block) { m_next_block = &next_block; return *this; }
69  FoundBlock& data(CBlock& data) { m_data = &data; return *this; }
70 
71  uint256* m_hash = nullptr;
72  int* m_height = nullptr;
73  int64_t* m_time = nullptr;
74  int64_t* m_max_time = nullptr;
75  int64_t* m_mtp_time = nullptr;
76  bool* m_in_active_chain = nullptr;
78  const FoundBlock* m_next_block = nullptr;
79  CBlock* m_data = nullptr;
80  mutable bool found = false;
81 };
82 
84 struct BlockInfo {
85  const uint256& hash;
86  const uint256* prev_hash = nullptr;
87  int height = -1;
88  int file_number = -1;
89  unsigned data_pos = 0;
90  const CBlock* data = nullptr;
91  const CBlockUndo* undo_data = nullptr;
92  // The maximum time in the chain up to and including this block.
93  // A timestamp that can only move forward.
94  unsigned int chain_time_max{0};
95 
97 };
98 
123 class Chain
124 {
125 public:
126  virtual ~Chain() {}
127 
131  virtual std::optional<int> getHeight() = 0;
132 
134  virtual uint256 getBlockHash(int height) = 0;
135 
138  virtual bool haveBlockOnDisk(int height) = 0;
139 
142 
145  virtual CBlockLocator getActiveChainLocator(const uint256& block_hash) = 0;
146 
150  virtual std::optional<int> findLocatorFork(const CBlockLocator& locator) = 0;
151 
153  virtual bool hasBlockFilterIndex(BlockFilterType filter_type) = 0;
154 
157  virtual std::optional<bool> blockFilterMatchesAny(BlockFilterType filter_type, const uint256& block_hash, const GCSFilter::ElementSet& filter_set) = 0;
158 
161  virtual bool findBlock(const uint256& hash, const FoundBlock& block={}) = 0;
162 
167  virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block={}) = 0;
168 
171  virtual bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out={}) = 0;
172 
175  virtual bool findAncestorByHash(const uint256& block_hash,
176  const uint256& ancestor_hash,
177  const FoundBlock& ancestor_out={}) = 0;
178 
181  virtual bool findCommonAncestor(const uint256& block_hash1,
182  const uint256& block_hash2,
183  const FoundBlock& ancestor_out={},
184  const FoundBlock& block1_out={},
185  const FoundBlock& block2_out={}) = 0;
186 
190  virtual void findCoins(std::map<COutPoint, Coin>& coins) = 0;
191 
194  virtual double guessVerificationProgress(const uint256& block_hash) = 0;
195 
199  virtual bool hasBlocks(const uint256& block_hash, int min_height = 0, std::optional<int> max_height = {}) = 0;
200 
203 
205  virtual bool isInMempool(const uint256& txid) = 0;
206 
208  virtual bool hasDescendantsInMempool(const uint256& txid) = 0;
209 
213  virtual bool broadcastTransaction(const CTransactionRef& tx,
214  const CAmount& max_tx_fee,
215  bool relay,
216  std::string& err_string) = 0;
217 
219  virtual void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) = 0;
220 
222  // feerate, including bumping its ancestors. For example, if the target feerate is 10sat/vbyte
223  // and this outpoint refers to a mempool transaction at 3sat/vbyte, the bump fee includes the
224  // cost to bump the mempool transaction to 10sat/vbyte (i.e. 7 * mempooltx.vsize). If that
225  // transaction also has, say, an unconfirmed parent with a feerate of 1sat/vbyte, the bump fee
226  // includes the cost to bump the parent (i.e. 9 * parentmempooltx.vsize).
227  //
228  // If the outpoint comes from an unconfirmed transaction that is already above the target
229  // feerate or bumped by its descendant(s) already, it does not need to be bumped. Its bump fee
230  // is 0. Likewise, if any of the transaction's ancestors are already bumped by a transaction
231  // in our mempool, they are not included in the transaction's bump fee.
232  //
233  // Also supported is bump-fee calculation in the case of replacements. If an outpoint
234  // conflicts with another transaction in the mempool, it is assumed that the goal is to replace
235  // that transaction. As such, the calculation will exclude the to-be-replaced transaction, but
236  // will include the fee-bumping cost. If bump fees of descendants of the to-be-replaced
237  // transaction are requested, the value will be 0. Fee-related RBF rules are not included as
238  // they are logically distinct.
239  //
240  // Any outpoints that are otherwise unavailable from the mempool (e.g. UTXOs from confirmed
241  // transactions or transactions not yet broadcast by the wallet) are given a bump fee of 0.
242  //
243  // If multiple outpoints come from the same transaction (which would be very rare because
244  // it means that one transaction has multiple change outputs or paid the same wallet using multiple
245  // outputs in the same transaction) or have shared ancestry, the bump fees are calculated
246  // independently, i.e. as if only one of them is spent. This may result in double-fee-bumping. This
247  // caveat can be rectified per use of the sister-function CalculateCombinedBumpFee(…).
248  virtual std::map<COutPoint, CAmount> calculateIndividualBumpFees(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) = 0;
249 
251  // as in CalculateIndividualBumpFees(…).
252  // Unlike CalculateIndividualBumpFees(…), this does not return individual
253  // bump fees per outpoint, but a single bump fee for the shared ancestry.
254  // The combined bump fee may be used to correct overestimation due to
255  // shared ancestry by multiple UTXOs after coin selection.
256  virtual std::optional<CAmount> calculateCombinedBumpFee(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) = 0;
257 
261  virtual void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) = 0;
262 
265 
267  virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc = nullptr) = 0;
268 
270  virtual unsigned int estimateMaxBlocks() = 0;
271 
273  virtual CFeeRate mempoolMinFee() = 0;
274 
276  virtual CFeeRate relayMinFee() = 0;
277 
280 
282  virtual CFeeRate relayDustFee() = 0;
283 
285  virtual bool havePruned() = 0;
286 
288  virtual bool isReadyToBroadcast() = 0;
289 
291  virtual bool isInitialBlockDownload() = 0;
292 
294  virtual bool shutdownRequested() = 0;
295 
297  virtual void initMessage(const std::string& message) = 0;
298 
300  virtual void initWarning(const bilingual_str& message) = 0;
301 
303  virtual void initError(const bilingual_str& message) = 0;
304 
306  virtual void showProgress(const std::string& title, int progress, bool resume_possible) = 0;
307 
310  {
311  public:
312  virtual ~Notifications() {}
313  virtual void transactionAddedToMempool(const CTransactionRef& tx) {}
315  virtual void blockConnected(ChainstateRole role, const BlockInfo& block) {}
316  virtual void blockDisconnected(const BlockInfo& block) {}
317  virtual void updatedBlockTip() {}
318  virtual void chainStateFlushed(ChainstateRole role, const CBlockLocator& locator) {}
319  };
320 
322  virtual std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) = 0;
323 
326  virtual void waitForNotificationsIfTipChanged(const uint256& old_tip) = 0;
327 
330  virtual std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) = 0;
331 
333  virtual bool rpcEnableDeprecated(const std::string& method) = 0;
334 
336  virtual void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) = 0;
337 
339  virtual common::SettingsValue getSetting(const std::string& arg) = 0;
340 
342  virtual std::vector<common::SettingsValue> getSettingsList(const std::string& arg) = 0;
343 
345  virtual common::SettingsValue getRwSetting(const std::string& name) = 0;
346 
349  virtual bool updateRwSetting(const std::string& name, const common::SettingsValue& value, bool write=true) = 0;
350 
359  virtual void requestMempoolTransactions(Notifications& notifications) = 0;
360 
362  virtual bool hasAssumedValidChain() = 0;
363 
366  virtual node::NodeContext* context() { return nullptr; }
367 };
368 
372 {
373 public:
374  virtual ~ChainClient() {}
375 
377  virtual void registerRpcs() = 0;
378 
380  virtual bool verify() = 0;
381 
383  virtual bool load() = 0;
384 
386  virtual void start(CScheduler& scheduler) = 0;
387 
389  virtual void flush() = 0;
390 
392  virtual void stop() = 0;
393 
395  virtual void setMockTime(int64_t time) = 0;
396 
398  virtual void schedulerMockForward(std::chrono::seconds delta_seconds) = 0;
399 };
400 
402 std::unique_ptr<Chain> MakeChain(node::NodeContext& node);
403 
404 } // namespace interfaces
405 
406 #endif // BITCOIN_INTERFACES_CHAIN_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define LIFETIMEBOUND
Definition: attributes.h:16
const auto command
BlockFilterType
Definition: blockfilter.h:93
Definition: block.h:69
Undo information for a CBlock.
Definition: undo.h:63
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:40
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
A UTXO entry.
Definition: coins.h:32
std::unordered_set< Element, ByteVectorHash > ElementSet
Definition: blockfilter.h:32
Chain notifications.
Definition: chain.h:310
virtual void blockConnected(ChainstateRole role, const BlockInfo &block)
Definition: chain.h:315
virtual void chainStateFlushed(ChainstateRole role, const CBlockLocator &locator)
Definition: chain.h:318
virtual void transactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason)
Definition: chain.h:314
virtual void blockDisconnected(const BlockInfo &block)
Definition: chain.h:316
virtual void updatedBlockTip()
Definition: chain.h:317
virtual void transactionAddedToMempool(const CTransactionRef &tx)
Definition: chain.h:313
Interface to let node manage chain clients (wallets, or maybe tools for monitoring and analysis in th...
Definition: chain.h:372
virtual void schedulerMockForward(std::chrono::seconds delta_seconds)=0
Mock the scheduler to fast forward in time.
virtual void stop()=0
Shut down client.
virtual void flush()=0
Save state to disk.
virtual bool load()=0
Load saved state.
virtual void registerRpcs()=0
Register rpcs.
virtual void start(CScheduler &scheduler)=0
Start client execution and provide a scheduler.
virtual bool verify()=0
Check for errors before loading.
virtual ~ChainClient()
Definition: chain.h:374
virtual void setMockTime(int64_t time)=0
Set mock time.
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:124
virtual void rpcRunLater(const std::string &name, std::function< void()> fn, int64_t seconds)=0
Run function after given number of seconds. Cancel any previous calls with same name.
virtual CBlockLocator getTipLocator()=0
Get locator for the current chain tip.
virtual bool isInitialBlockDownload()=0
Check if in IBD.
virtual bool hasDescendantsInMempool(const uint256 &txid)=0
Check if transaction has descendants in mempool.
virtual CBlockLocator getActiveChainLocator(const uint256 &block_hash)=0
Return a locator that refers to a block in the active chain.
virtual bool rpcEnableDeprecated(const std::string &method)=0
Check if deprecated RPC is enabled.
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 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 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.
virtual node::NodeContext * context()
Get internal node context.
Definition: chain.h:366
virtual RBFTransactionState isRBFOptIn(const CTransaction &tx)=0
Check if transaction is RBF opt in.
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.
virtual uint256 getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
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 util::Result< void > checkChainLimits(const CTransactionRef &tx)=0
Check if transaction will pass the mempool's chain limits.
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.
virtual void showProgress(const std::string &title, int progress, bool resume_possible)=0
Send progress indicator.
virtual bool havePruned()=0
Check if any block has been pruned.
virtual void findCoins(std::map< COutPoint, Coin > &coins)=0
Look up unspent output information.
virtual bool shutdownRequested()=0
Check if shutdown requested.
virtual bool hasBlockFilterIndex(BlockFilterType filter_type)=0
Returns whether a block filter index is available.
virtual common::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
virtual std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
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...
virtual void getTransactionAncestry(const uint256 &txid, size_t &ancestors, size_t &descendants, size_t *ancestorsize=nullptr, CAmount *ancestorfees=nullptr)=0
Calculate mempool ancestor and descendant counts for the given transaction.
virtual common::SettingsValue getSetting(const std::string &arg)=0
Get settings value.
virtual bool isReadyToBroadcast()=0
Check if the node is ready to broadcast transactions.
virtual bool hasAssumedValidChain()=0
Return true if an assumed-valid chain is in use.
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 bool findBlock(const uint256 &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
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 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...
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 CFeeRate mempoolMinFee()=0
Mempool minimum fee.
virtual void initMessage(const std::string &message)=0
Send init message.
virtual bool isInMempool(const uint256 &txid)=0
Check if transaction is in mempool.
virtual unsigned int estimateMaxBlocks()=0
Fee estimator max target.
virtual bool broadcastTransaction(const CTransactionRef &tx, const CAmount &max_tx_fee, bool relay, std::string &err_string)=0
Transaction is added to memory pool, if the transaction fee is below the amount specified by max_tx_f...
virtual void getPackageLimits(unsigned int &limit_ancestor_count, unsigned int &limit_descendant_count)=0
Get the node's package limits.
virtual bool updateRwSetting(const std::string &name, const common::SettingsValue &value, bool write=true)=0
Write a setting to <datadir>/settings.json.
virtual std::unique_ptr< Handler > handleNotifications(std::shared_ptr< Notifications > notifications)=0
Register handler for notifications.
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
virtual ~Chain()
Definition: chain.h:126
virtual std::unique_ptr< Handler > handleRpc(const CRPCCommand &command)=0
Register handler for RPC.
virtual CFeeRate relayDustFee()=0
Relay dust fee setting (-dustrelayfee), reflecting lowest rate it's economical to spend.
virtual void requestMempoolTransactions(Notifications &notifications)=0
Synchronously send transactionAddedToMempool notifications about all current mempool transactions to ...
virtual void initError(const bilingual_str &message)=0
Send init error.
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation *calc=nullptr)=0
Estimate smart fee.
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee and -incrementalrelayfee settings).
virtual std::vector< common::SettingsValue > getSettingsList(const std::string &arg)=0
Get list of settings values.
virtual CFeeRate relayIncrementalFee()=0
Relay incremental fee setting (-incrementalrelayfee), reflecting cost of relay.
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:54
CBlock * m_data
Definition: chain.h:79
const FoundBlock * m_next_block
Definition: chain.h:78
FoundBlock & height(int &height)
Definition: chain.h:57
FoundBlock & locator(CBlockLocator &locator)
Return locator if block is in the active chain.
Definition: chain.h:64
FoundBlock & hash(uint256 &hash)
Definition: chain.h:56
FoundBlock & mtpTime(int64_t &mtp_time)
Definition: chain.h:60
FoundBlock & nextBlock(const FoundBlock &next_block)
Return next block in the active chain if current block is in the active chain.
Definition: chain.h:66
FoundBlock & data(CBlock &data)
Read block data from disk.
Definition: chain.h:69
FoundBlock & inActiveChain(bool &in_active_chain)
Return whether block is in the active (most-work) chain.
Definition: chain.h:62
FoundBlock & maxTime(int64_t &max_time)
Definition: chain.h:59
int64_t * m_max_time
Definition: chain.h:74
int64_t * m_time
Definition: chain.h:73
bool * m_in_active_chain
Definition: chain.h:76
uint256 * m_hash
Definition: chain.h:71
int64_t * m_mtp_time
Definition: chain.h:75
FoundBlock & time(int64_t &time)
Definition: chain.h:58
CBlockLocator * m_locator
Definition: chain.h:77
256-bit opaque blob.
Definition: uint256.h:106
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition: chain.h:25
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
Definition: interfaces.cpp:835
Definition: init.h:25
RBFTransactionState
The rbf state of unconfirmed transactions.
Definition: rbf.h:29
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
const char * name
Definition: rest.cpp:50
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:124
Bilingual messages:
Definition: translation.h:18
Block data sent with blockConnected, blockDisconnected notifications.
Definition: chain.h:84
unsigned data_pos
Definition: chain.h:89
const uint256 * prev_hash
Definition: chain.h:86
const CBlock * data
Definition: chain.h:90
const uint256 & hash
Definition: chain.h:85
BlockInfo(const uint256 &hash LIFETIMEBOUND)
Definition: chain.h:96
const CBlockUndo * undo_data
Definition: chain.h:91
unsigned int chain_time_max
Definition: chain.h:94
Hash/height pair to help track and identify blocks.
Definition: chain.h:45
uint256 hash
Definition: chain.h:46
NodeContext struct containing references to chain state and connection state.
Definition: context.h:49