Bitcoin Core  28.1.0
P2P Digital Currency
interfaces.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <addrdb.h>
6 #include <banman.h>
7 #include <blockfilter.h>
8 #include <chain.h>
9 #include <chainparams.h>
10 #include <common/args.h>
11 #include <consensus/validation.h>
12 #include <deploymentstatus.h>
13 #include <external_signer.h>
14 #include <index/blockfilterindex.h>
15 #include <init.h>
16 #include <interfaces/chain.h>
17 #include <interfaces/handler.h>
18 #include <interfaces/mining.h>
19 #include <interfaces/node.h>
20 #include <interfaces/wallet.h>
21 #include <kernel/chain.h>
22 #include <kernel/context.h>
23 #include <kernel/mempool_entry.h>
24 #include <logging.h>
25 #include <mapport.h>
26 #include <net.h>
27 #include <net_processing.h>
28 #include <netaddress.h>
29 #include <netbase.h>
30 #include <node/blockstorage.h>
31 #include <node/coin.h>
32 #include <node/context.h>
33 #include <node/interface_ui.h>
34 #include <node/mini_miner.h>
35 #include <node/miner.h>
36 #include <node/transaction.h>
37 #include <node/types.h>
38 #include <node/warnings.h>
39 #include <policy/feerate.h>
40 #include <policy/fees.h>
41 #include <policy/policy.h>
42 #include <policy/rbf.h>
43 #include <policy/settings.h>
44 #include <primitives/block.h>
45 #include <primitives/transaction.h>
46 #include <rpc/protocol.h>
47 #include <rpc/server.h>
49 #include <sync.h>
50 #include <txmempool.h>
51 #include <uint256.h>
52 #include <univalue.h>
53 #include <util/check.h>
54 #include <util/result.h>
55 #include <util/signalinterrupt.h>
56 #include <util/string.h>
57 #include <util/translation.h>
58 #include <validation.h>
59 #include <validationinterface.h>
60 
61 #include <config/bitcoin-config.h> // IWYU pragma: keep
62 
63 #include <any>
64 #include <memory>
65 #include <optional>
66 #include <utility>
67 
68 #include <boost/signals2/signal.hpp>
69 
71 using interfaces::Chain;
75 using interfaces::Mining;
76 using interfaces::Node;
79 using util::Join;
80 
81 namespace node {
82 // All members of the classes in this namespace are intentionally public, as the
83 // classes themselves are private.
84 namespace {
85 #ifdef ENABLE_EXTERNAL_SIGNER
86 class ExternalSignerImpl : public interfaces::ExternalSigner
87 {
88 public:
89  ExternalSignerImpl(::ExternalSigner signer) : m_signer(std::move(signer)) {}
90  std::string getName() override { return m_signer.m_name; }
92 };
93 #endif
94 
95 class NodeImpl : public Node
96 {
97 public:
98  explicit NodeImpl(NodeContext& context) { setContext(&context); }
99  void initLogging() override { InitLogging(args()); }
100  void initParameterInteraction() override { InitParameterInteraction(args()); }
101  bilingual_str getWarnings() override { return Join(Assert(m_context->warnings)->GetMessages(), Untranslated("<hr />")); }
102  int getExitStatus() override { return Assert(m_context)->exit_status.load(); }
103  uint32_t getLogCategories() override { return LogInstance().GetCategoryMask(); }
104  bool baseInitialize() override
105  {
106  if (!AppInitBasicSetup(args(), Assert(context())->exit_status)) return false;
107  if (!AppInitParameterInteraction(args())) return false;
108 
109  m_context->warnings = std::make_unique<node::Warnings>();
110  m_context->kernel = std::make_unique<kernel::Context>();
111  m_context->ecc_context = std::make_unique<ECC_Context>();
112  if (!AppInitSanityChecks(*m_context->kernel)) return false;
113 
114  if (!AppInitLockDataDirectory()) return false;
115  if (!AppInitInterfaces(*m_context)) return false;
116 
117  return true;
118  }
119  bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info) override
120  {
121  if (AppInitMain(*m_context, tip_info)) return true;
122  // Error during initialization, set exit status before continue
123  m_context->exit_status.store(EXIT_FAILURE);
124  return false;
125  }
126  void appShutdown() override
127  {
130  }
131  void startShutdown() override
132  {
133  if (!(*Assert(Assert(m_context)->shutdown))()) {
134  LogError("Failed to send shutdown signal\n");
135  }
136  // Stop RPC for clean shutdown if any of waitfor* commands is executed.
137  if (args().GetBoolArg("-server", false)) {
138  InterruptRPC();
139  StopRPC();
140  }
141  }
142  bool shutdownRequested() override { return ShutdownRequested(*Assert(m_context)); };
143  bool isSettingIgnored(const std::string& name) override
144  {
145  bool ignored = false;
146  args().LockSettings([&](common::Settings& settings) {
147  if (auto* options = common::FindKey(settings.command_line_options, name)) {
148  ignored = !options->empty();
149  }
150  });
151  return ignored;
152  }
153  common::SettingsValue getPersistentSetting(const std::string& name) override { return args().GetPersistentSetting(name); }
154  void updateRwSetting(const std::string& name, const common::SettingsValue& value) override
155  {
156  args().LockSettings([&](common::Settings& settings) {
157  if (value.isNull()) {
158  settings.rw_settings.erase(name);
159  } else {
160  settings.rw_settings[name] = value;
161  }
162  });
164  }
165  void forceSetting(const std::string& name, const common::SettingsValue& value) override
166  {
167  args().LockSettings([&](common::Settings& settings) {
168  if (value.isNull()) {
169  settings.forced_settings.erase(name);
170  } else {
171  settings.forced_settings[name] = value;
172  }
173  });
174  }
175  void resetSettings() override
176  {
177  args().WriteSettingsFile(/*errors=*/nullptr, /*backup=*/true);
178  args().LockSettings([&](common::Settings& settings) {
179  settings.rw_settings.clear();
180  });
182  }
183  void mapPort(bool use_upnp, bool use_natpmp) override { StartMapPort(use_upnp, use_natpmp); }
184  bool getProxy(Network net, Proxy& proxy_info) override { return GetProxy(net, proxy_info); }
185  size_t getNodeCount(ConnectionDirection flags) override
186  {
187  return m_context->connman ? m_context->connman->GetNodeCount(flags) : 0;
188  }
189  bool getNodesStats(NodesStats& stats) override
190  {
191  stats.clear();
192 
193  if (m_context->connman) {
194  std::vector<CNodeStats> stats_temp;
195  m_context->connman->GetNodeStats(stats_temp);
196 
197  stats.reserve(stats_temp.size());
198  for (auto& node_stats_temp : stats_temp) {
199  stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
200  }
201 
202  // Try to retrieve the CNodeStateStats for each node.
203  if (m_context->peerman) {
204  TRY_LOCK(::cs_main, lockMain);
205  if (lockMain) {
206  for (auto& node_stats : stats) {
207  std::get<1>(node_stats) =
208  m_context->peerman->GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
209  }
210  }
211  }
212  return true;
213  }
214  return false;
215  }
216  bool getBanned(banmap_t& banmap) override
217  {
218  if (m_context->banman) {
219  m_context->banman->GetBanned(banmap);
220  return true;
221  }
222  return false;
223  }
224  bool ban(const CNetAddr& net_addr, int64_t ban_time_offset) override
225  {
226  if (m_context->banman) {
227  m_context->banman->Ban(net_addr, ban_time_offset);
228  return true;
229  }
230  return false;
231  }
232  bool unban(const CSubNet& ip) override
233  {
234  if (m_context->banman) {
235  m_context->banman->Unban(ip);
236  return true;
237  }
238  return false;
239  }
240  bool disconnectByAddress(const CNetAddr& net_addr) override
241  {
242  if (m_context->connman) {
243  return m_context->connman->DisconnectNode(net_addr);
244  }
245  return false;
246  }
247  bool disconnectById(NodeId id) override
248  {
249  if (m_context->connman) {
250  return m_context->connman->DisconnectNode(id);
251  }
252  return false;
253  }
254  std::vector<std::unique_ptr<interfaces::ExternalSigner>> listExternalSigners() override
255  {
256 #ifdef ENABLE_EXTERNAL_SIGNER
257  std::vector<ExternalSigner> signers = {};
258  const std::string command = args().GetArg("-signer", "");
259  if (command == "") return {};
260  ExternalSigner::Enumerate(command, signers, Params().GetChainTypeString());
261  std::vector<std::unique_ptr<interfaces::ExternalSigner>> result;
262  result.reserve(signers.size());
263  for (auto& signer : signers) {
264  result.emplace_back(std::make_unique<ExternalSignerImpl>(std::move(signer)));
265  }
266  return result;
267 #else
268  // This result is indistinguishable from a successful call that returns
269  // no signers. For the current GUI this doesn't matter, because the wallet
270  // creation dialog disables the external signer checkbox in both
271  // cases. The return type could be changed to std::optional<std::vector>
272  // (or something that also includes error messages) if this distinction
273  // becomes important.
274  return {};
275 #endif // ENABLE_EXTERNAL_SIGNER
276  }
277  int64_t getTotalBytesRecv() override { return m_context->connman ? m_context->connman->GetTotalBytesRecv() : 0; }
278  int64_t getTotalBytesSent() override { return m_context->connman ? m_context->connman->GetTotalBytesSent() : 0; }
279  size_t getMempoolSize() override { return m_context->mempool ? m_context->mempool->size() : 0; }
280  size_t getMempoolDynamicUsage() override { return m_context->mempool ? m_context->mempool->DynamicMemoryUsage() : 0; }
281  size_t getMempoolMaxUsage() override { return m_context->mempool ? m_context->mempool->m_opts.max_size_bytes : 0; }
282  bool getHeaderTip(int& height, int64_t& block_time) override
283  {
284  LOCK(::cs_main);
285  auto best_header = chainman().m_best_header;
286  if (best_header) {
287  height = best_header->nHeight;
288  block_time = best_header->GetBlockTime();
289  return true;
290  }
291  return false;
292  }
293  std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() override
294  {
295  if (m_context->connman)
296  return m_context->connman->getNetLocalAddresses();
297  else
298  return {};
299  }
300  int getNumBlocks() override
301  {
302  LOCK(::cs_main);
303  return chainman().ActiveChain().Height();
304  }
305  uint256 getBestBlockHash() override
306  {
307  const CBlockIndex* tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip());
308  return tip ? tip->GetBlockHash() : chainman().GetParams().GenesisBlock().GetHash();
309  }
310  int64_t getLastBlockTime() override
311  {
312  LOCK(::cs_main);
313  if (chainman().ActiveChain().Tip()) {
314  return chainman().ActiveChain().Tip()->GetBlockTime();
315  }
316  return chainman().GetParams().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
317  }
318  double getVerificationProgress() override
319  {
320  return GuessVerificationProgress(chainman().GetParams().TxData(), WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()));
321  }
322  bool isInitialBlockDownload() override
323  {
324  return chainman().IsInitialBlockDownload();
325  }
326  bool isLoadingBlocks() override { return chainman().m_blockman.LoadingBlocks(); }
327  void setNetworkActive(bool active) override
328  {
329  if (m_context->connman) {
330  m_context->connman->SetNetworkActive(active);
331  }
332  }
333  bool getNetworkActive() override { return m_context->connman && m_context->connman->GetNetworkActive(); }
334  CFeeRate getDustRelayFee() override
335  {
336  if (!m_context->mempool) return CFeeRate{DUST_RELAY_TX_FEE};
337  return m_context->mempool->m_opts.dust_relay_feerate;
338  }
339  UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
340  {
341  JSONRPCRequest req;
342  req.context = m_context;
343  req.params = params;
344  req.strMethod = command;
345  req.URI = uri;
347  }
348  std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
349  void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); }
350  void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); }
351  std::optional<Coin> getUnspentOutput(const COutPoint& output) override
352  {
353  LOCK(::cs_main);
354  Coin coin;
355  if (chainman().ActiveChainstate().CoinsTip().GetCoin(output, coin)) return coin;
356  return {};
357  }
358  TransactionError broadcastTransaction(CTransactionRef tx, CAmount max_tx_fee, std::string& err_string) override
359  {
360  return BroadcastTransaction(*m_context, std::move(tx), err_string, max_tx_fee, /*relay=*/ true, /*wait_callback=*/ false);
361  }
362  WalletLoader& walletLoader() override
363  {
364  return *Assert(m_context->wallet_loader);
365  }
366  std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
367  {
368  return MakeSignalHandler(::uiInterface.InitMessage_connect(fn));
369  }
370  std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
371  {
372  return MakeSignalHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
373  }
374  std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
375  {
376  return MakeSignalHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
377  }
378  std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
379  {
380  return MakeSignalHandler(::uiInterface.ShowProgress_connect(fn));
381  }
382  std::unique_ptr<Handler> handleInitWallet(InitWalletFn fn) override
383  {
384  return MakeSignalHandler(::uiInterface.InitWallet_connect(fn));
385  }
386  std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
387  {
388  return MakeSignalHandler(::uiInterface.NotifyNumConnectionsChanged_connect(fn));
389  }
390  std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
391  {
392  return MakeSignalHandler(::uiInterface.NotifyNetworkActiveChanged_connect(fn));
393  }
394  std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
395  {
396  return MakeSignalHandler(::uiInterface.NotifyAlertChanged_connect(fn));
397  }
398  std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
399  {
400  return MakeSignalHandler(::uiInterface.BannedListChanged_connect(fn));
401  }
402  std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
403  {
404  return MakeSignalHandler(::uiInterface.NotifyBlockTip_connect([fn](SynchronizationState sync_state, const CBlockIndex* block) {
405  fn(sync_state, BlockTip{block->nHeight, block->GetBlockTime(), block->GetBlockHash()},
406  GuessVerificationProgress(Params().TxData(), block));
407  }));
408  }
409  std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
410  {
411  return MakeSignalHandler(
412  ::uiInterface.NotifyHeaderTip_connect([fn](SynchronizationState sync_state, int64_t height, int64_t timestamp, bool presync) {
413  fn(sync_state, BlockTip{(int)height, timestamp, uint256{}}, presync);
414  }));
415  }
416  NodeContext* context() override { return m_context; }
417  void setContext(NodeContext* context) override
418  {
419  m_context = context;
420  }
421  ArgsManager& args() { return *Assert(Assert(m_context)->args); }
422  ChainstateManager& chainman() { return *Assert(m_context->chainman); }
423  NodeContext* m_context{nullptr};
424 };
425 
426 // NOLINTNEXTLINE(misc-no-recursion)
427 bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active, const BlockManager& blockman)
428 {
429  if (!index) return false;
430  if (block.m_hash) *block.m_hash = index->GetBlockHash();
431  if (block.m_height) *block.m_height = index->nHeight;
432  if (block.m_time) *block.m_time = index->GetBlockTime();
433  if (block.m_max_time) *block.m_max_time = index->GetBlockTimeMax();
434  if (block.m_mtp_time) *block.m_mtp_time = index->GetMedianTimePast();
435  if (block.m_in_active_chain) *block.m_in_active_chain = active[index->nHeight] == index;
436  if (block.m_locator) { *block.m_locator = GetLocator(index); }
437  if (block.m_next_block) FillBlock(active[index->nHeight] == index ? active[index->nHeight + 1] : nullptr, *block.m_next_block, lock, active, blockman);
438  if (block.m_data) {
439  REVERSE_LOCK(lock);
440  if (!blockman.ReadBlockFromDisk(*block.m_data, *index)) block.m_data->SetNull();
441  }
442  block.found = true;
443  return true;
444 }
445 
446 class NotificationsProxy : public CValidationInterface
447 {
448 public:
449  explicit NotificationsProxy(std::shared_ptr<Chain::Notifications> notifications)
450  : m_notifications(std::move(notifications)) {}
451  virtual ~NotificationsProxy() = default;
452  void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t mempool_sequence) override
453  {
454  m_notifications->transactionAddedToMempool(tx.info.m_tx);
455  }
456  void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
457  {
458  m_notifications->transactionRemovedFromMempool(tx, reason);
459  }
460  void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
461  {
462  m_notifications->blockConnected(role, kernel::MakeBlockInfo(index, block.get()));
463  }
464  void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
465  {
466  m_notifications->blockDisconnected(kernel::MakeBlockInfo(index, block.get()));
467  }
468  void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override
469  {
470  m_notifications->updatedBlockTip();
471  }
472  void ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) override {
473  m_notifications->chainStateFlushed(role, locator);
474  }
475  std::shared_ptr<Chain::Notifications> m_notifications;
476 };
477 
478 class NotificationsHandlerImpl : public Handler
479 {
480 public:
481  explicit NotificationsHandlerImpl(ValidationSignals& signals, std::shared_ptr<Chain::Notifications> notifications)
482  : m_signals{signals}, m_proxy{std::make_shared<NotificationsProxy>(std::move(notifications))}
483  {
485  }
486  ~NotificationsHandlerImpl() override { disconnect(); }
487  void disconnect() override
488  {
489  if (m_proxy) {
491  m_proxy.reset();
492  }
493  }
495  std::shared_ptr<NotificationsProxy> m_proxy;
496 };
497 
498 class RpcHandlerImpl : public Handler
499 {
500 public:
501  explicit RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command)
502  {
503  m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
504  if (!m_wrapped_command) return false;
505  try {
506  return m_wrapped_command->actor(request, result, last_handler);
507  } catch (const UniValue& e) {
508  // If this is not the last handler and a wallet not found
509  // exception was thrown, return false so the next handler can
510  // try to handle the request. Otherwise, reraise the exception.
511  if (!last_handler) {
512  const UniValue& code = e["code"];
513  if (code.isNum() && code.getInt<int>() == RPC_WALLET_NOT_FOUND) {
514  return false;
515  }
516  }
517  throw;
518  }
519  };
521  }
522 
523  void disconnect() final
524  {
525  if (m_wrapped_command) {
526  m_wrapped_command = nullptr;
528  }
529  }
530 
531  ~RpcHandlerImpl() override { disconnect(); }
532 
535 };
536 
537 class ChainImpl : public Chain
538 {
539 public:
540  explicit ChainImpl(NodeContext& node) : m_node(node) {}
541  std::optional<int> getHeight() override
542  {
543  const int height{WITH_LOCK(::cs_main, return chainman().ActiveChain().Height())};
544  return height >= 0 ? std::optional{height} : std::nullopt;
545  }
546  uint256 getBlockHash(int height) override
547  {
548  LOCK(::cs_main);
549  return Assert(chainman().ActiveChain()[height])->GetBlockHash();
550  }
551  bool haveBlockOnDisk(int height) override
552  {
553  LOCK(::cs_main);
554  const CBlockIndex* block{chainman().ActiveChain()[height]};
555  return block && ((block->nStatus & BLOCK_HAVE_DATA) != 0) && block->nTx > 0;
556  }
557  CBlockLocator getTipLocator() override
558  {
559  LOCK(::cs_main);
560  return chainman().ActiveChain().GetLocator();
561  }
562  CBlockLocator getActiveChainLocator(const uint256& block_hash) override
563  {
564  LOCK(::cs_main);
565  const CBlockIndex* index = chainman().m_blockman.LookupBlockIndex(block_hash);
566  return GetLocator(index);
567  }
568  std::optional<int> findLocatorFork(const CBlockLocator& locator) override
569  {
570  LOCK(::cs_main);
571  if (const CBlockIndex* fork = chainman().ActiveChainstate().FindForkInGlobalIndex(locator)) {
572  return fork->nHeight;
573  }
574  return std::nullopt;
575  }
576  bool hasBlockFilterIndex(BlockFilterType filter_type) override
577  {
578  return GetBlockFilterIndex(filter_type) != nullptr;
579  }
580  std::optional<bool> blockFilterMatchesAny(BlockFilterType filter_type, const uint256& block_hash, const GCSFilter::ElementSet& filter_set) override
581  {
582  const BlockFilterIndex* block_filter_index{GetBlockFilterIndex(filter_type)};
583  if (!block_filter_index) return std::nullopt;
584 
585  BlockFilter filter;
586  const CBlockIndex* index{WITH_LOCK(::cs_main, return chainman().m_blockman.LookupBlockIndex(block_hash))};
587  if (index == nullptr || !block_filter_index->LookupFilter(index, filter)) return std::nullopt;
588  return filter.GetFilter().MatchAny(filter_set);
589  }
590  bool findBlock(const uint256& hash, const FoundBlock& block) override
591  {
592  WAIT_LOCK(cs_main, lock);
593  return FillBlock(chainman().m_blockman.LookupBlockIndex(hash), block, lock, chainman().ActiveChain(), chainman().m_blockman);
594  }
595  bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block) override
596  {
597  WAIT_LOCK(cs_main, lock);
598  const CChain& active = chainman().ActiveChain();
599  return FillBlock(active.FindEarliestAtLeast(min_time, min_height), block, lock, active, chainman().m_blockman);
600  }
601  bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out) override
602  {
603  WAIT_LOCK(cs_main, lock);
604  const CChain& active = chainman().ActiveChain();
605  if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
606  if (const CBlockIndex* ancestor = block->GetAncestor(ancestor_height)) {
607  return FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman);
608  }
609  }
610  return FillBlock(nullptr, ancestor_out, lock, active, chainman().m_blockman);
611  }
612  bool findAncestorByHash(const uint256& block_hash, const uint256& ancestor_hash, const FoundBlock& ancestor_out) override
613  {
614  WAIT_LOCK(cs_main, lock);
615  const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash);
616  const CBlockIndex* ancestor = chainman().m_blockman.LookupBlockIndex(ancestor_hash);
617  if (block && ancestor && block->GetAncestor(ancestor->nHeight) != ancestor) ancestor = nullptr;
618  return FillBlock(ancestor, ancestor_out, lock, chainman().ActiveChain(), chainman().m_blockman);
619  }
620  bool findCommonAncestor(const uint256& block_hash1, const uint256& block_hash2, const FoundBlock& ancestor_out, const FoundBlock& block1_out, const FoundBlock& block2_out) override
621  {
622  WAIT_LOCK(cs_main, lock);
623  const CChain& active = chainman().ActiveChain();
624  const CBlockIndex* block1 = chainman().m_blockman.LookupBlockIndex(block_hash1);
625  const CBlockIndex* block2 = chainman().m_blockman.LookupBlockIndex(block_hash2);
626  const CBlockIndex* ancestor = block1 && block2 ? LastCommonAncestor(block1, block2) : nullptr;
627  // Using & instead of && below to avoid short circuiting and leaving
628  // output uninitialized. Cast bool to int to avoid -Wbitwise-instead-of-logical
629  // compiler warnings.
630  return int{FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman)} &
631  int{FillBlock(block1, block1_out, lock, active, chainman().m_blockman)} &
632  int{FillBlock(block2, block2_out, lock, active, chainman().m_blockman)};
633  }
634  void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(m_node, coins); }
635  double guessVerificationProgress(const uint256& block_hash) override
636  {
637  LOCK(::cs_main);
638  return GuessVerificationProgress(chainman().GetParams().TxData(), chainman().m_blockman.LookupBlockIndex(block_hash));
639  }
640  bool hasBlocks(const uint256& block_hash, int min_height, std::optional<int> max_height) override
641  {
642  // hasBlocks returns true if all ancestors of block_hash in specified
643  // range have block data (are not pruned), false if any ancestors in
644  // specified range are missing data.
645  //
646  // For simplicity and robustness, min_height and max_height are only
647  // used to limit the range, and passing min_height that's too low or
648  // max_height that's too high will not crash or change the result.
649  LOCK(::cs_main);
650  if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
651  if (max_height && block->nHeight >= *max_height) block = block->GetAncestor(*max_height);
652  for (; block->nStatus & BLOCK_HAVE_DATA; block = block->pprev) {
653  // Check pprev to not segfault if min_height is too low
654  if (block->nHeight <= min_height || !block->pprev) return true;
655  }
656  }
657  return false;
658  }
659  RBFTransactionState isRBFOptIn(const CTransaction& tx) override
660  {
661  if (!m_node.mempool) return IsRBFOptInEmptyMempool(tx);
662  LOCK(m_node.mempool->cs);
663  return IsRBFOptIn(tx, *m_node.mempool);
664  }
665  bool isInMempool(const uint256& txid) override
666  {
667  if (!m_node.mempool) return false;
668  LOCK(m_node.mempool->cs);
669  return m_node.mempool->exists(GenTxid::Txid(txid));
670  }
671  bool hasDescendantsInMempool(const uint256& txid) override
672  {
673  if (!m_node.mempool) return false;
674  LOCK(m_node.mempool->cs);
675  const auto entry{m_node.mempool->GetEntry(Txid::FromUint256(txid))};
676  if (entry == nullptr) return false;
677  return entry->GetCountWithDescendants() > 1;
678  }
679  bool broadcastTransaction(const CTransactionRef& tx,
680  const CAmount& max_tx_fee,
681  bool relay,
682  std::string& err_string) override
683  {
684  const TransactionError err = BroadcastTransaction(m_node, tx, err_string, max_tx_fee, relay, /*wait_callback=*/false);
685  // Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures.
686  // Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures
687  // that Chain clients do not need to know about.
688  return TransactionError::OK == err;
689  }
690  void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize, CAmount* ancestorfees) override
691  {
692  ancestors = descendants = 0;
693  if (!m_node.mempool) return;
694  m_node.mempool->GetTransactionAncestry(txid, ancestors, descendants, ancestorsize, ancestorfees);
695  }
696 
697  std::map<COutPoint, CAmount> calculateIndividualBumpFees(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
698  {
699  if (!m_node.mempool) {
700  std::map<COutPoint, CAmount> bump_fees;
701  for (const auto& outpoint : outpoints) {
702  bump_fees.emplace(outpoint, 0);
703  }
704  return bump_fees;
705  }
706  return MiniMiner(*m_node.mempool, outpoints).CalculateBumpFees(target_feerate);
707  }
708 
709  std::optional<CAmount> calculateCombinedBumpFee(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
710  {
711  if (!m_node.mempool) {
712  return 0;
713  }
714  return MiniMiner(*m_node.mempool, outpoints).CalculateTotalBumpFees(target_feerate);
715  }
716  void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) override
717  {
718  const CTxMemPool::Limits default_limits{};
719 
720  const CTxMemPool::Limits& limits{m_node.mempool ? m_node.mempool->m_opts.limits : default_limits};
721 
722  limit_ancestor_count = limits.ancestor_count;
723  limit_descendant_count = limits.descendant_count;
724  }
726  {
727  if (!m_node.mempool) return {};
728  LockPoints lp;
729  CTxMemPoolEntry entry(tx, 0, 0, 0, 0, false, 0, lp);
730  LOCK(m_node.mempool->cs);
731  return m_node.mempool->CheckPackageLimits({tx}, entry.GetTxSize());
732  }
733  CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc) override
734  {
735  if (!m_node.fee_estimator) return {};
736  return m_node.fee_estimator->estimateSmartFee(num_blocks, calc, conservative);
737  }
738  unsigned int estimateMaxBlocks() override
739  {
740  if (!m_node.fee_estimator) return 0;
741  return m_node.fee_estimator->HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
742  }
743  CFeeRate mempoolMinFee() override
744  {
745  if (!m_node.mempool) return {};
746  return m_node.mempool->GetMinFee();
747  }
748  CFeeRate relayMinFee() override
749  {
750  if (!m_node.mempool) return CFeeRate{DEFAULT_MIN_RELAY_TX_FEE};
751  return m_node.mempool->m_opts.min_relay_feerate;
752  }
753  CFeeRate relayIncrementalFee() override
754  {
755  if (!m_node.mempool) return CFeeRate{DEFAULT_INCREMENTAL_RELAY_FEE};
756  return m_node.mempool->m_opts.incremental_relay_feerate;
757  }
758  CFeeRate relayDustFee() override
759  {
760  if (!m_node.mempool) return CFeeRate{DUST_RELAY_TX_FEE};
761  return m_node.mempool->m_opts.dust_relay_feerate;
762  }
763  bool havePruned() override
764  {
765  LOCK(::cs_main);
766  return chainman().m_blockman.m_have_pruned;
767  }
768  bool isReadyToBroadcast() override { return !chainman().m_blockman.LoadingBlocks() && !isInitialBlockDownload(); }
769  bool isInitialBlockDownload() override
770  {
771  return chainman().IsInitialBlockDownload();
772  }
773  bool shutdownRequested() override { return ShutdownRequested(m_node); }
774  void initMessage(const std::string& message) override { ::uiInterface.InitMessage(message); }
775  void initWarning(const bilingual_str& message) override { InitWarning(message); }
776  void initError(const bilingual_str& message) override { InitError(message); }
777  void showProgress(const std::string& title, int progress, bool resume_possible) override
778  {
779  ::uiInterface.ShowProgress(title, progress, resume_possible);
780  }
781  std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) override
782  {
783  return std::make_unique<NotificationsHandlerImpl>(validation_signals(), std::move(notifications));
784  }
785  void waitForNotificationsIfTipChanged(const uint256& old_tip) override
786  {
787  if (!old_tip.IsNull() && old_tip == WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()->GetBlockHash())) return;
788  validation_signals().SyncWithValidationInterfaceQueue();
789  }
790  std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) override
791  {
792  return std::make_unique<RpcHandlerImpl>(command);
793  }
794  bool rpcEnableDeprecated(const std::string& method) override { return IsDeprecatedRPCEnabled(method); }
795  void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) override
796  {
797  RPCRunLater(name, std::move(fn), seconds);
798  }
799  common::SettingsValue getSetting(const std::string& name) override
800  {
801  return args().GetSetting(name);
802  }
803  std::vector<common::SettingsValue> getSettingsList(const std::string& name) override
804  {
805  return args().GetSettingsList(name);
806  }
807  common::SettingsValue getRwSetting(const std::string& name) override
808  {
809  common::SettingsValue result;
810  args().LockSettings([&](const common::Settings& settings) {
811  if (const common::SettingsValue* value = common::FindKey(settings.rw_settings, name)) {
812  result = *value;
813  }
814  });
815  return result;
816  }
817  bool updateRwSetting(const std::string& name,
818  const interfaces::SettingsUpdate& update_settings_func) override
819  {
820  std::optional<interfaces::SettingsAction> action;
821  args().LockSettings([&](common::Settings& settings) {
822  auto* ptr_value = common::FindKey(settings.rw_settings, name);
823  // Create value if it doesn't exist
824  auto& value = ptr_value ? *ptr_value : settings.rw_settings[name];
825  action = update_settings_func(value);
826  });
827  if (!action) return false;
828  // Now dump value to disk if requested
830  }
831  bool overwriteRwSetting(const std::string& name, common::SettingsValue& value, bool write) override
832  {
833  if (value.isNull()) return deleteRwSettings(name, write);
834  return updateRwSetting(name, [&](common::SettingsValue& settings) {
835  settings = std::move(value);
837  });
838  }
839  bool deleteRwSettings(const std::string& name, bool write) override
840  {
841  args().LockSettings([&](common::Settings& settings) {
842  settings.rw_settings.erase(name);
843  });
844  return !write || args().WriteSettingsFile();
845  }
846  void requestMempoolTransactions(Notifications& notifications) override
847  {
848  if (!m_node.mempool) return;
849  LOCK2(::cs_main, m_node.mempool->cs);
850  for (const CTxMemPoolEntry& entry : m_node.mempool->entryAll()) {
851  notifications.transactionAddedToMempool(entry.GetSharedTx());
852  }
853  }
854  bool hasAssumedValidChain() override
855  {
856  return chainman().IsSnapshotActive();
857  }
858 
859  NodeContext* context() override { return &m_node; }
860  ArgsManager& args() { return *Assert(m_node.args); }
861  ChainstateManager& chainman() { return *Assert(m_node.chainman); }
862  ValidationSignals& validation_signals() { return *Assert(m_node.validation_signals); }
863  NodeContext& m_node;
864 };
865 
866 class MinerImpl : public Mining
867 {
868 public:
869  explicit MinerImpl(NodeContext& node) : m_node(node) {}
870 
871  bool isTestChain() override
872  {
873  return chainman().GetParams().IsTestChain();
874  }
875 
876  bool isInitialBlockDownload() override
877  {
878  return chainman().IsInitialBlockDownload();
879  }
880 
881  std::optional<uint256> getTipHash() override
882  {
883  LOCK(::cs_main);
884  CBlockIndex* tip{chainman().ActiveChain().Tip()};
885  if (!tip) return {};
886  return tip->GetBlockHash();
887  }
888 
889  bool processNewBlock(const std::shared_ptr<const CBlock>& block, bool* new_block) override
890  {
891  return chainman().ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/new_block);
892  }
893 
894  unsigned int getTransactionsUpdated() override
895  {
896  return context()->mempool->GetTransactionsUpdated();
897  }
898 
899  bool testBlockValidity(const CBlock& block, bool check_merkle_root, BlockValidationState& state) override
900  {
901  LOCK(cs_main);
902  CBlockIndex* tip{chainman().ActiveChain().Tip()};
903  // Fail if the tip updated before the lock was taken
904  if (block.hashPrevBlock != tip->GetBlockHash()) {
905  state.Error("Block does not connect to current chain tip.");
906  return false;
907  }
908 
909  return TestBlockValidity(state, chainman().GetParams(), chainman().ActiveChainstate(), block, tip, /*fCheckPOW=*/false, check_merkle_root);
910  }
911 
912  std::unique_ptr<CBlockTemplate> createNewBlock(const CScript& script_pub_key, const BlockCreateOptions& options) override
913  {
914  BlockAssembler::Options assemble_options{options};
915  ApplyArgsManOptions(*Assert(m_node.args), assemble_options);
916  return BlockAssembler{chainman().ActiveChainstate(), context()->mempool.get(), assemble_options}.CreateNewBlock(script_pub_key);
917  }
918 
919  NodeContext* context() override { return &m_node; }
920  ChainstateManager& chainman() { return *Assert(m_node.chainman); }
921  NodeContext& m_node;
922 };
923 } // namespace
924 } // namespace node
925 
926 namespace interfaces {
927 std::unique_ptr<Node> MakeNode(node::NodeContext& context) { return std::make_unique<node::NodeImpl>(context); }
928 std::unique_ptr<Chain> MakeChain(node::NodeContext& context) { return std::make_unique<node::ChainImpl>(context); }
929 std::unique_ptr<Mining> MakeMining(node::NodeContext& context) { return std::make_unique<node::MinerImpl>(context); }
930 } // namespace interfaces
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
TransactionError
Definition: types.h:19
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:53
const GCSFilter & GetFilter() const LIFETIMEBOUND
Definition: blockfilter.h:136
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
virtual bool findCommonAncestor(const uint256 &block_hash1, const uint256 &block_hash2, const FoundBlock &ancestor_out={}, const FoundBlock &block1_out={}, const FoundBlock &block2_out={})=0
Find most recent common ancestor between two blocks and optionally return block information.
virtual void findCoins(std::map< COutPoint, Coin > &coins)=0
Look up unspent output information.
virtual void getTransactionAncestry(const uint256 &txid, size_t &ancestors, size_t &descendants, size_t *ancestorsize=nullptr, CAmount *ancestorfees=nullptr)=0
Calculate mempool ancestor and descendant counts for the given transaction.
virtual void getPackageLimits(unsigned int &limit_ancestor_count, unsigned int &limit_descendant_count)=0
Get the node&#39;s package limits.
RPC timer "driver".
Definition: server.h:57
Block tip (could be a header or not, depends on the subscribed signal).
Definition: node.h:282
std::any context
Definition: request.h:45
Enables interaction with an external signing device or service, such as a hardware wallet...
virtual void TransactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence)
Notifies listeners of a transaction leaving mempool.
static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
Definition: policy.h:35
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:828
bool Error(const std::string &reject_reason)
Definition: validation.h:115
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:82
BCLog::Logger & LogInstance()
Definition: logging.cpp:23
virtual std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock &block={})=0
Find first block in the chain with timestamp >= the given time and height >= than the given height...
CClientUIInterface uiInterface
int64_t GetBlockTime() const
Definition: chain.h:266
Generate a new block, without valid proof-of-work.
Definition: miner.h:139
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:123
NodeContext & m_node
Definition: interfaces.cpp:863
virtual std::unique_ptr< Handler > handleNotifications(std::shared_ptr< Notifications > notifications)=0
Register handler for notifications.
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected Provides the block that was disconnected.
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:147
#define TRY_LOCK(cs, name)
Definition: sync.h:261
RBFTransactionState IsRBFOptIn(const CTransaction &tx, const CTxMemPool &pool)
Determine whether an unconfirmed transaction is signaling opt-in to RBF according to BIP 125 This inv...
Definition: rbf.cpp:24
std::map< std::string, SettingsValue > forced_settings
Map of setting name to forced setting value.
Definition: settings.h:34
Stored settings.
Definition: settings.h:32
common::SettingsValue GetSetting(const std::string &arg) const
Get setting value.
Definition: args.cpp:800
A UTXO entry.
Definition: coins.h:32
Bilingual messages:
Definition: translation.h:18
Definition: block.h:68
Actor actor
Definition: server.h:115
virtual uint256 getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
virtual CFeeRate mempoolMinFee()=0
Mempool minimum fee.
virtual common::SettingsValue getSetting(const std::string &arg)=0
Get settings value.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:870
virtual CBlockLocator getActiveChainLocator(const uint256 &block_hash)=0
Return a locator that refers to a block in the active chain.
virtual void rpcRunLater(const std::string &name, std::function< void()> fn, int64_t seconds)=0
Run function after given number of seconds. Cancel any previous calls with same name.
Options struct containing limit options for a CTxMemPool.
int64_t * m_max_time
Definition: chain.h:74
An in-memory indexed chain of blocks.
Definition: chain.h:416
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:276
virtual CFeeRate relayDustFee()=0
Relay dust fee setting (-dustrelayfee), reflecting lowest rate it&#39;s economical to spend...
virtual bool hasBlockFilterIndex(BlockFilterType filter_type)=0
Returns whether a block filter index is available.
virtual std::vector< common::SettingsValue > getSettingsList(const std::string &arg)=0
Get list of settings values.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:48
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:165
bool GetProxy(enum Network net, Proxy &proxyInfoOut)
Definition: netbase.cpp:688
virtual bool isInitialBlockDownload()=0
Check if in IBD.
virtual bool overwriteRwSetting(const std::string &name, common::SettingsValue &value, bool write=true)=0
Replace a setting in <datadir>/settings.json with a new value.
static constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: policy.h:57
Interrupt(node)
bool MatchAny(const ElementSet &elements) const
Checks if any of the given elements may be in the set.
bool removeCommand(const std::string &name, const CRPCCommand *pcmd)
Definition: server.cpp:283
::ExternalSigner m_signer
Definition: interfaces.cpp:91
void InterruptRPC()
Definition: server.cpp:303
common::SettingsValue GetPersistentSetting(const std::string &name) const
Get current setting from config file or read/write settings file, ignoring nonpersistent command line...
Definition: args.cpp:444
bool isNum() const
Definition: univalue.h:84
void StartMapPort(bool use_upnp, bool use_natpmp)
Definition: mapport.cpp:298
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
const CRPCCommand * m_wrapped_command
Definition: interfaces.cpp:534
std::unique_ptr< Node > MakeNode(node::NodeContext &context)
Return implementation of Node interface.
Definition: interfaces.cpp:927
Int getInt() const
Definition: univalue.h:138
virtual std::optional< uint256 > getTipHash()=0
Returns the hash for the tip of this chain.
void InitWarning(const bilingual_str &str)
Show warning message.
#define REVERSE_LOCK(g)
Definition: sync.h:243
void RPCRunLater(const std::string &name, std::function< void()> func, int64_t nSeconds)
Run func nSeconds from now.
Definition: server.cpp:580
virtual unsigned int getTransactionsUpdated()=0
Return the number of transaction updates in the mempool, used to decide whether to make a new block t...
virtual void TransactionAddedToMempool(const NewMempoolTransactionInfo &tx, uint64_t mempool_sequence)
Notifies listeners of a transaction having been added to mempool.
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block) ...
std::string m_name
Name of signer.
virtual double guessVerificationProgress(const uint256 &block_hash)=0
Estimate fraction of total transactions verified if blocks up to the specified block hash are verifie...
Implement this to subscribe to events generated in validation and mempool.
int64_t * m_mtp_time
Definition: chain.h:75
CBlockLocator * m_locator
Definition: chain.h:77
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:574
RBFTransactionState
The rbf state of unconfirmed transactions.
Definition: rbf.h:29
uint256 * m_hash
Definition: chain.h:71
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:65
bool AppInitBasicSetup(const ArgsManager &args, std::atomic< int > &exit_status)
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:858
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: mempool_entry.h:65
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:501
virtual std::optional< int > findLocatorFork(const CBlockLocator &locator)=0
Return height of the highest block on chain in common with the locator, which will either be the orig...
CRPCCommand m_command
Definition: interfaces.cpp:533
std::string strMethod
Definition: request.h:39
uint256 GetBlockHash() const
Definition: chain.h:243
virtual bool hasDescendantsInMempool(const uint256 &txid)=0
Check if transaction has descendants in mempool.
CBlockIndex * FindEarliestAtLeast(int64_t nTime, int height) const
Find the earliest block with timestamp equal or greater than the given time and height equal or great...
Definition: chain.cpp:71
BlockFilterType
Definition: blockfilter.h:92
NodeContext struct containing references to chain state and connection state.
Definition: context.h:55
#define LOCK2(cs1, cs2)
Definition: sync.h:258
std::string name
Definition: server.h:114
CRPCTable tableRPC
Definition: server.cpp:590
Interface giving clients (RPC, Stratum v2 Template Provider in the future) ability to create block te...
Definition: mining.h:28
virtual bool hasAssumedValidChain()=0
Return true if an assumed-valid chain is in use.
RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction &tx)
Definition: rbf.cpp:53
virtual bool isInMempool(const uint256 &txid)=0
Check if transaction is in mempool.
ArgsManager & args
Definition: bitcoind.cpp:270
std::vector< common::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: args.cpp:808
std::function< std::optional< interfaces::SettingsAction >(common::SettingsValue &)> SettingsUpdate
Definition: chain.h:108
std::map< std::string, std::vector< SettingsValue > > command_line_options
Map of setting name to list of command line values.
Definition: settings.h:36
virtual bool findAncestorByHeight(const uint256 &block_hash, int ancestor_height, const FoundBlock &ancestor_out={})=0
Find ancestor of block at specified height and optionally return ancestor information.
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition: chain.h:25
UniValue params
Definition: request.h:40
virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation *calc=nullptr)=0
Estimate smart fee.
CBlock * m_data
Definition: chain.h:79
#define LOCK(cs)
Definition: sync.h:257
const char * name
Definition: rest.cpp:49
bool InitError(const bilingual_str &str)
Show error message.
virtual bool updateRwSetting(const std::string &name, const SettingsUpdate &update_function)=0
Updates a setting in <datadir>/settings.json.
Complete block filter struct as defined in BIP 157.
Definition: blockfilter.h:114
const FoundBlock * m_next_block
Definition: chain.h:78
virtual std::unique_ptr< Handler > handleRpc(const CRPCCommand &command)=0
Register handler for RPC.
uint256 hashPrevBlock
Definition: block.h:26
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
Notifies listeners when the block chain tip advances.
bool AppInitMain(NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
Definition: init.cpp:1138
int64_t GetBlockTimeMax() const
Definition: chain.h:271
virtual bool findBlock(const uint256 &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
uint32_t GetCategoryMask() const
Definition: logging.h:207
virtual void waitForNotificationsIfTipChanged(const uint256 &old_tip)=0
Wait for pending notifications to be processed unless block hash points to the current chain tip...
TransactionError BroadcastTransaction(NodeContext &node, const CTransactionRef tx, std::string &err_string, const CAmount &max_tx_fee, bool relay, bool wait_callback)
Submit a transaction to the mempool and (optionally) relay it to all P2P peers.
Definition: transaction.cpp:34
NodeContext * m_context
Definition: interfaces.cpp:423
virtual void requestMempoolTransactions(Notifications &notifications)=0
Synchronously send transactionAddedToMempool notifications about all current mempool transactions to ...
Network
A network type.
Definition: netaddress.h:32
static CService ip(uint32_t i)
Block and header tip information.
Definition: node.h:49
int64_t NodeId
Definition: net.h:97
virtual std::optional< CAmount > calculateCombinedBumpFee(const std::vector< COutPoint > &outpoints, const CFeeRate &target_feerate)=0
Calculate the combined bump fee for an input set per the same strategy.
virtual bool processNewBlock(const std::shared_ptr< const CBlock > &block, bool *new_block)=0
Processes new block.
#define WAIT_LOCK(cs, name)
Definition: sync.h:262
static bool Enumerate(const std::string &command, std::vector< ExternalSigner > &signers, const std::string chain)
Obtain a list of signers.
std::shared_ptr< NotificationsProxy > m_proxy
Definition: interfaces.cpp:495
virtual std::unique_ptr< node::CBlockTemplate > createNewBlock(const CScript &script_pub_key, const node::BlockCreateOptions &options={})=0
Construct a new block template.
Invalid wallet specified.
Definition: protocol.h:80
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:28
constexpr bool IsNull() const
Definition: uint256.h:46
Wallet chain client that in addition to having chain client methods for starting up, shutting down, and registering RPCs, also has additional methods (called by the GUI) to load and create wallets.
Definition: wallet.h:327
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:358
virtual bool isInitialBlockDownload()=0
Returns whether IBD is still in progress.
bool isNull() const
Definition: univalue.h:79
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
int64_t GetMedianTimePast() const
Definition: chain.h:278
void FindCoins(const NodeContext &node, std::map< COutPoint, Coin > &coins)
Look up unspent output information.
Definition: coin.cpp:12
External signer interface used by the GUI.
Definition: node.h:59
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
Definition: server.cpp:563
std::unordered_set< Element, ByteVectorHash > ElementSet
Definition: blockfilter.h:32
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
Definition: messages.h:20
Definition: netbase.h:58
Generic interface for managing an event handler or callback function registered with another interfac...
Definition: handler.h:22
int flags
Definition: bitcoin-tx.cpp:533
virtual node::NodeContext * context()
Get internal node context.
Definition: chain.h:384
static constexpr unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
Definition: policy.h:55
Network address.
Definition: netaddress.h:111
256-bit opaque blob.
Definition: uint256.h:178
virtual bool isReadyToBroadcast()=0
Check if the node is ready to broadcast transactions.
virtual node::NodeContext * context()
Get internal node context.
Definition: mining.h:78
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
Definition: interfaces.cpp:928
Shutdown(node)
void StopRPC()
Definition: server.cpp:314
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr, bool backup=false) const
Write settings file or backup settings file.
Definition: args.cpp:424
const auto command
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:895
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
virtual bool findAncestorByHash(const uint256 &block_hash, const uint256 &ancestor_hash, const FoundBlock &ancestor_out={})=0
Return whether block descends from a specified ancestor, and optionally return ancestor information...
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:134
void SetNull()
Definition: block.h:95
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:140
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
static transaction_identifier FromUint256(const uint256 &id)
bool ShutdownRequested(node::NodeContext &node)
Return whether node shutdown was requested.
Definition: init.cpp:232
#define LogError(...)
Definition: logging.h:271
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:456
std::string URI
Definition: request.h:42
int64_t * m_time
Definition: chain.h:73
virtual void initMessage(const std::string &message)=0
Send init message.
virtual std::map< COutPoint, CAmount > calculateIndividualBumpFees(const std::vector< COutPoint > &outpoints, const CFeeRate &target_feerate)=0
For each outpoint, calculate the fee-bumping cost to spend this outpoint at the specified.
virtual bool testBlockValidity(const CBlock &block, bool check_merkle_root, BlockValidationState &state)=0
Check a block is completely valid from start to finish.
virtual void ChainStateFlushed(ChainstateRole role, const CBlockLocator &locator)
Notifies listeners of the new active block chain on-disk.
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
Definition: init.cpp:1100
int exit_status
std::unique_ptr< Mining > MakeMining(node::NodeContext &node)
Return implementation of Mining interface.
Definition: interfaces.cpp:929
const CTransactionRef m_tx
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
virtual RBFTransactionState isRBFOptIn(const CTransaction &tx)=0
Check if transaction is RBF opt in.
bool * m_in_active_chain
Definition: chain.h:76
virtual bool hasBlocks(const uint256 &block_hash, int min_height=0, std::optional< int > max_height={})=0
Return true if data is available for all blocks in the specified range of blocks. ...
virtual void showProgress(const std::string &title, int progress, bool resume_possible)=0
Send progress indicator.
virtual void BlockConnected(ChainstateRole role, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
std::unique_ptr< Handler > MakeSignalHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: interfaces.cpp:47
std::map< CSubNet, CBanEntry > banmap_t
Definition: net_types.h:41
Wrapper around std::unique_lock style lock for MutexType.
Definition: sync.h:151
virtual unsigned int estimateMaxBlocks()=0
Fee estimator max target.
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
Definition: chain.cpp:50
std::map< std::string, SettingsValue > rw_settings
Map of setting name to read-write file setting value.
Definition: settings.h:38
virtual bool shutdownRequested()=0
Check if shutdown requested.
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:1131
interfaces::BlockInfo MakeBlockInfo(const CBlockIndex *index, const CBlock *data)
Return data from block index.
Definition: chain.cpp:14
virtual void disconnect()=0
Disconnect the handler.
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1119
virtual bool broadcastTransaction(const CTransactionRef &tx, const CAmount &max_tx_fee, bool relay, std::string &err_string)=0
Transaction is added to memory pool, if the transaction fee is below the amount specified by max_tx_f...
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:295
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:153
virtual util::Result< void > checkChainLimits(const CTransactionRef &tx)=0
Check if transaction will pass the mempool&#39;s chain limits.
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:120
virtual CBlockLocator getTipLocator()=0
Get locator for the current chain tip.
void LockSettings(Fn &&fn)
Access settings with lock held.
Definition: args.h:404
full block available in blk*.dat
Definition: chain.h:121
is a home for public enum and struct type definitions that are used by internally by node code...
virtual bool isTestChain()=0
If this chain is exclusively used for testing.
ValidationSignals & m_signals
Definition: interfaces.cpp:494
virtual bool rpcEnableDeprecated(const std::string &method)=0
Check if deprecated RPC is enabled.
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:538
virtual common::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
ConnectionDirection
Definition: netbase.h:33
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:115
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
virtual void initError(const bilingual_str &message)=0
Send init error.
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:69
virtual CFeeRate relayIncrementalFee()=0
Relay incremental fee setting (-incrementalrelayfee), reflecting cost of relay.
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee and -incrementalrelayfee settings).
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:170
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:69
static GenTxid Txid(const uint256 &hash)
Definition: transaction.h:434
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:736
virtual bool havePruned()=0
Check if any block has been pruned.
#define Assert(val)
Identity function.
Definition: check.h:77
std::shared_ptr< Chain::Notifications > m_notifications
Definition: interfaces.cpp:475
LockPoints lp
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:107
virtual std::optional< bool > blockFilterMatchesAny(BlockFilterType filter_type, const uint256 &block_hash, const GCSFilter::ElementSet &filter_set)=0
Returns whether any of the elements match the block via a BIP 157 block filter or std::nullopt if the...
virtual bool deleteRwSettings(const std::string &name, bool write=true)=0
Delete a given setting in <datadir>/settings.json.