Coverage Report

Created: 2024-09-19 18:47

/root/bitcoin/src/node/interfaces.cpp
Line
Count
Source (jump to first uncovered line)
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
#include <addrdb.h>
6
#include <banman.h>
7
#include <blockfilter.h>
8
#include <chain.h>
9
#include <chainparams.h>
10
#include <common/args.h>
11
#include <consensus/validation.h>
12
#include <deploymentstatus.h>
13
#include <external_signer.h>
14
#include <index/blockfilterindex.h>
15
#include <init.h>
16
#include <interfaces/chain.h>
17
#include <interfaces/handler.h>
18
#include <interfaces/mining.h>
19
#include <interfaces/node.h>
20
#include <interfaces/wallet.h>
21
#include <kernel/chain.h>
22
#include <kernel/context.h>
23
#include <kernel/mempool_entry.h>
24
#include <logging.h>
25
#include <mapport.h>
26
#include <net.h>
27
#include <net_processing.h>
28
#include <netaddress.h>
29
#include <netbase.h>
30
#include <node/blockstorage.h>
31
#include <node/coin.h>
32
#include <node/context.h>
33
#include <node/interface_ui.h>
34
#include <node/mini_miner.h>
35
#include <node/miner.h>
36
#include <node/transaction.h>
37
#include <node/types.h>
38
#include <node/warnings.h>
39
#include <policy/feerate.h>
40
#include <policy/fees.h>
41
#include <policy/policy.h>
42
#include <policy/rbf.h>
43
#include <policy/settings.h>
44
#include <primitives/block.h>
45
#include <primitives/transaction.h>
46
#include <rpc/protocol.h>
47
#include <rpc/server.h>
48
#include <support/allocators/secure.h>
49
#include <sync.h>
50
#include <txmempool.h>
51
#include <uint256.h>
52
#include <univalue.h>
53
#include <util/check.h>
54
#include <util/result.h>
55
#include <util/signalinterrupt.h>
56
#include <util/string.h>
57
#include <util/translation.h>
58
#include <validation.h>
59
#include <validationinterface.h>
60
61
#include <config/bitcoin-config.h> // IWYU pragma: keep
62
63
#include <any>
64
#include <memory>
65
#include <optional>
66
#include <utility>
67
68
#include <boost/signals2/signal.hpp>
69
70
using interfaces::BlockTemplate;
71
using interfaces::BlockTip;
72
using interfaces::Chain;
73
using interfaces::FoundBlock;
74
using interfaces::Handler;
75
using interfaces::MakeSignalHandler;
76
using interfaces::Mining;
77
using interfaces::Node;
78
using interfaces::WalletLoader;
79
using node::BlockAssembler;
80
using util::Join;
81
82
namespace node {
83
// All members of the classes in this namespace are intentionally public, as the
84
// classes themselves are private.
85
namespace {
86
#ifdef ENABLE_EXTERNAL_SIGNER
87
class ExternalSignerImpl : public interfaces::ExternalSigner
88
{
89
public:
90
    ExternalSignerImpl(::ExternalSigner signer) : m_signer(std::move(signer)) {}
91
    std::string getName() override { return m_signer.m_name; }
92
    ::ExternalSigner m_signer;
93
};
94
#endif
95
96
class NodeImpl : public Node
97
{
98
public:
99
0
    explicit NodeImpl(NodeContext& context) { setContext(&context); }
100
0
    void initLogging() override { InitLogging(args()); }
101
0
    void initParameterInteraction() override { InitParameterInteraction(args()); }
102
0
    bilingual_str getWarnings() override { return Join(Assert(m_context->warnings)->GetMessages(), Untranslated("<hr />")); }
103
0
    int getExitStatus() override { return Assert(m_context)->exit_status.load(); }
104
0
    BCLog::CategoryMask getLogCategories() override { return LogInstance().GetCategoryMask(); }
105
    bool baseInitialize() override
106
0
    {
107
0
        if (!AppInitBasicSetup(args(), Assert(context())->exit_status)) return false;
108
0
        if (!AppInitParameterInteraction(args())) return false;
109
110
0
        m_context->warnings = std::make_unique<node::Warnings>();
111
0
        m_context->kernel = std::make_unique<kernel::Context>();
112
0
        m_context->ecc_context = std::make_unique<ECC_Context>();
113
0
        if (!AppInitSanityChecks(*m_context->kernel)) return false;
114
115
0
        if (!AppInitLockDataDirectory()) return false;
116
0
        if (!AppInitInterfaces(*m_context)) return false;
117
118
0
        return true;
119
0
    }
120
    bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info) override
121
0
    {
122
0
        if (AppInitMain(*m_context, tip_info)) return true;
123
        // Error during initialization, set exit status before continue
124
0
        m_context->exit_status.store(EXIT_FAILURE);
125
0
        return false;
126
0
    }
127
    void appShutdown() override
128
0
    {
129
0
        Interrupt(*m_context);
130
0
        Shutdown(*m_context);
131
0
    }
132
    void startShutdown() override
133
0
    {
134
0
        if (!(*Assert(Assert(m_context)->shutdown))()) {
135
0
            LogError("Failed to send shutdown signal\n");
136
0
        }
137
        // Stop RPC for clean shutdown if any of waitfor* commands is executed.
138
0
        if (args().GetBoolArg("-server", false)) {
139
0
            InterruptRPC();
140
0
            StopRPC();
141
0
        }
142
0
    }
143
0
    bool shutdownRequested() override { return ShutdownRequested(*Assert(m_context)); };
144
    bool isSettingIgnored(const std::string& name) override
145
0
    {
146
0
        bool ignored = false;
147
0
        args().LockSettings([&](common::Settings& settings) {
148
0
            if (auto* options = common::FindKey(settings.command_line_options, name)) {
149
0
                ignored = !options->empty();
150
0
            }
151
0
        });
152
0
        return ignored;
153
0
    }
154
0
    common::SettingsValue getPersistentSetting(const std::string& name) override { return args().GetPersistentSetting(name); }
155
    void updateRwSetting(const std::string& name, const common::SettingsValue& value) override
156
0
    {
157
0
        args().LockSettings([&](common::Settings& settings) {
158
0
            if (value.isNull()) {
159
0
                settings.rw_settings.erase(name);
160
0
            } else {
161
0
                settings.rw_settings[name] = value;
162
0
            }
163
0
        });
164
0
        args().WriteSettingsFile();
165
0
    }
166
    void forceSetting(const std::string& name, const common::SettingsValue& value) override
167
0
    {
168
0
        args().LockSettings([&](common::Settings& settings) {
169
0
            if (value.isNull()) {
170
0
                settings.forced_settings.erase(name);
171
0
            } else {
172
0
                settings.forced_settings[name] = value;
173
0
            }
174
0
        });
175
0
    }
176
    void resetSettings() override
177
0
    {
178
0
        args().WriteSettingsFile(/*errors=*/nullptr, /*backup=*/true);
179
0
        args().LockSettings([&](common::Settings& settings) {
180
0
            settings.rw_settings.clear();
181
0
        });
182
0
        args().WriteSettingsFile();
183
0
    }
184
0
    void mapPort(bool use_upnp, bool use_natpmp) override { StartMapPort(use_upnp, use_natpmp); }
185
0
    bool getProxy(Network net, Proxy& proxy_info) override { return GetProxy(net, proxy_info); }
186
    size_t getNodeCount(ConnectionDirection flags) override
187
0
    {
188
0
        return m_context->connman ? m_context->connman->GetNodeCount(flags) : 0;
189
0
    }
190
    bool getNodesStats(NodesStats& stats) override
191
0
    {
192
0
        stats.clear();
193
194
0
        if (m_context->connman) {
195
0
            std::vector<CNodeStats> stats_temp;
196
0
            m_context->connman->GetNodeStats(stats_temp);
197
198
0
            stats.reserve(stats_temp.size());
199
0
            for (auto& node_stats_temp : stats_temp) {
200
0
                stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
201
0
            }
202
203
            // Try to retrieve the CNodeStateStats for each node.
204
0
            if (m_context->peerman) {
205
0
                TRY_LOCK(::cs_main, lockMain);
206
0
                if (lockMain) {
207
0
                    for (auto& node_stats : stats) {
208
0
                        std::get<1>(node_stats) =
209
0
                            m_context->peerman->GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
210
0
                    }
211
0
                }
212
0
            }
213
0
            return true;
214
0
        }
215
0
        return false;
216
0
    }
217
    bool getBanned(banmap_t& banmap) override
218
0
    {
219
0
        if (m_context->banman) {
220
0
            m_context->banman->GetBanned(banmap);
221
0
            return true;
222
0
        }
223
0
        return false;
224
0
    }
225
    bool ban(const CNetAddr& net_addr, int64_t ban_time_offset) override
226
0
    {
227
0
        if (m_context->banman) {
228
0
            m_context->banman->Ban(net_addr, ban_time_offset);
229
0
            return true;
230
0
        }
231
0
        return false;
232
0
    }
233
    bool unban(const CSubNet& ip) override
234
0
    {
235
0
        if (m_context->banman) {
236
0
            m_context->banman->Unban(ip);
237
0
            return true;
238
0
        }
239
0
        return false;
240
0
    }
241
    bool disconnectByAddress(const CNetAddr& net_addr) override
242
0
    {
243
0
        if (m_context->connman) {
244
0
            return m_context->connman->DisconnectNode(net_addr);
245
0
        }
246
0
        return false;
247
0
    }
248
    bool disconnectById(NodeId id) override
249
0
    {
250
0
        if (m_context->connman) {
251
0
            return m_context->connman->DisconnectNode(id);
252
0
        }
253
0
        return false;
254
0
    }
255
    std::vector<std::unique_ptr<interfaces::ExternalSigner>> listExternalSigners() override
256
0
    {
257
#ifdef ENABLE_EXTERNAL_SIGNER
258
        std::vector<ExternalSigner> signers = {};
259
        const std::string command = args().GetArg("-signer", "");
260
        if (command == "") return {};
261
        ExternalSigner::Enumerate(command, signers, Params().GetChainTypeString());
262
        std::vector<std::unique_ptr<interfaces::ExternalSigner>> result;
263
        result.reserve(signers.size());
264
        for (auto& signer : signers) {
265
            result.emplace_back(std::make_unique<ExternalSignerImpl>(std::move(signer)));
266
        }
267
        return result;
268
#else
269
        // This result is indistinguishable from a successful call that returns
270
        // no signers. For the current GUI this doesn't matter, because the wallet
271
        // creation dialog disables the external signer checkbox in both
272
        // cases. The return type could be changed to std::optional<std::vector>
273
        // (or something that also includes error messages) if this distinction
274
        // becomes important.
275
0
        return {};
276
0
#endif // ENABLE_EXTERNAL_SIGNER
277
0
    }
278
0
    int64_t getTotalBytesRecv() override { return m_context->connman ? m_context->connman->GetTotalBytesRecv() : 0; }
279
0
    int64_t getTotalBytesSent() override { return m_context->connman ? m_context->connman->GetTotalBytesSent() : 0; }
280
0
    size_t getMempoolSize() override { return m_context->mempool ? m_context->mempool->size() : 0; }
281
0
    size_t getMempoolDynamicUsage() override { return m_context->mempool ? m_context->mempool->DynamicMemoryUsage() : 0; }
282
0
    size_t getMempoolMaxUsage() override { return m_context->mempool ? m_context->mempool->m_opts.max_size_bytes : 0; }
283
    bool getHeaderTip(int& height, int64_t& block_time) override
284
0
    {
285
0
        LOCK(::cs_main);
286
0
        auto best_header = chainman().m_best_header;
287
0
        if (best_header) {
288
0
            height = best_header->nHeight;
289
0
            block_time = best_header->GetBlockTime();
290
0
            return true;
291
0
        }
292
0
        return false;
293
0
    }
294
    std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() override
295
0
    {
296
0
        if (m_context->connman)
297
0
            return m_context->connman->getNetLocalAddresses();
298
0
        else
299
0
            return {};
300
0
    }
301
    int getNumBlocks() override
302
0
    {
303
0
        LOCK(::cs_main);
304
0
        return chainman().ActiveChain().Height();
305
0
    }
306
    uint256 getBestBlockHash() override
307
0
    {
308
0
        const CBlockIndex* tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip());
309
0
        return tip ? tip->GetBlockHash() : chainman().GetParams().GenesisBlock().GetHash();
310
0
    }
311
    int64_t getLastBlockTime() override
312
0
    {
313
0
        LOCK(::cs_main);
314
0
        if (chainman().ActiveChain().Tip()) {
315
0
            return chainman().ActiveChain().Tip()->GetBlockTime();
316
0
        }
317
0
        return chainman().GetParams().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
318
0
    }
319
    double getVerificationProgress() override
320
0
    {
321
0
        return GuessVerificationProgress(chainman().GetParams().TxData(), WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()));
322
0
    }
