LCOV - code coverage report
Current view: top level - src/node - interfaces.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 57.0 % 588 335
Test Date: 2026-11-19 06:09:33 Functions: 52.0 % 177 92
Branches: 37.9 % 702 266

             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                 :             : #include <bitcoin-build-config.h>
       6                 :             : 
       7                 :             : #include <banman.h>
       8                 :             : #include <blockfilter.h>
       9                 :             : #include <chain.h>
      10                 :             : #include <chainparams.h>
      11                 :             : #include <coins.h>
      12                 :             : #include <common/args.h>
      13                 :             : #include <common/settings.h>
      14                 :             : #include <consensus/amount.h>
      15                 :             : #include <consensus/merkle.h>
      16                 :             : #include <consensus/validation.h>
      17                 :             : #include <external_signer.h>
      18                 :             : #include <httprpc.h>
      19                 :             : #include <index/blockfilterindex.h>
      20                 :             : #include <init.h>
      21                 :             : #include <interfaces/chain.h>
      22                 :             : #include <interfaces/handler.h>
      23                 :             : #include <interfaces/mining.h>
      24                 :             : #include <interfaces/node.h>
      25                 :             : #include <interfaces/rpc.h>
      26                 :             : #include <interfaces/types.h>
      27                 :             : #include <kernel/context.h>
      28                 :             : #include <key.h>
      29                 :             : #include <logging.h>
      30                 :             : #include <mapport.h>
      31                 :             : #include <net.h>
      32                 :             : #include <net_processing.h>
      33                 :             : #include <net_types.h>
      34                 :             : #include <netaddress.h>
      35                 :             : #include <netbase.h>
      36                 :             : #include <node/block_template_manager.h>
      37                 :             : #include <node/blockstorage.h>
      38                 :             : #include <node/coin.h>
      39                 :             : #include <node/context.h>
      40                 :             : #include <node/interface_ui.h>
      41                 :             : #include <node/kernel_notifications.h>
      42                 :             : #include <node/miner.h>
      43                 :             : #include <node/mini_miner.h>
      44                 :             : #include <node/mining_types.h>
      45                 :             : #include <node/transaction.h>
      46                 :             : #include <node/types.h>
      47                 :             : #include <node/warnings.h>
      48                 :             : #include <policy/feerate.h>
      49                 :             : #include <policy/fees/estimator_man.h>
      50                 :             : #include <policy/policy.h>
      51                 :             : #include <policy/rbf.h>
      52                 :             : #include <primitives/block.h>
      53                 :             : #include <primitives/transaction.h>
      54                 :             : #include <rpc/blockchain.h>
      55                 :             : #include <rpc/protocol.h>
      56                 :             : #include <rpc/request.h>
      57                 :             : #include <rpc/server.h>
      58                 :             : #include <sync.h>
      59                 :             : #include <txmempool.h>
      60                 :             : #include <uint256.h>
      61                 :             : #include <univalue.h>
      62                 :             : #include <util/btcsignals.h>
      63                 :             : #include <util/check.h>
      64                 :             : #include <util/expected.h>
      65                 :             : #include <util/fees.h>
      66                 :             : #include <util/not_null.h>
      67                 :             : #include <util/result.h>
      68                 :             : #include <util/signalinterrupt.h>
      69                 :             : #include <util/string.h>
      70                 :             : #include <util/time.h>
      71                 :             : #include <util/translation.h>
      72                 :             : #include <validation.h>
      73                 :             : #include <validationinterface.h>
      74                 :             : 
      75                 :             : #include <any>
      76                 :             : #include <atomic>
      77                 :             : #include <condition_variable>
      78                 :             : #include <cstdint>
      79                 :             : #include <cstdlib>
      80                 :             : #include <functional>
      81                 :             : #include <map>
      82                 :             : #include <memory>
      83                 :             : #include <optional>
      84                 :             : #include <string>
      85                 :             : #include <tuple>
      86                 :             : #include <utility>
      87                 :             : #include <vector>
      88                 :             : 
      89                 :             : using interfaces::BlockRef;
      90                 :             : using interfaces::BlockTemplate;
      91                 :             : using interfaces::BlockTip;
      92                 :             : using interfaces::Chain;
      93                 :             : using interfaces::FoundBlock;
      94                 :             : using interfaces::Handler;
      95                 :             : using interfaces::MakeSignalHandler;
      96                 :             : using interfaces::Mining;
      97                 :             : using interfaces::Node;
      98                 :             : using interfaces::Rpc;
      99                 :             : using interfaces::WalletLoader;
     100                 :             : using kernel::ChainstateRole;
     101                 :             : using node::BlockCreateOptions;
     102                 :             : using node::BlockWaitOptions;
     103                 :             : using node::CoinbaseTx;
     104                 :             : using util::Join;
     105                 :             : 
     106                 :             : namespace node {
     107                 :             : // All members of the classes in this namespace are intentionally public, as the
     108                 :             : // classes themselves are private.
     109                 :             : namespace {
     110                 :             : #ifdef ENABLE_EXTERNAL_SIGNER
     111                 :             : class ExternalSignerImpl : public interfaces::ExternalSigner
     112                 :             : {
     113                 :             : public:
     114                 :           0 :     ExternalSignerImpl(::ExternalSigner signer) : m_signer(std::move(signer)) {}
     115         [ #  # ]:           0 :     std::string getName() override { return m_signer.m_name; }
     116                 :             :     ::ExternalSigner m_signer;
     117                 :             : };
     118                 :             : #endif
     119                 :             : 
     120                 :             : class NodeImpl : public Node
     121                 :             : {
     122                 :             : public:
     123                 :           0 :     explicit NodeImpl(NodeContext& context) { setContext(&context); }
     124                 :           0 :     void initLogging() override { InitLogging(args()); }
     125                 :           0 :     void initParameterInteraction() override { InitParameterInteraction(args()); }
     126   [ #  #  #  #  :           0 :     bilingual_str getWarnings() override { return Join(Assert(m_context->warnings)->GetMessages(), Untranslated("<hr />")); }
             #  #  #  # ]
     127                 :           0 :     int getExitStatus() override { return Assert(m_context)->exit_status.load(); }
     128                 :           0 :     BCLog::CategoryMask getLogCategories() override { return LogInstance().GetCategoryMask(); }
     129                 :           0 :     bool baseInitialize() override
     130                 :             :     {
     131         [ #  # ]:           0 :         if (!AppInitBasicSetup(args(), Assert(context())->exit_status)) return false;
     132         [ #  # ]:           0 :         if (!AppInitParameterInteraction(args())) return false;
     133                 :             : 
     134                 :           0 :         m_context->warnings = std::make_unique<node::Warnings>();
     135                 :           0 :         m_context->kernel = std::make_unique<kernel::Context>();
     136                 :           0 :         m_context->ecc_context = std::make_unique<ECC_Context>();
     137         [ #  # ]:           0 :         if (!AppInitSanityChecks(*m_context->kernel)) return false;
     138                 :             : 
     139         [ #  # ]:           0 :         if (!AppInitLockDirectories()) return false;
     140         [ #  # ]:           0 :         if (!AppInitInterfaces(*m_context)) return false;
     141                 :             : 
     142                 :             :         return true;
     143                 :             :     }
     144                 :           0 :     bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info) override
     145                 :             :     {
     146         [ #  # ]:           0 :         if (AppInitMain(*m_context, tip_info)) return true;
     147                 :             :         // Error during initialization, set exit status before continue
     148                 :           0 :         m_context->exit_status.store(EXIT_FAILURE);
     149                 :           0 :         return false;
     150                 :             :     }
     151                 :           0 :     void appShutdown() override
     152                 :             :     {
     153                 :           0 :         Shutdown(*m_context);
     154                 :           0 :     }
     155                 :           0 :     void startShutdown() override
     156                 :             :     {
     157                 :           0 :         NodeContext& ctx{*Assert(m_context)};
     158         [ #  # ]:           0 :         if (!(Assert(ctx.shutdown_request))()) {
     159                 :           0 :             LogError("Failed to send shutdown signal\n");
     160                 :             :         }
     161                 :           0 :         Interrupt(*m_context);
     162                 :           0 :     }
     163                 :           0 :     bool shutdownRequested() override { return ShutdownRequested(*Assert(m_context)); };
     164                 :           0 :     bool isSettingIgnored(const std::string& name) override
     165                 :             :     {
     166                 :           0 :         bool ignored = false;
     167                 :           0 :         args().LockSettings([&](common::Settings& settings) {
     168         [ #  # ]:           0 :             if (auto* options = common::FindKey(settings.command_line_options, name)) {
     169                 :           0 :                 ignored = !options->empty();
     170                 :             :             }
     171                 :           0 :         });
     172                 :           0 :         return ignored;
     173                 :             :     }
     174                 :           0 :     common::SettingsValue getPersistentSetting(const std::string& name) override { return args().GetPersistentSetting(name); }
     175                 :           0 :     void updateRwSetting(const std::string& name, const common::SettingsValue& value) override
     176                 :             :     {
     177                 :           0 :         args().LockSettings([&](common::Settings& settings) {
     178         [ #  # ]:           0 :             if (value.isNull()) {
     179                 :           0 :                 settings.rw_settings.erase(name);
     180                 :             :             } else {
     181                 :           0 :                 settings.rw_settings[name] = value;
     182                 :             :             }
     183                 :           0 :         });
     184                 :           0 :         args().WriteSettingsFile();
     185                 :           0 :     }
     186                 :           0 :     void forceSetting(const std::string& name, const common::SettingsValue& value) override
     187                 :             :     {
     188                 :           0 :         args().LockSettings([&](common::Settings& settings) {
     189         [ #  # ]:           0 :             if (value.isNull()) {
     190                 :           0 :                 settings.forced_settings.erase(name);
     191                 :             :             } else {
     192                 :           0 :                 settings.forced_settings[name] = value;
     193                 :             :             }
     194                 :           0 :         });
     195                 :           0 :     }
     196                 :           0 :     void resetSettings() override
     197                 :             :     {
     198                 :           0 :         args().WriteSettingsFile(/*errors=*/nullptr, /*backup=*/true);
     199                 :           0 :         args().LockSettings([&](common::Settings& settings) {
     200         [ #  # ]:           0 :             settings.rw_settings.clear();
     201                 :             :         });
     202                 :           0 :         args().WriteSettingsFile();
     203                 :           0 :     }
     204                 :           0 :     void mapPort(bool enable) override { StartMapPort(enable); }
     205                 :           0 :     std::optional<Proxy> getProxy(Network net) override { return GetProxy(net); }
     206                 :           0 :     size_t getNodeCount(ConnectionDirection flags) override
     207                 :             :     {
     208         [ #  # ]:           0 :         return m_context->connman ? m_context->connman->GetNodeCount(flags) : 0;
     209                 :             :     }
     210                 :           0 :     bool getNodesStats(NodesStats& stats) override
     211                 :             :     {
     212                 :           0 :         stats.clear();
     213                 :             : 
     214         [ #  # ]:           0 :         if (m_context->connman) {
     215                 :           0 :             std::vector<CNodeStats> stats_temp;
     216         [ #  # ]:           0 :             m_context->connman->GetNodeStats(stats_temp);
     217                 :             : 
     218   [ #  #  #  # ]:           0 :             stats.reserve(stats_temp.size());
     219         [ #  # ]:           0 :             for (auto& node_stats_temp : stats_temp) {
     220         [ #  # ]:           0 :                 stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
     221                 :             :             }
     222                 :             : 
     223                 :             :             // Try to retrieve the CNodeStateStats for each node.
     224         [ #  # ]:           0 :             if (m_context->peerman) {
     225         [ #  # ]:           0 :                 TRY_LOCK(::cs_main, lockMain);
     226         [ #  # ]:           0 :                 if (lockMain) {
     227         [ #  # ]:           0 :                     for (auto& node_stats : stats) {
     228                 :           0 :                         std::get<1>(node_stats) =
     229         [ #  # ]:           0 :                             m_context->peerman->GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
     230                 :             :                     }
     231                 :             :                 }
     232                 :           0 :             }
     233                 :           0 :             return true;
     234                 :           0 :         }
     235                 :             :         return false;
     236                 :             :     }
     237                 :           0 :     bool getBanned(banmap_t& banmap) override
     238                 :             :     {
     239         [ #  # ]:           0 :         if (m_context->banman) {
     240                 :           0 :             m_context->banman->GetBanned(banmap);
     241                 :           0 :             return true;
     242                 :             :         }
     243                 :             :         return false;
     244                 :             :     }
     245                 :           0 :     bool ban(const CNetAddr& net_addr, int64_t ban_time_offset) override
     246                 :             :     {
     247         [ #  # ]:           0 :         if (m_context->banman) {
     248                 :           0 :             m_context->banman->Ban(net_addr, ban_time_offset);
     249                 :           0 :             return true;
     250                 :             :         }
     251                 :             :         return false;
     252                 :             :     }
     253                 :           0 :     bool unban(const CSubNet& ip) override
     254                 :             :     {
     255         [ #  # ]:           0 :         if (m_context->banman) {
     256                 :           0 :             m_context->banman->Unban(ip);
     257                 :           0 :             return true;
     258                 :             :         }
     259                 :             :         return false;
     260                 :             :     }
     261                 :           0 :     bool disconnectByAddress(const CNetAddr& net_addr) override
     262                 :             :     {
     263         [ #  # ]:           0 :         if (m_context->connman) {
     264                 :           0 :             return m_context->connman->DisconnectNode(net_addr);
     265                 :             :         }
     266                 :             :         return false;
     267                 :             :     }
     268                 :           0 :     bool disconnectById(NodeId id) override
     269                 :             :     {
     270         [ #  # ]:           0 :         if (m_context->connman) {
     271                 :           0 :             return m_context->connman->DisconnectNode(id);
     272                 :             :         }
     273                 :             :         return false;
     274                 :             :     }
     275                 :           0 :     std::vector<std::unique_ptr<interfaces::ExternalSigner>> listExternalSigners() override
     276                 :             :     {
     277                 :             : #ifdef ENABLE_EXTERNAL_SIGNER
     278                 :           0 :         std::vector<ExternalSigner> signers = {};
     279   [ #  #  #  #  :           0 :         const std::string command = args().GetArg("-signer", "");
             #  #  #  # ]
     280         [ #  # ]:           0 :         if (command == "") return {};
     281   [ #  #  #  #  :           0 :         ExternalSigner::Enumerate(command, signers, Params().GetChainTypeString());
                   #  # ]
     282                 :           0 :         std::vector<std::unique_ptr<interfaces::ExternalSigner>> result;
     283   [ #  #  #  # ]:           0 :         result.reserve(signers.size());
     284         [ #  # ]:           0 :         for (auto& signer : signers) {
     285   [ #  #  #  # ]:           0 :             result.emplace_back(std::make_unique<ExternalSignerImpl>(std::move(signer)));
     286                 :             :         }
     287                 :           0 :         return result;
     288                 :             : #else
     289                 :             :         // This result is indistinguishable from a successful call that returns
     290                 :             :         // no signers. For the current GUI this doesn't matter, because the wallet
     291                 :             :         // creation dialog disables the external signer checkbox in both
     292                 :             :         // cases. The return type could be changed to std::optional<std::vector>
     293                 :             :         // (or something that also includes error messages) if this distinction
     294                 :             :         // becomes important.
     295                 :             :         return {};
     296                 :             : #endif // ENABLE_EXTERNAL_SIGNER
     297                 :           0 :     }
     298         [ #  # ]:           0 :     int64_t getTotalBytesRecv() override { return m_context->connman ? m_context->connman->GetTotalBytesRecv() : 0; }
     299         [ #  # ]:           0 :     int64_t getTotalBytesSent() override { return m_context->connman ? m_context->connman->GetTotalBytesSent() : 0; }
     300         [ #  # ]:           0 :     size_t getMempoolSize() override { return m_context->mempool ? m_context->mempool->size() : 0; }
     301         [ #  # ]:           0 :     size_t getMempoolDynamicUsage() override { return m_context->mempool ? m_context->mempool->DynamicMemoryUsage() : 0; }
     302         [ #  # ]:           0 :     size_t getMempoolMaxUsage() override { return m_context->mempool ? m_context->mempool->m_opts.max_size_bytes : 0; }
     303                 :           0 :     bool getHeaderTip(int& height, int64_t& block_time) override
     304                 :             :     {
     305                 :           0 :         LOCK(::cs_main);
     306         [ #  # ]:           0 :         auto best_header = chainman().m_best_header;
     307         [ #  # ]:           0 :         if (best_header) {
     308                 :           0 :             height = best_header->nHeight;
     309                 :           0 :             block_time = best_header->GetBlockTime();
     310                 :           0 :             return true;
     311                 :             :         }
     312                 :             :         return false;
     313                 :           0 :     }
     314                 :           0 :     std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() override
     315                 :             :     {
     316         [ #  # ]:           0 :         if (m_context->connman)
     317                 :           0 :             return m_context->connman->getNetLocalAddresses();
     318                 :             :         else
     319                 :           0 :             return {};
     320                 :             :     }
     321                 :           0 :     int getNumBlocks() override
     322                 :             :     {
     323                 :           0 :         LOCK(::cs_main);
     324   [ #  #  #  #  :           0 :         return chainman().ActiveChain().Height();
             #  #  #  # ]
     325                 :           0 :     }
     326                 :           0 :     uint256 getBestBlockHash() override
     327                 :             :     {
     328   [ #  #  #  #  :           0 :         const CBlockIndex* tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip());
             #  #  #  # ]
     329         [ #  # ]:           0 :         return tip ? tip->GetBlockHash() : chainman().GetParams().GenesisBlock().GetHash();
     330                 :             :     }
     331                 :           0 :     int64_t getLastBlockTime() override
     332                 :             :     {
     333                 :           0 :         LOCK(::cs_main);
     334   [ #  #  #  #  :           0 :         if (chainman().ActiveChain().Tip()) {
             #  #  #  # ]
     335   [ #  #  #  #  :           0 :             return chainman().ActiveChain().Tip()->GetBlockTime();
                   #  # ]
     336                 :             :         }
     337         [ #  # ]:           0 :         return chainman().GetParams().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
     338                 :           0 :     }
     339                 :           0 :     double getVerificationProgress() override
     340                 :             :     {
     341                 :           0 :         LOCK(chainman().GetMutex());
     342   [ #  #  #  #  :           0 :         return chainman().GuessVerificationProgress(chainman().ActiveTip());
          #  #  #  #  #  
                      # ]
     343                 :           0 :     }
     344                 :           0 :     bool isInitialBlockDownload() override
     345                 :             :     {
     346                 :           0 :         return chainman().IsInitialBlockDownload();
     347                 :             :     }
     348                 :           0 :     bool isLoadingBlocks() override { return chainman().m_blockman.LoadingBlocks(); }
     349                 :           0 :     void setNetworkActive(bool active) override
     350                 :             :     {
     351         [ #  # ]:           0 :         if (m_context->connman) {
     352                 :           0 :             m_context->connman->SetNetworkActive(active);
     353                 :             :         }
     354                 :           0 :     }
     355   [ #  #  #  # ]:           0 :     bool getNetworkActive() override { return m_context->connman && m_context->connman->GetNetworkActive(); }
     356                 :           0 :     CFeeRate getDustRelayFee() override
     357                 :             :     {
     358         [ #  # ]:           0 :         if (!m_context->mempool) return CFeeRate{DUST_RELAY_TX_FEE};
     359                 :           0 :         return m_context->mempool->m_opts.dust_relay_feerate;
     360                 :             :     }
     361                 :           0 :     UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
     362                 :             :     {
     363                 :           0 :         JSONRPCRequest req;
     364                 :           0 :         req.context = m_context;
     365         [ #  # ]:           0 :         req.params = params;
     366         [ #  # ]:           0 :         req.strMethod = command;
     367         [ #  # ]:           0 :         req.URI = uri;
     368         [ #  # ]:           0 :         return ::tableRPC.execute(req);
     369                 :           0 :     }
     370                 :           0 :     std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
     371                 :           0 :     std::optional<Coin> getUnspentOutput(const COutPoint& output) override
     372                 :             :     {
     373                 :           0 :         LOCK(::cs_main);
     374   [ #  #  #  #  :           0 :         return chainman().ActiveChainstate().CoinsTip().GetCoin(output);
             #  #  #  # ]
     375                 :           0 :     }
     376                 :           0 :     TransactionError broadcastTransaction(CTransactionRef tx, CAmount max_tx_fee, CFeeRate max_tx_fee_rate, std::string& err_string) override
     377                 :             :     {
     378   [ #  #  #  # ]:           0 :         return BroadcastTransaction(*m_context, std::move(tx), err_string, max_tx_fee, max_tx_fee_rate, /*broadcast_method=*/TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL, /*wait_callback=*/false);
     379                 :             :     }
     380                 :           0 :     WalletLoader& walletLoader() override
     381                 :             :     {
     382                 :           0 :         return *Assert(m_context->wallet_loader);
     383                 :             :     }
     384                 :           0 :     std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
     385                 :             :     {
     386         [ #  # ]:           0 :         return MakeSignalHandler(::uiInterface.InitMessage.connect(fn));
     387                 :             :     }
     388                 :           0 :     std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
     389                 :             :     {
     390         [ #  # ]:           0 :         return MakeSignalHandler(::uiInterface.ThreadSafeMessageBox.connect(fn));
     391                 :             :     }
     392                 :           0 :     std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
     393                 :             :     {
     394         [ #  # ]:           0 :         return MakeSignalHandler(::uiInterface.ThreadSafeQuestion.connect(fn));
     395                 :             :     }
     396                 :           0 :     std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
     397                 :             :     {
     398         [ #  # ]:           0 :         return MakeSignalHandler(::uiInterface.ShowProgress.connect(fn));
     399                 :             :     }
     400                 :           0 :     std::unique_ptr<Handler> handleInitWallet(InitWalletFn fn) override
     401                 :             :     {
     402         [ #  # ]:           0 :         return MakeSignalHandler(::uiInterface.InitWallet.connect(fn));
     403                 :             :     }
     404                 :           0 :     std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
     405                 :             :     {
     406         [ #  # ]:           0 :         return MakeSignalHandler(::uiInterface.NotifyNumConnectionsChanged.connect(fn));
     407                 :             :     }
     408                 :           0 :     std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
     409                 :             :     {
     410         [ #  # ]:           0 :         return MakeSignalHandler(::uiInterface.NotifyNetworkActiveChanged.connect(fn));
     411                 :             :     }
     412                 :           0 :     std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
     413                 :             :     {
     414         [ #  # ]:           0 :         return MakeSignalHandler(::uiInterface.NotifyAlertChanged.connect(fn));
     415                 :             :     }
     416                 :           0 :     std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
     417                 :             :     {
     418         [ #  # ]:           0 :         return MakeSignalHandler(::uiInterface.BannedListChanged.connect(fn));
     419                 :             :     }
     420                 :           0 :     std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
     421                 :             :     {
     422   [ #  #  #  # ]:           0 :         return MakeSignalHandler(::uiInterface.NotifyBlockTip.connect([fn](SynchronizationState sync_state, const CBlockIndex& block, double verification_progress) {
     423                 :           0 :             fn(sync_state, BlockTip{block.nHeight, block.GetBlockTime(), block.GetBlockHash()}, verification_progress);
     424         [ #  # ]:           0 :         }));
     425                 :             :     }
     426                 :           0 :     std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
     427                 :             :     {
     428                 :           0 :         return MakeSignalHandler(
     429   [ #  #  #  # ]:           0 :             ::uiInterface.NotifyHeaderTip.connect([fn](SynchronizationState sync_state, int64_t height, int64_t timestamp, bool presync) {
     430                 :           0 :                 fn(sync_state, BlockTip{(int)height, timestamp, uint256{}}, presync);
     431         [ #  # ]:           0 :             }));
     432                 :             :     }
     433                 :           0 :     NodeContext* context() override { return m_context; }
     434                 :           0 :     void setContext(NodeContext* context) override
     435                 :             :     {
     436                 :           0 :         m_context = context;
     437                 :           0 :     }
     438                 :           0 :     ArgsManager& args() { return *Assert(Assert(m_context)->args); }
     439                 :           0 :     ChainstateManager& chainman() { return *Assert(m_context->chainman); }
     440                 :             :     NodeContext* m_context{nullptr};
     441                 :             : };
     442                 :             : 
     443                 :             : // NOLINTNEXTLINE(misc-no-recursion)
     444                 :      298763 : bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active, const BlockManager& blockman) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
     445                 :             : {
     446         [ +  + ]:      298763 :     if (!index) return false;
     447         [ +  + ]:      297657 :     if (block.m_hash) *block.m_hash = index->GetBlockHash();
     448         [ +  + ]:      297657 :     if (block.m_height) *block.m_height = index->nHeight;
     449         [ +  + ]:      297657 :     if (block.m_time) *block.m_time = index->GetBlockTime();
     450         [ +  + ]:      297657 :     if (block.m_max_time) *block.m_max_time = index->GetBlockTimeMax();
     451         [ +  + ]:      297657 :     if (block.m_mtp_time) *block.m_mtp_time = index->GetMedianTimePast();
     452   [ +  +  +  - ]:      472535 :     if (block.m_in_active_chain) *block.m_in_active_chain = active[index->nHeight] == index;
     453         [ +  + ]:      297657 :     if (block.m_locator) { *block.m_locator = GetLocator(index); }
     454   [ +  +  +  -  :      461802 :     if (block.m_next_block) FillBlock(active[index->nHeight] == index ? active[index->nHeight + 1] : nullptr, *block.m_next_block, lock, active, blockman);
             +  +  +  - ]
     455         [ +  + ]:      297657 :     if (block.m_data) {
     456                 :       81528 :         REVERSE_LOCK(lock, cs_main);
     457   [ +  -  +  + ]:       81528 :         if (!blockman.ReadBlock(*block.m_data, *index)) block.m_data->SetNull();
     458                 :       81528 :     }
     459                 :      297657 :     block.found = true;
     460                 :      297657 :     return true;
     461                 :             : }
     462                 :             : 
     463                 :             : class NotificationsProxy : public CValidationInterface
     464                 :             : {
     465                 :             : public:
     466                 :        1055 :     explicit NotificationsProxy(std::shared_ptr<Chain::Notifications> notifications)
     467                 :        1055 :         : m_notifications(std::move(notifications)) {}
     468         [ +  - ]:        1055 :     virtual ~NotificationsProxy() = default;
     469                 :        7867 :     void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t mempool_sequence) override
     470                 :             :     {
     471                 :        7867 :         m_notifications->transactionAddedToMempool(tx.info.m_tx);
     472                 :        7867 :     }
     473                 :         324 :     void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
     474                 :             :     {
     475                 :         324 :         m_notifications->transactionRemovedFromMempool(tx, reason);
     476                 :         324 :     }
     477                 :       54499 :     void BlockConnected(const ChainstateRole& role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
     478                 :             :     {
     479                 :       54499 :         m_notifications->blockConnected(role, kernel::MakeBlockInfo(index, block.get()));
     480                 :       54499 :     }
     481                 :        3460 :     void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
     482                 :             :     {
     483                 :        3460 :         m_notifications->blockDisconnected(kernel::MakeBlockInfo(index, block.get()));
     484                 :        3460 :     }
     485                 :       52311 :     void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override
     486                 :             :     {
     487                 :       52311 :         m_notifications->updatedBlockTip();
     488                 :       52311 :     }
     489                 :         102 :     void ChainStateFlushed(const ChainstateRole& role, const CBlockLocator& locator) override
     490                 :             :     {
     491                 :         102 :         m_notifications->chainStateFlushed(role, locator);
     492                 :         102 :     }
     493                 :             :     std::shared_ptr<Chain::Notifications> m_notifications;
     494                 :             : };
     495                 :             : 
     496                 :             : class NotificationsHandlerImpl : public Handler
     497                 :             : {
     498                 :             : public:
     499                 :        1055 :     explicit NotificationsHandlerImpl(ValidationSignals& signals, std::shared_ptr<Chain::Notifications> notifications)
     500         [ +  - ]:        1055 :         : m_signals{signals}, m_proxy{std::make_shared<NotificationsProxy>(std::move(notifications))}
     501                 :             :     {
     502   [ +  -  +  - ]:        2110 :         m_signals.RegisterSharedValidationInterface(m_proxy);
     503         [ -  - ]:        1055 :     }
     504         [ -  + ]:        2110 :     ~NotificationsHandlerImpl() override { disconnect(); }
     505                 :        2074 :     void disconnect() override
     506                 :             :     {
     507         [ +  + ]:        2074 :         if (m_proxy) {
     508   [ +  -  +  - ]:        2110 :             m_signals.UnregisterSharedValidationInterface(m_proxy);
     509                 :        1055 :             m_proxy.reset();
     510                 :             :         }
     511                 :        2074 :     }
     512                 :             :     ValidationSignals& m_signals;
     513                 :             :     std::shared_ptr<NotificationsProxy> m_proxy;
     514                 :             : };
     515                 :             : 
     516                 :             : class RpcHandlerImpl : public Handler
     517                 :             : {
     518                 :             : public:
     519         [ +  - ]:       27376 :     explicit RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command)
     520                 :             :     {
     521                 :       49973 :         m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
     522         [ +  - ]:       22597 :             if (!m_wrapped_command) return false;
     523                 :       22597 :             try {
     524         [ +  + ]:       22597 :                 return m_wrapped_command->actor(request, result, last_handler);
     525         [ -  + ]:         790 :             } catch (const UniValue& e) {
     526                 :             :                 // If this is not the last handler and a wallet not found
     527                 :             :                 // exception was thrown, return false so the next handler can
     528                 :             :                 // try to handle the request. Otherwise, reraise the exception.
     529         [ -  + ]:         790 :                 if (!last_handler) {
     530   [ -  -  -  - ]:           0 :                     const UniValue& code = e["code"];
     531   [ -  -  -  -  :           0 :                     if (code.isNum() && code.getInt<int>() == RPC_WALLET_NOT_FOUND) {
                   -  - ]
     532                 :           0 :                         return false;
     533                 :             :                     }
     534                 :             :                 }
     535                 :         790 :                 throw;
     536                 :         790 :             }
     537                 :       27376 :         };
     538         [ +  - ]:       27376 :         ::tableRPC.appendCommand(m_command.name, &m_command);
     539                 :       27376 :     }
     540                 :             : 
     541                 :       27376 :     void disconnect() final
     542                 :             :     {
     543         [ +  - ]:       27376 :         if (m_wrapped_command) {
     544                 :       27376 :             m_wrapped_command = nullptr;
     545                 :       27376 :             ::tableRPC.removeCommand(m_command.name, &m_command);
     546                 :             :         }
     547                 :       27376 :     }
     548                 :             : 
     549                 :       54752 :     ~RpcHandlerImpl() override { disconnect(); }
     550                 :             : 
     551                 :             :     CRPCCommand m_command;
     552                 :             :     const CRPCCommand* m_wrapped_command;
     553                 :             : };
     554                 :             : 
     555                 :             : class ChainImpl : public Chain
     556                 :             : {
     557                 :             : public:
     558                 :        2276 :     explicit ChainImpl(NodeContext& node) : m_node(node) {}
     559                 :        2732 :     std::optional<int> getHeight() override
     560                 :             :     {
     561   [ +  -  +  -  :        8196 :         const int height{WITH_LOCK(::cs_main, return chainman().ActiveChain().Height())};
             -  +  +  - ]
     562         [ +  + ]:        2732 :         return height >= 0 ? std::optional{height} : std::nullopt;
     563                 :             :     }
     564                 :        2903 :     uint256 getBlockHash(int height) override
     565                 :             :     {
     566                 :        2903 :         LOCK(::cs_main);
     567   [ +  -  +  -  :        5806 :         return Assert(chainman().ActiveChain()[height])->GetBlockHash();
          +  -  +  -  +  
                      - ]
     568                 :        2903 :     }
     569                 :        2658 :     bool haveBlockOnDisk(int height) override
     570                 :             :     {
     571                 :        2658 :         LOCK(::cs_main);
     572   [ +  -  +  -  :        2668 :         const CBlockIndex* block{chainman().ActiveChain()[height]};
                   +  - ]
     573   [ +  -  +  +  :        2668 :         return block && ((block->nStatus & BLOCK_HAVE_DATA) != 0) && block->nTx > 0;
             -  +  +  - ]
     574                 :        2658 :     }
     575                 :        1035 :     std::optional<int> findLocatorFork(const CBlockLocator& locator) override
     576                 :             :     {
     577                 :        1035 :         LOCK(::cs_main);
     578   [ +  -  +  -  :        1035 :         if (const CBlockIndex* fork = chainman().ActiveChainstate().FindForkInGlobalIndex(locator)) {
             +  -  +  + ]
     579                 :        1030 :             return fork->nHeight;
     580                 :             :         }
     581                 :           5 :         return std::nullopt;
     582                 :        1035 :     }
     583                 :         735 :     bool hasBlockFilterIndex(BlockFilterType filter_type) override
     584                 :             :     {
     585                 :         735 :         return GetBlockFilterIndex(filter_type) != nullptr;
     586                 :             :     }
     587                 :         722 :     std::optional<bool> blockFilterMatchesAny(BlockFilterType filter_type, const uint256& block_hash, const GCSFilter::ElementSet& filter_set) override
     588                 :             :     {
     589                 :         722 :         const BlockFilterIndex* block_filter_index{GetBlockFilterIndex(filter_type)};
     590         [ -  + ]:         722 :         if (!block_filter_index) return std::nullopt;
     591                 :             : 
     592                 :         722 :         BlockFilter filter;
     593   [ +  -  +  -  :        2166 :         const CBlockIndex* index{WITH_LOCK(::cs_main, return chainman().m_blockman.LookupBlockIndex(block_hash))};
             +  -  +  - ]
     594   [ +  -  +  -  :         722 :         if (index == nullptr || !block_filter_index->LookupFilter(index, filter)) return std::nullopt;
                   +  + ]
     595         [ +  - ]:         621 :         return filter.GetFilter().MatchAny(filter_set);
     596                 :         722 :     }
     597                 :      215848 :     bool findBlock(const uint256& hash, const FoundBlock& block) override
     598                 :             :     {
     599                 :      215848 :         WAIT_LOCK(cs_main, lock);
     600   [ +  -  +  -  :      215848 :         return FillBlock(chainman().m_blockman.LookupBlockIndex(hash), block, lock, chainman().ActiveChain(), chainman().m_blockman);
          +  -  +  -  +  
             -  +  -  +  
                      - ]
     601                 :      215848 :     }
     602                 :         720 :     bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block) override
     603                 :             :     {
     604                 :         720 :         WAIT_LOCK(cs_main, lock);
     605   [ +  -  +  - ]:         720 :         const CChain& active = chainman().ActiveChain();
     606   [ +  -  +  -  :         720 :         return FillBlock(active.FindEarliestAtLeast(min_time, min_height), block, lock, active, chainman().m_blockman);
             +  -  +  - ]
     607                 :         720 :     }
     608                 :          43 :     bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out) override
     609                 :             :     {
     610                 :          43 :         WAIT_LOCK(cs_main, lock);
     611   [ +  -  +  - ]:          43 :         const CChain& active = chainman().ActiveChain();
     612   [ +  -  +  -  :          43 :         if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
                   +  - ]
     613   [ +  -  +  + ]:          43 :             if (const CBlockIndex* ancestor = block->GetAncestor(ancestor_height)) {
     614   [ +  -  +  - ]:          42 :                 return FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman);
     615                 :             :             }
     616                 :             :         }
     617   [ +  -  +  - ]:           1 :         return FillBlock(nullptr, ancestor_out, lock, active, chainman().m_blockman);
     618                 :          43 :     }
     619                 :           9 :     bool findAncestorByHash(const uint256& block_hash, const uint256& ancestor_hash, const FoundBlock& ancestor_out) override
     620                 :             :     {
     621                 :           9 :         WAIT_LOCK(cs_main, lock);
     622   [ +  -  +  - ]:           9 :         const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash);
     623   [ +  -  +  - ]:           9 :         const CBlockIndex* ancestor = chainman().m_blockman.LookupBlockIndex(ancestor_hash);
     624   [ +  +  +  -  :           9 :         if (block && ancestor && block->GetAncestor(ancestor->nHeight) != ancestor) ancestor = nullptr;
                   +  + ]
     625   [ +  -  +  -  :           9 :         return FillBlock(ancestor, ancestor_out, lock, chainman().ActiveChain(), chainman().m_blockman);
          +  -  +  -  +  
                      - ]
     626                 :           9 :     }
     627                 :          23 :     bool findCommonAncestor(const uint256& block_hash1, const uint256& block_hash2, const FoundBlock& ancestor_out, const FoundBlock& block1_out, const FoundBlock& block2_out) override
     628                 :             :     {
     629                 :          23 :         WAIT_LOCK(cs_main, lock);
     630   [ +  -  +  - ]:          23 :         const CChain& active = chainman().ActiveChain();
     631   [ +  -  +  - ]:          23 :         const CBlockIndex* block1 = chainman().m_blockman.LookupBlockIndex(block_hash1);
     632   [ +  -  +  - ]:          23 :         const CBlockIndex* block2 = chainman().m_blockman.LookupBlockIndex(block_hash2);
     633   [ +  +  +  - ]:          23 :         const CBlockIndex* ancestor = block1 && block2 ? LastCommonAncestor(block1, block2) : nullptr;
     634                 :             :         // Using & instead of && below to avoid short circuiting and leaving
     635                 :             :         // output uninitialized. Cast bool to int to avoid -Wbitwise-instead-of-logical
     636                 :             :         // compiler warnings.
     637   [ +  -  +  - ]:          23 :         return int{FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman)} &
     638   [ +  -  +  - ]:          23 :                int{FillBlock(block1, block1_out, lock, active, chainman().m_blockman)} &
     639   [ +  -  +  -  :          23 :                int{FillBlock(block2, block2_out, lock, active, chainman().m_blockman)};
                   +  - ]
     640                 :          23 :     }
     641                 :        1054 :     void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(m_node, coins); }
     642                 :       83543 :     double guessVerificationProgress(const uint256& block_hash) override
     643                 :             :     {
     644                 :       83543 :         LOCK(chainman().GetMutex());
     645   [ +  -  +  -  :       83543 :         return chainman().GuessVerificationProgress(chainman().m_blockman.LookupBlockIndex(block_hash));
          +  -  +  -  +  
                      - ]
     646                 :       83543 :     }
     647                 :          35 :     bool hasBlocks(const uint256& block_hash, int min_height, std::optional<int> max_height) override
     648                 :             :     {
     649                 :             :         // hasBlocks returns true if all ancestors of block_hash in specified
     650                 :             :         // range have block data (are not pruned), false if any ancestors in
     651                 :             :         // specified range are missing data.
     652                 :             :         //
     653                 :             :         // For simplicity and robustness, min_height and max_height are only
     654                 :             :         // used to limit the range, and passing min_height that's too low or
     655                 :             :         // max_height that's too high will not crash or change the result.
     656                 :          35 :         LOCK(::cs_main);
     657   [ +  -  +  -  :          35 :         if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
                   +  - ]
     658   [ +  +  +  +  :          35 :             if (max_height && block->nHeight >= *max_height) block = block->GetAncestor(*max_height);
                   +  - ]
     659         [ +  + ]:        3389 :             for (; block->nStatus & BLOCK_HAVE_DATA; block = block->pprev) {
     660                 :             :                 // Check pprev to not segfault if min_height is too low
     661   [ +  +  +  + ]:        3373 :                 if (block->nHeight <= min_height || !block->pprev) return true;
     662                 :             :             }
     663                 :             :         }
     664                 :             :         return false;
     665                 :          35 :     }
     666                 :           1 :     RBFTransactionState isRBFOptIn(const CTransaction& tx) override
     667                 :             :     {
     668         [ -  + ]:           1 :         if (!m_node.mempool) return IsRBFOptInEmptyMempool(tx);
     669                 :           1 :         LOCK(m_node.mempool->cs);
     670   [ +  -  +  - ]:           1 :         return IsRBFOptIn(tx, *m_node.mempool);
     671                 :           1 :     }
     672                 :       18157 :     bool isInMempool(const Txid& txid) override
     673                 :             :     {
     674         [ +  - ]:       18157 :         if (!m_node.mempool) return false;
     675                 :       18157 :         return m_node.mempool->exists(txid);
     676                 :             :     }
     677                 :         245 :     bool hasDescendantsInMempool(const Txid& txid) override
     678                 :             :     {
     679         [ +  - ]:         245 :         if (!m_node.mempool) return false;
     680                 :         245 :         return m_node.mempool->HasDescendants(txid);
     681                 :             :     }
     682                 :        1871 :     bool broadcastTransaction(const CTransactionRef& tx,
     683                 :             :                               const CAmount& max_tx_fee,
     684                 :             :                               const CFeeRate& max_tx_fee_rate,
     685                 :             :                               TxBroadcast broadcast_method,
     686                 :             :                               std::string& err_string) override
     687                 :             :     {
     688   [ +  -  +  -  :        3742 :         const TransactionError err = BroadcastTransaction(m_node, tx, err_string, max_tx_fee, max_tx_fee_rate, broadcast_method, /*wait_callback=*/false);
                   +  - ]
     689                 :             :         // Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures.
     690                 :             :         // Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures
     691                 :             :         // that Chain clients do not need to know about.
     692                 :        1871 :         return TransactionError::OK == err;
     693                 :             :     }
     694                 :      580581 :     void getTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* ancestorsize, CAmount* ancestorfees) override
     695                 :             :     {
     696                 :      580581 :         ancestors = cluster_count = 0;
     697         [ +  - ]:      580581 :         if (!m_node.mempool) return;
     698                 :      580581 :         m_node.mempool->GetTransactionAncestry(txid, ancestors, cluster_count, ancestorsize, ancestorfees);
     699                 :             :     }
     700                 :             : 
     701                 :        4362 :     std::map<COutPoint, CAmount> calculateIndividualBumpFees(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
     702                 :             :     {
     703         [ -  + ]:        4362 :         if (!m_node.mempool) {
     704                 :           0 :             std::map<COutPoint, CAmount> bump_fees;
     705         [ #  # ]:           0 :             for (const auto& outpoint : outpoints) {
     706         [ #  # ]:           0 :                 bump_fees.emplace(outpoint, 0);
     707                 :             :             }
     708                 :             :             return bump_fees;
     709                 :           0 :         }
     710         [ +  - ]:        4362 :         return MiniMiner(*m_node.mempool, outpoints).CalculateBumpFees(target_feerate);
     711                 :             :     }
     712                 :             : 
     713                 :        9204 :     std::optional<CAmount> calculateCombinedBumpFee(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
     714                 :             :     {
     715         [ -  + ]:        9204 :         if (!m_node.mempool) {
     716                 :           0 :             return 0;
     717                 :             :         }
     718         [ +  - ]:        9204 :         return MiniMiner(*m_node.mempool, outpoints).CalculateTotalBumpFees(target_feerate);
     719                 :             :     }
     720                 :        3390 :     void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) override
     721                 :             :     {
     722                 :        3390 :         const CTxMemPool::Limits default_limits{};
     723                 :             : 
     724         [ +  - ]:        3390 :         const CTxMemPool::Limits& limits{m_node.mempool ? m_node.mempool->m_opts.limits : default_limits};
     725                 :             : 
     726                 :        3390 :         limit_ancestor_count = limits.ancestor_count;
     727                 :        3390 :         limit_descendant_count = limits.descendant_count;
     728                 :        3390 :     }
     729                 :        3649 :     util::Result<void> checkChainLimits(const CTransactionRef& tx) override
     730                 :             :     {
     731         [ -  + ]:        3649 :         if (!m_node.mempool) return {};
     732         [ +  + ]:        3649 :         if (!m_node.mempool->CheckPolicyLimits(tx)) {
     733         [ +  - ]:           3 :             return util::Error{Untranslated("too many unconfirmed transactions in cluster")};
     734                 :             :         }
     735                 :        3648 :         return {};
     736                 :             :     }
     737                 :        6805 :     util::Expected<FeeRateEstimation, FeeRateEstimationError> getFeeRateEstimate(int num_blocks, bool conservative) const override
     738                 :             :     {
     739         [ +  + ]:        6805 :         if (!m_node.fee_estimator_man) return EstimationError(FeeRateEstimatorType::AUTO, /*returned_target=*/0, /*error=*/{});
     740                 :        6783 :         return m_node.fee_estimator_man->GetFeeRateEstimate(num_blocks, conservative);
     741                 :             :     }
     742                 :        3859 :     unsigned int maximumFeeEstimationTargetBlocks() const override
     743                 :             :     {
     744         [ +  + ]:        3859 :         if (!m_node.fee_estimator_man) return 0;
     745                 :        3844 :         return m_node.fee_estimator_man->MaximumTarget();
     746                 :             :     }
     747                 :        3004 :     CFeeRate mempoolMinFee() override
     748                 :             :     {
     749         [ -  + ]:        3004 :         if (!m_node.mempool) return {};
     750                 :        3004 :         return m_node.mempool->GetMinFee();
     751                 :             :     }
     752                 :        4876 :     CFeeRate relayMinFee() override
     753                 :             :     {
     754         [ -  + ]:        4876 :         if (!m_node.mempool) return CFeeRate{DEFAULT_MIN_RELAY_TX_FEE};
     755                 :        4876 :         return m_node.mempool->m_opts.min_relay_feerate;
     756                 :             :     }
     757                 :         129 :     CFeeRate relayIncrementalFee() override
     758                 :             :     {
     759         [ -  + ]:         129 :         if (!m_node.mempool) return CFeeRate{DEFAULT_INCREMENTAL_RELAY_FEE};
     760                 :         129 :         return m_node.mempool->m_opts.incremental_relay_feerate;
     761                 :             :     }
     762                 :       44578 :     CFeeRate relayDustFee() override
     763                 :             :     {
     764         [ -  + ]:       44578 :         if (!m_node.mempool) return CFeeRate{DUST_RELAY_TX_FEE};
     765                 :       44578 :         return m_node.mempool->m_opts.dust_relay_feerate;
     766                 :             :     }
     767                 :          84 :     bool havePruned() override
     768                 :             :     {
     769                 :          84 :         LOCK(::cs_main);
     770   [ +  -  +  - ]:          84 :         return chainman().m_blockman.m_have_pruned;
     771                 :          84 :     }
     772                 :           1 :     std::optional<int> getPruneHeight() override
     773                 :             :     {
     774                 :           1 :         LOCK(chainman().GetMutex());
     775   [ +  -  +  -  :           1 :         return GetPruneHeight(chainman().m_blockman, chainman().ActiveChain());
             +  -  +  - ]
     776                 :           1 :     }
     777   [ +  -  +  + ]:         106 :     bool isReadyToBroadcast() override { return !chainman().m_blockman.LoadingBlocks() && !isInitialBlockDownload(); }
     778                 :        3238 :     bool isInitialBlockDownload() override
     779                 :             :     {
     780                 :        3238 :         return chainman().IsInitialBlockDownload();
     781                 :             :     }
     782                 :       82811 :     bool shutdownRequested() override { return ShutdownRequested(m_node); }
     783                 :        1528 :     void initMessage(const std::string& message) override { ::uiInterface.InitMessage(message); }
     784                 :           8 :     void initWarning(const bilingual_str& message) override { InitWarning(message); }
     785                 :          26 :     void initError(const bilingual_str& message) override { InitError(message); }
     786                 :           0 :     void showProgress(const std::string& title, int progress, bool resume_possible) override
     787                 :             :     {
     788                 :           0 :         ::uiInterface.ShowProgress(title, progress, resume_possible);
     789                 :           0 :     }
     790                 :        1055 :     std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) override
     791                 :             :     {
     792                 :        1055 :         return std::make_unique<NotificationsHandlerImpl>(validation_signals(), std::move(notifications));
     793                 :             :     }
     794                 :        7009 :     void waitForNotificationsIfTipChanged(const uint256& old_tip) override
     795                 :             :     {
     796   [ +  +  +  +  :       34991 :         if (!old_tip.IsNull() && old_tip == WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()->GetBlockHash())) return;
          +  -  +  -  -  
                +  +  - ]
     797                 :          95 :         validation_signals().SyncWithValidationInterfaceQueue();
     798                 :             :     }
     799                 :        1019 :     void waitForNotifications() override
     800                 :             :     {
     801                 :        1019 :         validation_signals().SyncWithValidationInterfaceQueue();
     802                 :        1019 :     }
     803                 :       27376 :     std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) override
     804                 :             :     {
     805                 :       27376 :         return std::make_unique<RpcHandlerImpl>(command);
     806                 :             :     }
     807                 :        4500 :     bool rpcEnableDeprecated(const std::string& method) override { return IsDeprecatedRPCEnabled(method); }
     808                 :           0 :     common::SettingsValue getSetting(const std::string& name) override
     809                 :             :     {
     810                 :           0 :         return args().GetSetting(name);
     811                 :             :     }
     812                 :         835 :     std::vector<common::SettingsValue> getSettingsList(const std::string& name) override
     813                 :             :     {
     814                 :         835 :         return args().GetSettingsList(name);
     815                 :             :     }
     816                 :           3 :     common::SettingsValue getRwSetting(const std::string& name) override
     817                 :             :     {
     818         [ +  - ]:           3 :         common::SettingsValue result;
     819   [ +  -  +  - ]:           3 :         args().LockSettings([&](const common::Settings& settings) {
     820         [ +  + ]:           3 :             if (const common::SettingsValue* value = common::FindKey(settings.rw_settings, name)) {
     821                 :           2 :                 result = *value;
     822                 :             :             }
     823                 :           3 :         });
     824                 :           3 :         return result;
     825                 :           0 :     }
     826                 :         221 :     bool updateRwSetting(const std::string& name,
     827                 :             :                          const interfaces::SettingsUpdate& update_settings_func) override
     828                 :             :     {
     829                 :         221 :         std::optional<interfaces::SettingsAction> action;
     830                 :         221 :         args().LockSettings([&](common::Settings& settings) {
     831         [ +  + ]:         221 :             if (auto* value = common::FindKey(settings.rw_settings, name)) {
     832                 :          59 :                 action = update_settings_func(*value);
     833         [ -  + ]:          59 :                 if (value->isNull()) settings.rw_settings.erase(name);
     834                 :             :             } else {
     835         [ +  - ]:         162 :                 UniValue new_value;
     836         [ +  - ]:         162 :                 action = update_settings_func(new_value);
     837   [ +  +  +  - ]:         162 :                 if (!new_value.isNull()) settings.rw_settings[name] = std::move(new_value);
     838                 :         162 :             }
     839                 :         221 :         });
     840         [ +  - ]:         221 :         if (!action) return false;
     841                 :             :         // Now dump value to disk if requested
     842   [ +  +  +  +  :         221 :         return *action != interfaces::SettingsAction::WRITE || (args().GetSettingsPath() && args().WriteSettingsFile());
                   +  - ]
     843                 :             :     }
     844                 :           2 :     bool overwriteRwSetting(const std::string& name, common::SettingsValue value, interfaces::SettingsAction action) override
     845                 :             :     {
     846         [ +  - ]:           2 :         return updateRwSetting(name, [&](common::SettingsValue& settings) {
     847                 :           2 :             settings = std::move(value);
     848                 :           2 :             return action;
     849                 :           2 :         });
     850                 :             :     }
     851                 :           0 :     bool deleteRwSettings(const std::string& name, interfaces::SettingsAction action) override
     852                 :             :     {
     853         [ #  # ]:           0 :         return overwriteRwSetting(name, {}, action);
     854                 :             :     }
     855                 :        1758 :     void requestMempoolTransactions(Notifications& notifications) override
     856                 :             :     {
     857         [ +  - ]:        1758 :         if (!m_node.mempool) return;
     858         [ +  - ]:        1758 :         LOCK2(::cs_main, m_node.mempool->cs);
     859   [ +  -  +  -  :        2345 :         for (const CTxMemPoolEntry& entry : m_node.mempool->entryAll()) {
                   +  + ]
     860   [ +  -  +  - ]:        1761 :             notifications.transactionAddedToMempool(entry.GetSharedTx());
     861         [ +  - ]:        1758 :         }
     862         [ +  - ]:        3516 :     }
     863                 :          68 :     bool hasAssumedValidChain() override
     864                 :             :     {
     865                 :          68 :         LOCK(::cs_main);
     866   [ +  -  +  - ]:          68 :         return bool{chainman().CurrentChainstate().m_from_snapshot_blockhash};
     867                 :          68 :     }
     868                 :             : 
     869                 :        1241 :     NodeContext* context() override { return &m_node; }
     870                 :        1472 :     ArgsManager& args() { return *Assert(m_node.args); }
     871                 :      920491 :     ChainstateManager& chainman() { return *Assert(m_node.chainman); }
     872                 :        2169 :     ValidationSignals& validation_signals() { return *Assert(m_node.validation_signals); }
     873                 :             :     NodeContext& m_node;
     874                 :             : };
     875                 :             : 
     876                 :             : class BlockTemplateImpl : public BlockTemplate
     877                 :             : {
     878                 :             : public:
     879                 :         130 :     explicit BlockTemplateImpl(BlockCreateOptions create_options,
     880                 :             :                                util::NotNullUniquePtr<CBlockTemplate> block_template,
     881                 :         130 :                                const NodeContext& node) : m_create_options(std::move(create_options)),
     882                 :         130 :                                                           m_block_template(std::move(block_template)),
     883                 :         130 :                                                           m_node(node)
     884                 :             :     {
     885                 :             :     }
     886                 :             : 
     887                 :           1 :     CBlockHeader getBlockHeader() override
     888                 :             :     {
     889                 :           1 :         return m_block_template->block;
     890                 :             :     }
     891                 :             : 
     892                 :         123 :     CBlock getBlock() override
     893                 :             :     {
     894                 :         123 :         return m_block_template->block;
     895                 :             :     }
     896                 :             : 
     897                 :           0 :     std::vector<CAmount> getTxFees() override
     898                 :             :     {
     899                 :           0 :         return m_block_template->vTxFees;
     900                 :             :     }
     901                 :             : 
     902                 :           0 :     std::vector<int64_t> getTxSigops() override
     903                 :             :     {
     904                 :           0 :         return m_block_template->vTxSigOpsCost;
     905                 :             :     }
     906                 :             : 
     907                 :           0 :     CoinbaseTx getCoinbaseTx() override
     908                 :             :     {
     909                 :           0 :         return m_block_template->m_coinbase_tx;
     910                 :             :     }
     911                 :             : 
     912                 :           0 :     std::vector<uint256> getCoinbaseMerklePath() override
     913                 :             :     {
     914                 :           0 :         return TransactionMerklePath(m_block_template->block, 0);
     915                 :             :     }
     916                 :             : 
     917                 :          55 :     bool submitSolution(uint32_t version, uint32_t timestamp, uint32_t nonce, CTransactionRef coinbase, std::string& reason, std::string& debug) override
     918                 :             :     {
     919         [ +  - ]:          55 :         if (!coinbase) return false;
     920         [ +  - ]:          55 :         AddMerkleRootAndCoinbase(m_block_template->block, std::move(coinbase), version, timestamp, nonce);
     921   [ +  -  +  - ]:         110 :         return block_template_manager().SubmitBlock(std::make_shared<const CBlock>(m_block_template->block), reason, debug);
     922                 :             :     }
     923                 :             : 
     924                 :          62 :     std::unique_ptr<BlockTemplate> waitNext(BlockWaitOptions options) override
     925                 :             :     {
     926                 :          62 :         auto new_template = block_template_manager().WaitAndCreateNewBlock(
     927                 :          62 :             *m_block_template, options, m_create_options, m_interrupt_wait);
     928   [ +  +  +  - ]:          62 :         if (new_template) return std::make_unique<BlockTemplateImpl>(m_create_options, util::NotNull{std::move(new_template)}, m_node);
     929                 :           4 :         return nullptr;
     930                 :          62 :     }
     931                 :             : 
     932                 :           0 :     void interruptWait() override
     933                 :             :     {
     934                 :           0 :         block_template_manager().InterruptWait(m_interrupt_wait);
     935                 :           0 :     }
     936                 :             : 
     937                 :             :     const BlockCreateOptions m_create_options;
     938                 :             : 
     939                 :             :     const util::NotNullUniquePtr<CBlockTemplate> m_block_template;
     940                 :             : 
     941                 :             :     bool m_interrupt_wait{false};
     942                 :         117 :     node::BlockTemplateManager& block_template_manager() { return *Assert(m_node.block_template_manager); }
     943                 :             :     const NodeContext& m_node;
     944                 :             : };
     945                 :             : 
     946                 :             : class MinerImpl : public Mining
     947                 :             : {
     948                 :             : public:
     949                 :           6 :     explicit MinerImpl(const NodeContext& node) : m_node(node) {}
     950                 :             : 
     951                 :           0 :     bool isTestChain() override
     952                 :             :     {
     953                 :           0 :         return chainman().GetParams().IsTestChain();
     954                 :             :     }
     955                 :             : 
     956                 :           0 :     bool isInitialBlockDownload() override
     957                 :             :     {
     958                 :           0 :         return chainman().IsInitialBlockDownload();
     959                 :             :     }
     960                 :             : 
     961                 :         110 :     std::optional<BlockRef> getTip() override
     962                 :             :     {
     963                 :         110 :         return block_template_manager().GetTip();
     964                 :             :     }
     965                 :             : 
     966                 :         133 :     std::optional<BlockRef> waitTipChanged(uint256 current_tip, MillisecondsDouble timeout) override
     967                 :             :     {
     968                 :         133 :         return block_template_manager().WaitTipChanged(current_tip, timeout, m_interrupt_mining);
     969                 :             :     }
     970                 :             : 
     971                 :          78 :     std::unique_ptr<BlockTemplate> createNewBlock(const BlockCreateOptions& options, bool cooldown) override
     972                 :             :     {
     973                 :             :         // Ensure m_tip_block is set so consumers of BlockTemplate can rely on that.
     974                 :          78 :         std::optional<BlockRef> maybe_tip{waitTipChanged(uint256::ZERO, MillisecondsDouble::max())};
     975                 :             : 
     976         [ -  + ]:          78 :         if (!maybe_tip) return {};
     977                 :             : 
     978         [ -  + ]:          78 :         if (cooldown) {
     979                 :             :             // Do not return a template during IBD, because it can have long
     980                 :             :             // pauses and sometimes takes a while to get started. Although this
     981                 :             :             // is useful in general, it's gated behind the cooldown argument,
     982                 :             :             // because on regtest and single miner signets this would wait
     983                 :             :             // forever if no block was mined in the past day.
     984         [ #  # ]:           0 :             while (chainman().IsInitialBlockDownload()) {
     985                 :           0 :                 maybe_tip = waitTipChanged(maybe_tip->hash, MillisecondsDouble{1000});
     986   [ #  #  #  #  :           0 :                 if (!maybe_tip || chainman().m_interrupt || WITH_LOCK(notifications().m_tip_block_mutex, return m_interrupt_mining)) return {};
          #  #  #  #  #  
                      # ]
     987                 :             :             }
     988                 :             : 
     989                 :             :             // Also wait during the final catch-up moments after IBD.
     990         [ #  # ]:           0 :             if (!block_template_manager().CooldownIfHeadersAhead(*maybe_tip, m_interrupt_mining)) return {};
     991                 :             :         }
     992                 :          78 :         auto new_template = block_template_manager().CreateNewTemplate(options);
     993         [ +  - ]:          72 :         return std::make_unique<BlockTemplateImpl>(options, std::move(new_template), m_node);
     994                 :          72 :     }
     995                 :             : 
     996                 :           0 :     void interrupt() override
     997                 :             :     {
     998                 :           0 :         block_template_manager().InterruptWait(m_interrupt_mining);
     999                 :           0 :     }
    1000                 :             : 
    1001                 :           3 :     bool checkBlock(const CBlock& block, const node::BlockCheckOptions& options, std::string& reason, std::string& debug) override
    1002                 :             :     {
    1003                 :           3 :         LOCK(chainman().GetMutex());
    1004   [ +  -  +  -  :           3 :         BlockValidationState state{TestBlockValidity(chainman().ActiveChainstate(), block, /*check_pow=*/options.check_pow, /*check_merkle_root=*/options.check_merkle_root)};
                   +  - ]
    1005         [ -  + ]:           6 :         reason = state.GetRejectReason();
    1006         [ -  + ]:           6 :         debug = state.GetDebugMessage();
    1007                 :           3 :         return state.IsValid();
    1008         [ +  - ]:           6 :     }
    1009                 :             : 
    1010                 :         110 :     bool submitBlock(const CBlock& block_in, std::string& reason, std::string& debug) override
    1011                 :             :     {
    1012   [ +  -  +  - ]:         220 :         return block_template_manager().SubmitBlock(std::make_shared<const CBlock>(block_in), reason, debug);
    1013                 :             :     }
    1014                 :             : 
    1015                 :           1 :     std::vector<CTransactionRef> getTransactionsByTxID(const std::vector<Txid>& txids) override
    1016                 :             :     {
    1017         [ -  + ]:           1 :         if (!m_node.mempool) return {};
    1018                 :             : 
    1019                 :           1 :         std::vector<CTransactionRef> results;
    1020   [ -  +  +  - ]:           1 :         results.reserve(txids.size());
    1021         [ +  - ]:           1 :         LOCK(m_node.mempool->cs);
    1022         [ +  + ]:           3 :         for (const auto& txid : txids) {
    1023   [ +  -  +  - ]:           4 :             results.emplace_back(m_node.mempool->get(txid));
    1024                 :             :         }
    1025         [ +  - ]:           1 :         return results;
    1026                 :           1 :     }
    1027                 :             : 
    1028                 :           1 :     std::vector<CTransactionRef> getTransactionsByWitnessID(const std::vector<Wtxid>& wtxids) override
    1029                 :             :     {
    1030         [ -  + ]:           1 :         if (!m_node.mempool) return {};
    1031                 :             : 
    1032                 :           1 :         std::vector<CTransactionRef> results;
    1033   [ -  +  +  - ]:           1 :         results.reserve(wtxids.size());
    1034         [ +  - ]:           1 :         LOCK(m_node.mempool->cs);
    1035         [ +  + ]:           3 :         for (const auto& wtxid : wtxids) {
    1036   [ +  -  +  - ]:           4 :             results.emplace_back(m_node.mempool->get(wtxid));
    1037                 :             :         }
    1038         [ +  - ]:           1 :         return results;
    1039                 :           1 :     }
    1040                 :             : 
    1041                 :           0 :     const NodeContext* context() override { return &m_node; }
    1042                 :           6 :     ChainstateManager& chainman() { return *Assert(m_node.chainman); }
    1043                 :           0 :     KernelNotifications& notifications() { return *Assert(m_node.notifications); }
    1044                 :         431 :     node::BlockTemplateManager& block_template_manager() { return *Assert(m_node.block_template_manager); }
    1045                 :             :     // Treat as if guarded by notifications().m_tip_block_mutex
    1046                 :             :     bool m_interrupt_mining{false};
    1047                 :             :     const NodeContext& m_node;
    1048                 :             : };
    1049                 :             : 
    1050                 :             : class RpcImpl : public Rpc
    1051                 :             : {
    1052                 :             : public:
    1053                 :           4 :     explicit RpcImpl(NodeContext& node) : m_node(node) {}
    1054                 :             : 
    1055                 :           4 :     UniValue executeRpc(UniValue request, std::string uri, std::string user) override
    1056                 :             :     {
    1057                 :           4 :         JSONRPCRequest req;
    1058                 :           4 :         req.context = &m_node;
    1059                 :           4 :         req.URI = std::move(uri);
    1060                 :           4 :         req.authUser = std::move(user);
    1061                 :           4 :         HTTPStatusCode status;
    1062         [ +  - ]:           8 :         return ExecuteHTTPRPC(request, req, status);
    1063                 :           4 :     }
    1064                 :             : 
    1065                 :             :     NodeContext& m_node;
    1066                 :             : };
    1067                 :             : } // namespace
    1068                 :             : } // namespace node
    1069                 :             : 
    1070                 :             : namespace interfaces {
    1071                 :           0 : std::unique_ptr<Node> MakeNode(node::NodeContext& context) { return std::make_unique<node::NodeImpl>(context); }
    1072                 :        2276 : std::unique_ptr<Chain> MakeChain(node::NodeContext& context) { return std::make_unique<node::ChainImpl>(context); }
    1073                 :           6 : std::unique_ptr<Mining> MakeMining(const node::NodeContext& context, bool wait_loaded)
    1074                 :             : {
    1075         [ -  + ]:           6 :     if (wait_loaded) {
    1076                 :           0 :         node::KernelNotifications& kernel_notifications(*Assert(context.notifications));
    1077                 :           0 :         util::SignalInterrupt& interrupt(*Assert(context.shutdown_signal));
    1078                 :           0 :         WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
    1079         [ #  # ]:           0 :         kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
    1080   [ #  #  #  # ]:           0 :             return kernel_notifications.m_state.chainstate_loaded || interrupt;
    1081                 :             :         });
    1082   [ #  #  #  #  :           0 :         if (interrupt) return nullptr;
                   #  # ]
    1083                 :           0 :     }
    1084                 :           6 :     return std::make_unique<node::MinerImpl>(context);
    1085                 :             : }
    1086                 :           4 : std::unique_ptr<Rpc> MakeRpc(node::NodeContext& context) { return std::make_unique<node::RpcImpl>(context); }
    1087                 :             : } // namespace interfaces
        

Generated by: LCOV version 2.0-1