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