323
    bool isInitialBlockDownload() override
324
0
    {
325
0
        return chainman().IsInitialBlockDownload();
326
0
    }
327
0
    bool isLoadingBlocks() override { return chainman().m_blockman.LoadingBlocks(); }
328
    void setNetworkActive(bool active) override
329
0
    {
330
0
        if (m_context->connman) {
331
0
            m_context->connman->SetNetworkActive(active);
332
0
        }
333
0
    }
334
0
    bool getNetworkActive() override { return m_context->connman && m_context->connman->GetNetworkActive(); }
335
    CFeeRate getDustRelayFee() override
336
0
    {
337
0
        if (!m_context->mempool) return CFeeRate{DUST_RELAY_TX_FEE};
338
0
        return m_context->mempool->m_opts.dust_relay_feerate;
339
0
    }
340
    UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
341
0
    {
342
0
        JSONRPCRequest req;
343
0
        req.context = m_context;
344
0
        req.params = params;
345
0
        req.strMethod = command;
346
0
        req.URI = uri;
347
0
        return ::tableRPC.execute(req);
348
0
    }
349
0
    std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
350
0
    void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); }
351
0
    void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); }
352
    std::optional<Coin> getUnspentOutput(const COutPoint& output) override
353
0
    {
354
0
        LOCK(::cs_main);
355
0
        Coin coin;
356
0
        if (chainman().ActiveChainstate().CoinsTip().GetCoin(output, coin)) return coin;
357
0
        return {};
358
0
    }
