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, CFeeRate max_tx_fee_rate, std::string& err_string) override
376 : : {
377 [ # # # # ]: 0 : return BroadcastTransaction(*m_context, std::move(tx), err_string, max_tx_fee, max_tx_fee_rate, /*broadcast_method=*/TxBroadcast::MEMPOOL_AND_BROADCAST_TO_ALL, /*wait_callback=*/false);
378 : : }
379 : 0 : WalletLoader& walletLoader() override
380 : : {
381 [ # # ]: 0 : return *Assert(m_context->wallet_loader);
382 : : }
383 : 0 : std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
384 : : {
385 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.InitMessage.connect(fn));
386 : : }
387 : 0 : std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
388 : : {
389 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.ThreadSafeMessageBox.connect(fn));
390 : : }
391 : 0 : std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
392 : : {
393 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.ThreadSafeQuestion.connect(fn));
394 : : }
395 : 0 : std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
396 : : {
397 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.ShowProgress.connect(fn));
398 : : }
399 : 0 : std::unique_ptr<Handler> handleInitWallet(InitWalletFn fn) override
400 : : {
401 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.InitWallet.connect(fn));
402 : : }
403 : 0 : std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
404 : : {
405 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.NotifyNumConnectionsChanged.connect(fn));
406 : : }
407 : 0 : std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
408 : : {
409 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.NotifyNetworkActiveChanged.connect(fn));
410 : : }
411 : 0 : std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
412 : : {
413 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.NotifyAlertChanged.connect(fn));
414 : : }
415 : 0 : std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
416 : : {
417 [ # # ]: 0 : return MakeSignalHandler(::uiInterface.BannedListChanged.connect(fn));
418 : : }
419 : 0 : std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
420 : : {
421 [ # # # # ]: 0 : return MakeSignalHandler(::uiInterface.NotifyBlockTip.connect([fn](SynchronizationState sync_state, const CBlockIndex& block, double verification_progress) {
422 : 0 : fn(sync_state, BlockTip{block.nHeight, block.GetBlockTime(), block.GetBlockHash()}, verification_progress);
423 [ # # ]: 0 : }));
424 : : }
425 : 0 : std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
426 : : {
427 : 0 : return MakeSignalHandler(
428 [ # # # # ]: 0 : ::uiInterface.NotifyHeaderTip.connect([fn](SynchronizationState sync_state, int64_t height, int64_t timestamp, bool presync) {
429 : 0 : fn(sync_state, BlockTip{(int)height, timestamp, uint256{}}, presync);
430 [ # # ]: 0 : }));
431 : : }
432 : 0 : NodeContext* context() override { return m_context; }
433 : 0 : void setContext(NodeContext* context) override
434 : : {
435 : 0 : m_context = context;
436 : 0 : }
437 [ # # # # ]: 0 : ArgsManager& args() { return *Assert(Assert(m_context)->args); }
438 [ # # ]: 0 : ChainstateManager& chainman() { return *Assert(m_context->chainman); }
439 : : NodeContext* m_context{nullptr};
440 : : };
441 : :
442 : : // NOLINTNEXTLINE(misc-no-recursion)
443 : 298206 : bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active, const BlockManager& blockman) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
444 : : {
445 [ + + ]: 298206 : if (!index) return false;
446 [ + + ]: 297101 : if (block.m_hash) *block.m_hash = index->GetBlockHash();
447 [ + + ]: 297101 : if (block.m_height) *block.m_height = index->nHeight;
448 [ + + ]: 297101 : if (block.m_time) *block.m_time = index->GetBlockTime();
449 [ + + ]: 297101 : if (block.m_max_time) *block.m_max_time = index->GetBlockTimeMax();
450 [ + + ]: 297101 : if (block.m_mtp_time) *block.m_mtp_time = index->GetMedianTimePast();
451 [ + + + - ]: 471723 : if (block.m_in_active_chain) *block.m_in_active_chain = active[index->nHeight] == index;
452 [ + + ]: 297101 : if (block.m_locator) { *block.m_locator = GetLocator(index); }
453 [ + + + - : 461020 : if (block.m_next_block) FillBlock(active[index->nHeight] == index ? active[index->nHeight + 1] : nullptr, *block.m_next_block, lock, active, blockman);
+ + + - ]
454 [ + + ]: 297101 : if (block.m_data) {
455 : 81417 : REVERSE_LOCK(lock, cs_main);
456 [ + - + + ]: 81417 : if (!blockman.ReadBlock(*block.m_data, *index)) block.m_data->SetNull();
457 : 81417 : }
458 : 297101 : block.found = true;
459 : 297101 : return true;
460 : : }
461 : :
462 : : class NotificationsProxy : public CValidationInterface
463 : : {
464 : : public:
465 : 1049 : explicit NotificationsProxy(std::shared_ptr<Chain::Notifications> notifications)
466 : 1049 : : m_notifications(std::move(notifications)) {}
467 [ + - ]: 1049 : virtual ~NotificationsProxy() = default;
468 : 7902 : void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t mempool_sequence) override
469 : : {
470 : 7902 : m_notifications->transactionAddedToMempool(tx.info.m_tx);
471 : 7902 : }
472 : 319 : void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
473 : : {
474 : 319 : m_notifications->transactionRemovedFromMempool(tx, reason);
475 : 319 : }
476 : 80677 : void BlockConnected(const ChainstateRole& role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
477 : : {
478 : 80677 : m_notifications->blockConnected(role, kernel::MakeBlockInfo(index, block.get()));
479 : 80677 : }
480 : 3460 : void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
481 : : {
482 : 3460 : m_notifications->blockDisconnected(kernel::MakeBlockInfo(index, block.get()));
483 : 3460 : }
484 : 78491 : void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override
485 : : {
486 : 78491 : m_notifications->updatedBlockTip();
487 : 78491 : }
488 : 100 : void ChainStateFlushed(const ChainstateRole& role, const CBlockLocator& locator) override
489 : : {
490 : 100 : m_notifications->chainStateFlushed(role, locator);
491 : 100 : }
492 : : std::shared_ptr<Chain::Notifications> m_notifications;
493 : : };
494 : :
495 : : class NotificationsHandlerImpl : public Handler
496 : : {
497 : : public:
498 : 1049 : explicit NotificationsHandlerImpl(ValidationSignals& signals, std::shared_ptr<Chain::Notifications> notifications)
499 [ + - ]: 1049 : : m_signals{signals}, m_proxy{std::make_shared<NotificationsProxy>(std::move(notifications))}
500 : : {
501 [ + - + - ]: 2098 : m_signals.RegisterSharedValidationInterface(m_proxy);
502 [ - - ]: 1049 : }
503 [ - + ]: 2098 : ~NotificationsHandlerImpl() override { disconnect(); }
504 : 2062 : void disconnect() override
505 : : {
506 [ + + ]: 2062 : if (m_proxy) {
507 [ + - + - ]: 2098 : m_signals.UnregisterSharedValidationInterface(m_proxy);
508 : 1049 : m_proxy.reset();
509 : : }
510 : 2062 : }
511 : : ValidationSignals& m_signals;
512 : : std::shared_ptr<NotificationsProxy> m_proxy;
513 : : };
514 : :
515 : : class RpcHandlerImpl : public Handler
516 : : {
517 : : public:
518 [ + - ]: 27360 : explicit RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command)
519 : : {
520 : 49694 : m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
521 [ + - ]: 22334 : if (!m_wrapped_command) return false;
522 : 22334 : try {
523 [ + + ]: 22334 : return m_wrapped_command->actor(request, result, last_handler);
524 [ - + ]: 789 : } catch (const UniValue& e) {
525 : : // If this is not the last handler and a wallet not found
526 : : // exception was thrown, return false so the next handler can
527 : : // try to handle the request. Otherwise, reraise the exception.
528 [ - + ]: 789 : if (!last_handler) {
529 [ - - - - ]: 0 : const UniValue& code = e["code"];
530 [ - - - - : 0 : if (code.isNum() && code.getInt<int>() == RPC_WALLET_NOT_FOUND) {
- - ]
531 : 0 : return false;
532 : : }
533 : : }
534 : 789 : throw;
535 : 789 : }
536 : 27360 : };
537 [ + - ]: 27360 : ::tableRPC.appendCommand(m_command.name, &m_command);
538 : 27360 : }
539 : :
540 : 27360 : void disconnect() final
541 : : {
542 [ + - ]: 27360 : if (m_wrapped_command) {
543 : 27360 : m_wrapped_command = nullptr;
544 : 27360 : ::tableRPC.removeCommand(m_command.name, &m_command);
545 : : }
546 : 27360 : }
547 : :
548 : 54720 : ~RpcHandlerImpl() override { disconnect(); }
549 : :
550 : : CRPCCommand m_command;
551 : : const CRPCCommand* m_wrapped_command;
552 : : };
553 : :
554 : : class ChainImpl : public Chain
555 : : {
556 : : public:
557 : 2202 : explicit ChainImpl(NodeContext& node) : m_node(node) {}
558 : 2716 : std::optional<int> getHeight() override
559 : : {
560 [ + - + - : 8148 : const int height{WITH_LOCK(::cs_main, return chainman().ActiveChain().Height())};
- + + - ]
561 [ + + ]: 2716 : return height >= 0 ? std::optional{height} : std::nullopt;
562 : : }
563 : 2860 : uint256 getBlockHash(int height) override
564 : : {
565 : 2860 : LOCK(::cs_main);
566 [ + - + - : 5720 : return Assert(chainman().ActiveChain()[height])->GetBlockHash();
+ - - + +
- ]
567 : 2860 : }
568 : 2663 : bool haveBlockOnDisk(int height) override
569 : : {
570 : 2663 : LOCK(::cs_main);
571 [ + - + - : 2673 : const CBlockIndex* block{chainman().ActiveChain()[height]};
+ - ]
572 [ + - + + : 2673 : return block && ((block->nStatus & BLOCK_HAVE_DATA) != 0) && block->nTx > 0;
- + + - ]
573 : 2663 : }
574 : 1029 : std::optional<int> findLocatorFork(const CBlockLocator& locator) override
575 : : {
576 : 1029 : LOCK(::cs_main);
577 [ + - + - : 1029 : if (const CBlockIndex* fork = chainman().ActiveChainstate().FindForkInGlobalIndex(locator)) {
+ - + + ]
578 : 1024 : return fork->nHeight;
579 : : }
580 : 5 : return std::nullopt;
581 : 1029 : }
582 : 734 : bool hasBlockFilterIndex(BlockFilterType filter_type) override
583 : : {
584 : 734 : return GetBlockFilterIndex(filter_type) != nullptr;
585 : : }
586 : 720 : std::optional<bool> blockFilterMatchesAny(BlockFilterType filter_type, const uint256& block_hash, const GCSFilter::ElementSet& filter_set) override
587 : : {
588 : 720 : const BlockFilterIndex* block_filter_index{GetBlockFilterIndex(filter_type)};
589 [ - + ]: 720 : if (!block_filter_index) return std::nullopt;
590 : :
591 : 720 : BlockFilter filter;
592 [ + - + - : 2160 : const CBlockIndex* index{WITH_LOCK(::cs_main, return chainman().m_blockman.LookupBlockIndex(block_hash))};
+ - + - ]
593 [ + - + - : 720 : if (index == nullptr || !block_filter_index->LookupFilter(index, filter)) return std::nullopt;
+ + ]
594 [ + - ]: 619 : return filter.GetFilter().MatchAny(filter_set);
595 : 720 : }
596 : 215406 : bool findBlock(const uint256& hash, const FoundBlock& block) override
597 : : {
598 : 215406 : WAIT_LOCK(cs_main, lock);
599 [ + - + - : 215406 : return FillBlock(chainman().m_blockman.LookupBlockIndex(hash), block, lock, chainman().ActiveChain(), chainman().m_blockman);
+ - + - +
- + - +
- ]
600 : 215406 : }
601 : 719 : bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block) override
602 : : {
603 : 719 : WAIT_LOCK(cs_main, lock);
604 [ + - + - ]: 719 : const CChain& active = chainman().ActiveChain();
605 [ + - + - : 719 : return FillBlock(active.FindEarliestAtLeast(min_time, min_height), block, lock, active, chainman().m_blockman);
+ - + - ]
606 : 719 : }
607 : 43 : bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out) override
608 : : {
609 : 43 : WAIT_LOCK(cs_main, lock);
610 [ + - + - ]: 43 : const CChain& active = chainman().ActiveChain();
611 [ + - + - : 43 : if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
+ - ]
612 [ + - + + ]: 43 : if (const CBlockIndex* ancestor = block->GetAncestor(ancestor_height)) {
613 [ + - + - ]: 42 : return FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman);
614 : : }
615 : : }
616 [ + - + - ]: 1 : return FillBlock(nullptr, ancestor_out, lock, active, chainman().m_blockman);
617 : 43 : }
618 : 8 : bool findAncestorByHash(const uint256& block_hash, const uint256& ancestor_hash, const FoundBlock& ancestor_out) override
619 : : {
620 : 8 : WAIT_LOCK(cs_main, lock);
621 [ + - + - ]: 8 : const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash);
622 [ + - + - ]: 8 : const CBlockIndex* ancestor = chainman().m_blockman.LookupBlockIndex(ancestor_hash);
623 [ + + + - : 8 : if (block && ancestor && block->GetAncestor(ancestor->nHeight) != ancestor) ancestor = nullptr;
+ + ]
624 [ + - + - : 8 : return FillBlock(ancestor, ancestor_out, lock, chainman().ActiveChain(), chainman().m_blockman);
+ - + - +
- ]
625 : 8 : }
626 : 23 : bool findCommonAncestor(const uint256& block_hash1, const uint256& block_hash2, const FoundBlock& ancestor_out, const FoundBlock& block1_out, const FoundBlock& block2_out) override
627 : : {
628 : 23 : WAIT_LOCK(cs_main, lock);
629 [ + - + - ]: 23 : const CChain& active = chainman().ActiveChain();
630 [ + - + - ]: 23 : const CBlockIndex* block1 = chainman().m_blockman.LookupBlockIndex(block_hash1);
631 [ + - + - ]: 23 : const CBlockIndex* block2 = chainman().m_blockman.LookupBlockIndex(block_hash2);
632 [ + + + - ]: 23 : const CBlockIndex* ancestor = block1 && block2 ? LastCommonAncestor(block1, block2) : nullptr;
633 : : // Using & instead of && below to avoid short circuiting and leaving
634 : : // output uninitialized. Cast bool to int to avoid -Wbitwise-instead-of-logical
635 : : // compiler warnings.
636 [ + - + - ]: 23 : return int{FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman)} &
637 [ + - + - ]: 23 : int{FillBlock(block1, block1_out, lock, active, chainman().m_blockman)} &
638 [ + - + - : 23 : int{FillBlock(block2, block2_out, lock, active, chainman().m_blockman)};
+ - ]
639 : 23 : }
640 : 1056 : void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(m_node, coins); }
641 : 83428 : double guessVerificationProgress(const uint256& block_hash) override
642 : : {
643 : 83428 : LOCK(chainman().GetMutex());
644 [ + - + - : 83428 : return chainman().GuessVerificationProgress(chainman().m_blockman.LookupBlockIndex(block_hash));
+ - + - +
- ]
645 : 83428 : }
646 : 35 : bool hasBlocks(const uint256& block_hash, int min_height, std::optional<int> max_height) override
647 : : {
648 : : // hasBlocks returns true if all ancestors of block_hash in specified
649 : : // range have block data (are not pruned), false if any ancestors in
650 : : // specified range are missing data.
651 : : //
652 : : // For simplicity and robustness, min_height and max_height are only
653 : : // used to limit the range, and passing min_height that's too low or
654 : : // max_height that's too high will not crash or change the result.
655 : 35 : LOCK(::cs_main);
656 [ + - + - : 35 : if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
+ - ]
657 [ + + + + : 35 : if (max_height && block->nHeight >= *max_height) block = block->GetAncestor(*max_height);
+ - ]
658 [ + + ]: 3389 : for (; block->nStatus & BLOCK_HAVE_DATA; block = block->pprev) {
659 : : // Check pprev to not segfault if min_height is too low
660 [ + + + + ]: 3373 : if (block->nHeight <= min_height || !block->pprev) return true;
661 : : }
662 : : }
663 : : return false;
664 : 35 : }
665 : 1 : RBFTransactionState isRBFOptIn(const CTransaction& tx) override
666 : : {
667 [ - + ]: 1 : if (!m_node.mempool) return IsRBFOptInEmptyMempool(tx);
668 : 1 : LOCK(m_node.mempool->cs);
669 [ + - + - ]: 1 : return IsRBFOptIn(tx, *m_node.mempool);
670 : 1 : }
671 : 18046 : bool isInMempool(const Txid& txid) override
672 : : {
673 [ + - ]: 18046 : if (!m_node.mempool) return false;
674 : 18046 : return m_node.mempool->exists(txid);
675 : : }
676 : 245 : bool hasDescendantsInMempool(const Txid& txid) override
677 : : {
678 [ + - ]: 245 : if (!m_node.mempool) return false;
679 : 245 : return m_node.mempool->HasDescendants(txid);
680 : : }
681 : 1869 : bool broadcastTransaction(const CTransactionRef& tx,
682 : : const CAmount& max_tx_fee,
683 : : const CFeeRate& max_tx_fee_rate,
684 : : TxBroadcast broadcast_method,
685 : : std::string& err_string) override
686 : : {
687 [ + - + - : 3738 : const TransactionError err = BroadcastTransaction(m_node, tx, err_string, max_tx_fee, max_tx_fee_rate, broadcast_method, /*wait_callback=*/false);
+ - ]
688 : : // Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures.
689 : : // Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures
690 : : // that Chain clients do not need to know about.
691 : 1869 : return TransactionError::OK == err;
692 : : }
693 : 579910 : void getTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* ancestorsize, CAmount* ancestorfees) override
694 : : {
695 : 579910 : ancestors = cluster_count = 0;
696 [ + - ]: 579910 : if (!m_node.mempool) return;
697 : 579910 : m_node.mempool->GetTransactionAncestry(txid, ancestors, cluster_count, ancestorsize, ancestorfees);
698 : : }
699 : :
700 : 4358 : std::map<COutPoint, CAmount> calculateIndividualBumpFees(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
701 : : {
702 [ - + ]: 4358 : if (!m_node.mempool) {
703 : 0 : std::map<COutPoint, CAmount> bump_fees;
704 [ # # ]: 0 : for (const auto& outpoint : outpoints) {
705 [ # # ]: 0 : bump_fees.emplace(outpoint, 0);
706 : : }
707 : : return bump_fees;
708 : 0 : }
709 [ + - ]: 4358 : return MiniMiner(*m_node.mempool, outpoints).CalculateBumpFees(target_feerate);
710 : : }
711 : :
712 : 9154 : std::optional<CAmount> calculateCombinedBumpFee(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
713 : : {
714 [ - + ]: 9154 : if (!m_node.mempool) {
715 : 0 : return 0;
716 : : }
717 [ + - ]: 9154 : return MiniMiner(*m_node.mempool, outpoints).CalculateTotalBumpFees(target_feerate);
718 : : }
719 : 3386 : void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) override
720 : : {
721 : 3386 : const CTxMemPool::Limits default_limits{};
722 : :
723 [ + - ]: 3386 : const CTxMemPool::Limits& limits{m_node.mempool ? m_node.mempool->m_opts.limits : default_limits};
724 : :
725 : 3386 : limit_ancestor_count = limits.ancestor_count;
726 : 3386 : limit_descendant_count = limits.descendant_count;
727 : 3386 : }
728 : 3647 : util::Result<void> checkChainLimits(const CTransactionRef& tx) override
729 : : {
730 [ - + ]: 3647 : if (!m_node.mempool) return {};
731 [ + + ]: 3647 : if (!m_node.mempool->CheckPolicyLimits(tx)) {
732 [ + - ]: 3 : return util::Error{Untranslated("too many unconfirmed transactions in cluster")};
733 : : }
734 : 3646 : return {};
735 : : }
736 : 6802 : util::Expected<FeeRateEstimation, FeeRateEstimationError> getFeeRateEstimate(int num_blocks, bool conservative) const override
737 : : {
738 [ + + ]: 6802 : if (!m_node.fee_estimator_man) return EstimationError(FeeRateEstimatorType::NONE, /*returned_target=*/0, /*error=*/{});
739 : 6780 : return m_node.fee_estimator_man->GetFeeRateEstimate(num_blocks, conservative);
740 : : }
741 : 3857 : unsigned int maximumFeeEstimationTargetBlocks() const override
742 : : {
743 [ + + ]: 3857 : if (!m_node.fee_estimator_man) return 0;
744 : 3842 : return m_node.fee_estimator_man->MaximumTarget();
745 : : }
746 : 3003 : CFeeRate mempoolMinFee() override
747 : : {
748 [ - + ]: 3003 : if (!m_node.mempool) return {};
749 : 3003 : return m_node.mempool->GetMinFee();
750 : : }
751 : 4865 : CFeeRate relayMinFee() override
752 : : {
753 [ - + ]: 4865 : if (!m_node.mempool) return CFeeRate{DEFAULT_MIN_RELAY_TX_FEE};
754 : 4865 : return m_node.mempool->m_opts.min_relay_feerate;
755 : : }
756 : 129 : CFeeRate relayIncrementalFee() override
757 : : {
758 [ - + ]: 129 : if (!m_node.mempool) return CFeeRate{DEFAULT_INCREMENTAL_RELAY_FEE};
759 : 129 : return m_node.mempool->m_opts.incremental_relay_feerate;
760 : : }
761 : 44572 : CFeeRate relayDustFee() override
762 : : {
763 [ - + ]: 44572 : if (!m_node.mempool) return CFeeRate{DUST_RELAY_TX_FEE};
764 : 44572 : return m_node.mempool->m_opts.dust_relay_feerate;
765 : : }
766 : 84 : bool havePruned() override
767 : : {
768 : 84 : LOCK(::cs_main);
769 [ + - + - ]: 84 : return chainman().m_blockman.m_have_pruned;
770 : 84 : }
771 : 1 : std::optional<int> getPruneHeight() override
772 : : {
773 : 1 : LOCK(chainman().GetMutex());
774 [ + - + - : 1 : return GetPruneHeight(chainman().m_blockman, chainman().ActiveChain());
+ - + - ]
775 : 1 : }
776 [ + - + + ]: 106 : bool isReadyToBroadcast() override { return !chainman().m_blockman.LoadingBlocks() && !isInitialBlockDownload(); }
777 : 3233 : bool isInitialBlockDownload() override
778 : : {
779 : 3233 : return chainman().IsInitialBlockDownload();
780 : : }
781 : 82697 : bool shutdownRequested() override { return ShutdownRequested(m_node); }
782 : 1514 : void initMessage(const std::string& message) override { ::uiInterface.InitMessage(message); }
783 : 7 : void initWarning(const bilingual_str& message) override { InitWarning(message); }
784 : 26 : void initError(const bilingual_str& message) override { InitError(message); }
785 : 0 : void showProgress(const std::string& title, int progress, bool resume_possible) override
786 : : {
787 : 0 : ::uiInterface.ShowProgress(title, progress, resume_possible);
788 : 0 : }
789 : 1049 : std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) override
790 : : {
791 : 1049 : return std::make_unique<NotificationsHandlerImpl>(validation_signals(), std::move(notifications));
792 : : }
793 : 6978 : void waitForNotificationsIfTipChanged(const uint256& old_tip) override
794 : : {
795 [ + + + + : 34836 : if (!old_tip.IsNull() && old_tip == WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()->GetBlockHash())) return;
+ - + - -
+ + - ]
796 : 104 : validation_signals().SyncWithValidationInterfaceQueue();
797 : : }
798 : 1013 : void waitForNotifications() override
799 : : {
800 : 1013 : validation_signals().SyncWithValidationInterfaceQueue();
801 : 1013 : }
802 : 27360 : std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) override
803 : : {
804 : 27360 : return std::make_unique<RpcHandlerImpl>(command);
805 : : }
806 : 4133 : bool rpcEnableDeprecated(const std::string& method) override { return IsDeprecatedRPCEnabled(method); }
807 : 0 : common::SettingsValue getSetting(const std::string& name) override
808 : : {
809 : 0 : return args().GetSetting(name);
810 : : }
811 : 819 : std::vector<common::SettingsValue> getSettingsList(const std::string& name) override
812 : : {
813 : 819 : return args().GetSettingsList(name);
814 : : }
815 : 3 : common::SettingsValue getRwSetting(const std::string& name) override
816 : : {
817 [ + - ]: 3 : common::SettingsValue result;
818 [ + - + - ]: 3 : args().LockSettings([&](const common::Settings& settings) {
819 [ + + ]: 3 : if (const common::SettingsValue* value = common::FindKey(settings.rw_settings, name)) {
820 : 2 : result = *value;
821 : : }
822 : 3 : });
823 : 3 : return result;
824 : 0 : }
825 : 219 : bool updateRwSetting(const std::string& name,
826 : : const interfaces::SettingsUpdate& update_settings_func) override
827 : : {
828 : 219 : std::optional<interfaces::SettingsAction> action;
829 : 219 : args().LockSettings([&](common::Settings& settings) {
830 [ + + ]: 219 : if (auto* value = common::FindKey(settings.rw_settings, name)) {
831 : 57 : action = update_settings_func(*value);
832 [ - + ]: 57 : if (value->isNull()) settings.rw_settings.erase(name);
833 : : } else {
834 [ + - ]: 162 : UniValue new_value;
835 [ + - ]: 162 : action = update_settings_func(new_value);
836 [ + + + - ]: 162 : if (!new_value.isNull()) settings.rw_settings[name] = std::move(new_value);
837 : 162 : }
838 : 219 : });
839 [ + - ]: 219 : if (!action) return false;
840 : : // Now dump value to disk if requested
841 [ + + + + : 219 : return *action != interfaces::SettingsAction::WRITE || (args().GetSettingsPath() && args().WriteSettingsFile());
+ - ]
842 : : }
843 : 2 : bool overwriteRwSetting(const std::string& name, common::SettingsValue value, interfaces::SettingsAction action) override
844 : : {
845 [ + - ]: 2 : return updateRwSetting(name, [&](common::SettingsValue& settings) {
846 : 2 : settings = std::move(value);
847 : 2 : return action;
848 : 2 : });
849 : : }
850 : 0 : bool deleteRwSettings(const std::string& name, interfaces::SettingsAction action) override
851 : : {
852 [ # # ]: 0 : return overwriteRwSetting(name, {}, action);
853 : : }
854 : 1751 : void requestMempoolTransactions(Notifications& notifications) override
855 : : {
856 [ + - ]: 1751 : if (!m_node.mempool) return;
857 [ + - ]: 1751 : LOCK2(::cs_main, m_node.mempool->cs);
858 [ + - + - : 2299 : for (const CTxMemPoolEntry& entry : m_node.mempool->entryAll()) {
+ + ]
859 [ + - + - ]: 1644 : notifications.transactionAddedToMempool(entry.GetSharedTx());
860 [ + - ]: 1751 : }
861 [ + - ]: 3502 : }
862 : 68 : bool hasAssumedValidChain() override
863 : : {
864 : 68 : LOCK(::cs_main);
865 [ + - + - ]: 68 : return bool{chainman().CurrentChainstate().m_from_snapshot_blockhash};
866 : 68 : }
867 : :
868 : 1260 : NodeContext* context() override { return &m_node; }
869 [ - + ]: 1452 : ArgsManager& args() { return *Assert(m_node.args); }
870 [ - + ]: 918716 : ChainstateManager& chainman() { return *Assert(m_node.chainman); }
871 [ - + ]: 2166 : ValidationSignals& validation_signals() { return *Assert(m_node.validation_signals); }
872 : : NodeContext& m_node;
873 : : };
874 : :
875 : : class BlockTemplateImpl : public BlockTemplate
876 : : {
877 : : public:
878 : 130 : explicit BlockTemplateImpl(BlockCreateOptions create_options,
879 : : std::unique_ptr<CBlockTemplate> block_template,
880 : 130 : const NodeContext& node) : m_create_options(std::move(create_options)),
881 [ - + ]: 130 : m_block_template(std::move(block_template)),
882 : 130 : m_node(node)
883 : : {
884 [ - + ]: 130 : assert(m_block_template);
885 : 130 : }
886 : :
887 : 1 : CBlockHeader getBlockHeader() override
888 : : {
889 : 1 : return m_block_template->block;
890 : : }
891 : :
892 : 123 : CBlock getBlock() override
893 : : {
894 : 123 : return m_block_template->block;
895 : : }
896 : :
897 : 0 : std::vector<CAmount> getTxFees() override
898 : : {
899 : 0 : return m_block_template->vTxFees;
900 : : }
901 : :
902 : 0 : std::vector<int64_t> getTxSigops() override
903 : : {
904 : 0 : return m_block_template->vTxSigOpsCost;
905 : : }
906 : :
907 : 0 : CoinbaseTx getCoinbaseTx() override
908 : : {
909 : 0 : return m_block_template->m_coinbase_tx;
910 : : }
911 : :
912 : 0 : std::vector<uint256> getCoinbaseMerklePath() override
913 : : {
914 : 0 : return TransactionMerklePath(m_block_template->block, 0);
915 : : }
916 : :
917 : 55 : bool submitSolution(uint32_t version, uint32_t timestamp, uint32_t nonce, CTransactionRef coinbase, std::string& reason, std::string& debug) override
918 : : {
919 [ + - ]: 55 : if (!coinbase) return false;
920 [ + - ]: 55 : AddMerkleRootAndCoinbase(m_block_template->block, std::move(coinbase), version, timestamp, nonce);
921 [ + - + - ]: 110 : return block_template_manager().SubmitBlock(std::make_shared<const CBlock>(m_block_template->block), reason, debug);
922 : : }
923 : :
924 : 62 : std::unique_ptr<BlockTemplate> waitNext(BlockWaitOptions options) override
925 : : {
926 : 62 : auto new_template = block_template_manager().WaitAndCreateNewBlock(
927 : 62 : m_block_template, options, m_create_options, m_interrupt_wait);
928 [ + + + - ]: 62 : if (new_template) return std::make_unique<BlockTemplateImpl>(m_create_options, std::move(new_template), m_node);
929 : 4 : return nullptr;
930 : 62 : }
931 : :
932 : 0 : void interruptWait() override
933 : : {
934 : 0 : block_template_manager().InterruptWait(m_interrupt_wait);
935 : 0 : }
936 : :
937 : : const BlockCreateOptions m_create_options;
938 : :
939 : : const std::unique_ptr<CBlockTemplate> m_block_template;
940 : :
941 : : bool m_interrupt_wait{false};
942 [ - + ]: 117 : node::BlockTemplateManager& block_template_manager() { return *Assert(m_node.block_template_manager); }
943 : : const NodeContext& m_node;
944 : : };
945 : :
946 : : class MinerImpl : public Mining
947 : : {
948 : : public:
949 : 6 : explicit MinerImpl(const NodeContext& node) : m_node(node) {}
950 : :
951 : 0 : bool isTestChain() override
952 : : {
953 : 0 : return chainman().GetParams().IsTestChain();
954 : : }
955 : :
956 : 0 : bool isInitialBlockDownload() override
957 : : {
958 : 0 : return chainman().IsInitialBlockDownload();
959 : : }
960 : :
961 : 110 : std::optional<BlockRef> getTip() override
962 : : {
963 : 110 : return block_template_manager().GetTip();
964 : : }
965 : :
966 : 133 : std::optional<BlockRef> waitTipChanged(uint256 current_tip, MillisecondsDouble timeout) override
967 : : {
968 : 133 : return block_template_manager().WaitTipChanged(current_tip, timeout, m_interrupt_mining);
969 : : }
970 : :
971 : 78 : std::unique_ptr<BlockTemplate> createNewBlock(const BlockCreateOptions& options, bool cooldown) override
972 : : {
973 : : // Ensure m_tip_block is set so consumers of BlockTemplate can rely on that.
974 : 78 : std::optional<BlockRef> maybe_tip{waitTipChanged(uint256::ZERO, MillisecondsDouble::max())};
975 : :
976 [ - + ]: 78 : if (!maybe_tip) return {};
977 : :
978 [ - + ]: 78 : if (cooldown) {
979 : : // Do not return a template during IBD, because it can have long
980 : : // pauses and sometimes takes a while to get started. Although this
981 : : // is useful in general, it's gated behind the cooldown argument,
982 : : // because on regtest and single miner signets this would wait
983 : : // forever if no block was mined in the past day.
984 [ # # ]: 0 : while (chainman().IsInitialBlockDownload()) {
985 : 0 : maybe_tip = waitTipChanged(maybe_tip->hash, MillisecondsDouble{1000});
986 [ # # # # : 0 : if (!maybe_tip || chainman().m_interrupt || WITH_LOCK(notifications().m_tip_block_mutex, return m_interrupt_mining)) return {};
# # # # #
# ]
987 : : }
988 : :
989 : : // Also wait during the final catch-up moments after IBD.
990 [ # # ]: 0 : if (!block_template_manager().CooldownIfHeadersAhead(*maybe_tip, m_interrupt_mining)) return {};
991 : : }
992 : 78 : auto new_template = block_template_manager().CreateNewTemplate(options);
993 [ + - ]: 72 : return std::make_unique<BlockTemplateImpl>(options, std::move(new_template), m_node);
994 : 72 : }
995 : :
996 : 0 : void interrupt() override
997 : : {
998 : 0 : block_template_manager().InterruptWait(m_interrupt_mining);
999 : 0 : }
1000 : :
1001 : 3 : bool checkBlock(const CBlock& block, const node::BlockCheckOptions& options, std::string& reason, std::string& debug) override
1002 : : {
1003 : 3 : LOCK(chainman().GetMutex());
1004 [ + - + - : 3 : BlockValidationState state{TestBlockValidity(chainman().ActiveChainstate(), block, /*check_pow=*/options.check_pow, /*check_merkle_root=*/options.check_merkle_root)};
+ - ]
1005 [ - + ]: 6 : reason = state.GetRejectReason();
1006 [ - + ]: 6 : debug = state.GetDebugMessage();
1007 : 3 : return state.IsValid();
1008 [ + - ]: 6 : }
1009 : :
1010 : 110 : bool submitBlock(const CBlock& block_in, std::string& reason, std::string& debug) override
1011 : : {
1012 [ + - + - ]: 220 : return block_template_manager().SubmitBlock(std::make_shared<const CBlock>(block_in), reason, debug);
1013 : : }
1014 : :
1015 : 1 : std::vector<CTransactionRef> getTransactionsByTxID(const std::vector<Txid>& txids) override
1016 : : {
1017 [ - + ]: 1 : if (!m_node.mempool) return {};
1018 : :
1019 : 1 : std::vector<CTransactionRef> results;
1020 [ - + + - ]: 1 : results.reserve(txids.size());
1021 [ + - ]: 1 : LOCK(m_node.mempool->cs);
1022 [ + + ]: 3 : for (const auto& txid : txids) {
1023 [ + - + - ]: 4 : results.emplace_back(m_node.mempool->get(txid));
1024 : : }
1025 [ + - ]: 1 : return results;
1026 : 1 : }
1027 : :
1028 : 1 : std::vector<CTransactionRef> getTransactionsByWitnessID(const std::vector<Wtxid>& wtxids) override
1029 : : {
1030 [ - + ]: 1 : if (!m_node.mempool) return {};
1031 : :
1032 : 1 : std::vector<CTransactionRef> results;
1033 [ - + + - ]: 1 : results.reserve(wtxids.size());
1034 [ + - ]: 1 : LOCK(m_node.mempool->cs);
1035 [ + + ]: 3 : for (const auto& wtxid : wtxids) {
1036 [ + - + - ]: 4 : results.emplace_back(m_node.mempool->get(wtxid));
1037 : : }
1038 [ + - ]: 1 : return results;
1039 : 1 : }
1040 : :
1041 : 0 : const NodeContext* context() override { return &m_node; }
1042 [ - + ]: 6 : ChainstateManager& chainman() { return *Assert(m_node.chainman); }
1043 [ # # ]: 0 : KernelNotifications& notifications() { return *Assert(m_node.notifications); }
1044 [ - + ]: 431 : node::BlockTemplateManager& block_template_manager() { return *Assert(m_node.block_template_manager); }
1045 : : // Treat as if guarded by notifications().m_tip_block_mutex
1046 : : bool m_interrupt_mining{false};
1047 : : const NodeContext& m_node;
1048 : : };
1049 : :
1050 : : class RpcImpl : public Rpc
1051 : : {
1052 : : public:
1053 : 4 : explicit RpcImpl(NodeContext& node) : m_node(node) {}
1054 : :
1055 : 4 : UniValue executeRpc(UniValue request, std::string uri, std::string user) override
1056 : : {
1057 : 4 : JSONRPCRequest req;
1058 : 4 : req.context = &m_node;
1059 : 4 : req.URI = std::move(uri);
1060 : 4 : req.authUser = std::move(user);
1061 : 4 : HTTPStatusCode status;
1062 [ + - ]: 8 : return ExecuteHTTPRPC(request, req, status);
1063 : 4 : }
1064 : :
1065 : : NodeContext& m_node;
1066 : : };
1067 : : } // namespace
1068 : : } // namespace node
1069 : :
1070 : : namespace interfaces {
1071 : 0 : std::unique_ptr<Node> MakeNode(node::NodeContext& context) { return std::make_unique<node::NodeImpl>(context); }
1072 : 2202 : std::unique_ptr<Chain> MakeChain(node::NodeContext& context) { return std::make_unique<node::ChainImpl>(context); }
1073 : 6 : std::unique_ptr<Mining> MakeMining(const node::NodeContext& context, bool wait_loaded)
1074 : : {
1075 [ - + ]: 6 : if (wait_loaded) {
1076 [ # # # # ]: 0 : node::KernelNotifications& kernel_notifications(*Assert(context.notifications));
1077 [ # # ]: 0 : util::SignalInterrupt& interrupt(*Assert(context.shutdown_signal));
1078 : 0 : WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
1079 [ # # ]: 0 : kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
1080 [ # # # # ]: 0 : return kernel_notifications.m_state.chainstate_loaded || interrupt;
1081 : : });
1082 [ # # # # : 0 : if (interrupt) return nullptr;
# # ]
1083 : 0 : }
1084 : 6 : return std::make_unique<node::MinerImpl>(context);
1085 : : }
1086 : 4 : std::unique_ptr<Rpc> MakeRpc(node::NodeContext& context) { return std::make_unique<node::RpcImpl>(context); }
1087 : : } // namespace interfaces
|