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