359
    TransactionError broadcastTransaction(CTransactionRef tx, CAmount max_tx_fee, std::string& err_string) override
360
0
    {
361
0
        return BroadcastTransaction(*m_context, std::move(tx), err_string, max_tx_fee, /*relay=*/ true, /*wait_callback=*/ false);
362
0
    }
363
    WalletLoader& walletLoader() override
364
0
    {
365
0
        return *Assert(m_context->wallet_loader);
366
0
    }
367
    std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
368
0
    {
369
0
        return MakeSignalHandler(::uiInterface.InitMessage_connect(fn));
370
0
    }
371
    std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
372
0
    {
373
0
        return MakeSignalHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
374
0
    }
375
    std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
376
0
    {
377
0
        return MakeSignalHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
378
0
    }
379
    std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
380
0
    {
381
0
        return MakeSignalHandler(::uiInterface.ShowProgress_connect(fn));
382
0
    }
383
    std::unique_ptr<Handler> handleInitWallet(InitWalletFn fn) override
384
0
    {
385
0
        return MakeSignalHandler(::uiInterface.InitWallet_connect(fn));
386
0
    }
387
    std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
388
0
    {
389
0
        return MakeSignalHandler(::uiInterface.NotifyNumConnectionsChanged_connect(fn));
390
0
    }
391
    std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
392
0
    {
393
0
        return MakeSignalHandler(::uiInterface.NotifyNetworkActiveChanged_connect(fn));
394
0
    }
395
    std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
396
0
    {
397
0
        return MakeSignalHandler(::uiInterface.NotifyAlertChanged_connect(fn));
398
0
    }
399
    std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
