Bitcoin Core  27.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 <deploymentstatus.h>
12 #include <external_signer.h>
13 #include <index/blockfilterindex.h>
14 #include <init.h>
15 #include <interfaces/chain.h>
16 #include <interfaces/handler.h>
17 #include <interfaces/node.h>
18 #include <interfaces/wallet.h>
19 #include <kernel/chain.h>
20 #include <kernel/mempool_entry.h>
21 #include <logging.h>
22 #include <mapport.h>
23 #include <net.h>
24 #include <net_processing.h>
25 #include <netaddress.h>
26 #include <netbase.h>
27 #include <node/blockstorage.h>
28 #include <node/coin.h>
29 #include <node/context.h>
30 #include <node/interface_ui.h>
31 #include <node/mini_miner.h>
32 #include <node/transaction.h>
33 #include <policy/feerate.h>
34 #include <policy/fees.h>
35 #include <policy/policy.h>
36 #include <policy/rbf.h>
37 #include <policy/settings.h>
38 #include <primitives/block.h>
39 #include <primitives/transaction.h>
40 #include <rpc/protocol.h>
41 #include <rpc/server.h>
43 #include <sync.h>
44 #include <txmempool.h>
45 #include <uint256.h>
46 #include <univalue.h>
47 #include <util/check.h>
48 #include <util/result.h>
49 #include <util/signalinterrupt.h>
50 #include <util/translation.h>
51 #include <validation.h>
52 #include <validationinterface.h>
53 #include <warnings.h>
54 
55 #if defined(HAVE_CONFIG_H)
56 #include <config/bitcoin-config.h>
57 #endif
58 
59 #include <any>
60 #include <memory>
61 #include <optional>
62 #include <utility>
63 
64 #include <boost/signals2/signal.hpp>
65 
67 using interfaces::Chain;
71 using interfaces::Node;
73 
74 namespace node {
75 // All members of the classes in this namespace are intentionally public, as the
76 // classes themselves are private.
77 namespace {
78 #ifdef ENABLE_EXTERNAL_SIGNER
79 class ExternalSignerImpl : public interfaces::ExternalSigner
80 {
81 public:
82  ExternalSignerImpl(::ExternalSigner signer) : m_signer(std::move(signer)) {}
83  std::string getName() override { return m_signer.m_name; }
85 };
86 #endif
87 
88 class NodeImpl : public Node
89 {
90 public:
91  explicit NodeImpl(NodeContext& context) { setContext(&context); }
92  void initLogging() override { InitLogging(args()); }
93  void initParameterInteraction() override { InitParameterInteraction(args()); }
94  bilingual_str getWarnings() override { return GetWarnings(true); }
95  int getExitStatus() override { return Assert(m_context)->exit_status.load(); }
96  uint32_t getLogCategories() override { return LogInstance().GetCategoryMask(); }
97  bool baseInitialize() override
98  {
99  if (!AppInitBasicSetup(args(), Assert(context())->exit_status)) return false;
100  if (!AppInitParameterInteraction(args())) return false;
101 
102  m_context->kernel = std::make_unique<kernel::Context>();
103  if (!AppInitSanityChecks(*m_context->kernel)) return false;
104 
105  if (!AppInitLockDataDirectory()) return false;
106  if (!AppInitInterfaces(*m_context)) return false;
107 
108  return true;
109  }
110  bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info) override
111  {
112  if (AppInitMain(*m_context, tip_info)) return true;
113  // Error during initialization, set exit status before continue
114  m_context->exit_status.store(EXIT_FAILURE);
115  return false;
116  }
117  void appShutdown() override
118  {
121  }
122  void startShutdown() override
123  {
124  if (!(*Assert(Assert(m_context)->shutdown))()) {
125  LogPrintf("Error: failed to send shutdown signal\n");
126  }
127  // Stop RPC for clean shutdown if any of waitfor* commands is executed.
128  if (args().GetBoolArg("-server", false)) {
129  InterruptRPC();
130  StopRPC();
131  }
132  }
133  bool shutdownRequested() override { return ShutdownRequested(*Assert(m_context)); };
134  bool isSettingIgnored(const std::string& name) override
135  {
136  bool ignored = false;
137  args().LockSettings([&](common::Settings& settings) {
138  if (auto* options = common::FindKey(settings.command_line_options, name)) {
139  ignored = !options->empty();
140  }
141  });
142  return ignored;
143  }
144  common::SettingsValue getPersistentSetting(const std::string& name) override { return args().GetPersistentSetting(name); }
145  void updateRwSetting(const std::string& name, const common::SettingsValue& value) override
146  {
147  args().LockSettings([&](common::Settings& settings) {
148  if (value.isNull()) {
149  settings.rw_settings.erase(name);
150  } else {
151  settings.rw_settings[name] = value;
152  }
153  });
155  }
156  void forceSetting(const std::string& name, const common::SettingsValue& value) override
157  {
158  args().LockSettings([&](common::Settings& settings) {
159  if (value.isNull()) {
160  settings.forced_settings.erase(name);
161  } else {
162  settings.forced_settings[name] = value;
163  }
164  });
165  }
166  void resetSettings() override
167  {
168  args().WriteSettingsFile(/*errors=*/nullptr, /*backup=*/true);
169  args().LockSettings([&](common::Settings& settings) {
170  settings.rw_settings.clear();
171  });
173  }
174  void mapPort(bool use_upnp, bool use_natpmp) override { StartMapPort(use_upnp, use_natpmp); }
175  bool getProxy(Network net, Proxy& proxy_info) override { return GetProxy(net, proxy_info); }
176  size_t getNodeCount(ConnectionDirection flags) override
177  {
178  return m_context->connman ? m_context->connman->GetNodeCount(flags) : 0;
179  }
180  bool getNodesStats(NodesStats& stats) override
181  {
182  stats.clear();
183 
184  if (m_context->connman) {
185  std::vector<CNodeStats> stats_temp;
186  m_context->connman->GetNodeStats(stats_temp);
187 
188  stats.reserve(stats_temp.size());
189  for (auto& node_stats_temp : stats_temp) {
190  stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
191  }
192 
193  // Try to retrieve the CNodeStateStats for each node.
194  if (m_context->peerman) {
195  TRY_LOCK(::cs_main, lockMain);
196  if (lockMain) {
197  for (auto& node_stats : stats) {
198  std::get<1>(node_stats) =
199  m_context->peerman->GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
200  }
201  }
202  }
203  return true;
204  }
205  return false;
206  }
207  bool getBanned(banmap_t& banmap) override
208  {
209  if (m_context->banman) {
210  m_context->banman->GetBanned(banmap);
211  return true;
212  }
213  return false;
214  }
215  bool ban(const CNetAddr& net_addr, int64_t ban_time_offset) override
216  {
217  if (m_context->banman) {
218  m_context->banman->Ban(net_addr, ban_time_offset);
219  return true;
220  }
221  return false;
222  }
223  bool unban(const CSubNet& ip) override
224  {
225  if (m_context->banman) {
226  m_context->banman->Unban(ip);
227  return true;
228  }
229  return false;
230  }
231  bool disconnectByAddress(const CNetAddr& net_addr) override
232  {
233  if (m_context->connman) {
234  return m_context->connman->DisconnectNode(net_addr);
235  }
236  return false;
237  }
238  bool disconnectById(NodeId id) override
239  {
240  if (m_context->connman) {
241  return m_context->connman->DisconnectNode(id);
242  }
243  return false;
244  }
245  std::vector<std::unique_ptr<interfaces::ExternalSigner>> listExternalSigners() override
246  {
247 #ifdef ENABLE_EXTERNAL_SIGNER
248  std::vector<ExternalSigner> signers = {};
249  const std::string command = args().GetArg("-signer", "");
250  if (command == "") return {};
251  ExternalSigner::Enumerate(command, signers, Params().GetChainTypeString());
252  std::vector<std::unique_ptr<interfaces::ExternalSigner>> result;
253  result.reserve(signers.size());
254  for (auto& signer : signers) {
255  result.emplace_back(std::make_unique<ExternalSignerImpl>(std::move(signer)));
256  }
257  return result;
258 #else
259  // This result is indistinguishable from a successful call that returns
260  // no signers. For the current GUI this doesn't matter, because the wallet
261  // creation dialog disables the external signer checkbox in both
262  // cases. The return type could be changed to std::optional<std::vector>
263  // (or something that also includes error messages) if this distinction
264  // becomes important.
265  return {};
266 #endif // ENABLE_EXTERNAL_SIGNER
267  }
268  int64_t getTotalBytesRecv() override { return m_context->connman ? m_context->connman->GetTotalBytesRecv() : 0; }
269  int64_t getTotalBytesSent() override { return m_context->connman ? m_context->connman->GetTotalBytesSent() : 0; }
270  size_t getMempoolSize() override { return m_context->mempool ? m_context->mempool->size() : 0; }
271  size_t getMempoolDynamicUsage() override { return m_context->mempool ? m_context->mempool->DynamicMemoryUsage() : 0; }
272  bool getHeaderTip(int& height, int64_t& block_time) override
273  {
274  LOCK(::cs_main);
275  auto best_header = chainman().m_best_header;
276  if (best_header) {
277  height = best_header->nHeight;
278  block_time = best_header->GetBlockTime();
279  return true;
280  }
281  return false;
282  }
283  int getNumBlocks() override
284  {
285  LOCK(::cs_main);
286  return chainman().ActiveChain().Height();
287  }
288  uint256 getBestBlockHash() override
289  {
290  const CBlockIndex* tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip());
291  return tip ? tip->GetBlockHash() : chainman().GetParams().GenesisBlock().GetHash();
292  }
293  int64_t getLastBlockTime() override
294  {
295  LOCK(::cs_main);
296  if (chainman().ActiveChain().Tip()) {
297  return chainman().ActiveChain().Tip()->GetBlockTime();
298  }
299  return chainman().GetParams().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
300  }
301  double getVerificationProgress() override
302  {
303  return GuessVerificationProgress(chainman().GetParams().TxData(), WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()));
304  }
305  bool isInitialBlockDownload() override
306  {
307  return chainman().IsInitialBlockDownload();
308  }
309  bool isLoadingBlocks() override { return chainman().m_blockman.LoadingBlocks(); }
310  void setNetworkActive(bool active) override
311  {
312  if (m_context->connman) {
313  m_context->connman->SetNetworkActive(active);
314  }
315  }
316  bool getNetworkActive() override { return m_context->connman && m_context->connman->GetNetworkActive(); }
317  CFeeRate getDustRelayFee() override
318  {
319  if (!m_context->mempool) return CFeeRate{DUST_RELAY_TX_FEE};
320  return m_context->mempool->m_dust_relay_feerate;
321  }
322  UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
323  {
324  JSONRPCRequest req;
325  req.context = m_context;
326  req.params = params;
327  req.strMethod = command;
328  req.URI = uri;
330  }
331  std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
332  void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); }
333  void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); }
334  std::optional<Coin> getUnspentOutput(const COutPoint& output) override
335  {
336  LOCK(::cs_main);
337  Coin coin;
338  if (chainman().ActiveChainstate().CoinsTip().GetCoin(output, coin)) return coin;
339  return {};
340  }
341  TransactionError broadcastTransaction(CTransactionRef tx, CAmount max_tx_fee, std::string& err_string) override
342  {
343  return BroadcastTransaction(*m_context, std::move(tx), err_string, max_tx_fee, /*relay=*/ true, /*wait_callback=*/ false);
344  }
345  WalletLoader& walletLoader() override
346  {
347  return *Assert(m_context->wallet_loader);
348  }
349  std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
350  {
351  return MakeSignalHandler(::uiInterface.InitMessage_connect(fn));
352  }
353  std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
354  {
355  return MakeSignalHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
356  }
357  std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
358  {
359  return MakeSignalHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
360  }
361  std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
362  {
363  return MakeSignalHandler(::uiInterface.ShowProgress_connect(fn));
364  }
365  std::unique_ptr<Handler> handleInitWallet(InitWalletFn fn) override
366  {
367  return MakeSignalHandler(::uiInterface.InitWallet_connect(fn));
368  }
369  std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
370  {
371  return MakeSignalHandler(::uiInterface.NotifyNumConnectionsChanged_connect(fn));
372  }
373  std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
374  {
375  return MakeSignalHandler(::uiInterface.NotifyNetworkActiveChanged_connect(fn));
376  }
377  std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
378  {
379  return MakeSignalHandler(::uiInterface.NotifyAlertChanged_connect(fn));
380  }
381  std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
382  {
383  return MakeSignalHandler(::uiInterface.BannedListChanged_connect(fn));
384  }
385  std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
386  {
387  return MakeSignalHandler(::uiInterface.NotifyBlockTip_connect([fn](SynchronizationState sync_state, const CBlockIndex* block) {
388  fn(sync_state, BlockTip{block->nHeight, block->GetBlockTime(), block->GetBlockHash()},
389  GuessVerificationProgress(Params().TxData(), block));
390  }));
391  }
392  std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
393  {
394  return MakeSignalHandler(
395  ::uiInterface.NotifyHeaderTip_connect([fn](SynchronizationState sync_state, int64_t height, int64_t timestamp, bool presync) {
396  fn(sync_state, BlockTip{(int)height, timestamp, uint256{}}, presync);
397  }));
398  }
399  NodeContext* context() override { return m_context; }
400  void setContext(NodeContext* context) override
401  {
402  m_context = context;
403  }
404  ArgsManager& args() { return *Assert(Assert(m_context)->args); }
405  ChainstateManager& chainman() { return *Assert(m_context->chainman); }
406  NodeContext* m_context{nullptr};
407 };
408 
409 bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active, const BlockManager& blockman)
410 {
411  if (!index) return false;
412  if (block.m_hash) *block.m_hash = index->GetBlockHash();
413  if (block.m_height) *block.m_height = index->nHeight;
414  if (block.m_time) *block.m_time = index->GetBlockTime();
415  if (block.m_max_time) *block.m_max_time = index->GetBlockTimeMax();
416  if (block.m_mtp_time) *block.m_mtp_time = index->GetMedianTimePast();
417  if (block.m_in_active_chain) *block.m_in_active_chain = active[index->nHeight] == index;
418  if (block.m_locator) { *block.m_locator = GetLocator(index); }
419  if (block.m_next_block) FillBlock(active[index->nHeight] == index ? active[index->nHeight + 1] : nullptr, *block.m_next_block, lock, active, blockman);
420  if (block.m_data) {
421  REVERSE_LOCK(lock);
422  if (!blockman.ReadBlockFromDisk(*block.m_data, *index)) block.m_data->SetNull();
423  }
424  block.found = true;
425  return true;
426 }
427 
428 class NotificationsProxy : public CValidationInterface
429 {
430 public:
431  explicit NotificationsProxy(std::shared_ptr<Chain::Notifications> notifications)
432  : m_notifications(std::move(notifications)) {}
433  virtual ~NotificationsProxy() = default;
434  void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t mempool_sequence) override
435  {
436  m_notifications->transactionAddedToMempool(tx.info.m_tx);
437  }
438  void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
439  {
440  m_notifications->transactionRemovedFromMempool(tx, reason);
441  }
442  void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
443  {
444  m_notifications->blockConnected(role, kernel::MakeBlockInfo(index, block.get()));
445  }
446  void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
447  {
448  m_notifications->blockDisconnected(kernel::MakeBlockInfo(index, block.get()));
449  }
450  void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override
451  {
452  m_notifications->updatedBlockTip();
453  }
454  void ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) override {
455  m_notifications->chainStateFlushed(role, locator);
456  }
457  std::shared_ptr<Chain::Notifications> m_notifications;
458 };
459 
460 class NotificationsHandlerImpl : public Handler
461 {
462 public:
463  explicit NotificationsHandlerImpl(std::shared_ptr<Chain::Notifications> notifications)
464  : m_proxy(std::make_shared<NotificationsProxy>(std::move(notifications)))
465  {
467  }
468  ~NotificationsHandlerImpl() override { disconnect(); }
469  void disconnect() override
470  {
471  if (m_proxy) {
473  m_proxy.reset();
474  }
475  }
476  std::shared_ptr<NotificationsProxy> m_proxy;
477 };
478 
479 class RpcHandlerImpl : public Handler
480 {
481 public:
482  explicit RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command)
483  {
484  m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
485  if (!m_wrapped_command) return false;
486  try {
487  return m_wrapped_command->actor(request, result, last_handler);
488  } catch (const UniValue& e) {
489  // If this is not the last handler and a wallet not found
490  // exception was thrown, return false so the next handler can
491  // try to handle the request. Otherwise, reraise the exception.
492  if (!last_handler) {
493  const UniValue& code = e["code"];
494  if (code.isNum() && code.getInt<int>() == RPC_WALLET_NOT_FOUND) {
495  return false;
496  }
497  }
498  throw;
499  }
500  };
502  }
503 
504  void disconnect() final
505  {
506  if (m_wrapped_command) {
507  m_wrapped_command = nullptr;
509  }
510  }
511 
512  ~RpcHandlerImpl() override { disconnect(); }
513 
516 };
517 
518 class ChainImpl : public Chain
519 {
520 public:
521  explicit ChainImpl(NodeContext& node) : m_node(node) {}
522  std::optional<int> getHeight() override
523  {
524  const int height{WITH_LOCK(::cs_main, return chainman().ActiveChain().Height())};
525  return height >= 0 ? std::optional{height} : std::nullopt;
526  }
527  uint256 getBlockHash(int height) override
528  {
529  LOCK(::cs_main);
530  return Assert(chainman().ActiveChain()[height])->GetBlockHash();
531  }
532  bool haveBlockOnDisk(int height) override
533  {
534  LOCK(::cs_main);
535  const CBlockIndex* block{chainman().ActiveChain()[height]};
536  return block && ((block->nStatus & BLOCK_HAVE_DATA) != 0) && block->nTx > 0;
537  }
538  CBlockLocator getTipLocator() override
539  {
540  LOCK(::cs_main);
541  return chainman().ActiveChain().GetLocator();
542  }
543  CBlockLocator getActiveChainLocator(const uint256& block_hash) override
544  {
545  LOCK(::cs_main);
546  const CBlockIndex* index = chainman().m_blockman.LookupBlockIndex(block_hash);
547  return GetLocator(index);
548  }
549  std::optional<int> findLocatorFork(const CBlockLocator& locator) override
550  {
551  LOCK(::cs_main);
552  if (const CBlockIndex* fork = chainman().ActiveChainstate().FindForkInGlobalIndex(locator)) {
553  return fork->nHeight;
554  }
555  return std::nullopt;
556  }
557  bool hasBlockFilterIndex(BlockFilterType filter_type) override
558  {
559  return GetBlockFilterIndex(filter_type) != nullptr;
560  }
561  std::optional<bool> blockFilterMatchesAny(BlockFilterType filter_type, const uint256& block_hash, const GCSFilter::ElementSet& filter_set) override
562  {
563  const BlockFilterIndex* block_filter_index{GetBlockFilterIndex(filter_type)};
564  if (!block_filter_index) return std::nullopt;
565 
566  BlockFilter filter;
567  const CBlockIndex* index{WITH_LOCK(::cs_main, return chainman().m_blockman.LookupBlockIndex(block_hash))};
568  if (index == nullptr || !block_filter_index->LookupFilter(index, filter)) return std::nullopt;
569  return filter.GetFilter().MatchAny(filter_set);
570  }
571  bool findBlock(const uint256& hash, const FoundBlock& block) override
572  {
573  WAIT_LOCK(cs_main, lock);
574  return FillBlock(chainman().m_blockman.LookupBlockIndex(hash), block, lock, chainman().ActiveChain(), chainman().m_blockman);
575  }
576  bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block) override
577  {
578  WAIT_LOCK(cs_main, lock);
579  const CChain& active = chainman().ActiveChain();
580  return FillBlock(active.FindEarliestAtLeast(min_time, min_height), block, lock, active, chainman().m_blockman);
581  }
582  bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out) override
583  {
584  WAIT_LOCK(cs_main, lock);
585  const CChain& active = chainman().ActiveChain();
586  if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
587  if (const CBlockIndex* ancestor = block->GetAncestor(ancestor_height)) {
588  return FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman);
589  }
590  }
591  return FillBlock(nullptr, ancestor_out, lock, active, chainman().m_blockman);
592  }
593  bool findAncestorByHash(const uint256& block_hash, const uint256& ancestor_hash, const FoundBlock& ancestor_out) override
594  {
595  WAIT_LOCK(cs_main, lock);
596  const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash);
597  const CBlockIndex* ancestor = chainman().m_blockman.LookupBlockIndex(ancestor_hash);
598  if (block && ancestor && block->GetAncestor(ancestor->nHeight) != ancestor) ancestor = nullptr;
599  return FillBlock(ancestor, ancestor_out, lock, chainman().ActiveChain(), chainman().m_blockman);
600  }
601  bool findCommonAncestor(const uint256& block_hash1, const uint256& block_hash2, const FoundBlock& ancestor_out, const FoundBlock& block1_out, const FoundBlock& block2_out) override
602  {
603  WAIT_LOCK(cs_main, lock);
604  const CChain& active = chainman().ActiveChain();
605  const CBlockIndex* block1 = chainman().m_blockman.LookupBlockIndex(block_hash1);
606  const CBlockIndex* block2 = chainman().m_blockman.LookupBlockIndex(block_hash2);
607  const CBlockIndex* ancestor = block1 && block2 ? LastCommonAncestor(block1, block2) : nullptr;
608  // Using & instead of && below to avoid short circuiting and leaving
609  // output uninitialized. Cast bool to int to avoid -Wbitwise-instead-of-logical
610  // compiler warnings.
611  return int{FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman)} &
612  int{FillBlock(block1, block1_out, lock, active, chainman().m_blockman)} &
613  int{FillBlock(block2, block2_out, lock, active, chainman().m_blockman)};
614  }
615  void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(m_node, coins); }
616  double guessVerificationProgress(const uint256& block_hash) override
617  {
618  LOCK(::cs_main);
619  return GuessVerificationProgress(chainman().GetParams().TxData(), chainman().m_blockman.LookupBlockIndex(block_hash));
620  }
621  bool hasBlocks(const uint256& block_hash, int min_height, std::optional<int> max_height) override
622  {
623  // hasBlocks returns true if all ancestors of block_hash in specified
624  // range have block data (are not pruned), false if any ancestors in
625  // specified range are missing data.
626  //
627  // For simplicity and robustness, min_height and max_height are only
628  // used to limit the range, and passing min_height that's too low or
629  // max_height that's too high will not crash or change the result.
630  LOCK(::cs_main);
631  if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
632  if (max_height && block->nHeight >= *max_height) block = block->GetAncestor(*max_height);
633  for (; block->nStatus & BLOCK_HAVE_DATA; block = block->pprev) {
634  // Check pprev to not segfault if min_height is too low
635  if (block->nHeight <= min_height || !block->pprev) return true;
636  }
637  }
638  return false;
639  }
640  RBFTransactionState isRBFOptIn(const CTransaction& tx) override
641  {
642  if (!m_node.mempool) return IsRBFOptInEmptyMempool(tx);
643  LOCK(m_node.mempool->cs);
644  return IsRBFOptIn(tx, *m_node.mempool);
645  }
646  bool isInMempool(const uint256& txid) override
647  {
648  if (!m_node.mempool) return false;
649  LOCK(m_node.mempool->cs);
650  return m_node.mempool->exists(GenTxid::Txid(txid));
651  }
652  bool hasDescendantsInMempool(const uint256& txid) override
653  {
654  if (!m_node.mempool) return false;
655  LOCK(m_node.mempool->cs);
656  const auto entry{m_node.mempool->GetEntry(Txid::FromUint256(txid))};
657  if (entry == nullptr) return false;
658  return entry->GetCountWithDescendants() > 1;
659  }
660  bool broadcastTransaction(const CTransactionRef& tx,
661  const CAmount& max_tx_fee,
662  bool relay,
663  std::string& err_string) override
664  {
665  const TransactionError err = BroadcastTransaction(m_node, tx, err_string, max_tx_fee, relay, /*wait_callback=*/false);
666  // Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures.
667  // Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures
668  // that Chain clients do not need to know about.
669  return TransactionError::OK == err;
670  }
671  void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize, CAmount* ancestorfees) override
672  {
673  ancestors = descendants = 0;
674  if (!m_node.mempool) return;
675  m_node.mempool->GetTransactionAncestry(txid, ancestors, descendants, ancestorsize, ancestorfees);
676  }
677 
678  std::map<COutPoint, CAmount> calculateIndividualBumpFees(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
679  {
680  if (!m_node.mempool) {
681  std::map<COutPoint, CAmount> bump_fees;
682  for (const auto& outpoint : outpoints) {
683  bump_fees.emplace(outpoint, 0);
684  }
685  return bump_fees;
686  }
687  return MiniMiner(*m_node.mempool, outpoints).CalculateBumpFees(target_feerate);
688  }
689 
690  std::optional<CAmount> calculateCombinedBumpFee(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
691  {
692  if (!m_node.mempool) {
693  return 0;
694  }
695  return MiniMiner(*m_node.mempool, outpoints).CalculateTotalBumpFees(target_feerate);
696  }
697  void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) override
698  {
699  const CTxMemPool::Limits default_limits{};
700 
701  const CTxMemPool::Limits& limits{m_node.mempool ? m_node.mempool->m_limits : default_limits};
702 
703  limit_ancestor_count = limits.ancestor_count;
704  limit_descendant_count = limits.descendant_count;
705  }
707  {
708  if (!m_node.mempool) return {};
709  LockPoints lp;
710  CTxMemPoolEntry entry(tx, 0, 0, 0, 0, false, 0, lp);
711  LOCK(m_node.mempool->cs);
712  return m_node.mempool->CheckPackageLimits({tx}, entry.GetTxSize());
713  }
714  CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc) override
715  {
716  if (!m_node.fee_estimator) return {};
717  return m_node.fee_estimator->estimateSmartFee(num_blocks, calc, conservative);
718  }
719  unsigned int estimateMaxBlocks() override
720  {
721  if (!m_node.fee_estimator) return 0;
722  return m_node.fee_estimator->HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
723  }
724  CFeeRate mempoolMinFee() override
725  {
726  if (!m_node.mempool) return {};
727  return m_node.mempool->GetMinFee();
728  }
729  CFeeRate relayMinFee() override
730  {
731  if (!m_node.mempool) return CFeeRate{DEFAULT_MIN_RELAY_TX_FEE};
732  return m_node.mempool->m_min_relay_feerate;
733  }
734  CFeeRate relayIncrementalFee() override
735  {
736  if (!m_node.mempool) return CFeeRate{DEFAULT_INCREMENTAL_RELAY_FEE};
737  return m_node.mempool->m_incremental_relay_feerate;
738  }
739  CFeeRate relayDustFee() override
740  {
741  if (!m_node.mempool) return CFeeRate{DUST_RELAY_TX_FEE};
742  return m_node.mempool->m_dust_relay_feerate;
743  }
744  bool havePruned() override
745  {
746  LOCK(::cs_main);
747  return chainman().m_blockman.m_have_pruned;
748  }
749  bool isReadyToBroadcast() override { return !chainman().m_blockman.LoadingBlocks() && !isInitialBlockDownload(); }
750  bool isInitialBlockDownload() override
751  {
752  return chainman().IsInitialBlockDownload();
753  }
754  bool shutdownRequested() override { return ShutdownRequested(m_node); }
755  void initMessage(const std::string& message) override { ::uiInterface.InitMessage(message); }
756  void initWarning(const bilingual_str& message) override { InitWarning(message); }
757  void initError(const bilingual_str& message) override { InitError(message); }
758  void showProgress(const std::string& title, int progress, bool resume_possible) override
759  {
760  ::uiInterface.ShowProgress(title, progress, resume_possible);
761  }
762  std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) override
763  {
764  return std::make_unique<NotificationsHandlerImpl>(std::move(notifications));
765  }
766  void waitForNotificationsIfTipChanged(const uint256& old_tip) override
767  {
768  if (!old_tip.IsNull() && old_tip == WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()->GetBlockHash())) return;
770  }
771  std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) override
772  {
773  return std::make_unique<RpcHandlerImpl>(command);
774  }
775  bool rpcEnableDeprecated(const std::string& method) override { return IsDeprecatedRPCEnabled(method); }
776  void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) override
777  {
778  RPCRunLater(name, std::move(fn), seconds);
779  }
780  common::SettingsValue getSetting(const std::string& name) override
781  {
782  return args().GetSetting(name);
783  }
784  std::vector<common::SettingsValue> getSettingsList(const std::string& name) override
785  {
786  return args().GetSettingsList(name);
787  }
788  common::SettingsValue getRwSetting(const std::string& name) override
789  {
790  common::SettingsValue result;
791  args().LockSettings([&](const common::Settings& settings) {
792  if (const common::SettingsValue* value = common::FindKey(settings.rw_settings, name)) {
793  result = *value;
794  }
795  });
796  return result;
797  }
798  bool updateRwSetting(const std::string& name, const common::SettingsValue& value, bool write) override
799  {
800  args().LockSettings([&](common::Settings& settings) {
801  if (value.isNull()) {
802  settings.rw_settings.erase(name);
803  } else {
804  settings.rw_settings[name] = value;
805  }
806  });
807  return !write || args().WriteSettingsFile();
808  }
809  void requestMempoolTransactions(Notifications& notifications) override
810  {
811  if (!m_node.mempool) return;
812  LOCK2(::cs_main, m_node.mempool->cs);
813  for (const CTxMemPoolEntry& entry : m_node.mempool->entryAll()) {
814  notifications.transactionAddedToMempool(entry.GetSharedTx());
815  }
816  }
817  bool hasAssumedValidChain() override
818  {
819  return chainman().IsSnapshotActive();
820  }
821 
822  NodeContext* context() override { return &m_node; }
823  ArgsManager& args() { return *Assert(m_node.args); }
824  ChainstateManager& chainman() { return *Assert(m_node.chainman); }
825  NodeContext& m_node;
826 };
827 } // namespace
828 } // namespace node
829 
830 namespace interfaces {
831 std::unique_ptr<Node> MakeNode(node::NodeContext& context) { return std::make_unique<node::NodeImpl>(context); }
832 std::unique_ptr<Chain> MakeChain(node::NodeContext& context) { return std::make_unique<node::ChainImpl>(context); }
833 } // namespace interfaces
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
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.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
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
virtual bool updateRwSetting(const std::string &name, const common::SettingsValue &value, bool write=true)=0
Write a setting to <datadir>/settings.json.
Block tip (could be a header or not, depends on the subscribed signal).
Definition: node.h:276
std::any context
Definition: request.h:38
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:814
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:80
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
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:282
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:825
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:156
#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:22
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:778
A UTXO entry.
Definition: coins.h:31
Bilingual messages:
Definition: translation.h:18
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:846
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:446
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.
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:580
virtual bool isInitialBlockDownload()=0
Check if in IBD.
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:84
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:443
bool isNum() const
Definition: univalue.h:83
void StartMapPort(bool use_upnp, bool use_natpmp)
Definition: mapport.cpp:321
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
const CRPCCommand * m_wrapped_command
Definition: interfaces.cpp:515
std::unique_ptr< Node > MakeNode(node::NodeContext &context)
Return implementation of Node interface.
Definition: interfaces.cpp:831
Int getInt() const
Definition: univalue.h:137
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:594
virtual void TransactionAddedToMempool(const NewMempoolTransactionInfo &tx, uint64_t mempool_sequence)
Notifies listeners of a transaction having been added to mempool.
std::string m_name
Name of signer.
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
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:588
RBFTransactionState
The rbf state of unconfirmed transactions.
Definition: rbf.h:27
uint256 * m_hash
Definition: chain.h:71
bool AppInitBasicSetup(const ArgsManager &args, std::atomic< int > &exit_status)
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:844
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:515
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:514
std::string strMethod
Definition: request.h:32
uint256 GetBlockHash() const
Definition: chain.h:258
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:48
#define LOCK2(cs1, cs2)
Definition: sync.h:258
std::string name
Definition: server.h:114
CRPCTable tableRPC
Definition: server.cpp:604
virtual bool hasAssumedValidChain()=0
Return true if an assumed-valid chain is in use.
RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction &tx)
Definition: rbf.cpp:51
virtual bool isInMempool(const uint256 &txid)=0
Check if transaction is in mempool.
ArgsManager & args
Definition: bitcoind.cpp:268
std::vector< common::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: args.cpp:786
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:33
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.
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.
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:1100
int64_t GetBlockTimeMax() const
Definition: chain.h:287
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:178
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:33
NodeContext * m_context
Definition: interfaces.cpp:406
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:102
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.
#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:476
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:42
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:322
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:358
bool isNull() const
Definition: univalue.h:78
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
int64_t GetMedianTimePast() const
Definition: chain.h:294
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:577
std::unordered_set< Element, ByteVectorHash > ElementSet
Definition: blockfilter.h:32
virtual void initWarning(const bilingual_str &message)=0
Send init warning.
Definition: init.h:25
Definition: netbase.h:46
Generic interface for managing an event handler or callback function registered with another interfac...
Definition: handler.h:22
int flags
Definition: bitcoin-tx.cpp:530
virtual node::NodeContext * context()
Get internal node context.
Definition: chain.h:366
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:106
virtual bool isReadyToBroadcast()=0
Check if the node is ready to broadcast transactions.
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
Definition: interfaces.cpp:832
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:35
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:423
const auto command
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:881
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:123
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:149
const CChainParams & Params()
Return the currently selected parameters.
static transaction_identifier FromUint256(const uint256 &id)
bool ShutdownRequested(node::NodeContext &node)
Return whether node shutdown was requested.
Definition: init.cpp:228
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:455
std::string URI
Definition: request.h:35
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 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:1067
int exit_status
const CTransactionRef m_tx
TransactionError
Definition: error.h:22
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:1094
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:1082
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:162
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:117
virtual bool rpcEnableDeprecated(const std::string &method)=0
Check if deprecated RPC is enabled.
#define LogPrintf(...)
Definition: logging.h:245
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:552
virtual common::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
ConnectionDirection
Definition: netbase.h:30
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).
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:181
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:61
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:722
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:457
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...