interfaces.cpp raw

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