400
0
    {
401
0
        return MakeSignalHandler(::uiInterface.BannedListChanged_connect(fn));
402
0
    }
403
    std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
404
0
    {
405
0
        return MakeSignalHandler(::uiInterface.NotifyBlockTip_connect([fn](SynchronizationState sync_state, const CBlockIndex* block) {
406
0
            fn(sync_state, BlockTip{block->nHeight, block->GetBlockTime(), block->GetBlockHash()},
407
0
                GuessVerificationProgress(Params().TxData(), block));
408
0
        }));
409
0
    }
410
    std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
411
0
    {
412
0
        return MakeSignalHandler(
413
0
            ::uiInterface.NotifyHeaderTip_connect([fn](SynchronizationState sync_state, int64_t height, int64_t timestamp, bool presync) {
414
0
                fn(sync_state, BlockTip{(int)height, timestamp, uint256{}}, presync);
415
0
            }));
416
0
    }
417
0
    NodeContext* context() override { return m_context; }
418
    void setContext(NodeContext* context) override
419
0
    {
420
0
        m_context = context;
421
0
    }
422
0
    ArgsManager& args() { return *Assert(Assert(m_context)->args); }
423
0
    ChainstateManager& chainman() { return *Assert(m_context->chainman); }
424
    NodeContext* m_context{nullptr};
425
};
426
427
// NOLINTNEXTLINE(misc-no-recursion)
428
bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active, const BlockManager& blockman)
429
0
{
430
0
    if (!index) return false;
431
0
    if (block.m_hash) *block.m_hash = index->GetBlockHash();
432
0
    if (block.m_height) *block.m_height = index->nHeight;
433
0
    if (block.m_time) *block.m_time = index->GetBlockTime();
434
0
    if (block.m_max_time) *block.m_max_time = index->GetBlockTimeMax();
435
0
    if (block.m_mtp_time) *block.m_mtp_time = index->GetMedianTimePast();
436
0
    if (block.m_in_active_chain) *block.m_in_active_chain = active[index->nHeight] == index;
437
0
    if (block.m_locator) { *block.m_locator = GetLocator(index); }
438
0
    if (block.m_next_block) FillBlock(active[index->nHeight] == index ? active[index->nHeight + 1] : nullptr, *block.m_next_block, lock, active, blockman);
439
0
    if (block.m_data) {
440
0
        REVERSE_LOCK(lock);
441
0
        if (!blockman.ReadBlockFromDisk(*block.m_data, *index)) block.m_data->SetNull();
442
0
    }
443
0
    block.found = true;
444
0
    return true;
445
0
}
446
447
class NotificationsProxy : public CValidationInterface
448
{
449
public:
450
    explicit NotificationsProxy(std::shared_ptr<Chain::Notifications> notifications)
451
0
        : m_notifications(std::move(notifications)) {}
452
0
    virtual ~NotificationsProxy() = default;
453
    void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t mempool_sequence) override
454
0
    {
455
0
        m_notifications->transactionAddedToMempool(tx.info.m_tx);
456
0
    }
457
    void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
458
0
    {
459
0
        m_notifications->transactionRemovedFromMempool(tx, reason);
460
0
    }
461
    void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
462
0
    {
463
0
        m_notifications->blockConnected(role, kernel::MakeBlockInfo(index, block.get()));
464
0
    }
465
    void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
466
0
    {
467
0
        m_notifications->blockDisconnected(kernel::MakeBlockInfo(index, block.get()));
468
0
    }
469
    void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override
470
0
    {
471
0
        m_notifications->updatedBlockTip();
472
0
    }
473
0
    void ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) override {
474
0
        m_notifications->chainStateFlushed(role, locator);
475
0
    }
476
    std::shared_ptr<Chain::Notifications> m_notifications;
477
};
478
479
class NotificationsHandlerImpl : public Handler
480
{
481
public:
482
    explicit NotificationsHandlerImpl(ValidationSignals& signals, std::shared_ptr<Chain::Notifications> notifications)
483
0
        : m_signals{signals}, m_proxy{std::make_shared<NotificationsProxy>(std::move(notifications))}
484
0
    {
485
0
        m_signals.RegisterSharedValidationInterface(m_proxy);
486
0
    }
487
0
    ~NotificationsHandlerImpl() override { disconnect(); }
488
    void disconnect() override
489
0
    {
490
0
        if (m_proxy) {
491
0
            m_signals.UnregisterSharedValidationInterface(m_proxy);
492
0
            m_proxy.reset();
493
0
        }
494
0
    }
495
    ValidationSignals& m_signals;
496
    std::shared_ptr<NotificationsProxy> m_proxy;
497
};
498
499
class RpcHandlerImpl : public Handler
500
{
501
public:
502
0
    explicit RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command)
503
0
    {
504
0
        m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
505
0
            if (!m_wrapped_command) return false;
506
0
            try {
507
0
                return m_wrapped_command->actor(request, result, last_handler);
508
0
            } catch (const UniValue& e) {
509
                // If this is not the last handler and a wallet not found
510
                // exception was thrown, return false so the next handler can
511
                // try to handle the request. Otherwise, reraise the exception.
512
0
                if (!last_handler) {
513
0
                    const UniValue& code = e["code"];
514
0
                    if (code.isNum() && code.getInt<int>() == RPC_WALLET_NOT_FOUND) {
515
0
                        return false;
516
0
                    }
517
0
                }
518
0
                throw;
519
0
            }
520
0
        };
