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