Bitcoin ABC 0.30.13
P2P Digital Currency
interfaces.cpp
Go to the documentation of this file.
1// Copyright (c) 2018 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 <chain.h>
8#include <chainparams.h>
9#include <common/args.h>
10#include <config.h>
11#include <init.h>
12#include <interfaces/chain.h>
13#include <interfaces/handler.h>
14#include <interfaces/node.h>
15#include <interfaces/wallet.h>
17#include <mapport.h>
18#include <net.h>
19#include <net_processing.h>
20#include <netaddress.h>
21#include <netbase.h>
22#include <node/blockstorage.h>
23#include <node/coin.h>
24#include <node/context.h>
25#include <node/transaction.h>
26#include <node/ui_interface.h>
27#include <policy/settings.h>
28#include <primitives/block.h>
30#include <rpc/protocol.h>
31#include <rpc/server.h>
32#include <shutdown.h>
33#include <sync.h>
34#include <txmempool.h>
35#include <uint256.h>
36#include <util/check.h>
37#include <util/translation.h>
38#include <validation.h>
39#include <validationinterface.h>
40#include <warnings.h>
41
42#if defined(HAVE_CONFIG_H)
43#include <config/bitcoin-config.h>
44#endif
45
46#include <univalue.h>
47
48#include <boost/signals2/signal.hpp>
49
50#include <memory>
51#include <utility>
52
54
62
63namespace node {
64namespace {
65
66 class NodeImpl : public Node {
67 private:
68 ChainstateManager &chainman() { return *Assert(m_context->chainman); }
69
70 public:
71 explicit NodeImpl(NodeContext *context) { setContext(context); }
72 void initLogging() override { InitLogging(*Assert(m_context->args)); }
73 void initParameterInteraction() override {
75 }
76 bilingual_str getWarnings() override { return GetWarnings(true); }
77 bool baseInitialize(Config &config) override {
79 return false;
80 }
81 if (!AppInitParameterInteraction(config, gArgs)) {
82 return false;
83 }
84
85 m_context->kernel = std::make_unique<kernel::Context>();
86 if (!AppInitSanityChecks(*m_context->kernel)) {
87 return false;
88 }
89
91 return false;
92 }
94 return false;
95 }
96
97 return true;
98 }
99 bool appInitMain(Config &config, RPCServer &rpcServer,
100 HTTPRPCRequestProcessor &httpRPCRequestProcessor,
101 interfaces::BlockAndHeaderTipInfo *tip_info) override {
102 return AppInitMain(config, rpcServer, httpRPCRequestProcessor,
103 *m_context, tip_info);
104 }
105 void appShutdown() override {
108 }
109 void startShutdown() override {
111 // Stop RPC for clean shutdown if any of waitfor* commands is
112 // executed.
113 if (gArgs.GetBoolArg("-server", false)) {
114 InterruptRPC();
115 StopRPC();
116 }
117 }
118 bool shutdownRequested() override { return ShutdownRequested(); }
119 bool isPersistentSettingIgnored(const std::string &name) override {
120 bool ignored = false;
121 gArgs.LockSettings([&](util::Settings &settings) {
122 if (auto *options =
124 ignored = !options->empty();
125 }
126 });
127 return ignored;
128 }
130 getPersistentSetting(const std::string &name) override {
132 }
133 void updateRwSetting(const std::string &name,
134 const util::SettingsValue &value) override {
135 gArgs.LockSettings([&](util::Settings &settings) {
136 if (value.isNull()) {
137 settings.rw_settings.erase(name);
138 } else {
139 settings.rw_settings[name] = value;
140 }
141 });
143 }
144 void forceSetting(const std::string &name,
145 const util::SettingsValue &value) override {
146 gArgs.LockSettings([&](util::Settings &settings) {
147 if (value.isNull()) {
148 settings.forced_settings.erase(name);
149 } else {
150 settings.forced_settings[name] = value;
151 }
152 });
153 }
154 void resetSettings() override {
155 gArgs.WriteSettingsFile(/*errors=*/nullptr, /*backup=*/true);
156 gArgs.LockSettings([&](util::Settings &settings) {
157 settings.rw_settings.clear();
158 });
160 }
161 void mapPort(bool use_upnp, bool use_natpmp) override {
162 StartMapPort(use_upnp, use_natpmp);
163 }
164 bool getProxy(Network net, proxyType &proxy_info) override {
165 return GetProxy(net, proxy_info);
166 }
167 size_t getNodeCount(ConnectionDirection flags) override {
168 return m_context->connman ? m_context->connman->GetNodeCount(flags)
169 : 0;
170 }
171 bool getNodesStats(NodesStats &stats) override {
172 stats.clear();
173
174 if (m_context->connman) {
175 std::vector<CNodeStats> stats_temp;
176 m_context->connman->GetNodeStats(stats_temp);
177
178 stats.reserve(stats_temp.size());
179 for (auto &node_stats_temp : stats_temp) {
180 stats.emplace_back(std::move(node_stats_temp), false,
182 }
183
184 // Try to retrieve the CNodeStateStats for each node.
185 if (m_context->peerman) {
186 TRY_LOCK(::cs_main, lockMain);
187 if (lockMain) {
188 for (auto &node_stats : stats) {
189 std::get<1>(node_stats) =
190 m_context->peerman->GetNodeStateStats(
191 std::get<0>(node_stats).nodeid,
192 std::get<2>(node_stats));
193 }
194 }
195 }
196 return true;
197 }
198 return false;
199 }
200 bool getBanned(banmap_t &banmap) override {
201 if (m_context->banman) {
202 m_context->banman->GetBanned(banmap);
203 return true;
204 }
205 return false;
206 }
207 bool ban(const CNetAddr &net_addr, int64_t ban_time_offset) override {
208 if (m_context->banman) {
209 m_context->banman->Ban(net_addr, ban_time_offset);
210 return true;
211 }
212 return false;
213 }
214 bool unban(const CSubNet &ip) override {
215 if (m_context->banman) {
216 m_context->banman->Unban(ip);
217 return true;
218 }
219 return false;
220 }
221 bool disconnectByAddress(const CNetAddr &net_addr) override {
222 if (m_context->connman) {
223 return m_context->connman->DisconnectNode(net_addr);
224 }
225 return false;
226 }
227 bool disconnectById(NodeId id) override {
228 if (m_context->connman) {
229 return m_context->connman->DisconnectNode(id);
230 }
231 return false;
232 }
233 int64_t getTotalBytesRecv() override {
234 return m_context->connman ? m_context->connman->GetTotalBytesRecv()
235 : 0;
236 }
237 int64_t getTotalBytesSent() override {
238 return m_context->connman ? m_context->connman->GetTotalBytesSent()
239 : 0;
240 }
241 size_t getMempoolSize() override {
242 return m_context->mempool ? m_context->mempool->size() : 0;
243 }
244 size_t getMempoolDynamicUsage() override {
245 return m_context->mempool ? m_context->mempool->DynamicMemoryUsage()
246 : 0;
247 }
248 bool getHeaderTip(int &height, int64_t &block_time) override {
250 auto best_header = chainman().m_best_header;
251 if (best_header) {
252 height = best_header->nHeight;
253 block_time = best_header->GetBlockTime();
254 return true;
255 }
256 return false;
257 }
258 int getNumBlocks() override {
260 return chainman().ActiveChain().Height();
261 }
262 BlockHash getBestBlockHash() override {
263 const CBlockIndex *tip =
264 WITH_LOCK(::cs_main, return chainman().ActiveTip());
265 return tip ? tip->GetBlockHash()
266 : chainman().GetParams().GenesisBlock().GetHash();
267 }
268 int64_t getLastBlockTime() override {
270 if (chainman().ActiveChain().Tip()) {
271 return chainman().ActiveChain().Tip()->GetBlockTime();
272 }
273 // Genesis block's time of current network
274 return chainman().GetParams().GenesisBlock().GetBlockTime();
275 }
276 double getVerificationProgress() override {
277 const CBlockIndex *tip;
278 {
280 tip = chainman().ActiveChain().Tip();
281 }
282 return GuessVerificationProgress(chainman().GetParams().TxData(),
283 tip);
284 }
285 bool isInitialBlockDownload() override {
286 return chainman().IsInitialBlockDownload();
287 }
288 bool isLoadingBlocks() override {
289 return chainman().m_blockman.LoadingBlocks();
290 }
291 void setNetworkActive(bool active) override {
292 if (m_context->connman) {
293 m_context->connman->SetNetworkActive(active);
294 }
295 }
296 bool getNetworkActive() override {
297 return m_context->connman && m_context->connman->GetNetworkActive();
298 }
299 CFeeRate getDustRelayFee() override {
300 if (!m_context->mempool) {
302 }
303 return m_context->mempool->m_dust_relay_feerate;
304 }
305 UniValue executeRpc(const Config &config, const std::string &command,
306 const UniValue &params,
307 const std::string &uri) override {
308 JSONRPCRequest req;
309 req.context = m_context;
310 req.params = params;
311 req.strMethod = command;
312 req.URI = uri;
313 return ::tableRPC.execute(config, req);
314 }
315 std::vector<std::string> listRpcCommands() override {
317 }
318 void rpcSetTimerInterfaceIfUnset(RPCTimerInterface *iface) override {
320 }
321 void rpcUnsetTimerInterface(RPCTimerInterface *iface) override {
323 }
324 bool getUnspentOutput(const COutPoint &output, Coin &coin) override {
326 return chainman().ActiveChainstate().CoinsTip().GetCoin(output,
327 coin);
328 }
329 WalletClient &walletClient() override {
330 return *Assert(m_context->wallet_client);
331 }
332 std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override {
333 return MakeHandler(::uiInterface.InitMessage_connect(fn));
334 }
335 std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override {
336 return MakeHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
337 }
338 std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override {
339 return MakeHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
340 }
341 std::unique_ptr<Handler>
342 handleShowProgress(ShowProgressFn fn) override {
343 return MakeHandler(::uiInterface.ShowProgress_connect(fn));
344 }
345 std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(
346 NotifyNumConnectionsChangedFn fn) override {
347 return MakeHandler(
348 ::uiInterface.NotifyNumConnectionsChanged_connect(fn));
349 }
350 std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(
351 NotifyNetworkActiveChangedFn fn) override {
352 return MakeHandler(
353 ::uiInterface.NotifyNetworkActiveChanged_connect(fn));
354 }
355 std::unique_ptr<Handler>
356 handleNotifyAlertChanged(NotifyAlertChangedFn fn) override {
357 return MakeHandler(::uiInterface.NotifyAlertChanged_connect(fn));
358 }
359 std::unique_ptr<Handler>
360 handleBannedListChanged(BannedListChangedFn fn) override {
361 return MakeHandler(::uiInterface.BannedListChanged_connect(fn));
362 }
363 std::unique_ptr<Handler>
364 handleNotifyBlockTip(NotifyBlockTipFn fn) override {
365 return MakeHandler(::uiInterface.NotifyBlockTip_connect(
366 [fn](SynchronizationState sync_state,
367 const CBlockIndex *block) {
368 fn(sync_state,
369 BlockTip{block->nHeight, block->GetBlockTime(),
370 block->GetBlockHash()},
371 GuessVerificationProgress(Params().TxData(), block));
372 }));
373 }
374 std::unique_ptr<Handler>
375 handleNotifyHeaderTip(NotifyHeaderTipFn fn) override {
376 /* verification progress is unused when a header was received */
377 return MakeHandler(::uiInterface.NotifyHeaderTip_connect(
378 [fn](SynchronizationState sync_state, int64_t height,
379 int64_t timestamp, bool presync) {
380 fn(sync_state,
381 BlockTip{int(height), timestamp, BlockHash{}}, presync);
382 }));
383 }
384 NodeContext *context() override { return m_context; }
385 void setContext(NodeContext *context) override { m_context = context; }
386 NodeContext *m_context{nullptr};
387 };
388
389 bool FillBlock(const CBlockIndex *index, const FoundBlock &block,
390 UniqueLock<RecursiveMutex> &lock, const CChain &active,
391 const BlockManager &blockman) {
392 if (!index) {
393 return false;
394 }
395 if (block.m_hash) {
396 *block.m_hash = index->GetBlockHash();
397 }
398 if (block.m_height) {
399 *block.m_height = index->nHeight;
400 }
401 if (block.m_time) {
402 *block.m_time = index->GetBlockTime();
403 }
404 if (block.m_max_time) {
405 *block.m_max_time = index->GetBlockTimeMax();
406 }
407 if (block.m_mtp_time) {
408 *block.m_mtp_time = index->GetMedianTimePast();
409 }
410 if (block.m_in_active_chain) {
411 *block.m_in_active_chain = active[index->nHeight] == index;
412 }
413 // TODO backport core#25494 with change from core#25717
414 if (block.m_next_block) {
415 FillBlock(active[index->nHeight] == index
416 ? active[index->nHeight + 1]
417 : nullptr,
418 *block.m_next_block, lock, active, blockman);
419 }
420 if (block.m_data) {
421 REVERSE_LOCK(lock);
422 if (!blockman.ReadBlockFromDisk(*block.m_data, *index)) {
423 block.m_data->SetNull();
424 }
425 }
426 return true;
427 }
428
429 class NotificationsProxy : public CValidationInterface {
430 public:
431 explicit NotificationsProxy(
432 std::shared_ptr<Chain::Notifications> notifications)
433 : m_notifications(std::move(notifications)) {}
434 virtual ~NotificationsProxy() = default;
435 void TransactionAddedToMempool(const CTransactionRef &tx,
436 std::shared_ptr<const std::vector<Coin>>,
437 uint64_t mempool_sequence) override {
438 m_notifications->transactionAddedToMempool(tx, mempool_sequence);
439 }
440 void TransactionRemovedFromMempool(const CTransactionRef &tx,
442 uint64_t mempool_sequence) override {
443 m_notifications->transactionRemovedFromMempool(tx, reason,
444 mempool_sequence);
445 }
446 void BlockConnected(const std::shared_ptr<const CBlock> &block,
447 const CBlockIndex *index) override {
448 m_notifications->blockConnected(*block, index->nHeight);
449 }
450 void BlockDisconnected(const std::shared_ptr<const CBlock> &block,
451 const CBlockIndex *index) override {
452 m_notifications->blockDisconnected(*block, index->nHeight);
453 }
454 void UpdatedBlockTip(const CBlockIndex *index,
455 const CBlockIndex *fork_index,
456 bool is_ibd) override {
457 m_notifications->updatedBlockTip();
458 }
459 void ChainStateFlushed(const CBlockLocator &locator) override {
460 m_notifications->chainStateFlushed(locator);
461 }
462 std::shared_ptr<Chain::Notifications> m_notifications;
463 };
464
465 class NotificationsHandlerImpl : public Handler {
466 public:
467 explicit NotificationsHandlerImpl(
468 std::shared_ptr<Chain::Notifications> notifications)
469 : m_proxy(std::make_shared<NotificationsProxy>(
470 std::move(notifications))) {
472 }
473 ~NotificationsHandlerImpl() override { disconnect(); }
474 void disconnect() override {
475 if (m_proxy) {
477 m_proxy.reset();
478 }
479 }
480 std::shared_ptr<NotificationsProxy> m_proxy;
481 };
482
483 class RpcHandlerImpl : public Handler {
484 public:
485 explicit RpcHandlerImpl(const CRPCCommand &command)
486 : m_command(command), m_wrapped_command(&command) {
487 m_command.actor = [this](const Config &config,
488 const JSONRPCRequest &request,
489 UniValue &result, bool last_handler) {
490 if (!m_wrapped_command) {
491 return false;
492 }
493 try {
494 return m_wrapped_command->actor(config, request, result,
495 last_handler);
496 } catch (const UniValue &e) {
497 // If this is not the last handler and a wallet not found
498 // exception was thrown, return false so the next handler
499 // can try to handle the request. Otherwise, reraise the
500 // exception.
501 if (!last_handler) {
502 const UniValue &code = e["code"];
503 if (code.isNum() &&
504 code.getInt<int>() == RPC_WALLET_NOT_FOUND) {
505 return false;
506 }
507 }
508 throw;
509 }
510 };
512 }
513
514 void disconnect() final {
515 if (m_wrapped_command) {
516 m_wrapped_command = nullptr;
518 }
519 }
520
521 ~RpcHandlerImpl() override { disconnect(); }
522
525 };
526
527 class ChainImpl : public Chain {
528 private:
529 ChainstateManager &chainman() { return *Assert(m_node.chainman); }
530
531 public:
532 explicit ChainImpl(NodeContext &node, const CChainParams &params)
533 : m_node(node), m_params(params) {}
534 std::optional<int> getHeight() override {
536 const CChain &active = Assert(m_node.chainman)->ActiveChain();
537 int height = active.Height();
538 if (height >= 0) {
539 return height;
540 }
541 return std::nullopt;
542 }
543 BlockHash getBlockHash(int height) override {
545 const CChain &active = Assert(m_node.chainman)->ActiveChain();
546 CBlockIndex *block = active[height];
547 assert(block);
548 return block->GetBlockHash();
549 }
550 bool haveBlockOnDisk(int height) override {
551 LOCK(cs_main);
552 const CChain &active = Assert(m_node.chainman)->ActiveChain();
553 CBlockIndex *block = active[height];
554 return block && (block->nStatus.hasData() != 0) && block->nTx > 0;
555 }
556 CBlockLocator getTipLocator() override {
557 LOCK(cs_main);
558 const CChain &active = Assert(m_node.chainman)->ActiveChain();
559 return active.GetLocator();
560 }
561 // TODO: backport core#25036 with changes from core#25717
562 std::optional<int>
563 findLocatorFork(const CBlockLocator &locator) override {
564 LOCK(cs_main);
565 const Chainstate &active =
566 Assert(m_node.chainman)->ActiveChainstate();
567 if (const CBlockIndex *fork =
568 active.FindForkInGlobalIndex(locator)) {
569 return fork->nHeight;
570 }
571 return std::nullopt;
572 }
573 bool findBlock(const BlockHash &hash,
574 const FoundBlock &block) override {
575 WAIT_LOCK(cs_main, lock);
576 const CChain &active = Assert(m_node.chainman)->ActiveChain();
577 return FillBlock(m_node.chainman->m_blockman.LookupBlockIndex(hash),
578 block, lock, active, chainman().m_blockman);
579 }
580 bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height,
581 const FoundBlock &block) override {
582 WAIT_LOCK(cs_main, lock);
583 const CChain &active = Assert(m_node.chainman)->ActiveChain();
584 return FillBlock(active.FindEarliestAtLeast(min_time, min_height),
585 block, lock, active, chainman().m_blockman);
586 }
587 bool findAncestorByHeight(const BlockHash &block_hash,
588 int ancestor_height,
589 const FoundBlock &ancestor_out) override {
590 WAIT_LOCK(cs_main, lock);
591 const CChain &active = Assert(m_node.chainman)->ActiveChain();
592 if (const CBlockIndex *block =
593 m_node.chainman->m_blockman.LookupBlockIndex(block_hash)) {
594 if (const CBlockIndex *ancestor =
595 block->GetAncestor(ancestor_height)) {
596 return FillBlock(ancestor, ancestor_out, lock, active,
597 chainman().m_blockman);
598 }
599 }
600 return FillBlock(nullptr, ancestor_out, lock, active,
601 chainman().m_blockman);
602 }
603 bool findAncestorByHash(const BlockHash &block_hash,
604 const BlockHash &ancestor_hash,
605 const FoundBlock &ancestor_out) override {
606 WAIT_LOCK(cs_main, lock);
607 const CChain &active = Assert(m_node.chainman)->ActiveChain();
608 const CBlockIndex *block =
609 m_node.chainman->m_blockman.LookupBlockIndex(block_hash);
610 const CBlockIndex *ancestor =
611 m_node.chainman->m_blockman.LookupBlockIndex(ancestor_hash);
612 if (block && ancestor &&
613 block->GetAncestor(ancestor->nHeight) != ancestor) {
614 ancestor = nullptr;
615 }
616 return FillBlock(ancestor, ancestor_out, lock, active,
617 chainman().m_blockman);
618 }
619 bool findCommonAncestor(const BlockHash &block_hash1,
620 const BlockHash &block_hash2,
621 const FoundBlock &ancestor_out,
622 const FoundBlock &block1_out,
623 const FoundBlock &block2_out) override {
624 WAIT_LOCK(cs_main, lock);
625 const CChain &active = Assert(m_node.chainman)->ActiveChain();
626 const CBlockIndex *block1 =
627 m_node.chainman->m_blockman.LookupBlockIndex(block_hash1);
628 const CBlockIndex *block2 =
629 m_node.chainman->m_blockman.LookupBlockIndex(block_hash2);
630 const CBlockIndex *ancestor =
631 block1 && block2 ? LastCommonAncestor(block1, block2) : nullptr;
632 // Using & instead of && below to avoid short circuiting and leaving
633 // output uninitialized. Cast bool to int to avoid
634 // -Wbitwise-instead-of-logical compiler warnings.
635 return int{FillBlock(ancestor, ancestor_out, lock, active,
636 chainman().m_blockman)} &
637 int{FillBlock(block1, block1_out, lock, active,
638 chainman().m_blockman)} &
639 int{FillBlock(block2, block2_out, lock, active,
640 chainman().m_blockman)};
641 }
642 void findCoins(std::map<COutPoint, Coin> &coins) override {
643 return FindCoins(m_node, coins);
644 }
645 double guessVerificationProgress(const BlockHash &block_hash) override {
646 LOCK(cs_main);
648 chainman().GetParams().TxData(),
649 chainman().m_blockman.LookupBlockIndex(block_hash));
650 }
651 bool hasBlocks(const BlockHash &block_hash, int min_height,
652 std::optional<int> max_height) override {
653 // hasBlocks returns true if all ancestors of block_hash in
654 // specified range have block data (are not pruned), false if any
655 // ancestors in specified range are missing data.
656 //
657 // For simplicity and robustness, min_height and max_height are only
658 // used to limit the range, and passing min_height that's too low or
659 // max_height that's too high will not crash or change the result.
661 if (const CBlockIndex *block =
662 chainman().m_blockman.LookupBlockIndex(block_hash)) {
663 if (max_height && block->nHeight >= *max_height) {
664 block = block->GetAncestor(*max_height);
665 }
666 for (; block->nStatus.hasData(); block = block->pprev) {
667 // Check pprev to not segfault if min_height is too low
668 if (block->nHeight <= min_height || !block->pprev) {
669 return true;
670 }
671 }
672 }
673 return false;
674 }
675 bool broadcastTransaction(const Config &config,
676 const CTransactionRef &tx,
677 const Amount &max_tx_fee, bool relay,
678 std::string &err_string) override {
679 const TransactionError err =
680 BroadcastTransaction(m_node, tx, err_string, max_tx_fee, relay,
681 /*wait_callback=*/false);
682 // Chain clients only care about failures to accept the tx to the
683 // mempool. Disregard non-mempool related failures. Note: this will
684 // need to be updated if BroadcastTransactions() is updated to
685 // return other non-mempool failures that Chain clients do not need
686 // to know about.
687 return err == TransactionError::OK;
688 }
689 CFeeRate estimateFee() const override {
690 if (!m_node.mempool) {
691 return {};
692 }
693 return m_node.mempool->estimateFee();
694 }
695 CFeeRate relayMinFee() override {
696 if (!m_node.mempool) {
698 }
699 return m_node.mempool->m_min_relay_feerate;
700 }
701 CFeeRate relayDustFee() override {
702 if (!m_node.mempool) {
704 }
705 return m_node.mempool->m_dust_relay_feerate;
706 }
707 bool havePruned() override {
708 LOCK(cs_main);
709 return m_node.chainman->m_blockman.m_have_pruned;
710 }
711 bool isReadyToBroadcast() override {
712 return !chainman().m_blockman.LoadingBlocks() &&
713 !isInitialBlockDownload();
714 }
715 bool isInitialBlockDownload() override {
716 return chainman().IsInitialBlockDownload();
717 }
718 bool shutdownRequested() override { return ShutdownRequested(); }
719 void initMessage(const std::string &message) override {
720 ::uiInterface.InitMessage(message);
721 }
722 void initWarning(const bilingual_str &message) override {
723 InitWarning(message);
724 }
725 void initError(const bilingual_str &message) override {
726 InitError(message);
727 }
728 void showProgress(const std::string &title, int progress,
729 bool resume_possible) override {
730 ::uiInterface.ShowProgress(title, progress, resume_possible);
731 }
732 std::unique_ptr<Handler> handleNotifications(
733 std::shared_ptr<Notifications> notifications) override {
734 return std::make_unique<NotificationsHandlerImpl>(
735 std::move(notifications));
736 }
737 void
738 waitForNotificationsIfTipChanged(const BlockHash &old_tip) override {
739 if (!old_tip.IsNull()) {
741 const CChain &active = Assert(m_node.chainman)->ActiveChain();
742 if (old_tip == active.Tip()->GetBlockHash()) {
743 return;
744 }
745 }
747 }
748
749 std::unique_ptr<Handler>
750 handleRpc(const CRPCCommand &command) override {
751 return std::make_unique<RpcHandlerImpl>(command);
752 }
753 bool rpcEnableDeprecated(const std::string &method) override {
754 return IsDeprecatedRPCEnabled(gArgs, method);
755 }
756 void rpcRunLater(const std::string &name, std::function<void()> fn,
757 int64_t seconds) override {
758 RPCRunLater(name, std::move(fn), seconds);
759 }
760 int rpcSerializationFlags() override { return RPCSerializationFlags(); }
761 util::SettingsValue getSetting(const std::string &name) override {
762 return gArgs.GetSetting(name);
763 }
764 std::vector<util::SettingsValue>
765 getSettingsList(const std::string &name) override {
766 return gArgs.GetSettingsList(name);
767 }
768 util::SettingsValue getRwSetting(const std::string &name) override {
769 util::SettingsValue result;
770 gArgs.LockSettings([&](const util::Settings &settings) {
771 if (const util::SettingsValue *value =
772 util::FindKey(settings.rw_settings, name)) {
773 result = *value;
774 }
775 });
776 return result;
777 }
778 bool updateRwSetting(const std::string &name,
779 const util::SettingsValue &value,
780 bool write) override {
781 gArgs.LockSettings([&](util::Settings &settings) {
782 if (value.isNull()) {
783 settings.rw_settings.erase(name);
784 } else {
785 settings.rw_settings[name] = value;
786 }
787 });
788 return !write || gArgs.WriteSettingsFile();
789 }
790 void requestMempoolTransactions(Notifications &notifications) override {
791 if (!m_node.mempool) {
792 return;
793 }
794 LOCK2(::cs_main, m_node.mempool->cs);
795 for (const CTxMemPoolEntryRef &entry : m_node.mempool->mapTx) {
796 notifications.transactionAddedToMempool(entry->GetSharedTx(),
797 /*mempool_sequence=*/0);
798 }
799 }
800 bool hasAssumedValidChain() override {
801 return Assert(m_node.chainman)->IsSnapshotActive();
802 }
803 const CChainParams &params() const override { return m_params; }
804 NodeContext *context() override { return &m_node; }
805 NodeContext &m_node;
807 };
808} // namespace
809} // namespace node
810
811namespace interfaces {
812std::unique_ptr<Node> MakeNode(node::NodeContext *context) {
813 return std::make_unique<node::NodeImpl>(context);
814}
815std::unique_ptr<Chain> MakeChain(node::NodeContext &node,
816 const CChainParams &params) {
817 return std::make_unique<node::ChainImpl>(node, params);
818}
819} // namespace interfaces
ArgsManager gArgs
Definition: args.cpp:38
int flags
Definition: bitcoin-tx.cpp:541
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:112
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:19
#define Assert(val)
Identity function.
Definition: check.h:84
util::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:483
void LockSettings(Fn &&fn)
Access settings with lock held.
Definition: args.h:398
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr, bool backup=false) const
Write settings file or backup settings file.
Definition: args.cpp:457
std::vector< util::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: args.cpp:837
util::SettingsValue GetSetting(const std::string &arg) const
Get setting value.
Definition: args.cpp:828
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:556
void SetNull()
Definition: block.h:80
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
int64_t GetBlockTime() const
Definition: blockindex.h:180
int64_t GetMedianTimePast() const
Definition: blockindex.h:192
int64_t GetBlockTimeMax() const
Definition: blockindex.h:182
unsigned int nTx
Number of transactions in this block.
Definition: blockindex.h:60
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: blockindex.cpp:78
BlockHash GetBlockHash() const
Definition: blockindex.h:146
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
An in-memory indexed chain of blocks.
Definition: chain.h:134
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:150
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
int Height() const
Return the maximal height in the chain.
Definition: chain.h:186
CBlockLocator GetLocator() const
Return a CBlockLocator that refers to the tip of this chain.
Definition: chain.cpp:45
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:85
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
Network address.
Definition: netaddress.h:121
std::string name
Definition: server.h:176
Actor actor
Definition: server.h:177
bool removeCommand(const std::string &name, const CRPCCommand *pcmd)
Definition: server.cpp:335
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:623
UniValue execute(const Config &config, const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:582
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:327
Implement this to subscribe to events generated in validation.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:699
void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block of this chain and a locator.
Definition: validation.cpp:125
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1140
A UTXO entry.
Definition: coins.h:28
Definition: config.h:19
UniValue params
Definition: request.h:34
std::string strMethod
Definition: request.h:33
std::string URI
Definition: request.h:36
std::any context
Definition: request.h:39
Definition: rcu.h:85
Class for registering and managing all RPC calls.
Definition: server.h:40
RPC timer "driver".
Definition: server.h:100
bool isNull() const
Definition: univalue.h:104
Int getInt() const
Definition: univalue.h:157
bool isNum() const
Definition: univalue.h:109
Wrapper around std::unique_lock style lock for Mutex.
Definition: sync.h:168
bool IsNull() const
Definition: uint256.h:32
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:129
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:54
const FoundBlock * m_next_block
Definition: chain.h:100
BlockHash * m_hash
Definition: chain.h:94
int64_t * m_max_time
Definition: chain.h:97
int64_t * m_time
Definition: chain.h:96
bool * m_in_active_chain
Definition: chain.h:99
int64_t * m_mtp_time
Definition: chain.h:98
Generic interface for managing an event handler or callback function registered with another interfac...
Definition: handler.h:22
Top-level interface for a bitcoin node (bitcoind process).
Definition: node.h:59
Wallet chain client that in addition to having chain client methods for starting up,...
Definition: wallet.h:304
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
TransactionError
Definition: error.h:22
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:201
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:1703
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition: init.cpp:2098
void Shutdown(NodeContext &node)
Definition: init.cpp:225
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
Definition: init.cpp:2120
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin: Basic context setup.
Definition: init.cpp:1730
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:2110
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1569
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:1777
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
Definition: init.cpp:2082
void StartMapPort(bool use_upnp, bool use_natpmp)
Definition: mapport.cpp:362
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: handler.cpp:48
std::unique_ptr< Node > MakeNode(node::NodeContext *context)
Return implementation of Node interface.
Definition: interfaces.cpp:812
std::unique_ptr< Chain > MakeChain(node::NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
Definition: interfaces.cpp:815
Definition: init.h:31
TransactionError BroadcastTransaction(const NodeContext &node, const CTransactionRef tx, std::string &err_string, const Amount 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:37
void FindCoins(const NodeContext &node, std::map< COutPoint, Coin > &coins)
Look up unspent output information.
Definition: coin.cpp:12
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:115
std::map< CSubNet, CBanEntry > banmap_t
Definition: net_types.h:13
Network
A network type.
Definition: netaddress.h:44
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
Definition: netbase.cpp:715
ConnectionDirection
Definition: netbase.h:32
NodeContext & m_node
Definition: interfaces.cpp:805
NodeContext * m_context
Definition: interfaces.cpp:386
std::shared_ptr< Chain::Notifications > m_notifications
Definition: interfaces.cpp:462
CRPCCommand m_command
Definition: interfaces.cpp:523
const CChainParams & m_params
Definition: interfaces.cpp:806
const CRPCCommand * m_wrapped_command
Definition: interfaces.cpp:524
std::shared_ptr< NotificationsProxy > m_proxy
Definition: interfaces.cpp:480
int64_t NodeId
Definition: nodeid.h:10
static constexpr Amount DUST_RELAY_TX_FEE(1000 *SATOSHI)
Min feerate for defining dust.
static constexpr Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
const char * name
Definition: rest.cpp:47
@ RPC_WALLET_NOT_FOUND
Invalid wallet specified.
Definition: protocol.h:109
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
Definition: server.cpp:648
bool IsDeprecatedRPCEnabled(const ArgsManager &args, const std::string &method)
Definition: server.cpp:407
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:658
void RPCRunLater(const std::string &name, std::function< void()> func, int64_t nSeconds)
Run func nSeconds from now.
Definition: server.cpp:664
void StopRPC()
Definition: server.cpp:365
int RPCSerializationFlags()
Retrieves any serialization flags requested in command line argument.
Definition: server.cpp:679
void InterruptRPC()
Definition: server.cpp:354
CRPCTable tableRPC
Definition: server.cpp:683
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:85
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:55
Definition: amount.h:19
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:105
Bilingual messages:
Definition: translation.h:17
Block and header tip information.
Definition: node.h:50
Block tip (could be a header or not, depends on the subscribed signal).
Definition: node.h:270
NodeContext struct containing references to chain state and connection state.
Definition: context.h:46
Stored settings.
Definition: settings.h:31
std::map< std::string, SettingsValue > rw_settings
Map of setting name to read-write file setting value.
Definition: settings.h:37
std::map< std::string, std::vector< SettingsValue > > command_line_options
Map of setting name to list of command line values.
Definition: settings.h:35
#define WAIT_LOCK(cs, name)
Definition: sync.h:317
#define LOCK2(cs1, cs2)
Definition: sync.h:309
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
#define TRY_LOCK(cs, name)
Definition: sync.h:314
#define REVERSE_LOCK(g)
Definition: sync.h:265
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:152
CClientUIInterface uiInterface
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
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...
assert(!tx.IsCoinBase())
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:114
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
bilingual_str GetWarnings(bool verbose)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:41