521
0
        ::tableRPC.appendCommand(m_command.name, &m_command);
522
0
    }
523
524
    void disconnect() final
525
0
    {
526
0
        if (m_wrapped_command) {
527
0
            m_wrapped_command = nullptr;
528
0
            ::tableRPC.removeCommand(m_command.name, &m_command);
529
0
        }
530
0
    }
531
532
0
    ~RpcHandlerImpl() override { disconnect(); }
533
534
    CRPCCommand m_command;
535
    const CRPCCommand* m_wrapped_command;
536
};
537
538
class ChainImpl : public Chain
539
{
540
public:
541
0
    explicit ChainImpl(NodeContext& node) : m_node(node) {}
542
    std::optional<int> getHeight() override
543
0
    {
544
0
        const int height{WITH_LOCK(::cs_main, return chainman().ActiveChain().Height())};
545
0
        return height >= 0 ? std::optional{height} : std::nullopt;
546
0
    }
547
    uint256 getBlockHash(int height) override
548
0
    {
549
0
        LOCK(::cs_main);
550
0
        return Assert(chainman().ActiveChain()[height])->GetBlockHash();
551
0
    }
552
    bool haveBlockOnDisk(int height) override
553
0
    {
554
0
        LOCK(::cs_main);
555
0
        const CBlockIndex* block{chainman().ActiveChain()[height]};
556
0
        return block && ((block->nStatus & BLOCK_HAVE_DATA) != 0) && block->nTx > 0;
557
0
    }
558
    CBlockLocator getTipLocator() override
559
0
    {
560
0
        LOCK(::cs_main);
561
0
        return chainman().ActiveChain().GetLocator();
562
0
    }
563
    CBlockLocator getActiveChainLocator(const uint256& block_hash) override
564
0
    {
565
0
        LOCK(::cs_main);
566
0
        const CBlockIndex* index = chainman().m_blockman.LookupBlockIndex(block_hash);
567
0
        return GetLocator(index);
568
0
    }
569
    std::optional<int> findLocatorFork(const CBlockLocator& locator) override
570
0
    {
571
0
        LOCK(::cs_main);
572
0
        if (const CBlockIndex* fork = chainman().ActiveChainstate().FindForkInGlobalIndex(locator)) {
573
0
            return fork->nHeight;
574
0
        }
575
0
        return std::nullopt;
576
0
    }
577
    bool hasBlockFilterIndex(BlockFilterType filter_type) override
578
0
    {
579
0
        return GetBlockFilterIndex(filter_type) != nullptr;
580
0
    }
581
    std::optional<bool> blockFilterMatchesAny(BlockFilterType filter_type, const uint256& block_hash, const GCSFilter::ElementSet& filter_set) override
582
0
    {
583
0
        const BlockFilterIndex* block_filter_index{GetBlockFilterIndex(filter_type)};
584
0
        if (!block_filter_index) return std::nullopt;
585
586
0
        BlockFilter filter;
587
0
        const CBlockIndex* index{WITH_LOCK(::cs_main, return chainman().m_blockman.LookupBlockIndex(block_hash))};
588
0
        if (index == nullptr || !block_filter_index->LookupFilter(index, filter)) return std::nullopt;
589
0
        return filter.GetFilter().MatchAny(filter_set);
590
0
    }
591
    bool findBlock(const uint256& hash, const FoundBlock& block) override
592
0
    {
593
0
        WAIT_LOCK(cs_main, lock);
594
0
        return FillBlock(chainman().m_blockman.LookupBlockIndex(hash), block, lock, chainman().ActiveChain(), chainman().m_blockman);
595
0
    }
596
    bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block) override
597
0
    {
598
0
        WAIT_LOCK(cs_main, lock);
599
0
        const CChain& active = chainman().ActiveChain();
600
0
        return FillBlock(active.FindEarliestAtLeast(min_time, min_height), block, lock, active, chainman().m_blockman);
601
0
    }
602
    bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out) override
603
0
    {
604
0
        WAIT_LOCK(cs_main, lock);
605
0
        const CChain& active = chainman().ActiveChain();
606
0
        if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
607
0
            if (const CBlockIndex* ancestor = block->GetAncestor(ancestor_height)) {
608
0
                return FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman);
609
0
            }
610
0
        }
611
0
        return FillBlock(nullptr, ancestor_out, lock, active, chainman().m_blockman);
612
0
    }
613
    bool findAncestorByHash(const uint256& block_hash, const uint256& ancestor_hash, const FoundBlock& ancestor_out) override
614
0
    {
615
0
        WAIT_LOCK(cs_main, lock);
616
0
        const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash);
617
0
        const CBlockIndex* ancestor = chainman().m_blockman.LookupBlockIndex(ancestor_hash);
618
0
        if (block && ancestor && block->GetAncestor(ancestor->nHeight) != ancestor) ancestor = nullptr;
619
0
        return FillBlock(ancestor, ancestor_out, lock, chainman().ActiveChain(), chainman().m_blockman);
620
0
    }
621
    bool findCommonAncestor(const uint256& block_hash1, const uint256& block_hash2, const FoundBlock& ancestor_out, const FoundBlock& block1_out, const FoundBlock& block2_out) override
