/ src / interfaces / chain.h
chain.h
  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  
 44  //! Helper for findBlock to selectively return pieces of block data. If block is
 45  //! found, data will be returned by setting specified output variables. If block
 46  //! is not found, output variables will keep their previous values.
 47  class FoundBlock
 48  {
 49  public:
 50      FoundBlock& hash(uint256& hash) { m_hash = &hash; return *this; }
 51      FoundBlock& height(int& height) { m_height = &height; return *this; }
 52      FoundBlock& time(int64_t& time) { m_time = &time; return *this; }
 53      FoundBlock& maxTime(int64_t& max_time) { m_max_time = &max_time; return *this; }
 54      FoundBlock& mtpTime(int64_t& mtp_time) { m_mtp_time = &mtp_time; return *this; }
 55      //! Return whether block is in the active (most-work) chain.
 56      FoundBlock& inActiveChain(bool& in_active_chain) { m_in_active_chain = &in_active_chain; return *this; }
 57      //! Return locator if block is in the active chain.
 58      FoundBlock& locator(CBlockLocator& locator) { m_locator = &locator; return *this; }
 59      //! Return next block in the active chain if current block is in the active chain.
 60      FoundBlock& nextBlock(const FoundBlock& next_block) { m_next_block = &next_block; return *this; }
 61      //! Read block data from disk. If the block exists but doesn't have data
 62      //! (for example due to pruning), the CBlock variable will be set to null.
 63      FoundBlock& data(CBlock& data) { m_data = &data; return *this; }
 64  
 65      uint256* m_hash = nullptr;
 66      int* m_height = nullptr;
 67      int64_t* m_time = nullptr;
 68      int64_t* m_max_time = nullptr;
 69      int64_t* m_mtp_time = nullptr;
 70      bool* m_in_active_chain = nullptr;
 71      CBlockLocator* m_locator = nullptr;
 72      const FoundBlock* m_next_block = nullptr;
 73      CBlock* m_data = nullptr;
 74      mutable bool found = false;
 75  };
 76  
 77  //! Block data sent with blockConnected, blockDisconnected notifications.
 78  struct BlockInfo {
 79      const uint256& hash;
 80      const uint256* prev_hash = nullptr;
 81      int height = -1;
 82      int file_number = -1;
 83      unsigned data_pos = 0;
 84      const CBlock* data = nullptr;
 85      const CBlockUndo* undo_data = nullptr;
 86      // The maximum time in the chain up to and including this block.
 87      // A timestamp that can only move forward.
 88      unsigned int chain_time_max{0};
 89  
 90      BlockInfo(const uint256& hash LIFETIMEBOUND) : hash(hash) {}
 91  };
 92  
 93  //! The action to be taken after updating a settings value.
 94  //! WRITE indicates that the updated value must be written to disk,
 95  //! while SKIP_WRITE indicates that the change will be kept in memory-only
 96  //! without persisting it.
 97  enum class SettingsAction {
 98      WRITE,
 99      SKIP_WRITE
100  };
101  
102  using SettingsUpdate = std::function<std::optional<interfaces::SettingsAction>(common::SettingsValue&)>;
103  
104  //! Interface giving clients (wallet processes, maybe other analysis tools in
105  //! the future) ability to access to the chain state, receive notifications,
106  //! estimate fees, and submit transactions.
107  //!
108  //! TODO: Current chain methods are too low level, exposing too much of the
109  //! internal workings of the bitcoin node, and not being very convenient to use.
110  //! Chain methods should be cleaned up and simplified over time. Examples:
111  //!
112  //! * The initMessages() and showProgress() methods which the wallet uses to send
113  //!   notifications to the GUI should go away when GUI and wallet can directly
114  //!   communicate with each other without going through the node
115  //!   (https://github.com/bitcoin/bitcoin/pull/15288#discussion_r253321096).
116  //!
117  //! * The handleRpc, registerRpcs, rpcEnableDeprecated methods and other RPC
118  //!   methods can go away if wallets listen for HTTP requests on their own
119  //!   ports instead of registering to handle requests on the node HTTP port.
120  //!
121  //! * Move fee estimation queries to an asynchronous interface and let the
122  //!   wallet cache it, fee estimation being driven by node mempool, wallet
123  //!   should be the consumer.
124  //!
125  //! * `guessVerificationProgress` and similar methods can go away if rescan
126  //!   logic moves out of the wallet, and the wallet just requests scans from the
127  //!   node (https://github.com/bitcoin/bitcoin/issues/11756)
128  class Chain
129  {
130  public:
131      virtual ~Chain() = default;
132  
133      //! Get current chain height, not including genesis block (returns 0 if
134      //! chain only contains genesis block, nullopt if chain does not contain
135      //! any blocks)
136      virtual std::optional<int> getHeight() = 0;
137  
138      //! Get block hash. Height must be valid or this function will abort.
139      virtual uint256 getBlockHash(int height) = 0;
140  
141      //! Check that the block is available on disk (i.e. has not been
142      //! pruned), and contains transactions.
143      virtual bool haveBlockOnDisk(int height) = 0;
144  
145      //! Get locator for the current chain tip.
146      virtual CBlockLocator getTipLocator() = 0;
147  
148      //! Return a locator that refers to a block in the active chain.
149      //! If specified block is not in the active chain, return locator for the latest ancestor that is in the chain.
150      virtual CBlockLocator getActiveChainLocator(const uint256& block_hash) = 0;
151  
152      //! Return height of the highest block on chain in common with the locator,
153      //! which will either be the original block used to create the locator,
154      //! or one of its ancestors.
155      virtual std::optional<int> findLocatorFork(const CBlockLocator& locator) = 0;
156  
157      //! Returns whether a block filter index is available.
158      virtual bool hasBlockFilterIndex(BlockFilterType filter_type) = 0;
159  
160      //! Returns whether any of the elements match the block via a BIP 157 block filter
161      //! or std::nullopt if the block filter for this block couldn't be found.
162      virtual std::optional<bool> blockFilterMatchesAny(BlockFilterType filter_type, const uint256& block_hash, const GCSFilter::ElementSet& filter_set) = 0;
163  
164      //! Return whether node has the block and optionally return block metadata
165      //! or contents.
166      virtual bool findBlock(const uint256& hash, const FoundBlock& block={}) = 0;
167  
168      //! Find first block in the chain with timestamp >= the given time
169      //! and height >= than the given height, return false if there is no block
170      //! with a high enough timestamp and height. Optionally return block
171      //! information.
172      virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block={}) = 0;
173  
174      //! Find ancestor of block at specified height and optionally return
175      //! ancestor information.
176      virtual bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out={}) = 0;
177  
178      //! Return whether block descends from a specified ancestor, and
179      //! optionally return ancestor information.
180      virtual bool findAncestorByHash(const uint256& block_hash,
181          const uint256& ancestor_hash,
182          const FoundBlock& ancestor_out={}) = 0;
183  
184      //! Find most recent common ancestor between two blocks and optionally
185      //! return block information.
186      virtual bool findCommonAncestor(const uint256& block_hash1,
187          const uint256& block_hash2,
188          const FoundBlock& ancestor_out={},
189          const FoundBlock& block1_out={},
190          const FoundBlock& block2_out={}) = 0;
191  
192      //! Look up unspent output information. Returns coins in the mempool and in
193      //! the current chain UTXO set. Iterates through all the keys in the map and
194      //! populates the values.
195      virtual void findCoins(std::map<COutPoint, Coin>& coins) = 0;
196  
197      //! Estimate fraction of total transactions verified if blocks up to
198      //! the specified block hash are verified.
199      virtual double guessVerificationProgress(const uint256& block_hash) = 0;
200  
201      //! Return true if data is available for all blocks in the specified range
202      //! of blocks. This checks all blocks that are ancestors of block_hash in
203      //! the height range from min_height to max_height, inclusive.
204      virtual bool hasBlocks(const uint256& block_hash, int min_height = 0, std::optional<int> max_height = {}) = 0;
205  
206      //! Check if transaction is RBF opt in.
207      virtual RBFTransactionState isRBFOptIn(const CTransaction& tx) = 0;
208  
209      //! Check if transaction is in mempool.
210      virtual bool isInMempool(const uint256& txid) = 0;
211  
212      //! Check if transaction has descendants in mempool.
213      virtual bool hasDescendantsInMempool(const uint256& txid) = 0;
214  
215      //! Transaction is added to memory pool, if the transaction fee is below the
216      //! amount specified by max_tx_fee, and broadcast to all peers if relay is set to true.
217      //! Return false if the transaction could not be added due to the fee or for another reason.
218      virtual bool broadcastTransaction(const CTransactionRef& tx,
219          const CAmount& max_tx_fee,
220          bool relay,
221          std::string& err_string) = 0;
222  
223      //! Calculate mempool ancestor and descendant counts for the given transaction.
224      virtual void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) = 0;
225  
226      //! For each outpoint, calculate the fee-bumping cost to spend this outpoint at the specified
227      //  feerate, including bumping its ancestors. For example, if the target feerate is 10sat/vbyte
228      //  and this outpoint refers to a mempool transaction at 3sat/vbyte, the bump fee includes the
229      //  cost to bump the mempool transaction to 10sat/vbyte (i.e. 7 * mempooltx.vsize). If that
230      //  transaction also has, say, an unconfirmed parent with a feerate of 1sat/vbyte, the bump fee
231      //  includes the cost to bump the parent (i.e. 9 * parentmempooltx.vsize).
232      //
233      //  If the outpoint comes from an unconfirmed transaction that is already above the target
234      //  feerate or bumped by its descendant(s) already, it does not need to be bumped. Its bump fee
235      //  is 0. Likewise, if any of the transaction's ancestors are already bumped by a transaction
236      //  in our mempool, they are not included in the transaction's bump fee.
237      //
238      //  Also supported is bump-fee calculation in the case of replacements. If an outpoint
239      //  conflicts with another transaction in the mempool, it is assumed that the goal is to replace
240      //  that transaction. As such, the calculation will exclude the to-be-replaced transaction, but
241      //  will include the fee-bumping cost. If bump fees of descendants of the to-be-replaced
242      //  transaction are requested, the value will be 0. Fee-related RBF rules are not included as
243      //  they are logically distinct.
244      //
245      //  Any outpoints that are otherwise unavailable from the mempool (e.g. UTXOs from confirmed
246      //  transactions or transactions not yet broadcast by the wallet) are given a bump fee of 0.
247      //
248      //  If multiple outpoints come from the same transaction (which would be very rare because
249      //  it means that one transaction has multiple change outputs or paid the same wallet using multiple
250      //  outputs in the same transaction) or have shared ancestry, the bump fees are calculated
251      //  independently, i.e. as if only one of them is spent. This may result in double-fee-bumping. This
252      //  caveat can be rectified per use of the sister-function CalculateCombinedBumpFee(…).
253      virtual std::map<COutPoint, CAmount> calculateIndividualBumpFees(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) = 0;
254  
255      //! Calculate the combined bump fee for an input set per the same strategy
256      //  as in CalculateIndividualBumpFees(…).
257      //  Unlike CalculateIndividualBumpFees(…), this does not return individual
258      //  bump fees per outpoint, but a single bump fee for the shared ancestry.
259      //  The combined bump fee may be used to correct overestimation due to
260      //  shared ancestry by multiple UTXOs after coin selection.
261      virtual std::optional<CAmount> calculateCombinedBumpFee(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) = 0;
262  
263      //! Get the node's package limits.
264      //! Currently only returns the ancestor and descendant count limits, but could be enhanced to
265      //! return more policy settings.
266      virtual void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) = 0;
267  
268      //! Check if transaction will pass the mempool's chain limits.
269      virtual util::Result<void> checkChainLimits(const CTransactionRef& tx) = 0;
270  
271      //! Estimate smart fee.
272      virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc = nullptr) = 0;
273  
274      //! Fee estimator max target.
275      virtual unsigned int estimateMaxBlocks() = 0;
276  
277      //! Mempool minimum fee.
278      virtual CFeeRate mempoolMinFee() = 0;
279  
280      //! Relay current minimum fee (from -minrelaytxfee and -incrementalrelayfee settings).
281      virtual CFeeRate relayMinFee() = 0;
282  
283      //! Relay incremental fee setting (-incrementalrelayfee), reflecting cost of relay.
284      virtual CFeeRate relayIncrementalFee() = 0;
285  
286      //! Relay dust fee setting (-dustrelayfee), reflecting lowest rate it's economical to spend.
287      virtual CFeeRate relayDustFee() = 0;
288  
289      //! Check if any block has been pruned.
290      virtual bool havePruned() = 0;
291  
292      //! Get the current prune height.
293      virtual std::optional<int> getPruneHeight() = 0;
294  
295      //! Check if the node is ready to broadcast transactions.
296      virtual bool isReadyToBroadcast() = 0;
297  
298      //! Check if in IBD.
299      virtual bool isInitialBlockDownload() = 0;
300  
301      //! Check if shutdown requested.
302      virtual bool shutdownRequested() = 0;
303  
304      //! Send init message.
305      virtual void initMessage(const std::string& message) = 0;
306  
307      //! Send init warning.
308      virtual void initWarning(const bilingual_str& message) = 0;
309  
310      //! Send init error.
311      virtual void initError(const bilingual_str& message) = 0;
312  
313      //! Send progress indicator.
314      virtual void showProgress(const std::string& title, int progress, bool resume_possible) = 0;
315  
316      //! Chain notifications.
317      class Notifications
318      {
319      public:
320          virtual ~Notifications() = default;
321          virtual void transactionAddedToMempool(const CTransactionRef& tx) {}
322          virtual void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) {}
323          virtual void blockConnected(ChainstateRole role, const BlockInfo& block) {}
324          virtual void blockDisconnected(const BlockInfo& block) {}
325          virtual void updatedBlockTip() {}
326          virtual void chainStateFlushed(ChainstateRole role, const CBlockLocator& locator) {}
327      };
328  
329      //! Register handler for notifications.
330      virtual std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) = 0;
331  
332      //! Wait for pending notifications to be processed unless block hash points to the current
333      //! chain tip.
334      virtual void waitForNotificationsIfTipChanged(const uint256& old_tip) = 0;
335  
336      //! Register handler for RPC. Command is not copied, so reference
337      //! needs to remain valid until Handler is disconnected.
338      virtual std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) = 0;
339  
340      //! Check if deprecated RPC is enabled.
341      virtual bool rpcEnableDeprecated(const std::string& method) = 0;
342  
343      //! Run function after given number of seconds. Cancel any previous calls with same name.
344      virtual void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) = 0;
345  
346      //! Get settings value.
347      virtual common::SettingsValue getSetting(const std::string& arg) = 0;
348  
349      //! Get list of settings values.
350      virtual std::vector<common::SettingsValue> getSettingsList(const std::string& arg) = 0;
351  
352      //! Return <datadir>/settings.json setting value.
353      virtual common::SettingsValue getRwSetting(const std::string& name) = 0;
354  
355      //! Updates a setting in <datadir>/settings.json.
356      //! Null can be passed to erase the setting. There is intentionally no
357      //! support for writing null values to settings.json.
358      //! Depending on the action returned by the update function, this will either
359      //! update the setting in memory or write the updated settings to disk.
360      virtual bool updateRwSetting(const std::string& name, const SettingsUpdate& update_function) = 0;
361  
362      //! Replace a setting in <datadir>/settings.json with a new value.
363      //! Null can be passed to erase the setting.
364      //! This method provides a simpler alternative to updateRwSetting when
365      //! atomically reading and updating the setting is not required.
366      virtual bool overwriteRwSetting(const std::string& name, common::SettingsValue value, SettingsAction action = SettingsAction::WRITE) = 0;
367  
368      //! Delete a given setting in <datadir>/settings.json.
369      //! This method provides a simpler alternative to overwriteRwSetting when
370      //! erasing a setting, for ease of use and readability.
371      virtual bool deleteRwSettings(const std::string& name, SettingsAction action = SettingsAction::WRITE) = 0;
372  
373      //! Synchronously send transactionAddedToMempool notifications about all
374      //! current mempool transactions to the specified handler and return after
375      //! the last one is sent. These notifications aren't coordinated with async
376      //! notifications sent by handleNotifications, so out of date async
377      //! notifications from handleNotifications can arrive during and after
378      //! synchronous notifications from requestMempoolTransactions. Clients need
379      //! to be prepared to handle this by ignoring notifications about unknown
380      //! removed transactions and already added new transactions.
381      virtual void requestMempoolTransactions(Notifications& notifications) = 0;
382  
383      //! Return true if an assumed-valid chain is in use.
384      virtual bool hasAssumedValidChain() = 0;
385  
386      //! Get internal node context. Useful for testing, but not
387      //! accessible across processes.
388      virtual node::NodeContext* context() { return nullptr; }
389  };
390  
391  //! Interface to let node manage chain clients (wallets, or maybe tools for
392  //! monitoring and analysis in the future).
393  class ChainClient
394  {
395  public:
396      virtual ~ChainClient() = default;
397  
398      //! Register rpcs.
399      virtual void registerRpcs() = 0;
400  
401      //! Check for errors before loading.
402      virtual bool verify() = 0;
403  
404      //! Load saved state.
405      virtual bool load() = 0;
406  
407      //! Start client execution and provide a scheduler.
408      virtual void start(CScheduler& scheduler) = 0;
409  
410      //! Save state to disk.
411      virtual void flush() = 0;
412  
413      //! Shut down client.
414      virtual void stop() = 0;
415  
416      //! Set mock time.
417      virtual void setMockTime(int64_t time) = 0;
418  
419      //! Mock the scheduler to fast forward in time.
420      virtual void schedulerMockForward(std::chrono::seconds delta_seconds) = 0;
421  };
422  
423  //! Return implementation of Chain interface.
424  std::unique_ptr<Chain> MakeChain(node::NodeContext& node);
425  
426  } // namespace interfaces
427  
428  #endif // BITCOIN_INTERFACES_CHAIN_H