Branch data Line data Source code
1 : : // Copyright (c) 2018-present 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 <bitcoin-build-config.h> // IWYU pragma: keep
6 : :
7 : : #include <banman.h>
8 : : #include <blockfilter.h>
9 : : #include <chain.h>
10 : : #include <chainparams.h>
11 : : #include <coins.h>
12 : : #include <common/args.h>
13 : : #include <common/settings.h>
14 : : #include <consensus/amount.h>
15 : : #include <consensus/merkle.h>
16 : : #include <consensus/validation.h>
17 : : #include <external_signer.h>
18 : : #include <httprpc.h>
19 : : #include <index/blockfilterindex.h>
20 : : #include <init.h>
21 : : #include <interfaces/chain.h>
22 : : #include <interfaces/handler.h>
23 : : #include <interfaces/mining.h>
24 : : #include <interfaces/node.h>
25 : : #include <interfaces/rpc.h>
26 : : #include <interfaces/types.h>
27 : : #include <kernel/context.h>
28 : : #include <key.h>
29 : : #include <logging.h>
30 : : #include <mapport.h>
31 : : #include <net.h>
32 : : #include <net_processing.h>
33 : : #include <net_types.h>
34 : : #include <netaddress.h>
35 : : #include <netbase.h>
36 : : #include <node/block_template_manager.h>
37 : : #include <node/blockstorage.h>
38 : : #include <node/coin.h>
39 : : #include <node/context.h>
40 : : #include <node/interface_ui.h>
41 : : #include <node/kernel_notifications.h>
42 : : #include <node/miner.h>
43 : : #include <node/mini_miner.h>
44 : : #include <node/mining_types.h>
45 : : #include <node/transaction.h>
46 : : #include <node/types.h>
47 : : #include <node/warnings.h>
48 : : #include <policy/feerate.h>
49 : : #include <policy/fees/estimator_man.h>
50 : : #include <policy/policy.h>
51 : : #include <policy/rbf.h>
52 : : #include <primitives/block.h>
53 : : #include <primitives/transaction.h>
54 : : #include <rpc/blockchain.h>
55 : : #include <rpc/protocol.h>
56 : : #include <rpc/request.h>
57 : : #include <rpc/server.h>
58 : : #include <sync.h>
59 : : #include <txmempool.h>
60 : : #include <uint256.h>
61 : : #include <univalue.h>
62 : : #include <util/btcsignals.h>
63 : : #include <util/check.h>
64 : : #include <util/expected.h>
65 : : #include <util/fees.h>
66 : : #include <util/result.h>
67 : : #include <util/signalinterrupt.h>
68 : : #include <util/string.h>
69 : : #include <util/time.h>
70 : : #include <util/translation.h>
71 : : #include <validation.h>
72 : : #include <validationinterface.h>
73 : :
74 : : #include <any>
75 : : #include <atomic>
76 : : #include <condition_variable>
77 : : #include <cstdint>
78 : : #include <cstdlib>
79 : : #include <functional>
80 : : #include <map>
81 : : #include <memory>
82 : : #include <optional>
83 : : #include <string>
84 : : #include <tuple>
85 : : #include <utility>
86 : : #include <vector>
87 : :
88 : : using interfaces::BlockRef;
89 : : using interfaces::BlockTemplate;
90 : : using interfaces::BlockTip;
91 : : using interfaces::Chain;
92 : : using interfaces::FoundBlock;
93 : : using interfaces::Handler;
94 : : using interfaces::MakeSignalHandler;
95 : : using interfaces::Mining;
96 : : using interfaces::Node;
97 : : using interfaces::Rpc;
98 : : using interfaces::WalletLoader;
99 : : using kernel::ChainstateRole;
100 : : using node::BlockCreateOptions;
101 : : using node::BlockWaitOptions;
102 : : using node::CoinbaseTx;
103 : : using util::Join;
104 : :
105 : : namespace node {
106 : : // All members of the classes in this namespace are intentionally public, as the
107 : : // classes themselves are private.
108 : : namespace {
109 : : #ifdef ENABLE_EXTERNAL_SIGNER
110 : : class ExternalSignerImpl : public interfaces::ExternalSigner
111 : : {
112 : : public:
113 : 0 : ExternalSignerImpl(::ExternalSigner signer) : m_signer(std::move(signer)) {}
114 [ # # ]: 0 : std::string getName() override { return m_signer.m_name; }
115 : : ::ExternalSigner m_signer;
116 : : };
117 : : #endif
118 : :
119 : : class NodeImpl : public Node
120 : : {
121 : : public:
122 : 0 : explicit NodeImpl(NodeContext& context) { setContext(&context); }
123 : 0 : void initLogging() override { InitLogging(args()); }
124 : 0 : void initParameterInteraction() override { InitParameterInteraction(args()); }
125 [ # # # # : 0 : bilingual_str getWarnings() override { return Join(Assert(m_context->warnings)->GetMessages(), Untranslated("<hr />")); }
# # # # ]
126 [ # # ]: 0 : int getExitStatus() override { return Assert(m_context)->exit_status.load(); }
127 : 0 : BCLog::CategoryMask getLogCategories() override { return LogInstance().GetCategoryMask(); }
128 : 0 : bool baseInitialize() override
129 : : {
130 [ # # # # ]: 0 : if (!AppInitBasicSetup(args(), Assert(context())->exit_status)) return false;
131 [ # # ]: 0 : if (!AppInitParameterInteraction(args())) return false;
132 : :
133 : 0 : m_context->warnings = std::make_unique<node::Warnings>();
134 : 0 : m_context->kernel = std::make_unique<kernel::Context>();
135 : 0 : m_context->ecc_context = std::make_unique<ECC_Context>();
136 [ # # ]: 0 : if (!AppInitSanityChecks(*m_context->kernel)) return false;
137 : :
138 [ # # ]: 0 : if (!AppInitLockDirectories()) return false;
139 [ # # ]: 0 : if (!AppInitInterfaces(*m_context)) return false;
140 : :
141 : : return true;
142 : : }
143 : 0 : bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info) override
144 : : {
145 [ # # ]: 0 : if (AppInitMain(*m_context, tip_info)) return true;
146 : : // Error during initialization, set exit status before continue
147 : 0 : m_context->exit_status.store(EXIT_FAILURE);
148 : 0 : return false;
149 : : }
150 : 0 : void appShutdown() override
151 : : {
152 : 0 : Shutdown(*m_context);
153 : 0 : }
154 : 0 : void startShutdown() override
155 : : {
156 [ # # ]: 0 : NodeContext& ctx{*Assert(m_context)};
157 [ # # # # ]: 0 : if (!(Assert(ctx.shutdown_request))()) {
158 : 0 : LogError("Failed to send shutdown signal\n");
159 : : }
160 : 0 : Interrupt(*m_context);
161 : 0 : }
162 [ # # ]: 0 : bool shutdownRequested() override { return ShutdownRequested(*Assert(m_context)); };
163 : 0 : bool isSettingIgnored(const std::string& name) override
164 : : {
165 : 0 : bool ignored = false;
166 : 0 : args().LockSettings([&](common::Settings& settings) {
167 [ # # ]: 0 : if (auto* options = common::FindKey(settings.command_line_options, name)) {
168 : 0 : ignored = !options->empty();
169 : : }
170 : 0 : });
171 : 0 : return ignored;
172 : : }
173 : 0 : common::SettingsValue getPersistentSetting(const std::string& name) override { return args().GetPersistentSetting(name); }
174 : 0 : void updateRwSetting(const std::string& name, const common::SettingsValue& value) override
175 : : {
176 : 0 : args().LockSettings([&](common::Settings& settings) {
177 [ # # ]: 0 : if (value.isNull()) {
178 : 0 : settings.rw_settings.erase(name);
179 : : } else {
180 : 0 : settings.rw_settings[name] = value;
181 : : }
182 : 0 : });
183 : 0 : args().WriteSettingsFile();
184 : 0 : }
185 : 0 : void forceSetting(const std::string& name, const common::SettingsValue& value) override
186 : : {
187 : 0 : args().LockSettings([&](common::Settings& settings) {
188 [ # # ]: 0 : if (value.isNull()) {
189 : 0 : settings.forced_settings.erase(name);
190 : : } else {
191 : 0 : settings.forced_settings[name] = value;
192 : : }
193 : 0 : });
194 : 0 : }
195 : 0 : void resetSettings() override
196 : : {
197 : 0 : args().WriteSettingsFile(/*errors=*/nullptr, /*backup=*/true);
198 : 0 : args().LockSettings([&](common::Settings& settings) {
199 [ # # ]: 0 : settings.rw_settings.clear();
200 : : });
201 : 0 : args().WriteSettingsFile();
202 : 0 : }
203 : 0 : void mapPort(bool enable) override { StartMapPort(enable); }
204 : 0 : std::optional<Proxy> getProxy(Network net) override { return GetProxy(net); }
205 : 0 : size_t getNodeCount(ConnectionDirection flags) override
206 : : {
207 [ # # ]: 0 : return m_context->connman ? m_context->connman->GetNodeCount(flags) : 0;
208 : : }
209 : 0 : bool getNodesStats(NodesStats& stats) override
210 : : {
211 : 0 : stats.clear();
212 : :
213 [ # # ]: 0 : if (m_context->connman) {
214 : 0 : std::vector<CNodeStats> stats_temp;
215 [ # # ]: 0 : m_context->connman->GetNodeStats(stats_temp);
216 : :
217 [ # # # # ]: 0 : stats.reserve(stats_temp.size());
218 [ # # ]: 0 : for (auto& node_stats_temp : stats_temp) {
219 [ # # ]: 0 : stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
220 : : }
221 : :
222 : : // Try to retrieve the CNodeStateStats for each node.
223 [ # # ]: 0 : if (m_context->peerman) {
224 [ # # ]: 0 : TRY_LOCK(::cs_main, lockMain);
225 [ # # ]: 0 : if (lockMain) {
226 [ # # ]: 0 : for (auto& node_stats : stats) {
227 : 0 : std::get<1>(node_stats) =
228 [ # # ]: 0 : m_context->peerman->GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
229 : : }
230 : : }
231 : 0 : }
232 : 0 : return true;
233 : 0 : }
234 : : return false;
235 : : }
236 : 0 : bool getBanned(banmap_t& banmap) override
237 : : {
238 [ # # ]: 0 : if (m_context->banman) {
239 : 0 : m_context->banman->GetBanned(banmap);
240 : 0 : return true;
241 : : }
242 : : return false;
243 : : }
244 : 0 : bool ban(const CNetAddr& net_addr, int64_t ban_time_offset) override
245 : : {
246 [ # # ]: 0 : if (m_context->banman) {
247 : 0 : m_context->banman->Ban(net_addr, ban_time_offset);
248 : 0 : return true;
249 : : }
250 : : return false;
251 : : }
252 : 0 : bool unban(const CSubNet& ip) override
253 : : {
254 [ # # ]: 0 : if (m_context->banman) {
255 : 0 : m_context->banman->Unban(ip);
256 : 0 : return true;
257 : : }
258 : : return false;
259 : : }
260 : 0 : bool disconnectByAddress(const CNetAddr& net_addr) override
261 : : {
262 [ # # ]: 0 : if (m_context->connman) {
263 : 0 : return m_context->connman->DisconnectNode(net_addr);
264 : : }
265 : : return false;
266 : : }
267 : 0 : bool disconnectById(NodeId id) override
268 : : {
269 [ # # ]: 0 : if (m_context->connman) {
270 : 0 : return m_context->connman->DisconnectNode(id);
271 : : }
272 : : return false;
273 : : }
274 : 0 : std::vector<std::unique_ptr<interfaces::ExternalSigner>> listExternalSigners() override
275 : : {
276 : : #ifdef ENABLE_EXTERNAL_SIGNER
277 : 0 : std::vector<ExternalSigner> signers = {};
278 [ # # # # : 0 : const std::string command = args().GetArg("-signer", "");
# # # # ]
279 [ # # ]: 0 : if (command == "") return {};
280 [ # # # # : 0 : ExternalSigner::Enumerate(command, signers, Params().GetChainTypeString());
# # ]
281 : 0 : std::vector<std::unique_ptr<interfaces::ExternalSigner>> result;
282 [ # # # # ]: 0 : result.reserve(signers.size());
283 [ # # ]: 0 : for (auto& signer : signers) {
284 [ # # # # ]: 0 : result.emplace_back(std::make_unique<ExternalSignerImpl>(std::move(signer)));
285 : : }
286 : 0 : return result;
287 : : #else
288 : : // This result is indistinguishable from a successful call that returns
289 : : // no signers. For the current GUI this doesn't matter, because the wallet
290 : : // creation dialog disables the external signer checkbox in both
291 : : // cases. The return type could be changed to std::optional<std::vector>
292 : : // (or something that also includes error messages) if this distinction
293 : : // becomes important.
294 : : return {};
295 : : #endif // ENABLE_EXTERNAL_SIGNER
296 : 0 : }
297 [ # # ]: 0 : int64_t getTotalBytesRecv() override { return m_context->connman ? m_context->connman->GetTotalBytesRecv() : 0; }
298 [ # # ]: 0 : int64_t getTotalBytesSent() override { return m_context->connman ? m_context->connman->GetTotalBytesSent() : 0; }
299 [ # # ]: 0 : size_t getMempoolSize() override { return m_context->mempool ? m_context->mempool->size() : 0; }
300 [ # # ]: 0 : size_t getMempoolDynamicUsage() override { return m_context->mempool ? m_context->mempool->DynamicMemoryUsage() : 0; }
301 [ # # ]: 0 : size_t getMempoolMaxUsage() override { return m_context->mempool ? m_context->mempool->m_opts.max_size_bytes : 0; }
302 : 0 : bool getHeaderTip(int& height, int64_t& block_time) override
303 : : {
304 : 0 : LOCK(::cs_main);
305 [ # # ]: 0 : auto best_header = chainman().m_best_header;
306 [ # # ]: 0 : if (best_header) {
307 : 0 : height = best_header->nHeight;
308 : 0 : block_time = best_header->GetBlockTime();
309 : 0 : return true;
310 : : }
311 : : return false;
312 : 0 : }
313 : 0 : std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() override
314 : : {
315 [ # # ]: 0 : if (m_context->connman)
316 : 0 : return m_context->connman->getNetLocalAddresses();
317 : : else
318 : 0 : return {};
319 : : }
320 : 0 : int getNumBlocks() override
321 : : {
322 : 0 : LOCK(::cs_main);
323 [ # # # # : 0 : return chainman().ActiveChain().Height();
# # # # ]
324 : 0 : }
325 : 0 : uint256 getBestBlockHash() override
326 : : {
327 [ # # # # : 0 : const CBlockIndex* tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip());
# # # # ]
328 [ # # ]: 0 : return tip ? tip->GetBlockHash() : chainman().GetParams().GenesisBlock().GetHash();
329 : : }
330 : 0 : int64_t getLastBlockTime() override
331 : : {
332 : 0 : LOCK(::cs_main);
333 [ # # # # : 0 : if (chainman().ActiveChain().Tip()) {
# # # # ]
334 [ # # # # : 0 : return chainman().ActiveChain().Tip()->GetBlockTime();
# # ]
335 : : }
336 [ # # ]: 0 : return chainman().GetParams().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
337 : 0 : }
338 : 0 : double getVerificationProgress() override
339 : : {
340 : 0 : LOCK(chainman().GetMutex());
341 [ # # # # : 0 : return chainman().GuessVerificationProgress(chainman().ActiveTip());
# # # # #
# ]
342 : 0 : }
343 : 0 : bool isInitialBlockDownload() override
344 : : {
345 : 0 : return chainman().IsInitialBlockDownload();
346 : : }
347 : 0 : bool isLoadingBlocks() override { return chainman().m_blockman.LoadingBlocks(); }
348 : 0 : void setNetworkActive(bool active) override
349 : : {
350 [ # # ]: 0 : if (m_context->connman) {
351 : 0 : m_context->connman->SetNetworkActive(active);
352 : : }
353 : 0 : }
354 [ # # # # ]: 0 : bool getNetworkActive() override { return m_context->connman && m_context->connman->GetNetworkActive(); }
355 : 0 : CFeeRate getDustRelayFee() override
356 : : {
357 [ # # ]: 0 : if (!m_context->mempool) return CFeeRate{DUST_RELAY_TX_FEE};
358 : 0 : return m_context->mempool->m_opts.dust_relay_feerate;
359 : : }
360 : 0 : UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
361 : : {
362 : 0 : JSONRPCRequest req;
363 : 0 : req.context = m_context;
364 [ # # ]: 0 : req.params = params;
365 [ # # ]: 0 : req.strMethod = command;
366 [ # # ]: 0 : req.URI = uri;
367 [ # # ]: 0 : return ::tableRPC.execute(req);
368 : 0 : }
369 : 0 : std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
370 : 0 : std::optional<Coin> getUnspentOutput(const COutPoint& output) override
371 : : {
372 : 0 : LOCK(::cs_main);
373 [ # # # # : 0 : return chainman().ActiveChainstate().CoinsTip().GetCoin(output);
# # # # ]
374 : 0 : }
375 : 0 : TransactionError broadcastTransaction(CTransactionRef tx, CAmount max_tx_fee, std::string& err_string) override
376 : : {
377 [ # # # # ]: 0 : return BroadcastTransaction(*m_context,
378 : : std::move(tx),
379 : : err_string,
380 : : max_tx_fee,
381 : : TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL,
382 : 0 : /*wait_callback=*/false);
383 : : }
384 : 0 : WalletLoader& walletLoader() override
385 : : {
386 [ # # ]: 0 : return *Assert(m_context->wallet_loader);
387 : : }
388 : 0 : std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
389 : : {
390 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.InitMessage.connect(fn));
391 : : }
392 : 0 : std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
393 : : {
394 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.ThreadSafeMessageBox.connect(fn));
395 : : }
396 : 0 : std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
397 : : {
398 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.ThreadSafeQuestion.connect(fn));
399 : : }
400 : 0 : std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
401 : : {
402 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.ShowProgress.connect(fn));
403 : : }
404 : 0 : std::unique_ptr<Handler> handleInitWallet(InitWalletFn fn) override
405 : : {
406 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.InitWallet.connect(fn));
407 : : }
408 : 0 : std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
409 : : {
410 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.NotifyNumConnectionsChanged.connect(fn));
411 : : }
412 : 0 : std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
413 : : {
414 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.NotifyNetworkActiveChanged.connect(fn));
415 : : }
416 : 0 : std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
417 : : {
418 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.NotifyAlertChanged.connect(fn));
419 : : }
420 : 0 : std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
421 : : {
422 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.BannedListChanged.connect(fn));
423 : : }
424 : 0 : std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
425 : : {
426 [ # # # # ]: 0 : return MakeSignalHandler(::uiInterface.NotifyBlockTip.connect([fn](SynchronizationState sync_state, const CBlockIndex& block, double verification_progress) {
427 : 0 : fn(sync_state, BlockTip{block.nHeight, block.GetBlockTime(), block.GetBlockHash()}, verification_progress);
428 [ # # ]: 0 : }));
429 : : }
430 : 0 : std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
431 : : {
432 : 0 : return MakeSignalHandler(
433 [ # # # # ]: 0 : ::uiInterface.NotifyHeaderTip.connect([fn](SynchronizationState sync_state, int64_t height, int64_t timestamp, bool presync) {
434 : 0 : fn(sync_state, BlockTip{(int)height, timestamp, uint256{}}, presync);
435 [ # # ]: 0 : }));
436 : : }
437 : 0 : NodeContext* context() override { return m_context; }
438 : 0 : void setContext(NodeContext* context) override
439 : : {
440 : 0 : m_context = context;
441 : 0 : }
442 [ # # # # ]: 0 : ArgsManager& args() { return *Assert(Assert(m_context)->args); }
443 [ # # ]: 0 : ChainstateManager& chainman() { return *Assert(m_context->chainman); }
444 : : NodeContext* m_context{nullptr};
445 : : };
446 : :
447 : : // NOLINTNEXTLINE(misc-no-recursion)
448 : 296429 : bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active, const BlockManager& blockman) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
449 : : {
450 [ + + ]: 296429 : if (!index) return false;
451 [ + + ]: 295324 : if (block.m_hash) *block.m_hash = index->GetBlockHash();
452 [ + + ]: 295324 : if (block.m_height) *block.m_height = index->nHeight;
453 [ + + ]: 295324 : if (block.m_time) *block.m_time = index->GetBlockTime();
454 [ + + ]: 295324 : if (block.m_max_time) *block.m_max_time = index->GetBlockTimeMax();
455 [ + + ]: 295324 : if (block.m_mtp_time) *block.m_mtp_time = index->GetMedianTimePast();
456 [ + + + - ]: 468262 : if (block.m_in_active_chain) *block.m_in_active_chain = active[index->nHeight] == index;
457 [ + + ]: 295324 : if (block.m_locator) { *block.m_locator = GetLocator(index); }
458 [ + + + - : 459243 : if (block.m_next_block) FillBlock(active[index->nHeight] == index ? active[index->nHeight + 1] : nullptr, *block.m_next_block, lock, active, blockman);
+ + + - ]
459 [ + + ]: 295324 : if (block.m_data) {
460 : 81419 : REVERSE_LOCK(lock, cs_main);
461 [ + - + + ]: 81419 : if (!blockman.ReadBlock(*block.m_data, *index)) block.m_data->SetNull();
462 : 81419 : }
463 : 295324 : block.found = true;
464 : 295324 : return true;
465 : : }
466 : :
467 : : class NotificationsProxy : public CValidationInterface
468 : : {
469 : : public:
470 : 1031 : explicit NotificationsProxy(std::shared_ptr<Chain::Notifications> notifications)
471 : 1031 : : m_notifications(std::move(notifications)) {}
472 [ + - ]: 1031 : virtual ~NotificationsProxy() = default;
473 : 7852 : void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t mempool_sequence) override
474 : : {
475 : 7852 : m_notifications->transactionAddedToMempool(tx.info.m_tx);
476 : 7852 : }
477 : 331 : void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
478 : : {
479 : 331 : m_notifications->transactionRemovedFromMempool(tx, reason);
480 : 331 : }
481 : 80652 : void BlockConnected(const ChainstateRole& role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
482 : : {
483 : 80652 : m_notifications->blockConnected(role, kernel::MakeBlockInfo(index, block.get()));
484 : 80652 : }
485 : 3460 : void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
486 : : {
487 : 3460 : m_notifications->blockDisconnected(kernel::MakeBlockInfo(index, block.get()));
488 : 3460 : }
489 : 78466 : void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override
490 : : {
491 : 78466 : m_notifications->updatedBlockTip();
492 : 78466 : }
493 : 100 : void ChainStateFlushed(const ChainstateRole& role, const CBlockLocator& locator) override
494 : : {
495 : 100 : m_notifications->chainStateFlushed(role, locator);
496 : 100 : }
497 : : std::shared_ptr<Chain::Notifications> m_notifications;
498 : : };
499 : :
500 : : class NotificationsHandlerImpl : public Handler
501 : : {
502 : : public:
503 : 1031 : explicit NotificationsHandlerImpl(ValidationSignals& signals, std::shared_ptr<Chain::Notifications> notifications)
504 [ + - ]: 1031 : : m_signals{signals}, m_proxy{std::make_shared<NotificationsProxy>(std::move(notifications))}
505 : : {
506 [ + - + - ]: 2062 : m_signals.RegisterSharedValidationInterface(m_proxy);
507 [ - - ]: 1031 : }
508 [ - + ]: 2062 : ~NotificationsHandlerImpl() override { disconnect(); }
509 : 2026 : void disconnect() override
510 : : {
511 [ + + ]: 2026 : if (m_proxy) {
512 [ + - + - ]: 2062 : m_signals.UnregisterSharedValidationInterface(m_proxy);
513 : 1031 : m_proxy.reset();
514 : : }
515 : 2026 : }
516 : : ValidationSignals& m_signals;
517 : : std::shared_ptr<NotificationsProxy> m_proxy;
518 : : };
519 : :
520 : : class RpcHandlerImpl : public Handler
521 : : {
522 : : public:
523 [ + - ]: 26700 : explicit RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command)
524 : : {
525 : 48981 : m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
526 [ + - ]: 22281 : if (!m_wrapped_command) return false;
527 : 22281 : try {
528 [ + + ]: 22281 : return m_wrapped_command->actor(request, result, last_handler);
529 [ - + ]: 780 : } catch (const UniValue& e) {
530 : : // If this is not the last handler and a wallet not found
531 : : // exception was thrown, return false so the next handler can
532 : : // try to handle the request. Otherwise, reraise the exception.
533 [ - + ]: 780 : if (!last_handler) {
534 [ - - - - ]: 0 : const UniValue& code = e["code"];
535 [ - - - - : 0 : if (code.isNum() && code.getInt<int>() == RPC_WALLET_NOT_FOUND) {
- - ]
536 : 0 : return false;
537 : : }
538 : : }
539 : 780 : throw;
540 : 780 : }
541 : 26700 : };
542 [ + - ]: 26700 : ::tableRPC.appendCommand(m_command.name, &m_command);
543 : 26700 : }
544 : :
545 : 26700 : void disconnect() final
546 : : {
547 [ + - ]: 26700 : if (m_wrapped_command) {
548 : 26700 : m_wrapped_command = nullptr;
549 : 26700 : ::tableRPC.removeCommand(m_command.name, &m_command);
550 : : }
551 : 26700 : }
552 : :
553 : 53400 : ~RpcHandlerImpl() override { disconnect(); }
554 : :
555 : : CRPCCommand m_command;
556 : : const CRPCCommand* m_wrapped_command;
557 : : };
558 : :
559 : : class ChainImpl : public Chain
560 : : {
561 : : public:
562 : 2191 : explicit ChainImpl(NodeContext& node) : m_node(node) {}
563 : 2676 : std::optional<int> getHeight() override
564 : : {
565 [ + - + - : 8028 : const int height{WITH_LOCK(::cs_main, return chainman().ActiveChain().Height())};
- + + - ]
566 [ + + ]: 2676 : return height >= 0 ? std::optional{height} : std::nullopt;
567 : : }
568 : 2828 : uint256 getBlockHash(int height) override
569 : : {
570 : 2828 : LOCK(::cs_main);
571 [ + - + - : 5656 : return Assert(chainman().ActiveChain()[height])->GetBlockHash();
+ - - + +
- ]
572 : 2828 : }
573 : 2657 : bool haveBlockOnDisk(int height) override
574 : : {
575 : 2657 : LOCK(::cs_main);
576 [ + - + - : 2667 : const CBlockIndex* block{chainman().ActiveChain()[height]};
+ - ]
577 [ + - + + : 2667 : return block && ((block->nStatus & BLOCK_HAVE_DATA) != 0) && block->nTx > 0;
- + + - ]
578 : 2657 : }
579 : 1011 : std::optional<int> findLocatorFork(const CBlockLocator& locator) override
580 : : {
581 : 1011 : LOCK(::cs_main);
582 [ + - + - : 1011 : if (const CBlockIndex* fork = chainman().ActiveChainstate().FindForkInGlobalIndex(locator)) {
+ - + + ]
583 : 1006 : return fork->nHeight;
584 : : }
585 : 5 : return std::nullopt;
586 : 1011 : }
587 : 734 : bool hasBlockFilterIndex(BlockFilterType filter_type) override
588 : : {
589 : 734 : return GetBlockFilterIndex(filter_type) != nullptr;
590 : : }
591 : 720 : std::optional<bool> blockFilterMatchesAny(BlockFilterType filter_type, const uint256& block_hash, const GCSFilter::ElementSet& filter_set) override
592 : : {
593 : 720 : const BlockFilterIndex* block_filter_index{GetBlockFilterIndex(filter_type)};
594 [ - + ]: 720 : if (!block_filter_index) return std::nullopt;
595 : :
596 : 720 : BlockFilter filter;
597 [ + - + - : 2160 : const CBlockIndex* index{WITH_LOCK(::cs_main, return chainman().m_blockman.LookupBlockIndex(block_hash))};
+ - + - ]
598 [ + - + - : 720 : if (index == nullptr || !block_filter_index->LookupFilter(index, filter)) return std::nullopt;
+ + ]
599 [ + - ]: 619 : return filter.GetFilter().MatchAny(filter_set);
600 : 720 : }
601 : 213630 : bool findBlock(const uint256& hash, const FoundBlock& block) override
602 : : {
603 : 213630 : WAIT_LOCK(cs_main, lock);
604 [ + - + - : 213630 : return FillBlock(chainman().m_blockman.LookupBlockIndex(hash), block, lock, chainman().ActiveChain(), chainman().m_blockman);
+ - + - +
- + - +
- ]
605 : 213630 : }
606 : 719 : bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block) override
607 : : {
608 : 719 : WAIT_LOCK(cs_main, lock);
609 [ + - + - ]: 719 : const CChain& active = chainman().ActiveChain();
610 [ + - + - : 719 : return FillBlock(active.FindEarliestAtLeast(min_time, min_height), block, lock, active, chainman().m_blockman);
+ - + - ]
611 : 719 : }
612 : 43 : bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out) override
613 : : {
614 : 43 : WAIT_LOCK(cs_main, lock);
615 [ + - + - ]: 43 : const CChain& active = chainman().ActiveChain();
616 [ + - + - : 43 : if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
+ - ]
617 [ + - + + ]: 43 : if (const CBlockIndex* ancestor = block->GetAncestor(ancestor_height)) {
618 [ + - + - ]: 42 : return FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman);
619 : : }
620 : : }
621 [ + - + - ]: 1 : return FillBlock(nullptr, ancestor_out, lock, active, chainman().m_blockman);
622 : 43 : }
623 : 7 : bool findAncestorByHash(const uint256& block_hash, const uint256& ancestor_hash, const FoundBlock& ancestor_out) override
624 : : {
625 : 7 : WAIT_LOCK(cs_main, lock);
626 [ + - + - ]: 7 : const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash);
627 [ + - + - ]: 7 : const CBlockIndex* ancestor = chainman().m_blockman.LookupBlockIndex(ancestor_hash);
628 [ + + + - : 7 : if (block && ancestor && block->GetAncestor(ancestor->nHeight) != ancestor) ancestor = nullptr;
+ + ]
629 [ + - + - : 7 : return FillBlock(ancestor, ancestor_out, lock, chainman().ActiveChain(), chainman().m_blockman);
+ - + - +
- ]
630 : 7 : }
631 : 23 : bool findCommonAncestor(const uint256& block_hash1, const uint256& block_hash2, const FoundBlock& ancestor_out, const FoundBlock& block1_out, const FoundBlock& block2_out) override
632 : : {
633 : 23 : WAIT_LOCK(cs_main, lock);
634 [ + - + - ]: 23 : const CChain& active = chainman().ActiveChain();
635 [ + - + - ]: 23 : const CBlockIndex* block1 = chainman().m_blockman.LookupBlockIndex(block_hash1);
636 [ + - + - ]: 23 : const CBlockIndex* block2 = chainman().m_blockman.LookupBlockIndex(block_hash2);
637 [ + + + - ]: 23 : const CBlockIndex* ancestor = block1 && block2 ? LastCommonAncestor(block1, block2) : nullptr;
638 : : // Using & instead of && below to avoid short circuiting and leaving
639 : : // output uninitialized. Cast bool to int to avoid -Wbitwise-instead-of-logical
640 : : // compiler warnings.
641 [ + - + - ]: 23 : return int{FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman)} &
642 [ + - + - ]: 23 : int{FillBlock(block1, block1_out, lock, active, chainman().m_blockman)} &
643 [ + - + - : 23 : int{FillBlock(block2, block2_out, lock, active, chainman().m_blockman)};
+ - ]
644 : 23 : }
645 : 1054 : void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(m_node, coins); }
646 : 83428 : double guessVerificationProgress(const uint256& block_hash) override
647 : : {
648 : 83428 : LOCK(chainman().GetMutex());
649 [ + - + - : 83428 : return chainman().GuessVerificationProgress(chainman().m_blockman.LookupBlockIndex(block_hash));
+ - + - +
- ]
650 : 83428 : }
651 : 35 : bool hasBlocks(const uint256& block_hash, int min_height, std::optional<int> max_height) override
652 : : {
653 : : // hasBlocks returns true if all ancestors of block_hash in specified
654 : : // range have block data (are not pruned), false if any ancestors in
655 : : // 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.
660 : 35 : LOCK(::cs_main);
661 [ + - + - : 35 : if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
+ - ]
662 [ + + + + : 35 : if (max_height && block->nHeight >= *max_height) block = block->GetAncestor(*max_height);
+ - ]
663 [ + + ]: 3389 : for (; block->nStatus & BLOCK_HAVE_DATA; block = block->pprev) {
664 : : // Check pprev to not segfault if min_height is too low
665 [ + + + + ]: 3373 : if (block->nHeight <= min_height || !block->pprev) return true;
666 : : }
667 : : }
668 : : return false;
669 : 35 : }
670 : 1 : RBFTransactionState isRBFOptIn(const CTransaction& tx) override
671 : : {
672 [ - + ]: 1 : if (!m_node.mempool) return IsRBFOptInEmptyMempool(tx);
673 : 1 : LOCK(m_node.mempool->cs);
674 [ + - + - ]: 1 : return IsRBFOptIn(tx, *m_node.mempool);
675 : 1 : }
676 : 17985 : bool isInMempool(const Txid& txid) override
677 : : {
678 [ + - ]: 17985 : if (!m_node.mempool) return false;
679 : 17985 : return m_node.mempool->exists(txid);
680 : : }
681 : 244 : bool hasDescendantsInMempool(const Txid& txid) override
682 : : {
683 [ + - ]: 244 : if (!m_node.mempool) return false;
684 : 244 : return m_node.mempool->HasDescendants(txid);
685 : : }
686 : 1836 : bool broadcastTransaction(const CTransactionRef& tx,
687 : : const CAmount& max_tx_fee,
688 : : TxBroadcast broadcast_method,
689 : : std::string& err_string) override
690 : : {
691 [ + - + - : 3672 : const TransactionError err = BroadcastTransaction(m_node, tx, err_string, max_tx_fee, broadcast_method, /*wait_callback=*/false);
+ - ]
692 : : // Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures.
693 : : // Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures
694 : : // that Chain clients do not need to know about.
695 : 1836 : return TransactionError::OK == err;
696 : : }
697 : 578419 : void getTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* ancestorsize, CAmount* ancestorfees) override
698 : : {
699 : 578419 : ancestors = cluster_count = 0;
700 [ + - ]: 578419 : if (!m_node.mempool) return;
701 : 578419 : m_node.mempool->GetTransactionAncestry(txid, ancestors, cluster_count, ancestorsize, ancestorfees);
702 : : }
703 : :
704 : 4320 : std::map<COutPoint, CAmount> calculateIndividualBumpFees(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
705 : : {
706 [ - + ]: 4320 : if (!m_node.mempool) {
707 : 0 : std::map<COutPoint, CAmount> bump_fees;
708 [ # # ]: 0 : for (const auto& outpoint : outpoints) {
709 [ # # ]: 0 : bump_fees.emplace(outpoint, 0);
710 : : }
711 : : return bump_fees;
712 : 0 : }
713 [ + - ]: 4320 : return MiniMiner(*m_node.mempool, outpoints).CalculateBumpFees(target_feerate);
714 : : }
715 : :
716 : 8926 : std::optional<CAmount> calculateCombinedBumpFee(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
717 : : {
718 [ - + ]: 8926 : if (!m_node.mempool) {
719 : 0 : return 0;
720 : : }
721 [ + - ]: 8926 : return MiniMiner(*m_node.mempool, outpoints).CalculateTotalBumpFees(target_feerate);
722 : : }
723 : 3348 : void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) override
724 : : {
725 : 3348 : const CTxMemPool::Limits default_limits{};
726 : :
727 [ + - ]: 3348 : const CTxMemPool::Limits& limits{m_node.mempool ? m_node.mempool->m_opts.limits : default_limits};
728 : :
729 : 3348 : limit_ancestor_count = limits.ancestor_count;
730 : 3348 : limit_descendant_count = limits.descendant_count;
731 : 3348 : }
732 : 3611 : util::Result<void> checkChainLimits(const CTransactionRef& tx) override
733 : : {
734 [ - + ]: 3611 : if (!m_node.mempool) return {};
735 [ + + ]: 3611 : if (!m_node.mempool->CheckPolicyLimits(tx)) {
736 [ + - ]: 3 : return util::Error{Untranslated("too many unconfirmed transactions in cluster")};
737 : : }
738 : 3610 : return {};
739 : : }
740 : 6741 : util::Expected<FeeRateEstimation, FeeRateEstimationError> getFeeRateEstimate(int num_blocks, bool conservative) const override
741 : : {
742 [ + + ]: 6741 : if (!m_node.fee_estimator_man) return EstimationError(FeeRateEstimatorType::NONE, /*returned_target=*/0, /*error=*/{});
743 : 6719 : return m_node.fee_estimator_man->GetFeeRateEstimate(num_blocks, conservative);
744 : : }
745 : 3820 : unsigned int maximumFeeEstimationTargetBlocks() const override
746 : : {
747 [ + + ]: 3820 : if (!m_node.fee_estimator_man) return 0;
748 : 3805 : return m_node.fee_estimator_man->MaximumTarget();
749 : : }
750 : 2977 : CFeeRate mempoolMinFee() override
751 : : {
752 [ - + ]: 2977 : if (!m_node.mempool) return {};
753 : 2977 : return m_node.mempool->GetMinFee();
754 : : }
755 : 4773 : CFeeRate relayMinFee() override
756 : : {
757 [ - + ]: 4773 : if (!m_node.mempool) return CFeeRate{DEFAULT_MIN_RELAY_TX_FEE};
758 : 4773 : return m_node.mempool->m_opts.min_relay_feerate;
759 : : }
760 : 128 : CFeeRate relayIncrementalFee() override
761 : : {
762 [ - + ]: 128 : if (!m_node.mempool) return CFeeRate{DEFAULT_INCREMENTAL_RELAY_FEE};
763 : 128 : return m_node.mempool->m_opts.incremental_relay_feerate;
764 : : }
765 : 44495 : CFeeRate relayDustFee() override
766 : : {
767 [ - + ]: 44495 : if (!m_node.mempool) return CFeeRate{DUST_RELAY_TX_FEE};
768 : 44495 : return m_node.mempool->m_opts.dust_relay_feerate;
769 : : }
770 : 84 : bool havePruned() override
771 : : {
772 : 84 : LOCK(::cs_main);
773 [ + - + - ]: 84 : return chainman().m_blockman.m_have_pruned;
774 : 84 : }
775 : 1 : std::optional<int> getPruneHeight() override
776 : : {
777 : 1 : LOCK(chainman().GetMutex());
778 [ + - + - : 1 : return GetPruneHeight(chainman().m_blockman, chainman().ActiveChain());
+ - + - ]
779 : 1 : }
780 [ + - + + ]: 150 : bool isReadyToBroadcast() override { return !chainman().m_blockman.LoadingBlocks() && !isInitialBlockDownload(); }
781 : 3238 : bool isInitialBlockDownload() override
782 : : {
783 : 3238 : return chainman().IsInitialBlockDownload();
784 : : }
785 : 82697 : bool shutdownRequested() override { return ShutdownRequested(m_node); }
786 : 1484 : void initMessage(const std::string& message) override { ::uiInterface.InitMessage(message); }
787 : 5 : void initWarning(const bilingual_str& message) override { InitWarning(message); }
788 : 26 : void initError(const bilingual_str& message) override { InitError(message); }
789 : 0 : void showProgress(const std::string& title, int progress, bool resume_possible) override
790 : : {
791 : 0 : ::uiInterface.ShowProgress(title, progress, resume_possible);
792 : 0 : }
793 : 1031 : std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) override
794 : : {
795 : 1031 : return std::make_unique<NotificationsHandlerImpl>(validation_signals(), std::move(notifications));
796 : : }
797 : 6935 : void waitForNotificationsIfTipChanged(const uint256& old_tip) override
798 : : {
799 [ + + + + : 34621 : if (!old_tip.IsNull() && old_tip == WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()->GetBlockHash())) return;
+ - + - -
+ + - ]
800 : 120 : validation_signals().SyncWithValidationInterfaceQueue();
801 : : }
802 : 995 : void waitForNotifications() override
803 : : {
804 : 995 : validation_signals().SyncWithValidationInterfaceQueue();
805 : 995 : }
806 : 26700 : std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) override
807 : : {
808 : 26700 : return std::make_unique<RpcHandlerImpl>(command);
809 : : }
810 : 4125 : bool rpcEnableDeprecated(const std::string& method) override { return IsDeprecatedRPCEnabled(method); }
811 : 0 : common::SettingsValue getSetting(const std::string& name) override
812 : : {
813 : 0 : return args().GetSetting(name);
814 : : }
815 : 797 : std::vector<common::SettingsValue> getSettingsList(const std::string& name) override
816 : : {
817 : 797 : return args().GetSettingsList(name);
818 : : }
819 : 3 : common::SettingsValue getRwSetting(const std::string& name) override
820 : : {
821 [ + - ]: 3 : common::SettingsValue result;
822 [ + - + - ]: 3 : args().LockSettings([&](const common::Settings& settings) {
823 [ + + ]: 3 : if (const common::SettingsValue* value = common::FindKey(settings.rw_settings, name)) {
824 : 2 : result = *value;
825 : : }
826 : 3 : });
827 : 3 : return result;
828 : 0 : }
829 : 217 : bool updateRwSetting(const std::string& name,
830 : : const interfaces::SettingsUpdate& update_settings_func) override
831 : : {
832 : 217 : std::optional<interfaces::SettingsAction> action;
833 : 217 : args().LockSettings([&](common::Settings& settings) {
834 [ + + ]: 217 : if (auto* value = common::FindKey(settings.rw_settings, name)) {
835 : 55 : action = update_settings_func(*value);
836 [ - + ]: 55 : if (value->isNull()) settings.rw_settings.erase(name);
837 : : } else {
838 [ + - ]: 162 : UniValue new_value;
839 [ + - ]: 162 : action = update_settings_func(new_value);
840 [ + + + - ]: 162 : if (!new_value.isNull()) settings.rw_settings[name] = std::move(new_value);
841 : 162 : }
842 : 217 : });
843 [ + - ]: 217 : if (!action) return false;
844 : : // Now dump value to disk if requested
845 [ + + + + : 217 : return *action != interfaces::SettingsAction::WRITE || (args().GetSettingsPath() && args().WriteSettingsFile());
+ - ]
846 : : }
847 : 2 : bool overwriteRwSetting(const std::string& name, common::SettingsValue value, interfaces::SettingsAction action) override
848 : : {
849 [ + - ]: 2 : return updateRwSetting(name, [&](common::SettingsValue& settings) {
850 : 2 : settings = std::move(value);
851 : 2 : return action;
852 : 2 : });
853 : : }
854 : 0 : bool deleteRwSettings(const std::string& name, interfaces::SettingsAction action) override
855 : : {
856 [ # # ]: 0 : return overwriteRwSetting(name, {}, action);
857 : : }
858 : 1733 : void requestMempoolTransactions(Notifications& notifications) override
859 : : {
860 [ + - ]: 1733 : if (!m_node.mempool) return;
861 [ + - ]: 1733 : LOCK2(::cs_main, m_node.mempool->cs);
862 [ + - + - : 2295 : for (const CTxMemPoolEntry& entry : m_node.mempool->entryAll()) {
+ + ]
863 [ + - + - ]: 1686 : notifications.transactionAddedToMempool(entry.GetSharedTx());
864 [ + - ]: 1733 : }
865 [ + - ]: 3466 : }
866 : 68 : bool hasAssumedValidChain() override
867 : : {
868 : 68 : LOCK(::cs_main);
869 [ + - + - ]: 68 : return bool{chainman().CurrentChainstate().m_from_snapshot_blockhash};
870 : 68 : }
871 : :
872 : 1259 : NodeContext* context() override { return &m_node; }
873 [ - + ]: 1424 : ArgsManager& args() { return *Assert(m_node.args); }
874 [ - + ]: 913294 : ChainstateManager& chainman() { return *Assert(m_node.chainman); }
875 [ - + ]: 2146 : ValidationSignals& validation_signals() { return *Assert(m_node.validation_signals); }
876 : : NodeContext& m_node;
877 : : };
878 : :
879 : : class BlockTemplateImpl : public BlockTemplate
880 : : {
881 : : public:
882 : 130 : explicit BlockTemplateImpl(BlockCreateOptions create_options,
883 : : std::unique_ptr<CBlockTemplate> block_template,
884 : 130 : const NodeContext& node) : m_create_options(std::move(create_options)),
885 [ - + ]: 130 : m_block_template(std::move(block_template)),
886 : 130 : m_node(node)
887 : : {
888 [ - + ]: 130 : assert(m_block_template);
889 : 130 : }
890 : :
891 : 1 : CBlockHeader getBlockHeader() override
892 : : {
893 : 1 : return m_block_template->block;
894 : : }
895 : :
896 : 123 : CBlock getBlock() override
897 : : {
898 : 123 : return m_block_template->block;
899 : : }
900 : :
901 : 0 : std::vector<CAmount> getTxFees() override
902 : : {
903 : 0 : return m_block_template->vTxFees;
904 : : }
905 : :
906 : 0 : std::vector<int64_t> getTxSigops() override
907 : : {
908 : 0 : return m_block_template->vTxSigOpsCost;
909 : : }
910 : :
911 : 0 : CoinbaseTx getCoinbaseTx() override
912 : : {
913 : 0 : return m_block_template->m_coinbase_tx;
914 : : }
915 : :
916 : 0 : std::vector<uint256> getCoinbaseMerklePath() override
917 : : {
918 : 0 : return TransactionMerklePath(m_block_template->block, 0);
919 : : }
920 : :
921 : 55 : bool submitSolution(uint32_t version, uint32_t timestamp, uint32_t nonce, CTransactionRef coinbase, std::string& reason, std::string& debug) override
922 : : {
923 [ + - ]: 55 : if (!coinbase) return false;
924 [ + - ]: 55 : AddMerkleRootAndCoinbase(m_block_template->block, std::move(coinbase), version, timestamp, nonce);
925 [ + - + - ]: 110 : return block_template_manager().SubmitBlock(std::make_shared<const CBlock>(m_block_template->block), reason, debug);
926 : : }
927 : :
928 : 62 : std::unique_ptr<BlockTemplate> waitNext(BlockWaitOptions options) override
929 : : {
930 : 62 : auto new_template = block_template_manager().WaitAndCreateNewBlock(
931 : 62 : m_block_template, options, m_create_options, m_interrupt_wait);
932 [ + + + - ]: 62 : if (new_template) return std::make_unique<BlockTemplateImpl>(m_create_options, std::move(new_template), m_node);
933 : 4 : return nullptr;
934 : 62 : }
935 : :
936 : 0 : void interruptWait() override
937 : : {
938 : 0 : block_template_manager().InterruptWait(m_interrupt_wait);
939 : 0 : }
940 : :
941 : : const BlockCreateOptions m_create_options;
942 : :
943 : : const std::unique_ptr<CBlockTemplate> m_block_template;
944 : :
945 : : bool m_interrupt_wait{false};
946 [ - + ]: 117 : node::BlockTemplateManager& block_template_manager() { return *Assert(m_node.block_template_manager); }
947 : : const NodeContext& m_node;
948 : : };
949 : :
950 : : class MinerImpl : public Mining
951 : : {
952 : : public:
953 : 6 : explicit MinerImpl(const NodeContext& node) : m_node(node) {}
954 : :
955 : 0 : bool isTestChain() override
956 : : {
957 : 0 : return chainman().GetParams().IsTestChain();
958 : : }
959 : :
960 : 0 : bool isInitialBlockDownload() override
961 : : {
962 : 0 : return chainman().IsInitialBlockDownload();
963 : : }
964 : :
965 : 110 : std::optional<BlockRef> getTip() override
966 : : {
967 : 110 : return block_template_manager().GetTip();
968 : : }
969 : :
970 : 133 : std::optional<BlockRef> waitTipChanged(uint256 current_tip, MillisecondsDouble timeout) override
971 : : {
972 : 133 : return block_template_manager().WaitTipChanged(current_tip, timeout, m_interrupt_mining);
973 : : }
974 : :
975 : 78 : std::unique_ptr<BlockTemplate> createNewBlock(const BlockCreateOptions& options, bool cooldown) override
976 : : {
977 : : // Ensure m_tip_block is set so consumers of BlockTemplate can rely on that.
978 : 78 : std::optional<BlockRef> maybe_tip{waitTipChanged(uint256::ZERO, MillisecondsDouble::max())};
979 : :
980 [ - + ]: 78 : if (!maybe_tip) return {};
981 : :
982 [ - + ]: 78 : if (cooldown) {
983 : : // Do not return a template during IBD, because it can have long
984 : : // pauses and sometimes takes a while to get started. Although this
985 : : // is useful in general, it's gated behind the cooldown argument,
986 : : // because on regtest and single miner signets this would wait
987 : : // forever if no block was mined in the past day.
988 [ # # ]: 0 : while (chainman().IsInitialBlockDownload()) {
989 : 0 : maybe_tip = waitTipChanged(maybe_tip->hash, MillisecondsDouble{1000});
990 [ # # # # : 0 : if (!maybe_tip || chainman().m_interrupt || WITH_LOCK(notifications().m_tip_block_mutex, return m_interrupt_mining)) return {};
# # # # #
# ]
991 : : }
992 : :
993 : : // Also wait during the final catch-up moments after IBD.
994 [ # # ]: 0 : if (!block_template_manager().CooldownIfHeadersAhead(*maybe_tip, m_interrupt_mining)) return {};
995 : : }
996 : 78 : auto new_template = block_template_manager().CreateNewTemplate(options);
997 [ + - ]: 72 : return std::make_unique<BlockTemplateImpl>(options, std::move(new_template), m_node);
998 : 72 : }
999 : :
1000 : 0 : void interrupt() override
1001 : : {
1002 : 0 : block_template_manager().InterruptWait(m_interrupt_mining);
1003 : 0 : }
1004 : :
1005 : 3 : bool checkBlock(const CBlock& block, const node::BlockCheckOptions& options, std::string& reason, std::string& debug) override
1006 : : {
1007 : 3 : LOCK(chainman().GetMutex());
1008 [ + - + - : 3 : BlockValidationState state{TestBlockValidity(chainman().ActiveChainstate(), block, /*check_pow=*/options.check_pow, /*check_merkle_root=*/options.check_merkle_root)};
+ - ]
1009 [ - + ]: 6 : reason = state.GetRejectReason();
1010 [ - + ]: 6 : debug = state.GetDebugMessage();
1011 : 3 : return state.IsValid();
1012 [ + - ]: 6 : }
1013 : :
1014 : 110 : bool submitBlock(const CBlock& block_in, std::string& reason, std::string& debug) override
1015 : : {
1016 [ + - + - ]: 220 : return block_template_manager().SubmitBlock(std::make_shared<const CBlock>(block_in), reason, debug);
1017 : : }
1018 : :
1019 : 1 : std::vector<CTransactionRef> getTransactionsByTxID(const std::vector<Txid>& txids) override
1020 : : {
1021 [ - + ]: 1 : if (!m_node.mempool) return {};
1022 : :
1023 : 1 : std::vector<CTransactionRef> results;
1024 [ - + + - ]: 1 : results.reserve(txids.size());
1025 [ + - ]: 1 : LOCK(m_node.mempool->cs);
1026 [ + + ]: 3 : for (const auto& txid : txids) {
1027 [ + - + - ]: 4 : results.emplace_back(m_node.mempool->get(txid));
1028 : : }
1029 [ + - ]: 1 : return results;
1030 : 1 : }
1031 : :
1032 : 1 : std::vector<CTransactionRef> getTransactionsByWitnessID(const std::vector<Wtxid>& wtxids) override
1033 : : {
1034 [ - + ]: 1 : if (!m_node.mempool) return {};
1035 : :
1036 : 1 : std::vector<CTransactionRef> results;
1037 [ - + + - ]: 1 : results.reserve(wtxids.size());
1038 [ + - ]: 1 : LOCK(m_node.mempool->cs);
1039 [ + + ]: 3 : for (const auto& wtxid : wtxids) {
1040 [ + - + - ]: 4 : results.emplace_back(m_node.mempool->get(wtxid));
1041 : : }
1042 [ + - ]: 1 : return results;
1043 : 1 : }
1044 : :
1045 : 0 : const NodeContext* context() override { return &m_node; }
1046 [ - + ]: 6 : ChainstateManager& chainman() { return *Assert(m_node.chainman); }
1047 [ # # ]: 0 : KernelNotifications& notifications() { return *Assert(m_node.notifications); }
1048 [ - + ]: 431 : node::BlockTemplateManager& block_template_manager() { return *Assert(m_node.block_template_manager); }
1049 : : // Treat as if guarded by notifications().m_tip_block_mutex
1050 : : bool m_interrupt_mining{false};
1051 : : const NodeContext& m_node;
1052 : : };
1053 : :
1054 : : class RpcImpl : public Rpc
1055 : : {
1056 : : public:
1057 : 4 : explicit RpcImpl(NodeContext& node) : m_node(node) {}
1058 : :
1059 : 4 : UniValue executeRpc(UniValue request, std::string uri, std::string user) override
1060 : : {
1061 : 4 : JSONRPCRequest req;
1062 : 4 : req.context = &m_node;
1063 : 4 : req.URI = std::move(uri);
1064 : 4 : req.authUser = std::move(user);
1065 : 4 : HTTPStatusCode status;
1066 [ + - ]: 8 : return ExecuteHTTPRPC(request, req, status);
1067 : 4 : }
1068 : :
1069 : : NodeContext& m_node;
1070 : : };
1071 : : } // namespace
1072 : : } // namespace node
1073 : :
1074 : : namespace interfaces {
1075 : 0 : std::unique_ptr<Node> MakeNode(node::NodeContext& context) { return std::make_unique<node::NodeImpl>(context); }
1076 : 2191 : std::unique_ptr<Chain> MakeChain(node::NodeContext& context) { return std::make_unique<node::ChainImpl>(context); }
1077 : 6 : std::unique_ptr<Mining> MakeMining(const node::NodeContext& context, bool wait_loaded)
1078 : : {
1079 [ - + ]: 6 : if (wait_loaded) {
1080 [ # # # # ]: 0 : node::KernelNotifications& kernel_notifications(*Assert(context.notifications));
1081 [ # # ]: 0 : util::SignalInterrupt& interrupt(*Assert(context.shutdown_signal));
1082 : 0 : WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
1083 [ # # ]: 0 : kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
1084 [ # # # # ]: 0 : return kernel_notifications.m_state.chainstate_loaded || interrupt;
1085 : : });
1086 [ # # # # : 0 : if (interrupt) return nullptr;
# # ]
1087 : 0 : }
1088 : 6 : return std::make_unique<node::MinerImpl>(context);
1089 : : }
1090 : 4 : std::unique_ptr<Rpc> MakeRpc(node::NodeContext& context) { return std::make_unique<node::RpcImpl>(context); }
1091 : : } // namespace interfaces
|