5#include <bitcoin-build-config.h>
8#include <blockfilter.h>
10#include <chainparams.h>
76#include <condition_variable>
110#ifdef ENABLE_EXTERNAL_SIGNER
111class ExternalSignerImpl :
public interfaces::ExternalSigner
114 ExternalSignerImpl(::ExternalSigner signer) : m_signer(std::move(signer)) {}
115 std::string getName()
override {
return m_signer.m_name; }
116 ::ExternalSigner m_signer;
120class NodeImpl :
public Node
123 explicit NodeImpl(NodeContext& context) { setContext(&context); }
126 bilingual_str getWarnings()
override {
return Join(
Assert(m_context->warnings)->GetMessages(),
Untranslated(
"<hr />")); }
127 int getExitStatus()
override {
return Assert(m_context)->exit_status.load(); }
129 bool baseInitialize()
override
134 m_context->warnings = std::make_unique<node::Warnings>();
135 m_context->kernel = std::make_unique<kernel::Context>();
136 m_context->ecc_context = std::make_unique<ECC_Context>();
144 bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info)
override
146 if (
AppInitMain(*m_context, tip_info))
return true;
148 m_context->exit_status.store(EXIT_FAILURE);
151 void appShutdown()
override
155 void startShutdown()
override
157 NodeContext& ctx{*
Assert(m_context)};
159 LogError(
"Failed to send shutdown signal\n");
164 bool isSettingIgnored(
const std::string& name)
override
166 bool ignored =
false;
169 ignored = !options->empty();
196 void resetSettings()
override
204 void mapPort(
bool enable)
override {
StartMapPort(enable); }
205 std::optional<Proxy> getProxy(
Network net)
override {
return GetProxy(net); }
208 return m_context->connman ? m_context->connman->GetNodeCount(flags) : 0;
210 bool getNodesStats(NodesStats& stats)
override
214 if (m_context->connman) {
215 std::vector<CNodeStats> stats_temp;
216 m_context->connman->GetNodeStats(stats_temp);
218 stats.reserve(stats_temp.size());
219 for (
auto& node_stats_temp : stats_temp) {
220 stats.emplace_back(std::move(node_stats_temp),
false, CNodeStateStats());
224 if (m_context->peerman) {
227 for (
auto& node_stats : stats) {
228 std::get<1>(node_stats) =
229 m_context->peerman->GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
237 bool getBanned(
banmap_t& banmap)
override
239 if (m_context->banman) {
240 m_context->banman->GetBanned(banmap);
245 bool ban(
const CNetAddr& net_addr, int64_t ban_time_offset)
override
247 if (m_context->banman) {
248 m_context->banman->Ban(net_addr, ban_time_offset);
253 bool unban(
const CSubNet& ip)
override
255 if (m_context->banman) {
256 m_context->banman->Unban(ip);
261 bool disconnectByAddress(
const CNetAddr& net_addr)
override
263 if (m_context->connman) {
264 return m_context->connman->DisconnectNode(net_addr);
268 bool disconnectById(
NodeId id)
override
270 if (m_context->connman) {
271 return m_context->connman->DisconnectNode(
id);
275 std::vector<std::unique_ptr<interfaces::ExternalSigner>> listExternalSigners()
override
277#ifdef ENABLE_EXTERNAL_SIGNER
278 std::vector<ExternalSigner> signers = {};
282 std::vector<std::unique_ptr<interfaces::ExternalSigner>> result;
283 result.reserve(signers.size());
284 for (
auto& signer : signers) {
285 result.emplace_back(std::make_unique<ExternalSignerImpl>(std::move(signer)));
298 int64_t getTotalBytesRecv()
override {
return m_context->connman ? m_context->connman->GetTotalBytesRecv() : 0; }
299 int64_t getTotalBytesSent()
override {
return m_context->connman ? m_context->connman->GetTotalBytesSent() : 0; }
300 size_t getMempoolSize()
override {
return m_context->mempool ? m_context->mempool->size() : 0; }
301 size_t getMempoolDynamicUsage()
override {
return m_context->mempool ? m_context->mempool->DynamicMemoryUsage() : 0; }
302 size_t getMempoolMaxUsage()
override {
return m_context->mempool ? m_context->mempool->m_opts.max_size_bytes : 0; }
303 bool getHeaderTip(
int& height, int64_t& block_time)
override
306 auto best_header = chainman().m_best_header;
308 height = best_header->nHeight;
309 block_time = best_header->GetBlockTime();
314 std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses()
override
316 if (m_context->connman)
317 return m_context->connman->getNetLocalAddresses();
321 int getNumBlocks()
override
324 return chainman().ActiveChain().Height();
326 uint256 getBestBlockHash()
override
329 return tip ? tip->
GetBlockHash() : chainman().GetParams().GenesisBlock().GetHash();
331 int64_t getLastBlockTime()
override
334 if (chainman().ActiveChain().Tip()) {
335 return chainman().ActiveChain().Tip()->GetBlockTime();
337 return chainman().GetParams().GenesisBlock().GetBlockTime();
339 double getVerificationProgress()
override
341 LOCK(chainman().GetMutex());
342 return chainman().GuessVerificationProgress(chainman().ActiveTip());
344 bool isInitialBlockDownload()
override
346 return chainman().IsInitialBlockDownload();
348 bool isLoadingBlocks()
override {
return chainman().m_blockman.LoadingBlocks(); }
349 void setNetworkActive(
bool active)
override
351 if (m_context->connman) {
352 m_context->connman->SetNetworkActive(active);
355 bool getNetworkActive()
override {
return m_context->connman && m_context->connman->GetNetworkActive(); }
356 CFeeRate getDustRelayFee()
override
359 return m_context->mempool->m_opts.dust_relay_feerate;
361 UniValue executeRpc(
const std::string&
command,
const UniValue& params,
const std::string& uri)
override
364 req.context = m_context;
368 return ::tableRPC.execute(
req);
370 std::vector<std::string> listRpcCommands()
override { return ::tableRPC.listCommands(); }
371 std::optional<Coin> getUnspentOutput(
const COutPoint& output)
override
374 return chainman().ActiveChainstate().CoinsTip().GetCoin(output);
385 WalletLoader& walletLoader()
override
387 return *
Assert(m_context->wallet_loader);
389 std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn)
override
393 std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn)
override
397 std::unique_ptr<Handler> handleQuestion(QuestionFn fn)
override
401 std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn)
override
405 std::unique_ptr<Handler> handleInitWallet(InitWalletFn fn)
override
409 std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn)
override
413 std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn)
override
417 std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn)
override
421 std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn)
override
425 std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn)
override
428 fn(sync_state, BlockTip{block.nHeight, block.GetBlockTime(), block.GetBlockHash()}, verification_progress);
431 std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn)
override
435 fn(sync_state, BlockTip{(int)height, timestamp, uint256{}}, presync);
438 NodeContext* context()
override {
return m_context; }
444 ChainstateManager& chainman() {
return *
Assert(m_context->chainman); }
451 if (!index)
return false;
452 if (block.m_hash) *block.m_hash = index->GetBlockHash();
453 if (block.m_height) *block.m_height = index->nHeight;
454 if (block.m_time) *block.m_time = index->GetBlockTime();
455 if (block.m_max_time) *block.m_max_time = index->GetBlockTimeMax();
456 if (block.m_mtp_time) *block.m_mtp_time = index->GetMedianTimePast();
457 if (block.m_in_active_chain) *block.m_in_active_chain = active[index->nHeight] == index;
458 if (block.m_locator) { *block.m_locator =
GetLocator(index); }
459 if (block.m_next_block) FillBlock(active[index->nHeight] == index ? active[index->nHeight + 1] :
nullptr, *block.m_next_block, lock, active, blockman);
462 if (!blockman.ReadBlock(*block.m_data, *index)) block.m_data->SetNull();
471 explicit NotificationsProxy(std::shared_ptr<Chain::Notifications> notifications)
472 : m_notifications(std::move(notifications)) {}
473 virtual ~NotificationsProxy() =
default;
474 void TransactionAddedToMempool(
const NewMempoolTransactionInfo& tx, uint64_t mempool_sequence)
override
476 m_notifications->transactionAddedToMempool(tx.
info.
m_tx);
480 m_notifications->transactionRemovedFromMempool(tx, reason);
482 void BlockConnected(
const ChainstateRole& role,
const std::shared_ptr<const CBlock>& block,
const CBlockIndex* index)
override
486 void BlockDisconnected(
const std::shared_ptr<const CBlock>& block,
const CBlockIndex* index)
override
490 void UpdatedBlockTip(
const CBlockIndex* index,
const CBlockIndex* fork_index,
bool is_ibd)
override
492 m_notifications->updatedBlockTip();
494 void ChainStateFlushed(
const ChainstateRole& role,
const CBlockLocator& locator)
override
496 m_notifications->chainStateFlushed(role, locator);
498 std::shared_ptr<Chain::Notifications> m_notifications;
501class NotificationsHandlerImpl :
public Handler
504 explicit NotificationsHandlerImpl(ValidationSignals& signals, std::shared_ptr<Chain::Notifications> notifications)
505 : m_signals{signals}, m_proxy{std::make_shared<NotificationsProxy>(std::move(notifications))}
509 ~NotificationsHandlerImpl()
override { disconnect(); }
510 void disconnect()
override
513 m_signals.UnregisterSharedValidationInterface(m_proxy);
517 ValidationSignals& m_signals;
518 std::shared_ptr<NotificationsProxy> m_proxy;
521class RpcHandlerImpl :
public Handler
524 explicit RpcHandlerImpl(
const CRPCCommand&
command) : m_command(
command), m_wrapped_command(&
command)
526 m_command.actor = [
this](
const JSONRPCRequest&
request, UniValue& result,
bool last_handler) {
527 if (!m_wrapped_command)
return false;
529 return m_wrapped_command->actor(
request, result, last_handler);
530 }
catch (
const UniValue& e) {
535 const UniValue& code = e[
"code"];
546 void disconnect() final
548 if (m_wrapped_command) {
549 m_wrapped_command =
nullptr;
554 ~RpcHandlerImpl()
override { disconnect(); }
556 CRPCCommand m_command;
557 const CRPCCommand* m_wrapped_command;
560class ChainImpl :
public Chain
563 explicit ChainImpl(NodeContext& node) : m_node(node) {}
564 std::optional<int> getHeight()
override
567 return height >= 0 ? std::optional{height} : std::nullopt;
569 uint256 getBlockHash(
int height)
override
572 return Assert(chainman().ActiveChain()[height])->GetBlockHash();
574 bool haveBlockOnDisk(
int height)
override
577 const CBlockIndex* block{chainman().ActiveChain()[height]};
580 std::optional<int> findLocatorFork(
const CBlockLocator& locator)
override
583 if (
const CBlockIndex* fork = chainman().ActiveChainstate().FindForkInGlobalIndex(locator)) {
584 return fork->nHeight;
595 if (!block_filter_index)
return std::nullopt;
598 const CBlockIndex* index{
WITH_LOCK(
::cs_main,
return chainman().m_blockman.LookupBlockIndex(block_hash))};
599 if (index ==
nullptr || !block_filter_index->
LookupFilter(index, filter))
return std::nullopt;
602 bool findBlock(
const uint256& hash,
const FoundBlock& block)
override
605 return FillBlock(chainman().m_blockman.LookupBlockIndex(hash), block, lock, chainman().ActiveChain(), chainman().m_blockman);
607 bool findFirstBlockWithTimeAndHeight(int64_t min_time,
int min_height,
const FoundBlock& block)
override
610 const CChain& active = chainman().ActiveChain();
611 return FillBlock(active.
FindEarliestAtLeast(min_time, min_height), block, lock, active, chainman().m_blockman);
613 bool findAncestorByHeight(
const uint256& block_hash,
int ancestor_height,
const FoundBlock& ancestor_out)
override
616 const CChain& active = chainman().ActiveChain();
617 if (
const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
618 if (
const CBlockIndex* ancestor = block->GetAncestor(ancestor_height)) {
619 return FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman);
622 return FillBlock(
nullptr, ancestor_out, lock, active, chainman().m_blockman);
624 bool findAncestorByHash(
const uint256& block_hash,
const uint256& ancestor_hash,
const FoundBlock& ancestor_out)
override
627 const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash);
628 const CBlockIndex* ancestor = chainman().m_blockman.LookupBlockIndex(ancestor_hash);
629 if (block && ancestor && block->
GetAncestor(ancestor->
nHeight) != ancestor) ancestor =
nullptr;
630 return FillBlock(ancestor, ancestor_out, lock, chainman().ActiveChain(), chainman().m_blockman);
632 bool findCommonAncestor(
const uint256& block_hash1,
const uint256& block_hash2,
const FoundBlock& ancestor_out,
const FoundBlock& block1_out,
const FoundBlock& block2_out)
override
635 const CChain& active = chainman().ActiveChain();
636 const CBlockIndex* block1 = chainman().m_blockman.LookupBlockIndex(block_hash1);
637 const CBlockIndex* block2 = chainman().m_blockman.LookupBlockIndex(block_hash2);
638 const CBlockIndex* ancestor = block1 && block2 ?
LastCommonAncestor(block1, block2) : nullptr;
642 return int{FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman)} &
643 int{FillBlock(block1, block1_out, lock, active, chainman().m_blockman)} &
644 int{FillBlock(block2, block2_out, lock, active, chainman().m_blockman)};
646 void findCoins(std::map<COutPoint, Coin>& coins)
override {
return FindCoins(m_node, coins); }
647 double guessVerificationProgress(
const uint256& block_hash)
override
649 LOCK(chainman().GetMutex());
650 return chainman().GuessVerificationProgress(chainman().m_blockman.LookupBlockIndex(block_hash));
652 bool hasBlocks(
const uint256& block_hash,
int min_height, std::optional<int> max_height)
override
662 if (
const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
663 if (max_height && block->
nHeight >= *max_height) block = block->
GetAncestor(*max_height);
666 if (block->
nHeight <= min_height || !block->
pprev)
return true;
674 LOCK(m_node.mempool->cs);
677 bool isInMempool(
const Txid& txid)
override
679 if (!m_node.mempool)
return false;
680 return m_node.mempool->exists(txid);
682 bool hasDescendantsInMempool(
const Txid& txid)
override
684 if (!m_node.mempool)
return false;
685 return m_node.mempool->HasDescendants(txid);
689 TxBroadcast broadcast_method,
690 std::string& err_string)
override
696 return TransactionError::OK == err;
698 void getTransactionAncestry(
const Txid& txid,
size_t& ancestors,
size_t& cluster_count,
size_t* ancestorsize,
CAmount* ancestorfees)
override
700 ancestors = cluster_count = 0;
701 if (!m_node.mempool)
return;
702 m_node.mempool->GetTransactionAncestry(txid, ancestors, cluster_count, ancestorsize, ancestorfees);
705 std::map<COutPoint, CAmount> calculateIndividualBumpFees(
const std::vector<COutPoint>& outpoints,
const CFeeRate& target_feerate)
override
707 if (!m_node.mempool) {
708 std::map<COutPoint, CAmount> bump_fees;
709 for (
const auto& outpoint : outpoints) {
710 bump_fees.emplace(outpoint, 0);
714 return MiniMiner(*m_node.mempool, outpoints).CalculateBumpFees(target_feerate);
717 std::optional<CAmount> calculateCombinedBumpFee(
const std::vector<COutPoint>& outpoints,
const CFeeRate& target_feerate)
override
719 if (!m_node.mempool) {
722 return MiniMiner(*m_node.mempool, outpoints).CalculateTotalBumpFees(target_feerate);
724 void getPackageLimits(
unsigned int& limit_ancestor_count,
unsigned int& limit_descendant_count)
override
728 const CTxMemPool::Limits& limits{m_node.mempool ? m_node.mempool->m_opts.limits : default_limits};
733 util::Result<void> checkChainLimits(
const CTransactionRef& tx)
override
735 if (!m_node.mempool)
return {};
736 if (!m_node.mempool->CheckPolicyLimits(tx)) {
737 return util::Error{
Untranslated(
"too many unconfirmed transactions in cluster")};
741 util::Expected<FeeRateEstimation, FeeRateEstimationError> getFeeRateEstimate(
int num_blocks,
bool conservative)
const override
744 return m_node.fee_estimator_man->GetFeeRateEstimate(num_blocks, conservative);
746 unsigned int maximumFeeEstimationTargetBlocks()
const override
748 if (!m_node.fee_estimator_man)
return 0;
749 return m_node.fee_estimator_man->MaximumTarget();
751 CFeeRate mempoolMinFee()
override
753 if (!m_node.mempool)
return {};
754 return m_node.mempool->GetMinFee();
756 CFeeRate relayMinFee()
override
759 return m_node.mempool->m_opts.min_relay_feerate;
761 CFeeRate relayIncrementalFee()
override
764 return m_node.mempool->m_opts.incremental_relay_feerate;
766 CFeeRate relayDustFee()
override
769 return m_node.mempool->m_opts.dust_relay_feerate;
771 bool havePruned()
override
774 return chainman().m_blockman.m_have_pruned;
776 std::optional<int> getPruneHeight()
override
778 LOCK(chainman().GetMutex());
779 return GetPruneHeight(chainman().m_blockman, chainman().ActiveChain());
781 bool isReadyToBroadcast()
override {
return !chainman().m_blockman.LoadingBlocks() && !isInitialBlockDownload(); }
782 bool isInitialBlockDownload()
override
784 return chainman().IsInitialBlockDownload();
788 void initWarning(
const bilingual_str& message)
override {
InitWarning(message); }
789 void initError(
const bilingual_str& message)
override {
InitError(message); }
790 void showProgress(
const std::string& title,
int progress,
bool resume_possible)
override
794 std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications)
override
796 return std::make_unique<NotificationsHandlerImpl>(validation_signals(), std::move(notifications));
798 void waitForNotificationsIfTipChanged(
const uint256& old_tip)
override
800 if (!old_tip.
IsNull() && old_tip ==
WITH_LOCK(
::cs_main,
return chainman().ActiveChain().Tip()->GetBlockHash()))
return;
801 validation_signals().SyncWithValidationInterfaceQueue();
803 void waitForNotifications()
override
805 validation_signals().SyncWithValidationInterfaceQueue();
807 std::unique_ptr<Handler> handleRpc(
const CRPCCommand&
command)
override
809 return std::make_unique<RpcHandlerImpl>(
command);
816 std::vector<common::SettingsValue> getSettingsList(
const std::string& name)
override
830 bool updateRwSetting(
const std::string& name,
833 std::optional<interfaces::SettingsAction> action;
836 action = update_settings_func(*value);
840 action = update_settings_func(new_value);
844 if (!action)
return false;
851 settings = std::move(value);
857 return overwriteRwSetting(name, {}, action);
859 void requestMempoolTransactions(Notifications& notifications)
override
861 if (!m_node.mempool)
return;
863 for (
const CTxMemPoolEntry& entry : m_node.mempool->entryAll()) {
864 notifications.transactionAddedToMempool(entry.GetSharedTx());
867 bool hasAssumedValidChain()
override
870 return bool{chainman().CurrentChainstate().m_from_snapshot_blockhash};
873 NodeContext* context()
override {
return &m_node; }
874 ArgsManager&
args() {
return *
Assert(m_node.args); }
875 ChainstateManager& chainman() {
return *
Assert(m_node.chainman); }
876 ValidationSignals& validation_signals() {
return *
Assert(m_node.validation_signals); }
883 explicit BlockTemplateImpl(BlockCreateOptions create_options,
884 std::unique_ptr<CBlockTemplate> block_template,
885 const NodeContext& node) : m_create_options(std::move(create_options)),
886 m_block_template(std::move(block_template)),
892 CBlockHeader getBlockHeader()
override
894 return m_block_template->block;
897 CBlock getBlock()
override
899 return m_block_template->block;
902 std::vector<CAmount> getTxFees()
override
904 return m_block_template->vTxFees;
907 std::vector<int64_t> getTxSigops()
override
909 return m_block_template->vTxSigOpsCost;
912 CoinbaseTx getCoinbaseTx()
override
914 return m_block_template->m_coinbase_tx;
917 std::vector<uint256> getCoinbaseMerklePath()
override
922 bool submitSolution(uint32_t version, uint32_t timestamp, uint32_t nonce,
CTransactionRef coinbase, std::string& reason, std::string& debug)
override
924 if (!coinbase)
return false;
926 return SubmitBlock(chainman(), std::make_shared<const CBlock>(m_block_template->block), reason, debug);
929 std::unique_ptr<BlockTemplate> waitNext(BlockWaitOptions options)
override
933 m_node.mempool.get(),
938 if (new_template)
return std::make_unique<BlockTemplateImpl>(m_create_options, std::move(new_template), m_node);
942 void interruptWait()
override
947 const BlockCreateOptions m_create_options;
949 const std::unique_ptr<CBlockTemplate> m_block_template;
951 bool m_interrupt_wait{
false};
952 ChainstateManager& chainman() {
return *
Assert(m_node.chainman); }
953 KernelNotifications& notifications() {
return *
Assert(m_node.notifications); }
954 const NodeContext& m_node;
957class MinerImpl :
public Mining
960 explicit MinerImpl(
const NodeContext& node) : m_node(node) {}
962 bool isTestChain()
override
964 return chainman().GetParams().IsTestChain();
967 bool isInitialBlockDownload()
override
969 return chainman().IsInitialBlockDownload();
972 std::optional<BlockRef>
getTip()
override
974 return GetTip(chainman());
977 std::optional<BlockRef> waitTipChanged(uint256 current_tip,
MillisecondsDouble timeout)
override
979 return WaitTipChanged(chainman(), notifications(), current_tip, timeout, m_interrupt_mining);
982 std::unique_ptr<BlockTemplate> createNewBlock(
const BlockCreateOptions& options,
bool cooldown)
override
985 std::optional<BlockRef> maybe_tip{waitTipChanged(
uint256::ZERO, MillisecondsDouble::max())};
987 if (!maybe_tip)
return {};
995 while (chainman().IsInitialBlockDownload()) {
997 if (!maybe_tip || chainman().m_interrupt ||
WITH_LOCK(notifications().m_tip_block_mutex,
return m_interrupt_mining))
return {};
1003 const BlockCreateOptions create_options{
MergeMiningOptions(options, m_node.mining_args)};
1004 return std::make_unique<BlockTemplateImpl>(create_options,
1006 chainman().ActiveChainstate(),
1007 m_node.mempool.get(),
1013 void interrupt()
override
1018 bool checkBlock(
const CBlock& block,
const node::BlockCheckOptions& options, std::string& reason, std::string& debug)
override
1020 LOCK(chainman().GetMutex());
1027 bool submitBlock(
const CBlock& block_in, std::string& reason, std::string& debug)
override
1029 return SubmitBlock(chainman(), std::make_shared<const CBlock>(block_in), reason, debug);
1032 std::vector<CTransactionRef> getTransactionsByTxID(
const std::vector<Txid>& txids)
override
1034 if (!m_node.mempool)
return {};
1036 std::vector<CTransactionRef> results;
1037 results.reserve(txids.size());
1038 LOCK(m_node.mempool->cs);
1039 for (
const auto& txid : txids) {
1040 results.emplace_back(m_node.mempool->get(txid));
1045 std::vector<CTransactionRef> getTransactionsByWitnessID(
const std::vector<Wtxid>& wtxids)
override
1047 if (!m_node.mempool)
return {};
1049 std::vector<CTransactionRef> results;
1050 results.reserve(wtxids.size());
1051 LOCK(m_node.mempool->cs);
1052 for (
const auto& wtxid : wtxids) {
1053 results.emplace_back(m_node.mempool->get(wtxid));
1058 const NodeContext* context()
override {
return &m_node; }
1059 ChainstateManager& chainman() {
return *
Assert(m_node.chainman); }
1060 KernelNotifications& notifications() {
return *
Assert(m_node.notifications); }
1062 bool m_interrupt_mining{
false};
1063 const NodeContext& m_node;
1066class RpcImpl :
public Rpc
1069 explicit RpcImpl(NodeContext& node) : m_node(node) {}
1071 UniValue executeRpc(UniValue
request, std::string uri, std::string user)
override
1074 req.context = &m_node;
1075 req.URI = std::move(uri);
1076 req.authUser = std::move(user);
1081 NodeContext& m_node;
1096 return kernel_notifications.m_state.chainstate_loaded || interrupt;
1098 if (interrupt)
return nullptr;
1100 return std::make_unique<node::MinerImpl>(context);
int64_t CAmount
Amount in satoshis (Can be negative).
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
std::optional< int > GetPruneHeight(const BlockManager &blockman, const CChain &chain)
Return height of highest block that has been pruned, or std::nullopt if no blocks have been pruned.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
CBlockLocator GetLocator(const CBlockIndex *index)
Get a locator for a block index entry.
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
@ BLOCK_HAVE_DATA
full block available in blk*.dat
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
std::vector< common::SettingsValue > GetSettingsList(const std::string &arg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get list of setting values.
common::SettingsValue GetSetting(const std::string &arg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get setting value.
bool GetSettingsPath(fs::path *filepath=nullptr, bool temp=false, bool backup=false) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get settings file path, or return false if read-write settings were disabled with -nosettings.
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr, bool backup=false) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Write settings file or backup settings file.
void LockSettings(Fn &&fn) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Access settings with lock held.
common::SettingsValue GetPersistentSetting(const std::string &name) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get current setting from config file or read/write settings file, ignoring nonpersistent command line...
std::string GetArg(const std::string &strArg, const std::string &strDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return string argument or default value.
CategoryMask GetCategoryMask() const
const GCSFilter & GetFilter() const LIFETIMEBOUND
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
The block chain is a tree shaped structure starting with the genesis block at the root,...
CBlockIndex * pprev
pointer to the index of the predecessor of this block
uint256 GetBlockHash() const
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
int nHeight
height of the entry in the chain. The genesis block has height 0
An in-memory indexed chain of blocks.
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...
btcsignals::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
btcsignals::signal< void(const std::string &title, int nProgress, bool resume_possible)> ShowProgress
Show progress e.g.
bool removeCommand(const std::string &name, const CRPCCommand *pcmd)
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
kernel::MemPoolLimits Limits
Implement this to subscribe to events generated in validation and mempool.
static bool Enumerate(const std::string &command, std::vector< ExternalSigner > &signers, const std::string &chain)
std::unordered_set< Element, ByteVectorHash > ElementSet
bool MatchAny(const ElementSet &elements) const
Checks if any of the given elements may be in the set.
Wrapper around std::unique_lock style lock for MutexType.
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
std::string GetRejectReason() const
std::string GetDebugMessage() const
constexpr bool IsNull() const
Block template interface.
Top-level interface for a bitcoin node (bitcoind process).
Interface giving clients ability to emulate HTTP RPC calls.
Generate a new block, without valid proof-of-work.
static const uint256 ZERO
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
std::vector< uint256 > TransactionMerklePath(const CBlock &block, uint32_t position)
Compute merkle path to the specified transaction.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
UniValue ExecuteHTTPRPC(const UniValue &valRequest, JSONRPCRequest &jreq, HTTPStatusCode &status)
Execute a single HTTP request containing one or more JSONRPC requests.
const std::string request
void InitLogging(const ArgsManager &args)
Initialize global loggers.
bool AppInitBasicSetup(const ArgsManager &args, std::atomic< int > &exit_status)
Initialize bitcoin core: Basic context setup.
bool ShutdownRequested(node::NodeContext &node)
Return whether node shutdown was requested.
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
bool AppInitMain(NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
bool AppInitLockDirectories()
Lock bitcoin core critical directories.
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
CClientUIInterface uiInterface
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
BCLog::Logger & LogInstance()
void StartMapPort(bool enable)
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
std::unique_ptr< Node > MakeNode(node::NodeContext &context)
Return implementation of Node interface.
std::unique_ptr< Rpc > MakeRpc(node::NodeContext &node)
Return implementation of Rpc interface.
std::function< std::optional< interfaces::SettingsAction >(common::SettingsValue &)> SettingsUpdate
std::unique_ptr< Mining > MakeMining(const node::NodeContext &node, bool wait_loaded=true)
std::unique_ptr< Handler > MakeSignalHandler(btcsignals::connection connection)
Return handler wrapping a btcsignals connection.
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
interfaces::BlockInfo MakeBlockInfo(const CBlockIndex *index, const CBlock *data)
Return data from block index.
std::optional< BlockRef > WaitTipChanged(ChainstateManager &chainman, KernelNotifications &kernel_notifications, const uint256 ¤t_tip, MillisecondsDouble &timeout, bool &interrupt)
@ MEMPOOL_AND_BROADCAST_TO_ALL
Add the transaction to the mempool and broadcast to all peers for which tx relay is enabled.
BlockCreateOptions MergeMiningOptions(BlockCreateOptions x, const BlockCreateOptions &y)
Merge two BlockCreateOptions structs, replacing null values in x with non-null values from y.
TransactionError BroadcastTransaction(NodeContext &node, const CTransactionRef tx, std::string &err_string, const CAmount &max_tx_fee, TxBroadcast broadcast_method, bool wait_callback)
Submit a transaction to the mempool and (optionally) relay it to all P2P peers.
void InterruptWait(KernelNotifications &kernel_notifications, bool &interrupt_wait)
std::unique_ptr< CBlockTemplate > WaitAndCreateNewBlock(ChainstateManager &chainman, KernelNotifications &kernel_notifications, CTxMemPool *mempool, const std::unique_ptr< CBlockTemplate > &block_template, const BlockWaitOptions &wait_options, const BlockCreateOptions &create_options, bool &interrupt_wait)
Return a new block template when fees rise to a certain threshold or after a new tip; return nullopt ...
void AddMerkleRootAndCoinbase(CBlock &block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce)
bool CooldownIfHeadersAhead(ChainstateManager &chainman, KernelNotifications &kernel_notifications, const BlockRef &last_tip, bool &interrupt_mining)
Wait while the best known header extends the current chain tip AND at least one block is being added ...
std::optional< BlockRef > GetTip(ChainstateManager &chainman)
bool SubmitBlock(ChainstateManager &chainman, const std::shared_ptr< const CBlock > &block, std::string &reason, std::string &debug)
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
std::map< CSubNet, CBanEntry > banmap_t
std::optional< Proxy > GetProxy(enum Network net)
std::unique_ptr< Handler > MakeSignalHandler(btcsignals::connection connection)
Return handler wrapping a btcsignals connection.
RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction &tx)
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...
RBFTransactionState
The rbf state of unconfirmed transactions.
constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
constexpr unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
std::shared_ptr< const CTransaction > CTransactionRef
void FindCoins(const node::NodeContext &node, std::map< COutPoint, Coin > &coins)
Look up unspent output information.
HTTPStatusCode
HTTP status codes.
@ RPC_WALLET_NOT_FOUND
Invalid wallet specified.
bool IsDeprecatedRPCEnabled(const std::string &method)
std::function< bool()> shutdown_request
Function to request a shutdown.
const CTransactionRef m_tx
std::map< std::string, SettingsValue > forced_settings
Map of setting name to forced setting value.
std::map< std::string, SettingsValue > rw_settings
Map of setting name to read-write file setting value.
std::map< std::string, std::vector< SettingsValue > > command_line_options
Map of setting name to list of command line values.
Hash/height pair to help track and identify blocks.
Block tip (could be a header or not, depends on the subscribed signal).
Information about chainstate that notifications are sent from.
int64_t descendant_count
The maximum allowed number of transactions in a package including the entry and its descendants.
int64_t ancestor_count
The maximum allowed number of transactions in a package including the entry and its ancestors.
bool check_pow
Set false to omit the proof-of-work check.
bool check_merkle_root
Set false to omit the merkle root check.
Block template creation options.
Template containing all coinbase transaction fields that are set by our miner code.
std::unique_ptr< KernelNotifications > notifications
Issues blocking calls about sync status, errors and warnings.
util::SignalInterrupt * shutdown_signal
Interrupt object used to track whether node shutdown was requested.
#define WAIT_LOCK(cs, name)
#define REVERSE_LOCK(g, cs)
#define WITH_LOCK(cs, code)
#define TRY_LOCK(cs, name)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
transaction_identifier< false > Txid
Txid commits to all transaction fields except the witness.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
util::Unexpected< FeeRateEstimationError > EstimationError(FeeRateEstimatorType estimator, int returned_target, std::string error)
Build a fee rate estimation error result: a zero-value estimation identifying the estimator and targe...
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
BlockValidationState TestBlockValidity(Chainstate &chainstate, const CBlock &block, const bool check_pow, const bool check_merkle_root)
Verify a block, including transactions.
SynchronizationState
Current sync state passed to tip changed callbacks.
TipBlock getTip(const CChainParams ¶ms, const node::NodeContext &context)