622
0
    {
623
0
        WAIT_LOCK(cs_main, lock);
624
0
        const CChain& active = chainman().ActiveChain();
625
0
        const CBlockIndex* block1 = chainman().m_blockman.LookupBlockIndex(block_hash1);
626
0
        const CBlockIndex* block2 = chainman().m_blockman.LookupBlockIndex(block_hash2);
627
0
        const CBlockIndex* ancestor = block1 && block2 ? LastCommonAncestor(block1, block2) : nullptr;
628
        // Using & instead of && below to avoid short circuiting and leaving
629
        // output uninitialized. Cast bool to int to avoid -Wbitwise-instead-of-logical
630
        // compiler warnings.
631
0
        return int{FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman)} &
632
0
               int{FillBlock(block1, block1_out, lock, active, chainman().m_blockman)} &
633
0
               int{FillBlock(block2, block2_out, lock, active, chainman().m_blockman)};
634
0
    }
635
0
    void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(m_node, coins); }
636
    double guessVerificationProgress(const uint256& block_hash) override
637
0
    {
638
0
        LOCK(::cs_main);
639
0
        return GuessVerificationProgress(chainman().GetParams().TxData(), chainman().m_blockman.LookupBlockIndex(block_hash));
640
0
    }
641
    bool hasBlocks(const uint256& block_hash, int min_height, std::optional<int> max_height) override
642
0
    {
643
        // hasBlocks returns true if all ancestors of block_hash in specified
644
        // range have block data (are not pruned), false if any ancestors in
645
        // specified range are missing data.
646
        //
647
        // For simplicity and robustness, min_height and max_height are only
648
        // used to limit the range, and passing min_height that's too low or
649
        // max_height that's too high will not crash or change the result.
650
0
        LOCK(::cs_main);
651
0
        if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
652
0
            if (max_height && block->nHeight >= *max_height) block = block->GetAncestor(*max_height);
653
0
            for (; block->nStatus & BLOCK_HAVE_DATA; block = block->pprev) {
654
                // Check pprev to not segfault if min_height is too low
655
0
                if (block->nHeight <= min_height || !block->pprev) return true;
656
0
            }
657
0
        }
658
0
        return false;
659
0
    }
660
    RBFTransactionState isRBFOptIn(const CTransaction& tx) override
661
0
    {
662
0
        if (!m_node.mempool) return IsRBFOptInEmptyMempool(tx);
663
0
        LOCK(m_node.mempool->cs);
664
0
        return IsRBFOptIn(tx, *m_node.mempool);
665
0
    }
666
    bool isInMempool(const uint256& txid) override
667
0
    {
668
0
        if (!m_node.mempool) return false;
669
0
        LOCK(m_node.mempool->cs);
670
0
        return m_node.mempool->exists(GenTxid::Txid(txid));
671
0
    }
672
    bool hasDescendantsInMempool(const uint256& txid) override
673
0
    {
674
0
        if (!m_node.mempool) return false;
675
0
        LOCK(m_node.mempool->cs);
676
0
        const auto entry{m_node.mempool->GetEntry(Txid::FromUint256(txid))};
677
0
        if (entry == nullptr) return false;
678
0
        return entry->GetCountWithDescendants() > 1;
679
0
    }
680
    bool broadcastTransaction(const CTransactionRef& tx,
681
        const CAmount& max_tx_fee,
682
        bool relay,
683
        std::string& err_string) override
684
0
    {
685
0
        const TransactionError err = BroadcastTransaction(m_node, tx, err_string, max_tx_fee, relay, /*wait_callback=*/false);
686
        // Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures.
687
        // Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures
688
        // that Chain clients do not need to know about.
689
0
        return TransactionError::OK == err;
690
0
    }
691
    void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize, CAmount* ancestorfees) override
692
0
    {
693
0
        ancestors = descendants = 0;
694
0
        if (!m_node.mempool) return;
695
0
        m_node.mempool->GetTransactionAncestry(txid, ancestors, descendants, ancestorsize, ancestorfees);
696
0
    }
697
698
    std::map<COutPoint, CAmount> calculateIndividualBumpFees(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
699
0
    {
700
0
        if (!m_node.mempool) {
701
0
            std::map<COutPoint, CAmount> bump_fees;
702
0
            for (const auto& outpoint : outpoints) {
703
0
                bump_fees.emplace(outpoint, 0);
704
0
            }
705
0
            return bump_fees;
706
0
        }
707
0
        return MiniMiner(*m_node.mempool, outpoints).CalculateBumpFees(target_feerate);
708
0
    }
709
710
    std::optional<CAmount> calculateCombinedBumpFee(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
711
0
    {
712
0
        if (!m_node.mempool) {
713
0
            return 0;
714
0
        }
715
0
        return MiniMiner(*m_node.mempool, outpoints).CalculateTotalBumpFees(target_feerate);
716
0
    }
717
    void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) override
718
0
    {
719
0
        const CTxMemPool::Limits default_limits{};
720
721
0
        const CTxMemPool::Limits& limits{m_node.mempool ? m_node.mempool->m_opts.limits : default_limits};
722
723
0
        limit_ancestor_count = limits.ancestor_count;
724
0
        limit_descendant_count = limits.descendant_count;
725
0
    }
726
    util::Result<void> checkChainLimits(const CTransactionRef& tx) override
727
0
    {
728
0
        if (!m_node.mempool) return {};
729
0
        LockPoints lp;
730
0
        CTxMemPoolEntry entry(tx, 0, 0, 0, 0, false, 0, lp);
731
0
        LOCK(m_node.mempool->cs);
732
0
        return m_node.mempool->CheckPackageLimits({tx}, entry.GetTxSize());
733
0
    }
734
    CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc) override
