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