Bitcoin Core  21.99.0
P2P Digital Currency
interfaces.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018-2020 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 <boost/signals2/signal.hpp>
8 #include <chain.h>
9 #include <chainparams.h>
10 #include <init.h>
11 #include <interfaces/chain.h>
12 #include <interfaces/handler.h>
13 #include <interfaces/node.h>
14 #include <interfaces/wallet.h>
15 #include <mapport.h>
16 #include <net.h>
17 #include <net_processing.h>
18 #include <netaddress.h>
19 #include <netbase.h>
20 #include <node/coin.h>
21 #include <node/context.h>
22 #include <node/transaction.h>
23 #include <node/ui_interface.h>
24 #include <policy/feerate.h>
25 #include <policy/fees.h>
26 #include <policy/policy.h>
27 #include <policy/rbf.h>
28 #include <policy/settings.h>
29 #include <primitives/block.h>
30 #include <primitives/transaction.h>
31 #include <rpc/protocol.h>
32 #include <rpc/server.h>
33 #include <shutdown.h>
35 #include <sync.h>
36 #include <timedata.h>
37 #include <txmempool.h>
38 #include <uint256.h>
39 #include <univalue.h>
40 #include <util/check.h>
41 #include <util/ref.h>
42 #include <util/system.h>
43 #include <util/translation.h>
44 #include <validation.h>
45 #include <validationinterface.h>
46 #include <warnings.h>
47 
48 #if defined(HAVE_CONFIG_H)
49 #include <config/bitcoin-config.h>
50 #endif
51 
52 #include <memory>
53 #include <utility>
54 
56 using interfaces::Chain;
60 using interfaces::Node;
62 
63 namespace node {
64 namespace {
65 class NodeImpl : public Node
66 {
67 public:
68  explicit NodeImpl(NodeContext* context) { setContext(context); }
69  void initLogging() override { InitLogging(*Assert(m_context->args)); }
70  void initParameterInteraction() override { InitParameterInteraction(*Assert(m_context->args)); }
71  bilingual_str getWarnings() override { return GetWarnings(true); }
72  uint32_t getLogCategories() override { return LogInstance().GetCategoryMask(); }
73  bool baseInitialize() override
74  {
77  }
78  bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info) override
79  {
80  return AppInitMain(m_context_ref, *m_context, tip_info);
81  }
82  void appShutdown() override
83  {
86  }
87  void startShutdown() override
88  {
89  StartShutdown();
90  // Stop RPC for clean shutdown if any of waitfor* commands is executed.
91  if (gArgs.GetBoolArg("-server", false)) {
92  InterruptRPC();
93  StopRPC();
94  }
95  }
96  bool shutdownRequested() override { return ShutdownRequested(); }
97  void mapPort(bool use_upnp, bool use_natpmp) override { StartMapPort(use_upnp, use_natpmp); }
98  bool getProxy(Network net, proxyType& proxy_info) override { return GetProxy(net, proxy_info); }
99  size_t getNodeCount(CConnman::NumConnections flags) override
100  {
101  return m_context->connman ? m_context->connman->GetNodeCount(flags) : 0;
102  }
103  bool getNodesStats(NodesStats& stats) override
104  {
105  stats.clear();
106 
107  if (m_context->connman) {
108  std::vector<CNodeStats> stats_temp;
109  m_context->connman->GetNodeStats(stats_temp);
110 
111  stats.reserve(stats_temp.size());
112  for (auto& node_stats_temp : stats_temp) {
113  stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
114  }
115 
116  // Try to retrieve the CNodeStateStats for each node.
117  if (m_context->peerman) {
118  TRY_LOCK(::cs_main, lockMain);
119  if (lockMain) {
120  for (auto& node_stats : stats) {
121  std::get<1>(node_stats) =
122  m_context->peerman->GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
123  }
124  }
125  }
126  return true;
127  }
128  return false;
129  }
130  bool getBanned(banmap_t& banmap) override
131  {
132  if (m_context->banman) {
133  m_context->banman->GetBanned(banmap);
134  return true;
135  }
136  return false;
137  }
138  bool ban(const CNetAddr& net_addr, int64_t ban_time_offset) override
139  {
140  if (m_context->banman) {
141  m_context->banman->Ban(net_addr, ban_time_offset);
142  return true;
143  }
144  return false;
145  }
146  bool unban(const CSubNet& ip) override
147  {
148  if (m_context->banman) {
149  m_context->banman->Unban(ip);
150  return true;
151  }
152  return false;
153  }
154  bool disconnectByAddress(const CNetAddr& net_addr) override
155  {
156  if (m_context->connman) {
157  return m_context->connman->DisconnectNode(net_addr);
158  }
159  return false;
160  }
161  bool disconnectById(NodeId id) override
162  {
163  if (m_context->connman) {
164  return m_context->connman->DisconnectNode(id);
165  }
166  return false;
167  }
168  int64_t getTotalBytesRecv() override { return m_context->connman ? m_context->connman->GetTotalBytesRecv() : 0; }
169  int64_t getTotalBytesSent() override { return m_context->connman ? m_context->connman->GetTotalBytesSent() : 0; }
170  size_t getMempoolSize() override { return m_context->mempool ? m_context->mempool->size() : 0; }
171  size_t getMempoolDynamicUsage() override { return m_context->mempool ? m_context->mempool->DynamicMemoryUsage() : 0; }
172  bool getHeaderTip(int& height, int64_t& block_time) override
173  {
174  LOCK(::cs_main);
175  if (::pindexBestHeader) {
176  height = ::pindexBestHeader->nHeight;
177  block_time = ::pindexBestHeader->GetBlockTime();
178  return true;
179  }
180  return false;
181  }
182  int getNumBlocks() override
183  {
184  LOCK(::cs_main);
186  }
187  uint256 getBestBlockHash() override
188  {
189  const CBlockIndex* tip = WITH_LOCK(::cs_main, return ::ChainActive().Tip());
190  return tip ? tip->GetBlockHash() : Params().GenesisBlock().GetHash();
191  }
192  int64_t getLastBlockTime() override
193  {
194  LOCK(::cs_main);
195  if (::ChainActive().Tip()) {
197  }
198  return Params().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
199  }
200  double getVerificationProgress() override
201  {
202  const CBlockIndex* tip;
203  {
204  LOCK(::cs_main);
205  tip = ::ChainActive().Tip();
206  }
207  return GuessVerificationProgress(Params().TxData(), tip);
208  }
209  bool isInitialBlockDownload() override { return ::ChainstateActive().IsInitialBlockDownload(); }
210  bool getReindex() override { return ::fReindex; }
211  bool getImporting() override { return ::fImporting; }
212  void setNetworkActive(bool active) override
213  {
214  if (m_context->connman) {
215  m_context->connman->SetNetworkActive(active);
216  }
217  }
218  bool getNetworkActive() override { return m_context->connman && m_context->connman->GetNetworkActive(); }
219  CFeeRate getDustRelayFee() override { return ::dustRelayFee; }
220  UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
221  {
223  req.params = params;
224  req.strMethod = command;
225  req.URI = uri;
227  }
228  std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
229  void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); }
230  void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); }
231  bool getUnspentOutput(const COutPoint& output, Coin& coin) override
232  {
233  LOCK(::cs_main);
234  return ::ChainstateActive().CoinsTip().GetCoin(output, coin);
235  }
236  WalletClient& walletClient() override
237  {
238  return *Assert(m_context->wallet_client);
239  }
240  std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
241  {
242  return MakeHandler(::uiInterface.InitMessage_connect(fn));
243  }
244  std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
245  {
246  return MakeHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
247  }
248  std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
249  {
250  return MakeHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
251  }
252  std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
253  {
254  return MakeHandler(::uiInterface.ShowProgress_connect(fn));
255  }
256  std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
257  {
258  return MakeHandler(::uiInterface.NotifyNumConnectionsChanged_connect(fn));
259  }
260  std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
261  {
262  return MakeHandler(::uiInterface.NotifyNetworkActiveChanged_connect(fn));
263  }
264  std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
265  {
266  return MakeHandler(::uiInterface.NotifyAlertChanged_connect(fn));
267  }
268  std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
269  {
270  return MakeHandler(::uiInterface.BannedListChanged_connect(fn));
271  }
272  std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
273  {
274  return MakeHandler(::uiInterface.NotifyBlockTip_connect([fn](SynchronizationState sync_state, const CBlockIndex* block) {
275  fn(sync_state, BlockTip{block->nHeight, block->GetBlockTime(), block->GetBlockHash()},
276  GuessVerificationProgress(Params().TxData(), block));
277  }));
278  }
279  std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
280  {
281  return MakeHandler(
282  ::uiInterface.NotifyHeaderTip_connect([fn](SynchronizationState sync_state, const CBlockIndex* block) {
283  fn(sync_state, BlockTip{block->nHeight, block->GetBlockTime(), block->GetBlockHash()},
284  /* verification progress is unused when a header was received */ 0);
285  }));
286  }
287  NodeContext* context() override { return m_context; }
288  void setContext(NodeContext* context) override
289  {
290  m_context = context;
291  if (context) {
292  m_context_ref.Set(*context);
293  } else {
295  }
296  }
299 };
300 
301 bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active)
302 {
303  if (!index) return false;
304  if (block.m_hash) *block.m_hash = index->GetBlockHash();
305  if (block.m_height) *block.m_height = index->nHeight;
306  if (block.m_time) *block.m_time = index->GetBlockTime();
307  if (block.m_max_time) *block.m_max_time = index->GetBlockTimeMax();
308  if (block.m_mtp_time) *block.m_mtp_time = index->GetMedianTimePast();
309  if (block.m_in_active_chain) *block.m_in_active_chain = active[index->nHeight] == index;
310  if (block.m_next_block) FillBlock(active[index->nHeight] == index ? active[index->nHeight + 1] : nullptr, *block.m_next_block, lock, active);
311  if (block.m_data) {
312  REVERSE_LOCK(lock);
313  if (!ReadBlockFromDisk(*block.m_data, index, Params().GetConsensus())) block.m_data->SetNull();
314  }
315  return true;
316 }
317 
318 class NotificationsProxy : public CValidationInterface
319 {
320 public:
321  explicit NotificationsProxy(std::shared_ptr<Chain::Notifications> notifications)
322  : m_notifications(std::move(notifications)) {}
323  virtual ~NotificationsProxy() = default;
324  void TransactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) override
325  {
326  m_notifications->transactionAddedToMempool(tx, mempool_sequence);
327  }
328  void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
329  {
330  m_notifications->transactionRemovedFromMempool(tx, reason, mempool_sequence);
331  }
332  void BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
333  {
334  m_notifications->blockConnected(*block, index->nHeight);
335  }
336  void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
337  {
338  m_notifications->blockDisconnected(*block, index->nHeight);
339  }
340  void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override
341  {
342  m_notifications->updatedBlockTip();
343  }
344  void ChainStateFlushed(const CBlockLocator& locator) override { m_notifications->chainStateFlushed(locator); }
345  std::shared_ptr<Chain::Notifications> m_notifications;
346 };
347 
348 class NotificationsHandlerImpl : public Handler
349 {
350 public:
351  explicit NotificationsHandlerImpl(std::shared_ptr<Chain::Notifications> notifications)
352  : m_proxy(std::make_shared<NotificationsProxy>(std::move(notifications)))
353  {
355  }
356  ~NotificationsHandlerImpl() override { disconnect(); }
357  void disconnect() override
358  {
359  if (m_proxy) {
361  m_proxy.reset();
362  }
363  }
364  std::shared_ptr<NotificationsProxy> m_proxy;
365 };
366 
367 class RpcHandlerImpl : public Handler
368 {
369 public:
370  explicit RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command)
371  {
372  m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
373  if (!m_wrapped_command) return false;
374  try {
375  return m_wrapped_command->actor(request, result, last_handler);
376  } catch (const UniValue& e) {
377  // If this is not the last handler and a wallet not found
378  // exception was thrown, return false so the next handler can
379  // try to handle the request. Otherwise, reraise the exception.
380  if (!last_handler) {
381  const UniValue& code = e["code"];
382  if (code.isNum() && code.get_int() == RPC_WALLET_NOT_FOUND) {
383  return false;
384  }
385  }
386  throw;
387  }
388  };
390  }
391 
392  void disconnect() final
393  {
394  if (m_wrapped_command) {
395  m_wrapped_command = nullptr;
397  }
398  }
399 
400  ~RpcHandlerImpl() override { disconnect(); }
401 
404 };
405 
406 class ChainImpl : public Chain
407 {
408 public:
409  explicit ChainImpl(NodeContext& node) : m_node(node) {}
410  Optional<int> getHeight() override
411  {
412  LOCK(::cs_main);
413  const CChain& active = Assert(m_node.chainman)->ActiveChain();
414  int height = active.Height();
415  if (height >= 0) {
416  return height;
417  }
418  return nullopt;
419  }
420  uint256 getBlockHash(int height) override
421  {
422  LOCK(::cs_main);
423  const CChain& active = Assert(m_node.chainman)->ActiveChain();
424  CBlockIndex* block = active[height];
425  assert(block);
426  return block->GetBlockHash();
427  }
428  bool haveBlockOnDisk(int height) override
429  {
430  LOCK(cs_main);
431  const CChain& active = Assert(m_node.chainman)->ActiveChain();
432  CBlockIndex* block = active[height];
433  return block && ((block->nStatus & BLOCK_HAVE_DATA) != 0) && block->nTx > 0;
434  }
435  CBlockLocator getTipLocator() override
436  {
437  LOCK(cs_main);
438  const CChain& active = Assert(m_node.chainman)->ActiveChain();
439  return active.GetLocator();
440  }
441  bool checkFinalTx(const CTransaction& tx) override
442  {
443  LOCK(cs_main);
444  return CheckFinalTx(tx);
445  }
446  Optional<int> findLocatorFork(const CBlockLocator& locator) override
447  {
448  LOCK(cs_main);
449  const CChain& active = Assert(m_node.chainman)->ActiveChain();
450  if (CBlockIndex* fork = FindForkInGlobalIndex(active, locator)) {
451  return fork->nHeight;
452  }
453  return nullopt;
454  }
455  bool findBlock(const uint256& hash, const FoundBlock& block) override
456  {
457  WAIT_LOCK(cs_main, lock);
458  const CChain& active = Assert(m_node.chainman)->ActiveChain();
459  return FillBlock(LookupBlockIndex(hash), block, lock, active);
460  }
461  bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block) override
462  {
463  WAIT_LOCK(cs_main, lock);
464  const CChain& active = Assert(m_node.chainman)->ActiveChain();
465  return FillBlock(active.FindEarliestAtLeast(min_time, min_height), block, lock, active);
466  }
467  bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out) override
468  {
469  WAIT_LOCK(cs_main, lock);
470  const CChain& active = Assert(m_node.chainman)->ActiveChain();
471  if (const CBlockIndex* block = LookupBlockIndex(block_hash)) {
472  if (const CBlockIndex* ancestor = block->GetAncestor(ancestor_height)) {
473  return FillBlock(ancestor, ancestor_out, lock, active);
474  }
475  }
476  return FillBlock(nullptr, ancestor_out, lock, active);
477  }
478  bool findAncestorByHash(const uint256& block_hash, const uint256& ancestor_hash, const FoundBlock& ancestor_out) override
479  {
480  WAIT_LOCK(cs_main, lock);
481  const CChain& active = Assert(m_node.chainman)->ActiveChain();
482  const CBlockIndex* block = LookupBlockIndex(block_hash);
483  const CBlockIndex* ancestor = LookupBlockIndex(ancestor_hash);
484  if (block && ancestor && block->GetAncestor(ancestor->nHeight) != ancestor) ancestor = nullptr;
485  return FillBlock(ancestor, ancestor_out, lock, active);
486  }
487  bool findCommonAncestor(const uint256& block_hash1, const uint256& block_hash2, const FoundBlock& ancestor_out, const FoundBlock& block1_out, const FoundBlock& block2_out) override
488  {
489  WAIT_LOCK(cs_main, lock);
490  const CChain& active = Assert(m_node.chainman)->ActiveChain();
491  const CBlockIndex* block1 = LookupBlockIndex(block_hash1);
492  const CBlockIndex* block2 = LookupBlockIndex(block_hash2);
493  const CBlockIndex* ancestor = block1 && block2 ? LastCommonAncestor(block1, block2) : nullptr;
494  // Using & instead of && below to avoid short circuiting and leaving
495  // output uninitialized.
496  return FillBlock(ancestor, ancestor_out, lock, active) & FillBlock(block1, block1_out, lock, active) & FillBlock(block2, block2_out, lock, active);
497  }
498  void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(m_node, coins); }
499  double guessVerificationProgress(const uint256& block_hash) override
500  {
501  LOCK(cs_main);
502  return GuessVerificationProgress(Params().TxData(), LookupBlockIndex(block_hash));
503  }
504  bool hasBlocks(const uint256& block_hash, int min_height, Optional<int> max_height) override
505  {
506  // hasBlocks returns true if all ancestors of block_hash in specified
507  // range have block data (are not pruned), false if any ancestors in
508  // specified range are missing data.
509  //
510  // For simplicity and robustness, min_height and max_height are only
511  // used to limit the range, and passing min_height that's too low or
512  // max_height that's too high will not crash or change the result.
513  LOCK(::cs_main);
514  if (CBlockIndex* block = LookupBlockIndex(block_hash)) {
515  if (max_height && block->nHeight >= *max_height) block = block->GetAncestor(*max_height);
516  for (; block->nStatus & BLOCK_HAVE_DATA; block = block->pprev) {
517  // Check pprev to not segfault if min_height is too low
518  if (block->nHeight <= min_height || !block->pprev) return true;
519  }
520  }
521  return false;
522  }
523  RBFTransactionState isRBFOptIn(const CTransaction& tx) override
524  {
525  if (!m_node.mempool) return IsRBFOptInEmptyMempool(tx);
526  LOCK(m_node.mempool->cs);
527  return IsRBFOptIn(tx, *m_node.mempool);
528  }
529  bool hasDescendantsInMempool(const uint256& txid) override
530  {
531  if (!m_node.mempool) return false;
532  LOCK(m_node.mempool->cs);
533  auto it = m_node.mempool->GetIter(txid);
534  return it && (*it)->GetCountWithDescendants() > 1;
535  }
536  bool broadcastTransaction(const CTransactionRef& tx,
537  const CAmount& max_tx_fee,
538  bool relay,
539  std::string& err_string) override
540  {
541  const TransactionError err = BroadcastTransaction(m_node, tx, err_string, max_tx_fee, relay, /*wait_callback*/ false);
542  // Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures.
543  // Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures
544  // that Chain clients do not need to know about.
545  return TransactionError::OK == err;
546  }
547  void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) override
548  {
549  ancestors = descendants = 0;
550  if (!m_node.mempool) return;
551  m_node.mempool->GetTransactionAncestry(txid, ancestors, descendants);
552  }
553  void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) override
554  {
555  limit_ancestor_count = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
556  limit_descendant_count = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
557  }
558  bool checkChainLimits(const CTransactionRef& tx) override
559  {
560  if (!m_node.mempool) return true;
561  LockPoints lp;
562  CTxMemPoolEntry entry(tx, 0, 0, 0, false, 0, lp);
563  CTxMemPool::setEntries ancestors;
564  auto limit_ancestor_count = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
565  auto limit_ancestor_size = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000;
566  auto limit_descendant_count = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
567  auto limit_descendant_size = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000;
568  std::string unused_error_string;
569  LOCK(m_node.mempool->cs);
570  return m_node.mempool->CalculateMemPoolAncestors(
571  entry, ancestors, limit_ancestor_count, limit_ancestor_size,
572  limit_descendant_count, limit_descendant_size, unused_error_string);
573  }
574  CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc) override
575  {
576  if (!m_node.fee_estimator) return {};
577  return m_node.fee_estimator->estimateSmartFee(num_blocks, calc, conservative);
578  }
579  unsigned int estimateMaxBlocks() override
580  {
581  if (!m_node.fee_estimator) return 0;
582  return m_node.fee_estimator->HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
583  }
584  CFeeRate mempoolMinFee() override
585  {
586  if (!m_node.mempool) return {};
587  return m_node.mempool->GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
588  }
589  CFeeRate relayMinFee() override { return ::minRelayTxFee; }
590  CFeeRate relayIncrementalFee() override { return ::incrementalRelayFee; }
591  CFeeRate relayDustFee() override { return ::dustRelayFee; }
592  bool havePruned() override
593  {
594  LOCK(cs_main);
596  }
597  bool isReadyToBroadcast() override { return !::fImporting && !::fReindex && !isInitialBlockDownload(); }
598  bool isInitialBlockDownload() override { return ::ChainstateActive().IsInitialBlockDownload(); }
599  bool shutdownRequested() override { return ShutdownRequested(); }
600  int64_t getAdjustedTime() override { return GetAdjustedTime(); }
601  void initMessage(const std::string& message) override { ::uiInterface.InitMessage(message); }
602  void initWarning(const bilingual_str& message) override { InitWarning(message); }
603  void initError(const bilingual_str& message) override { InitError(message); }
604  void showProgress(const std::string& title, int progress, bool resume_possible) override
605  {
606  ::uiInterface.ShowProgress(title, progress, resume_possible);
607  }
608  std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) override
609  {
610  return MakeUnique<NotificationsHandlerImpl>(std::move(notifications));
611  }
612  void waitForNotificationsIfTipChanged(const uint256& old_tip) override
613  {
614  if (!old_tip.IsNull()) {
615  LOCK(::cs_main);
616  const CChain& active = Assert(m_node.chainman)->ActiveChain();
617  if (old_tip == active.Tip()->GetBlockHash()) return;
618  }
620  }
621  std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) override
622  {
623  return MakeUnique<RpcHandlerImpl>(command);
624  }
625  bool rpcEnableDeprecated(const std::string& method) override { return IsDeprecatedRPCEnabled(method); }
626  void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) override
627  {
628  RPCRunLater(name, std::move(fn), seconds);
629  }
630  int rpcSerializationFlags() override { return RPCSerializationFlags(); }
631  util::SettingsValue getRwSetting(const std::string& name) override
632  {
633  util::SettingsValue result;
634  gArgs.LockSettings([&](const util::Settings& settings) {
635  if (const util::SettingsValue* value = util::FindKey(settings.rw_settings, name)) {
636  result = *value;
637  }
638  });
639  return result;
640  }
641  bool updateRwSetting(const std::string& name, const util::SettingsValue& value) override
642  {
643  gArgs.LockSettings([&](util::Settings& settings) {
644  if (value.isNull()) {
645  settings.rw_settings.erase(name);
646  } else {
647  settings.rw_settings[name] = value;
648  }
649  });
650  return gArgs.WriteSettingsFile();
651  }
652  void requestMempoolTransactions(Notifications& notifications) override
653  {
654  if (!m_node.mempool) return;
655  LOCK2(::cs_main, m_node.mempool->cs);
656  for (const CTxMemPoolEntry& entry : m_node.mempool->mapTx) {
657  notifications.transactionAddedToMempool(entry.GetSharedTx(), 0 /* mempool_sequence */);
658  }
659  }
661 };
662 } // namespace
663 } // namespace node
664 
665 namespace interfaces {
666 std::unique_ptr<Node> MakeNode(NodeContext* context) { return MakeUnique<node::NodeImpl>(context); }
667 std::unique_ptr<Chain> MakeChain(NodeContext& context) { return MakeUnique<node::ChainImpl>(context); }
668 } // namespace interfaces
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
std::map< std::string, SettingsValue > rw_settings
Map of setting name to read-write file setting value.
Definition: settings.h:37
Stored settings.
Definition: settings.h:31
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:39
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:60
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:88
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
RPC timer "driver".
Definition: server.h:60
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:62
Block tip (could be a header or not, depends on the subscribed signal).
Definition: node.h:231
std::deque< CInv >::iterator it
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:871
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:98
BCLog::Logger & LogInstance()
Definition: logging.cpp:14
int64_t GetBlockTime() const
Definition: chain.h:247
assert(!tx.IsCoinBase())
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:114
NodeContext & m_node
Definition: interfaces.cpp:660
#define TRY_LOCK(cs, name)
Definition: sync.h:236
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:8
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:174
util::Ref m_context_ref
Definition: interfaces.cpp:298
void Shutdown(NodeContext &node)
Definition: init.cpp:176
A UTXO entry.
Definition: coins.h:30
Bilingual messages:
Definition: translation.h:16
Actor actor
Definition: server.h:120
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:112
std::unique_ptr< BanMan > banman
Definition: context.h:43
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:32
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:39
int64_t * m_max_time
Definition: chain.h:58
An in-memory indexed chain of blocks.
Definition: chain.h:379
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:137
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:264
void InitWarning(const bilingual_str &str)
Show warning message.
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:58
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:156
int Height() const
Return the maximal height in the chain.
Definition: chain.h:415
bool removeCommand(const std::string &name, const CRPCCommand *pcmd)
Definition: server.cpp:271
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr) const
Write settings file.
Definition: system.cpp:442
void InterruptRPC()
Definition: server.cpp:291
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:568
static auto & nullopt
Substitute for C++17 std::nullopt DEPRECATED use std::nullopt in new code.
Definition: optional.h:18
bool isNum() const
Definition: univalue.h:82
const CBlock & GenesisBlock() const
Definition: chainparams.h:69
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
Definition: txmempool.h:392
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: handler.cpp:36
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:479
void StartMapPort(bool use_upnp, bool use_natpmp)
Definition: mapport.cpp:324
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
const CRPCCommand * m_wrapped_command
Definition: interfaces.cpp:403
#define REVERSE_LOCK(g)
Definition: sync.h:227
void RPCRunLater(const std::string &name, std::function< void()> func, int64_t nSeconds)
Run func nSeconds from now.
Definition: server.cpp:499
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:309
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:100
Implement this to subscribe to events generated in validation.
bool IsNull() const
Definition: uint256.h:31
int64_t * m_mtp_time
Definition: chain.h:59
std::unique_ptr< Chain > MakeChain(NodeContext &node)
Return implementation of Chain interface.
Definition: interfaces.cpp:667
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:493
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:917
RBFTransactionState
The rbf state of unconfirmed transactions.
Definition: rbf.h:11
uint256 * m_hash
Definition: chain.h:55
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:78
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:435
CRPCCommand m_command
Definition: interfaces.cpp:402
std::string strMethod
Definition: request.h:35
uint256 GetBlockHash() const
Definition: chain.h:233
void Set(T &value)
Definition: ref.h:27
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:62
#define LOCK2(cs1, cs2)
Definition: sync.h:233
std::string name
Definition: server.h:119
CRPCTable tableRPC
Definition: server.cpp:517
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1222
ChainstateManager * chainman
Definition: context.h:42
bool CheckFinalTx(const CTransaction &tx, int flags)
Transaction validation functions.
Definition: validation.cpp:203
RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction &tx)
Definition: rbf.cpp:40
NodeContext struct containing references to chain state and connection state.
Definition: context.h:37
std::unique_ptr< CConnman > connman
Definition: context.h:38
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:160
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:148
UniValue params
Definition: request.h:36
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:130
CBlock * m_data
Definition: chain.h:62
#define LOCK(cs)
Definition: sync.h:232
const char * name
Definition: rest.cpp:41
CTransactionRef GetSharedTx() const
Definition: txmempool.h:120
interfaces::WalletClient * wallet_client
Reference to chain client that should used to load or create wallets opened by the gui...
Definition: context.h:50
const FoundBlock * m_next_block
Definition: chain.h:61
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:128
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:64
int64_t GetBlockTimeMax() const
Definition: chain.h:252
uint32_t GetCategoryMask() const
Definition: logging.h:129
NodeContext * m_context
Definition: interfaces.cpp:297
Network
A network type.
Definition: netaddress.h:43
Block and header tip information.
Definition: node.h:42
int64_t NodeId
Definition: net.h:83
bool InitError(const bilingual_str &str)
Show error message.
#define WAIT_LOCK(cs, name)
Definition: sync.h:237
NumConnections
Definition: net.h:799
int get_int() const
std::atomic_bool fImporting
std::shared_ptr< NotificationsProxy > m_proxy
Definition: interfaces.cpp:364
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:26
int64_t GetBlockTime() const
Definition: block.h:55
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:346
bool isNull() const
Definition: univalue.h:77
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:276
int64_t GetMedianTimePast() const
Definition: chain.h:259
std::unique_ptr< PeerManager > peerman
Definition: context.h:41
CFeeRate incrementalRelayFee
Definition: settings.cpp:12
Type-safe dynamic reference.
Definition: ref.h:21
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
Definition: server.cpp:482
Generic interface for managing an event handler or callback function registered with another interfac...
Definition: handler.h:22
int flags
Definition: bitcoin-tx.cpp:512
std::atomic_bool fReindex
Network address.
Definition: netaddress.h:119
uint256 GetHash() const
Definition: block.cpp:11
CBlockIndex * LookupBlockIndex(const uint256 &hash)
Definition: validation.cpp:170
256-bit opaque blob.
Definition: uint256.h:124
ArgsManager * args
Definition: context.h:44
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:29
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
Definition: validation.cpp:105
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:31
void StopRPC()
Definition: server.cpp:302
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:57
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:962
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:89
void SetNull()
Definition: block.h:88
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:137
const CChainParams & Params()
Return the currently selected parameters.
int RPCSerializationFlags()
Definition: server.cpp:509
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: system.cpp:467
std::string URI
Definition: request.h:38
int64_t * m_time
Definition: chain.h:57
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:177
int64_t GetAdjustedTime()
Definition: timedata.cpp:34
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:390
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network) ...
ArgsManager gArgs
Definition: system.cpp:77
TransactionError
Definition: error.h:22
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
void FindCoins(const NodeContext &node, std::map< COutPoint, Coin > &coins)
Look up unspent output information.
Definition: coin.cpp:11
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip). ...
Definition: chain.cpp:23
bool * m_in_active_chain
Definition: chain.h:60
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:50
std::unique_ptr< CBlockPolicyEstimator > fee_estimator
Definition: context.h:40
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:581
std::map< CSubNet, CBanEntry > banmap_t
Definition: net_types.h:13
Wrapper around std::unique_lock style lock for Mutex.
Definition: sync.h:135
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:727
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:1255
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1243
bool AppInitMain(const util::Ref &context, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
Definition: init.cpp:1266
CClientUIInterface uiInterface
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:150
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:111
void LockSettings(Fn &&fn)
Access settings with lock held.
Definition: system.h:388
full block available in blk*.dat
Definition: chain.h:121
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:475
std::unique_ptr< Node > MakeNode(NodeContext *context=nullptr)
Return implementation of Node interface.
Definition: interfaces.cpp:666
void Clear()
Definition: ref.h:29
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:52
CFeeRate dustRelayFee
Definition: settings.cpp:13
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:166
std::optional< T > Optional
Substitute for C++17 std::optional DEPRECATED use std::optional in new code.
Definition: optional.h:14
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:796
#define Assert(val)
Identity function.
Definition: check.h:57
std::shared_ptr< Chain::Notifications > m_notifications
Definition: interfaces.cpp:345
LockPoints lp