735
0
    {
736
0
        if (!m_node.fee_estimator) return {};
737
0
        return m_node.fee_estimator->estimateSmartFee(num_blocks, calc, conservative);
738
0
    }
739
    unsigned int estimateMaxBlocks() override
740
0
    {
741
0
        if (!m_node.fee_estimator) return 0;
742
0
        return m_node.fee_estimator->HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
743
0
    }
744
    CFeeRate mempoolMinFee() override
745
0
    {
746
0
        if (!m_node.mempool) return {};
747
0
        return m_node.mempool->GetMinFee();
748
0
    }
749
    CFeeRate relayMinFee() override
750
0
    {
751
0
        if (!m_node.mempool) return CFeeRate{DEFAULT_MIN_RELAY_TX_FEE};
752
0
        return m_node.mempool->m_opts.min_relay_feerate;
753
0
    }
754
    CFeeRate relayIncrementalFee() override
755
0
    {
756
0
        if (!m_node.mempool) return CFeeRate{DEFAULT_INCREMENTAL_RELAY_FEE};
757
0
        return m_node.mempool->m_opts.incremental_relay_feerate;
758
0
    }
759
    CFeeRate relayDustFee() override
760
0
    {
761
0
        if (!m_node.mempool) return CFeeRate{DUST_RELAY_TX_FEE};
762
0
        return m_node.mempool->m_opts.dust_relay_feerate;
763
0
    }
764
    bool havePruned() override
765
0
    {
766
0
        LOCK(::cs_main);
767
0
        return chainman().m_blockman.m_have_pruned;
768
0
    }
769
0
    bool isReadyToBroadcast() override { return !chainman().m_blockman.LoadingBlocks() && !isInitialBlockDownload(); }
770
    bool isInitialBlockDownload() override
771
0
    {
772
0
        return chainman().IsInitialBlockDownload();
773
0
    }
774
0
    bool shutdownRequested() override { return ShutdownRequested(m_node); }
775
0
    void initMessage(const std::string& message) override { ::uiInterface.InitMessage(message); }
776
0
    void initWarning(const bilingual_str& message) override { InitWarning(message); }
777
0
    void initError(const bilingual_str& message) override { InitError(message); }
778
    void showProgress(const std::string& title, int progress, bool resume_possible) override
779
0
    {
780
0
        ::uiInterface.ShowProgress(title, progress, resume_possible);
781
0
    }
782
    std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) override
783
0
    {
784
0
        return std::make_unique<NotificationsHandlerImpl>(validation_signals(), std::move(notifications));
785
0
    }
786
    void waitForNotificationsIfTipChanged(const uint256& old_tip) override
787
0
    {
788
0
        if (!old_tip.IsNull() && old_tip == WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()->GetBlockHash())) return;
789
0
        validation_signals().SyncWithValidationInterfaceQueue();
790
0
    }
791
    std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) override
792
0
    {
793
0
        return std::make_unique<RpcHandlerImpl>(command);
794
0
    }
795
0
    bool rpcEnableDeprecated(const std::string& method) override { return IsDeprecatedRPCEnabled(method); }
796
    void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) override
797
0
    {
798
0
        RPCRunLater(name, std::move(fn), seconds);
799
0
    }
800
    common::SettingsValue getSetting(const std::string& name) override
801
0
    {
802
0
        return args().GetSetting(name);
803
0
    }
804
    std::vector<common::SettingsValue> getSettingsList(const std::string& name) override
805
0
    {
806
0
        return args().GetSettingsList(name);
807
0
    }
808
    common::SettingsValue getRwSetting(const std::string& name) override
809
0
    {
810
0
        common::SettingsValue result;
811
0
        args().LockSettings([&](const common::Settings& settings) {
812
0
            if (const common::SettingsValue* value = common::FindKey(settings.rw_settings, name)) {
813
0
                result = *value;
814
0
            }
815
0
        });
816
0
        return result;
817
0
    }
818
    bool updateRwSetting(const std::string& name,
819
                         const interfaces::SettingsUpdate& update_settings_func) override
820
0
    {
821
0
        std::optional<interfaces::SettingsAction> action;
822
0
        args().LockSettings([&](common::Settings& settings) {
823
0
            auto* ptr_value = common::FindKey(settings.rw_settings, name);
824
            // Create value if it doesn't exist
825
0
            auto& value = ptr_value ? *ptr_value : settings.rw_settings[name];
826
0
            action = update_settings_func(value);
827
0
        });
828
0
        if (!action) return false;
829
        // Now dump value to disk if requested
830
0
        return *action == interfaces::SettingsAction::SKIP_WRITE || args().WriteSettingsFile();
831
0
    }
832
    bool overwriteRwSetting(const std::string& name, common::SettingsValue& value, bool write) override
833
0
    {
834
0
        if (value.isNull()) return deleteRwSettings(name, write);
835
0
        return updateRwSetting(name, [&](common::SettingsValue& settings) {
836
0
            settings = std::move(value);
837
0
            return write ? interfaces::SettingsAction::WRITE : interfaces::SettingsAction::SKIP_WRITE;
838
0
        });
839
0
    }
840
    bool deleteRwSettings(const std::string& name, bool write) override
841
0
    {
842
0
        args().LockSettings([&](common::Settings& settings) {
843
0
            settings.rw_settings.erase(name);
844
0
        });
845
0
        return !write || args().WriteSettingsFile();
846
0
    }
