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