Bitcoin ABC 0.31.2
P2P Digital Currency
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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/blockchain.h>
31#include <rpc/protocol.h>
32#include <rpc/server.h>
33#include <shutdown.h>
34#include <sync.h>
35#include <txmempool.h>
36#include <uint256.h>
37#include <util/check.h>
38#include <util/translation.h>
39#include <validation.h>
40#include <validationinterface.h>
41#include <warnings.h>
42
43#if defined(HAVE_CONFIG_H)
44#include <config/bitcoin-config.h>
45#endif
46
47#include <univalue.h>
48
49#include <boost/signals2/signal.hpp>
50
51#include <memory>
52#include <utility>
53
55
63
64namespace node {
65namespace {
66
67 class NodeImpl : public Node {
68 private:
69 ChainstateManager &chainman() { return *Assert(m_context->chainman); }
70
71 public:
72 explicit NodeImpl(NodeContext *context) { setContext(context); }
73 void initLogging() override { InitLogging(*Assert(m_context->args)); }
74 void initParameterInteraction() override {
76 }
77 bilingual_str getWarnings() override { return GetWarnings(true); }
78 bool baseInitialize(Config &config) override {
80 return false;
81 }
82 if (!AppInitParameterInteraction(config, gArgs)) {
83 return false;
84 }
85
86 m_context->kernel = std::make_unique<kernel::Context>();
87 if (!AppInitSanityChecks(*m_context->kernel)) {
88 return false;
89 }
90
92 return false;
93 }
95 return false;
96 }
97
98 return true;
99 }
100 bool appInitMain(Config &config, RPCServer &rpcServer,
101 HTTPRPCRequestProcessor &httpRPCRequestProcessor,
102 interfaces::BlockAndHeaderTipInfo *tip_info) override {
103 return AppInitMain(config, rpcServer, httpRPCRequestProcessor,
104 *m_context, tip_info);
105 }
106 void appShutdown() override {
109 }
110 void startShutdown() override {
112 // Stop RPC for clean shutdown if any of waitfor* commands is
113 // executed.
114 if (gArgs.GetBoolArg("-server", false)) {
115 InterruptRPC();
116 StopRPC();
117 }
118 }
119 bool shutdownRequested() override { return ShutdownRequested(); }
120 bool isPersistentSettingIgnored(const std::string &name) override {
121 bool ignored = false;
122 gArgs.LockSettings([&](util::Settings &settings) {
123 if (auto *options =
125 ignored = !options->empty();
126 }
127 });
128 return ignored;
129 }
131 getPersistentSetting(const std::string &name) override {
133 }
134 void updateRwSetting(const std::string &name,
135 const util::SettingsValue &value) override {
136 gArgs.LockSettings([&](util::Settings &settings) {
137 if (value.isNull()) {
138 settings.rw_settings.erase(name);
139 } else {
140 settings.rw_settings[name] = value;
141 }
142 });
144 }
145 void forceSetting(const std::string &name,
146 const util::SettingsValue &value) override {
147 gArgs.LockSettings([&](util::Settings &settings) {
148 if (value.isNull()) {
149 settings.forced_settings.erase(name);
150 } else {
151 settings.forced_settings[name] = value;
152 }
153 });
154 }
155 void resetSettings() override {
156 gArgs.WriteSettingsFile(/*errors=*/nullptr, /*backup=*/true);
157 gArgs.LockSettings([&](util::Settings &settings) {
158 settings.rw_settings.clear();
159 });
161 }
162 void mapPort(bool use_upnp, bool use_natpmp) override {
163 StartMapPort(use_upnp, use_natpmp);
164 }
165 bool getProxy(Network net, proxyType &proxy_info) override {
166 return GetProxy(net, proxy_info);
167 }
168 size_t getNodeCount(ConnectionDirection flags) override {
169 return m_context->connman ? m_context->connman->GetNodeCount(flags)
170 : 0;
171 }
172 bool getNodesStats(NodesStats &stats) override {
173 stats.clear();
174
175 if (m_context->connman) {
176 std::vector<CNodeStats> stats_temp;
177 m_context->connman->GetNodeStats(stats_temp);
178
179 stats.reserve(stats_temp.size());
180 for (auto &node_stats_temp : stats_temp) {
181 stats.emplace_back(std::move(node_stats_temp), false,
183 }
184
185 // Try to retrieve the CNodeStateStats for each node.
186 if (m_context->peerman) {
187 TRY_LOCK(::cs_main, lockMain);
188 if (lockMain) {
189 for (auto &node_stats : stats) {
190 std::get<1>(node_stats) =
191 m_context->peerman->GetNodeStateStats(
192 std::get<0>(node_stats).nodeid,
193 std::get<2>(node_stats));
194 }
195 }
196 }
197 return true;
198 }
199 return false;
200 }
201 bool getBanned(banmap_t &banmap) override {
202 if (m_context->banman) {
203 m_context->banman->GetBanned(banmap);
204 return true;
205 }
206 return false;
207 }
208 bool ban(const CNetAddr &net_addr, int64_t ban_time_offset) override {
209 if (m_context->banman) {
210 m_context->banman->Ban(net_addr, ban_time_offset);
211 return true;
212 }
213 return false;
214 }
215 bool unban(const CSubNet &ip) override {
216 if (m_context->banman) {
217 m_context->banman->Unban(ip);
218 return true;
219 }
220 return false;
221 }
222 bool disconnectByAddress(const CNetAddr &net_addr) override {
223 if (m_context->connman) {
224 return m_context->connman->DisconnectNode(net_addr);
225 }
226 return false;
227 }
228 bool disconnectById(NodeId id) override {
229 if (m_context->connman) {
230 return m_context->connman->DisconnectNode(id);
231 }
232 return false;
233 }
234 int64_t getTotalBytesRecv() override {
235 return m_context->connman ? m_context->connman->GetTotalBytesRecv()
236 : 0;
237 }
238 int64_t getTotalBytesSent() override {
239 return m_context->connman ? m_context->connman->GetTotalBytesSent()
240 : 0;
241 }
242 size_t getMempoolSize() override {
243 return m_context->mempool ? m_context->mempool->size() : 0;
244 }
245 size_t getMempoolDynamicUsage() override {
246 return m_context->mempool ? m_context->mempool->DynamicMemoryUsage()
247 : 0;
248 }
249 bool getHeaderTip(int &height, int64_t &block_time) override {
251 auto best_header = chainman().m_best_header;
252 if (best_header) {
253 height = best_header->nHeight;
254 block_time = best_header->GetBlockTime();
255 return true;
256 }
257 return false;
258 }
259 int getNumBlocks() override {
261 return chainman().ActiveChain().Height();
262 }
263 BlockHash getBestBlockHash() override {
264 const CBlockIndex *tip =
265 WITH_LOCK(::cs_main, return chainman().ActiveTip());
266 return tip ? tip->GetBlockHash()
267 : chainman().GetParams().GenesisBlock().GetHash();
268 }
269 int64_t getLastBlockTime() override {
271 if (chainman().ActiveChain().Tip()) {
272 return chainman().ActiveChain().Tip()->GetBlockTime();
273 }
274 // Genesis block's time of current network
275 return chainman().GetParams().GenesisBlock().GetBlockTime();
276 }
277 double getVerificationProgress() override {
278 const CBlockIndex *tip;
279 {
281 tip = chainman().ActiveChain().Tip();
282 }
283 return GuessVerificationProgress(chainman().GetParams().TxData(),
284 tip);
285 }
286 bool isInitialBlockDownload() override {
287 return chainman().IsInitialBlockDownload();
288 }
289 bool isLoadingBlocks() override {
290 return chainman().m_blockman.LoadingBlocks();
291 }
292 void setNetworkActive(bool active) override {
293 if (m_context->connman) {
294 m_context->connman->SetNetworkActive(active);
295 }
296 }
297 bool getNetworkActive() override {
298 return m_context->connman && m_context->connman->GetNetworkActive();
299 }
300 CFeeRate getDustRelayFee() override {
301 if (!m_context->mempool) {
303 }
304 return m_context->mempool->m_dust_relay_feerate;
305 }
306 UniValue executeRpc(const Config &config, const std::string &command,
307 const UniValue &params,
308 const std::string &uri) override {
309 JSONRPCRequest req;
310 req.context = m_context;
311 req.params = params;
312 req.strMethod = command;
313 req.URI = uri;
314 return ::tableRPC.execute(config, req);
315 }
316 std::vector<std::string> listRpcCommands() override {
318 }
319 void rpcSetTimerInterfaceIfUnset(RPCTimerInterface *iface) override {
321 }
322 void rpcUnsetTimerInterface(RPCTimerInterface *iface) override {
324 }
325 bool getUnspentOutput(const COutPoint &output, Coin &coin) override {
327 return chainman().ActiveChainstate().CoinsTip().GetCoin(output,
328 coin);
329 }
330 WalletClient &walletClient() override {
331 return *Assert(m_context->wallet_client);
332 }
333 std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override {
334 return MakeHandler(::uiInterface.InitMessage_connect(fn));
335 }
336 std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override {
337 return MakeHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
338 }
339 std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override {
340 return MakeHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
341 }
342 std::unique_ptr<Handler>
343 handleShowProgress(ShowProgressFn fn) override {
344 return MakeHandler(::uiInterface.ShowProgress_connect(fn));
345 }
346 std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(
347 NotifyNumConnectionsChangedFn fn) override {
348 return MakeHandler(
349 ::uiInterface.NotifyNumConnectionsChanged_connect(fn));
350 }
351 std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(
352 NotifyNetworkActiveChangedFn fn) override {
353 return MakeHandler(
354 ::uiInterface.NotifyNetworkActiveChanged_connect(fn));
355 }
356 std::unique_ptr<Handler>
357 handleNotifyAlertChanged(NotifyAlertChangedFn fn) override {
358 return MakeHandler(::uiInterface.NotifyAlertChanged_connect(fn));
359 }
360 std::unique_ptr<Handler>
361 handleBannedListChanged(BannedListChangedFn fn) override {
362 return MakeHandler(::uiInterface.BannedListChanged_connect(fn));
363 }
364 std::unique_ptr<Handler>
365 handleNotifyBlockTip(NotifyBlockTipFn fn) override {
366 return MakeHandler(::uiInterface.NotifyBlockTip_connect(
367 [fn](SynchronizationState sync_state,
368 const CBlockIndex *block) {
369 fn(sync_state,
370 BlockTip{block->nHeight, block->GetBlockTime(),
371 block->GetBlockHash()},
372 GuessVerificationProgress(Params().TxData(), block));
373 }));
374 }
375 std::unique_ptr<Handler>
376 handleNotifyHeaderTip(NotifyHeaderTipFn fn) override {
377 /* verification progress is unused when a header was received */
378 return MakeHandler(::uiInterface.NotifyHeaderTip_connect(
379 [fn](SynchronizationState sync_state, int64_t height,
380 int64_t timestamp, bool presync) {
381 fn(sync_state,
382 BlockTip{int(height), timestamp, BlockHash{}}, presync);
383 }));
384 }
385 NodeContext *context() override { return m_context; }
386 void setContext(NodeContext *context) override { m_context = context; }
387 NodeContext *m_context{nullptr};
388 };
389
390 bool FillBlock(const CBlockIndex *index, const FoundBlock &block,
391 UniqueLock<RecursiveMutex> &lock, const CChain &active,
392 const BlockManager &blockman) {
393 if (!index) {
394 return false;
395 }
396 if (block.m_hash) {
397 *block.m_hash = index->GetBlockHash();
398 }
399 if (block.m_height) {
400 *block.m_height = index->nHeight;
401 }
402 if (block.m_time) {
403 *block.m_time = index->GetBlockTime();
404 }
405 if (block.m_max_time) {
406 *block.m_max_time = index->GetBlockTimeMax();
407 }
408 if (block.m_mtp_time) {
409 *block.m_mtp_time = index->GetMedianTimePast();
410 }
411 if (block.m_in_active_chain) {
412 *block.m_in_active_chain = active[index->nHeight] == index;
413 }
414 if (block.m_locator) {
415 *block.m_locator = GetLocator(index);
416 }
417 if (block.m_next_block) {
418 FillBlock(active[index->nHeight] == index
419 ? active[index->nHeight + 1]
420 : nullptr,
421 *block.m_next_block, lock, active, blockman);
422 }
423 if (block.m_data) {
424 REVERSE_LOCK(lock);
425 if (!blockman.ReadBlockFromDisk(*block.m_data, *index)) {
426 block.m_data->SetNull();
427 }
428 }
429 return true;
430 }
431
432 class NotificationsProxy : public CValidationInterface {
433 public:
434 explicit NotificationsProxy(
435 std::shared_ptr<Chain::Notifications> notifications)
436 : m_notifications(std::move(notifications)) {}
437 virtual ~NotificationsProxy() = default;
438 void TransactionAddedToMempool(const CTransactionRef &tx,
439 std::shared_ptr<const std::vector<Coin>>,
440 uint64_t mempool_sequence) override {
441 m_notifications->transactionAddedToMempool(tx, mempool_sequence);
442 }
443 void TransactionRemovedFromMempool(const CTransactionRef &tx,
445 uint64_t mempool_sequence) override {
446 m_notifications->transactionRemovedFromMempool(tx, reason,
447 mempool_sequence);
448 }
449 void BlockConnected(ChainstateRole role,
450 const std::shared_ptr<const CBlock> &block,
451 const CBlockIndex *index) override {
452 m_notifications->blockConnected(role, *block, index->nHeight);
453 }
454 void BlockDisconnected(const std::shared_ptr<const CBlock> &block,
455 const CBlockIndex *index) override {
456 m_notifications->blockDisconnected(*block, index->nHeight);
457 }
458 void UpdatedBlockTip(const CBlockIndex *index,
459 const CBlockIndex *fork_index,
460 bool is_ibd) override {
461 m_notifications->updatedBlockTip();
462 }
463 void ChainStateFlushed(ChainstateRole role,
464 const CBlockLocator &locator) override {
465 m_notifications->chainStateFlushed(role, locator);
466 }
467 std::shared_ptr<Chain::Notifications> m_notifications;
468 };
469
470 class NotificationsHandlerImpl : public Handler {
471 public:
472 explicit NotificationsHandlerImpl(
473 std::shared_ptr<Chain::Notifications> notifications)
474 : m_proxy(std::make_shared<NotificationsProxy>(
475 std::move(notifications))) {
477 }
478 ~NotificationsHandlerImpl() override { disconnect(); }
479 void disconnect() override {
480 if (m_proxy) {
482 m_proxy.reset();
483 }
484 }
485 std::shared_ptr<NotificationsProxy> m_proxy;
486 };
487
488 class RpcHandlerImpl : public Handler {
489 public:
490 explicit RpcHandlerImpl(const CRPCCommand &command)
491 : m_command(command), m_wrapped_command(&command) {
492 m_command.actor = [this](const Config &config,
493 const JSONRPCRequest &request,
494 UniValue &result, bool last_handler) {
495 if (!m_wrapped_command) {
496 return false;
497 }
498 try {
499 return m_wrapped_command->actor(config, request, result,
500 last_handler);
501 } catch (const UniValue &e) {
502 // If this is not the last handler and a wallet not found
503 // exception was thrown, return false so the next handler
504 // can try to handle the request. Otherwise, reraise the
505 // exception.
506 if (!last_handler) {
507 const UniValue &code = e["code"];
508 if (code.isNum() &&
509 code.getInt<int>() == RPC_WALLET_NOT_FOUND) {
510 return false;
511 }
512 }
513 throw;
514 }
515 };
517 }
518
519 void disconnect() final {
520 if (m_wrapped_command) {
521 m_wrapped_command = nullptr;
523 }
524 }
525
526 ~RpcHandlerImpl() override { disconnect(); }
527
530 };
531
532 class ChainImpl : public Chain {
533 private:
534 ChainstateManager &chainman() { return *Assert(m_node.chainman); }
535
536 public:
537 explicit ChainImpl(NodeContext &node, const CChainParams &params)
538 : m_node(node), m_params(params) {}
539 std::optional<int> getHeight() override {
541 const CChain &active = Assert(m_node.chainman)->ActiveChain();
542 int height = active.Height();
543 if (height >= 0) {
544 return height;
545 }
546 return std::nullopt;
547 }
548 BlockHash getBlockHash(int height) override {
550 const CChain &active = Assert(m_node.chainman)->ActiveChain();
551 CBlockIndex *block = active[height];
552 assert(block);
553 return block->GetBlockHash();
554 }
555 bool haveBlockOnDisk(int height) override {
556 LOCK(cs_main);
557 const CChain &active = Assert(m_node.chainman)->ActiveChain();
558 CBlockIndex *block = active[height];
559 return block && (block->nStatus.hasData() != 0) && block->nTx > 0;
560 }
561 CBlockLocator getTipLocator() override {
562 LOCK(cs_main);
563 const CChain &active = Assert(m_node.chainman)->ActiveChain();
564 return active.GetLocator();
565 }
566 // TODO: backport core#25036 with changes from core#25717
567 std::optional<int>
568 findLocatorFork(const CBlockLocator &locator) override {
569 LOCK(cs_main);
570 const Chainstate &active =
571 Assert(m_node.chainman)->ActiveChainstate();
572 if (const CBlockIndex *fork =
573 active.FindForkInGlobalIndex(locator)) {
574 return fork->nHeight;
575 }
576 return std::nullopt;
577 }
578 bool findBlock(const BlockHash &hash,
579 const FoundBlock &block) override {
580 WAIT_LOCK(cs_main, lock);
581 const CChain &active = Assert(m_node.chainman)->ActiveChain();
582 return FillBlock(m_node.chainman->m_blockman.LookupBlockIndex(hash),
583 block, lock, active, chainman().m_blockman);
584 }
585 bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height,
586 const FoundBlock &block) override {
587 WAIT_LOCK(cs_main, lock);
588 const CChain &active = Assert(m_node.chainman)->ActiveChain();
589 return FillBlock(active.FindEarliestAtLeast(min_time, min_height),
590 block, lock, active, chainman().m_blockman);
591 }
592 bool findAncestorByHeight(const BlockHash &block_hash,
593 int ancestor_height,
594 const FoundBlock &ancestor_out) override {
595 WAIT_LOCK(cs_main, lock);
596 const CChain &active = Assert(m_node.chainman)->ActiveChain();
597 if (const CBlockIndex *block =
598 m_node.chainman->m_blockman.LookupBlockIndex(block_hash)) {
599 if (const CBlockIndex *ancestor =
600 block->GetAncestor(ancestor_height)) {
601 return FillBlock(ancestor, ancestor_out, lock, active,
602 chainman().m_blockman);
603 }
604 }
605 return FillBlock(nullptr, ancestor_out, lock, active,
606 chainman().m_blockman);
607 }
608 bool findAncestorByHash(const BlockHash &block_hash,
609 const BlockHash &ancestor_hash,
610 const FoundBlock &ancestor_out) override {
611 WAIT_LOCK(cs_main, lock);
612 const CChain &active = Assert(m_node.chainman)->ActiveChain();
613 const CBlockIndex *block =
614 m_node.chainman->m_blockman.LookupBlockIndex(block_hash);
615 const CBlockIndex *ancestor =
616 m_node.chainman->m_blockman.LookupBlockIndex(ancestor_hash);
617 if (block && ancestor &&
618 block->GetAncestor(ancestor->nHeight) != ancestor) {
619 ancestor = nullptr;
620 }
621 return FillBlock(ancestor, ancestor_out, lock, active,
622 chainman().m_blockman);
623 }
624 bool findCommonAncestor(const BlockHash &block_hash1,
625 const BlockHash &block_hash2,
626 const FoundBlock &ancestor_out,
627 const FoundBlock &block1_out,
628 const FoundBlock &block2_out) override {
629 WAIT_LOCK(cs_main, lock);
630 const CChain &active = Assert(m_node.chainman)->ActiveChain();
631 const CBlockIndex *block1 =
632 m_node.chainman->m_blockman.LookupBlockIndex(block_hash1);
633 const CBlockIndex *block2 =
634 m_node.chainman->m_blockman.LookupBlockIndex(block_hash2);
635 const CBlockIndex *ancestor =
636 block1 && block2 ? LastCommonAncestor(block1, block2) : nullptr;
637 // Using & instead of && below to avoid short circuiting and leaving
638 // output uninitialized. Cast bool to int to avoid
639 // -Wbitwise-instead-of-logical compiler warnings.
640 return int{FillBlock(ancestor, ancestor_out, lock, active,
641 chainman().m_blockman)} &
642 int{FillBlock(block1, block1_out, lock, active,
643 chainman().m_blockman)} &
644 int{FillBlock(block2, block2_out, lock, active,
645 chainman().m_blockman)};
646 }
647 void findCoins(std::map<COutPoint, Coin> &coins) override {
648 return FindCoins(m_node, coins);
649 }
650 double guessVerificationProgress(const BlockHash &block_hash) override {
651 LOCK(cs_main);
653 chainman().GetParams().TxData(),
654 chainman().m_blockman.LookupBlockIndex(block_hash));
655 }
656 bool hasBlocks(const BlockHash &block_hash, int min_height,
657 std::optional<int> max_height) override {
658 // hasBlocks returns true if all ancestors of block_hash in
659 // specified range have block data (are not pruned), false if any
660 // ancestors in specified range are missing data.
661 //
662 // For simplicity and robustness, min_height and max_height are only
663 // used to limit the range, and passing min_height that's too low or
664 // max_height that's too high will not crash or change the result.
666 if (const CBlockIndex *block =
667 chainman().m_blockman.LookupBlockIndex(block_hash)) {
668 if (max_height && block->nHeight >= *max_height) {
669 block = block->GetAncestor(*max_height);
670 }
671 for (; block->nStatus.hasData(); block = block->pprev) {
672 // Check pprev to not segfault if min_height is too low
673 if (block->nHeight <= min_height || !block->pprev) {
674 return true;
675 }
676 }
677 }
678 return false;
679 }
680 bool broadcastTransaction(const Config &config,
681 const CTransactionRef &tx,
682 const Amount &max_tx_fee, bool relay,
683 std::string &err_string) override {
684 const TransactionError err =
685 BroadcastTransaction(m_node, tx, err_string, max_tx_fee, relay,
686 /*wait_callback=*/false);
687 // Chain clients only care about failures to accept the tx to the
688 // mempool. Disregard non-mempool related failures. Note: this will
689 // need to be updated if BroadcastTransactions() is updated to
690 // return other non-mempool failures that Chain clients do not need
691 // to know about.
692 return err == TransactionError::OK;
693 }
694 CFeeRate estimateFee() const override {
695 if (!m_node.mempool) {
696 return {};
697 }
698 return m_node.mempool->estimateFee();
699 }
700 CFeeRate relayMinFee() override {
701 if (!m_node.mempool) {
703 }
704 return m_node.mempool->m_min_relay_feerate;
705 }
706 CFeeRate relayDustFee() override {
707 if (!m_node.mempool) {
709 }
710 return m_node.mempool->m_dust_relay_feerate;
711 }
712 bool havePruned() override {
713 LOCK(cs_main);
714 return m_node.chainman->m_blockman.m_have_pruned;
715 }
716 bool isReadyToBroadcast() override {
717 return !chainman().m_blockman.LoadingBlocks() &&
718 !isInitialBlockDownload();
719 }
720 std::optional<int> getPruneHeight() override {
721 LOCK(chainman().GetMutex());
722 return GetPruneHeight(chainman().m_blockman,
723 chainman().ActiveChain());
724 }
725 bool isInitialBlockDownload() override {
726 return chainman().IsInitialBlockDownload();
727 }
728 bool shutdownRequested() override { return ShutdownRequested(); }
729 void initMessage(const std::string &message) override {
730 ::uiInterface.InitMessage(message);
731 }
732 void initWarning(const bilingual_str &message) override {
733 InitWarning(message);
734 }
735 void initError(const bilingual_str &message) override {
736 InitError(message);
737 }
738 void showProgress(const std::string &title, int progress,
739 bool resume_possible) override {
740 ::uiInterface.ShowProgress(title, progress, resume_possible);
741 }
742 std::unique_ptr<Handler> handleNotifications(
743 std::shared_ptr<Notifications> notifications) override {
744 return std::make_unique<NotificationsHandlerImpl>(
745 std::move(notifications));
746 }
747 void
748 waitForNotificationsIfTipChanged(const BlockHash &old_tip) override {
749 if (!old_tip.IsNull()) {
751 const CChain &active = Assert(m_node.chainman)->ActiveChain();
752 if (old_tip == active.Tip()->GetBlockHash()) {
753 return;
754 }
755 }
757 }
758
759 std::unique_ptr<Handler>
760 handleRpc(const CRPCCommand &command) override {
761 return std::make_unique<RpcHandlerImpl>(command);
762 }
763 bool rpcEnableDeprecated(const std::string &method) override {
764 return IsDeprecatedRPCEnabled(gArgs, method);
765 }
766 void rpcRunLater(const std::string &name, std::function<void()> fn,
767 int64_t seconds) override {
768 RPCRunLater(name, std::move(fn), seconds);
769 }
770 int rpcSerializationFlags() override { return RPCSerializationFlags(); }
771 util::SettingsValue getSetting(const std::string &name) override {
772 return gArgs.GetSetting(name);
773 }
774 std::vector<util::SettingsValue>
775 getSettingsList(const std::string &name) override {
776 return gArgs.GetSettingsList(name);
777 }
778 util::SettingsValue getRwSetting(const std::string &name) override {
779 util::SettingsValue result;
780 gArgs.LockSettings([&](const util::Settings &settings) {
781 if (const util::SettingsValue *value =
782 util::FindKey(settings.rw_settings, name)) {
783 result = *value;
784 }
785 });
786 return result;
787 }
788 bool updateRwSetting(const std::string &name,
789 const util::SettingsValue &value,
790 bool write) override {
791 gArgs.LockSettings([&](util::Settings &settings) {
792 if (value.isNull()) {
793 settings.rw_settings.erase(name);
794 } else {
795 settings.rw_settings[name] = value;
796 }
797 });
798 return !write || gArgs.WriteSettingsFile();
799 }
800 void requestMempoolTransactions(Notifications &notifications) override {
801 if (!m_node.mempool) {
802 return;
803 }
804 LOCK2(::cs_main, m_node.mempool->cs);
805 for (const CTxMemPoolEntryRef &entry : m_node.mempool->mapTx) {
806 notifications.transactionAddedToMempool(entry->GetSharedTx(),
807 /*mempool_sequence=*/0);
808 }
809 }
810 bool hasAssumedValidChain() override {
811 return Assert(m_node.chainman)->IsSnapshotActive();
812 }
813 const CChainParams &params() const override { return m_params; }
814 NodeContext *context() override { return &m_node; }
815 NodeContext &m_node;
817 };
818} // namespace
819} // namespace node
820
821namespace interfaces {
822std::unique_ptr<Node> MakeNode(node::NodeContext *context) {
823 return std::make_unique<node::NodeImpl>(context);
824}
825std::unique_ptr<Chain> MakeChain(node::NodeContext &node,
826 const CChainParams &params) {
827 return std::make_unique<node::ChainImpl>(node, params);
828}
829} // namespace interfaces
ArgsManager gArgs
Definition: args.cpp:38
int flags
Definition: bitcoin-tx.cpp:541
std::optional< int > GetPruneHeight(const BlockManager &blockman, const CChain &chain)
Definition: blockchain.cpp:819
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
Definition: chain.cpp:41
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:160
int64_t GetMedianTimePast() const
Definition: blockindex.h:172
int64_t GetBlockTimeMax() const
Definition: blockindex.h:162
unsigned int nTx
Number of transactions in this block.
Definition: blockindex.h:55
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: blockindex.cpp:62
BlockHash GetBlockHash() const
Definition: blockindex.h:130
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:700
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:127
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1149
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:136
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:55
const FoundBlock * m_next_block
Definition: chain.h:107
BlockHash * m_hash
Definition: chain.h:100
int64_t * m_max_time
Definition: chain.h:103
int64_t * m_time
Definition: chain.h:102
bool * m_in_active_chain
Definition: chain.h:105
int64_t * m_mtp_time
Definition: chain.h:104
CBlockLocator * m_locator
Definition: chain.h:106
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:303
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:1705
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition: init.cpp:2100
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:2122
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin: Basic context setup.
Definition: init.cpp:1732
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:2112
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1571
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:1779
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
Definition: init.cpp:2084
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition: chain.h:14
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:822
std::unique_ptr< Chain > MakeChain(node::NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
Definition: interfaces.cpp:825
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:815
NodeContext * m_context
Definition: interfaces.cpp:387
std::shared_ptr< Chain::Notifications > m_notifications
Definition: interfaces.cpp:467
CRPCCommand m_command
Definition: interfaces.cpp:528
const CChainParams & m_params
Definition: interfaces.cpp:816
const CRPCCommand * m_wrapped_command
Definition: interfaces.cpp:529
std::shared_ptr< NotificationsProxy > m_proxy
Definition: interfaces.cpp:485
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:153
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:115
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