847
    void requestMempoolTransactions(Notifications& notifications) override
848
0
    {
849
0
        if (!m_node.mempool) return;
850
0
        LOCK2(::cs_main, m_node.mempool->cs);
851
0
        for (const CTxMemPoolEntry& entry : m_node.mempool->entryAll()) {
852
0
            notifications.transactionAddedToMempool(entry.GetSharedTx());
853
0
        }
854
0
    }
855
    bool hasAssumedValidChain() override
856
0
    {
857
0
        return chainman().IsSnapshotActive();
858
0
    }
859
860
0
    NodeContext* context() override { return &m_node; }
861
0
    ArgsManager& args() { return *Assert(m_node.args); }
862
0
    ChainstateManager& chainman() { return *Assert(m_node.chainman); }
863
0
    ValidationSignals& validation_signals() { return *Assert(m_node.validation_signals); }
864
    NodeContext& m_node;
865
};
866
867
class BlockTemplateImpl : public BlockTemplate
868
{
869
public:
870
0
    explicit BlockTemplateImpl(std::unique_ptr<CBlockTemplate> block_template) : m_block_template(std::move(block_template))
871
0
    {
872
0
        assert(m_block_template);
873
0
    }
874
875
    CBlockHeader getBlockHeader() override
876
0
    {
877
0
        return m_block_template->block;
878
0
    }
879
880
    CBlock getBlock() override
881
0
    {
882
0
        return m_block_template->block;
883
0
    }
884
885
    std::vector<CAmount> getTxFees() override
886
0
    {
887
0
        return m_block_template->vTxFees;
888
0
    }
889
890
    std::vector<int64_t> getTxSigops() override
891
0
    {
892
0
        return m_block_template->vTxSigOpsCost;
893
0
    }
894
895
    CTransactionRef getCoinbaseTx() override
896
0
    {
897
0
        return m_block_template->block.vtx[0];
898
0
    }
899
900
    std::vector<unsigned char> getCoinbaseCommitment() override
901
0
    {
902
0
        return m_block_template->vchCoinbaseCommitment;
903
0
    }
904
905
    int getWitnessCommitmentIndex() override
906
0
    {
907
0
        return GetWitnessCommitmentIndex(m_block_template->block);
908
0
    }
909
910
    const std::unique_ptr<CBlockTemplate> m_block_template;
911
};
912
913
class MinerImpl : public Mining
914
{
915
public:
916
0
    explicit MinerImpl(NodeContext& node) : m_node(node) {}
917
918
    bool isTestChain() override
919
0
    {
920
0
        return chainman().GetParams().IsTestChain();
921
0
    }
922
923
    bool isInitialBlockDownload() override
924
0
    {
925
0
        return chainman().IsInitialBlockDownload();
926
0
    }
927
928
    std::optional<uint256> getTipHash() override
929
0
    {
930
0
        LOCK(::cs_main);
931
0
        CBlockIndex* tip{chainman().ActiveChain().Tip()};
932
0
        if (!tip) return {};
933
0
        return tip->GetBlockHash();
934
0
    }
935
936
    bool processNewBlock(const std::shared_ptr<const CBlock>& block, bool* new_block) override
937
0
    {
938
0
        return chainman().ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/new_block);
939
0
    }
940
941
    unsigned int getTransactionsUpdated() override
942
0
    {
943
0
        return context()->mempool->GetTransactionsUpdated();
944
0
    }
945
946
    bool testBlockValidity(const CBlock& block, bool check_merkle_root, BlockValidationState& state) override
947
0
    {
948
0
        LOCK(cs_main);
949
0
        CBlockIndex* tip{chainman().ActiveChain().Tip()};
950
        // Fail if the tip updated before the lock was taken
951
0
        if (block.hashPrevBlock != tip->GetBlockHash()) {
952
0
            state.Error("Block does not connect to current chain tip.");
953
0
            return false;
954
0
        }
955
956
0
        return TestBlockValidity(state, chainman().GetParams(), chainman().ActiveChainstate(), block, tip, /*fCheckPOW=*/false, check_merkle_root);
957
0
    }
958
959
    std::unique_ptr<BlockTemplate> createNewBlock(const CScript& script_pub_key, const BlockCreateOptions& options) override
960
0
    {
961
0
        BlockAssembler::Options assemble_options{options};
962
0
        ApplyArgsManOptions(*Assert(m_node.args), assemble_options);
963
0
        return std::make_unique<BlockTemplateImpl>(BlockAssembler{chainman().ActiveChainstate(), context()->mempool.get(), assemble_options}.CreateNewBlock(script_pub_key));
964
0
    }
965
966
0
    NodeContext* context() override { return &m_node; }
967
0
    ChainstateManager& chainman() { return *Assert(m_node.chainman); }
968
    NodeContext& m_node;
969
};
970
} // namespace
971
} // namespace node
972
973
namespace interfaces {
974
0
std::unique_ptr<Node> MakeNode(node::NodeContext& context) { return std::make_unique<node::NodeImpl>(context); }
975
0
std::unique_ptr<Chain> MakeChain(node::NodeContext& context) { return std::make_unique<node::ChainImpl>(context); }
976
0
std::unique_ptr<Mining> MakeMining(node::NodeContext& context) { return std::make_unique<node::MinerImpl>(context); }
977
} // namespace interfaces