Branch data Line data Source code
1 : : // Copyright (c) 2018-2022 The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #include <addrdb.h>
6 : : #include <banman.h>
7 : : #include <blockfilter.h>
8 : : #include <chain.h>
9 : : #include <chainparams.h>
10 : : #include <common/args.h>
11 : : #include <consensus/merkle.h>
12 : : #include <consensus/validation.h>
13 : : #include <deploymentstatus.h>
14 : : #include <external_signer.h>
15 : : #include <index/blockfilterindex.h>
16 : : #include <init.h>
17 : : #include <interfaces/chain.h>
18 : : #include <interfaces/handler.h>
19 : : #include <interfaces/mining.h>
20 : : #include <interfaces/node.h>
21 : : #include <interfaces/types.h>
22 : : #include <interfaces/wallet.h>
23 : : #include <kernel/chain.h>
24 : : #include <kernel/context.h>
25 : : #include <kernel/mempool_entry.h>
26 : : #include <logging.h>
27 : : #include <mapport.h>
28 : : #include <net.h>
29 : : #include <net_processing.h>
30 : : #include <netaddress.h>
31 : : #include <netbase.h>
32 : : #include <node/blockstorage.h>
33 : : #include <node/coin.h>
34 : : #include <node/context.h>
35 : : #include <node/interface_ui.h>
36 : : #include <node/mini_miner.h>
37 : : #include <node/miner.h>
38 : : #include <node/kernel_notifications.h>
39 : : #include <node/transaction.h>
40 : : #include <node/types.h>
41 : : #include <node/warnings.h>
42 : : #include <policy/feerate.h>
43 : : #include <policy/fees.h>
44 : : #include <policy/policy.h>
45 : : #include <policy/rbf.h>
46 : : #include <policy/settings.h>
47 : : #include <primitives/block.h>
48 : : #include <primitives/transaction.h>
49 : : #include <rpc/blockchain.h>
50 : : #include <rpc/protocol.h>
51 : : #include <rpc/server.h>
52 : : #include <support/allocators/secure.h>
53 : : #include <sync.h>
54 : : #include <txmempool.h>
55 : : #include <uint256.h>
56 : : #include <univalue.h>
57 : : #include <util/check.h>
58 : : #include <util/result.h>
59 : : #include <util/signalinterrupt.h>
60 : : #include <util/string.h>
61 : : #include <util/translation.h>
62 : : #include <validation.h>
63 : : #include <validationinterface.h>
64 : :
65 : : #include <bitcoin-build-config.h> // IWYU pragma: keep
66 : :
67 : : #include <any>
68 : : #include <memory>
69 : : #include <optional>
70 : : #include <utility>
71 : :
72 : : #include <boost/signals2/signal.hpp>
73 : :
74 : : using interfaces::BlockRef;
75 : : using interfaces::BlockTemplate;
76 : : using interfaces::BlockTip;
77 : : using interfaces::Chain;
78 : : using interfaces::FoundBlock;
79 : : using interfaces::Handler;
80 : : using interfaces::MakeSignalHandler;
81 : : using interfaces::Mining;
82 : : using interfaces::Node;
83 : : using interfaces::WalletLoader;
84 : : using node::BlockAssembler;
85 : : using util::Join;
86 : :
87 : : namespace node {
88 : : // All members of the classes in this namespace are intentionally public, as the
89 : : // classes themselves are private.
90 : : namespace {
91 : : #ifdef ENABLE_EXTERNAL_SIGNER
92 : : class ExternalSignerImpl : public interfaces::ExternalSigner
93 : : {
94 : : public:
95 : 0 : ExternalSignerImpl(::ExternalSigner signer) : m_signer(std::move(signer)) {}
96 : 0 : std::string getName() override { return m_signer.m_name; }
97 : : ::ExternalSigner m_signer;
98 : : };
99 : : #endif
100 : :
101 : : class NodeImpl : public Node
102 : : {
103 : : public:
104 : 0 : explicit NodeImpl(NodeContext& context) { setContext(&context); }
105 : 0 : void initLogging() override { InitLogging(args()); }
106 : 0 : void initParameterInteraction() override { InitParameterInteraction(args()); }
107 [ # # # # : 0 : bilingual_str getWarnings() override { return Join(Assert(m_context->warnings)->GetMessages(), Untranslated("<hr />")); }
# # # # ]
108 : 0 : int getExitStatus() override { return Assert(m_context)->exit_status.load(); }
109 : 0 : BCLog::CategoryMask getLogCategories() override { return LogInstance().GetCategoryMask(); }
110 : 0 : bool baseInitialize() override
111 : : {
112 [ # # ]: 0 : if (!AppInitBasicSetup(args(), Assert(context())->exit_status)) return false;
113 [ # # ]: 0 : if (!AppInitParameterInteraction(args())) return false;
114 : :
115 : 0 : m_context->warnings = std::make_unique<node::Warnings>();
116 : 0 : m_context->kernel = std::make_unique<kernel::Context>();
117 : 0 : m_context->ecc_context = std::make_unique<ECC_Context>();
118 [ # # ]: 0 : if (!AppInitSanityChecks(*m_context->kernel)) return false;
119 : :
120 [ # # ]: 0 : if (!AppInitLockDirectories()) return false;
121 [ # # ]: 0 : if (!AppInitInterfaces(*m_context)) return false;
122 : :
123 : : return true;
124 : : }
125 : 0 : bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info) override
126 : : {
127 [ # # ]: 0 : if (AppInitMain(*m_context, tip_info)) return true;
128 : : // Error during initialization, set exit status before continue
129 : 0 : m_context->exit_status.store(EXIT_FAILURE);
130 : 0 : return false;
131 : : }
132 : 0 : void appShutdown() override
133 : : {
134 : 0 : Interrupt(*m_context);
135 : 0 : Shutdown(*m_context);
136 : 0 : }
137 : 0 : void startShutdown() override
138 : : {
139 : 0 : NodeContext& ctx{*Assert(m_context)};
140 [ # # ]: 0 : if (!(Assert(ctx.shutdown_request))()) {
141 : 0 : LogError("Failed to send shutdown signal\n");
142 : : }
143 : :
144 : : // Stop RPC for clean shutdown if any of waitfor* commands is executed.
145 [ # # # # ]: 0 : if (args().GetBoolArg("-server", false)) {
146 : 0 : InterruptRPC();
147 : 0 : StopRPC();
148 : : }
149 : 0 : }
150 : 0 : bool shutdownRequested() override { return ShutdownRequested(*Assert(m_context)); };
151 : 0 : bool isSettingIgnored(const std::string& name) override
152 : : {
153 : 0 : bool ignored = false;
154 : 0 : args().LockSettings([&](common::Settings& settings) {
155 [ # # ]: 0 : if (auto* options = common::FindKey(settings.command_line_options, name)) {
156 : 0 : ignored = !options->empty();
157 : : }
158 : 0 : });
159 : 0 : return ignored;
160 : : }
161 : 0 : common::SettingsValue getPersistentSetting(const std::string& name) override { return args().GetPersistentSetting(name); }
162 : 0 : void updateRwSetting(const std::string& name, const common::SettingsValue& value) override
163 : : {
164 : 0 : args().LockSettings([&](common::Settings& settings) {
165 [ # # ]: 0 : if (value.isNull()) {
166 : 0 : settings.rw_settings.erase(name);
167 : : } else {
168 : 0 : settings.rw_settings[name] = value;
169 : : }
170 : 0 : });
171 : 0 : args().WriteSettingsFile();
172 : 0 : }
173 : 0 : void forceSetting(const std::string& name, const common::SettingsValue& value) override
174 : : {
175 : 0 : args().LockSettings([&](common::Settings& settings) {
176 [ # # ]: 0 : if (value.isNull()) {
177 : 0 : settings.forced_settings.erase(name);
178 : : } else {
179 : 0 : settings.forced_settings[name] = value;
180 : : }
181 : 0 : });
182 : 0 : }
183 : 0 : void resetSettings() override
184 : : {
185 : 0 : args().WriteSettingsFile(/*errors=*/nullptr, /*backup=*/true);
186 : 0 : args().LockSettings([&](common::Settings& settings) {
187 [ # # ]: 0 : settings.rw_settings.clear();
188 : : });
189 : 0 : args().WriteSettingsFile();
190 : 0 : }
191 : 0 : void mapPort(bool enable) override { StartMapPort(enable); }
192 : 0 : bool getProxy(Network net, Proxy& proxy_info) override { return GetProxy(net, proxy_info); }
193 : 0 : size_t getNodeCount(ConnectionDirection flags) override
194 : : {
195 [ # # ]: 0 : return m_context->connman ? m_context->connman->GetNodeCount(flags) : 0;
196 : : }
197 : 0 : bool getNodesStats(NodesStats& stats) override
198 : : {
199 : 0 : stats.clear();
200 : :
201 [ # # ]: 0 : if (m_context->connman) {
202 : 0 : std::vector<CNodeStats> stats_temp;
203 [ # # ]: 0 : m_context->connman->GetNodeStats(stats_temp);
204 : :
205 [ # # ]: 0 : stats.reserve(stats_temp.size());
206 [ # # ]: 0 : for (auto& node_stats_temp : stats_temp) {
207 [ # # ]: 0 : stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats());
208 : : }
209 : :
210 : : // Try to retrieve the CNodeStateStats for each node.
211 [ # # ]: 0 : if (m_context->peerman) {
212 [ # # ]: 0 : TRY_LOCK(::cs_main, lockMain);
213 [ # # ]: 0 : if (lockMain) {
214 [ # # ]: 0 : for (auto& node_stats : stats) {
215 : 0 : std::get<1>(node_stats) =
216 [ # # ]: 0 : m_context->peerman->GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats));
217 : : }
218 : : }
219 : 0 : }
220 : 0 : return true;
221 : 0 : }
222 : : return false;
223 : : }
224 : 0 : bool getBanned(banmap_t& banmap) override
225 : : {
226 [ # # ]: 0 : if (m_context->banman) {
227 : 0 : m_context->banman->GetBanned(banmap);
228 : 0 : return true;
229 : : }
230 : : return false;
231 : : }
232 : 0 : bool ban(const CNetAddr& net_addr, int64_t ban_time_offset) override
233 : : {
234 [ # # ]: 0 : if (m_context->banman) {
235 : 0 : m_context->banman->Ban(net_addr, ban_time_offset);
236 : 0 : return true;
237 : : }
238 : : return false;
239 : : }
240 : 0 : bool unban(const CSubNet& ip) override
241 : : {
242 [ # # ]: 0 : if (m_context->banman) {
243 : 0 : m_context->banman->Unban(ip);
244 : 0 : return true;
245 : : }
246 : : return false;
247 : : }
248 : 0 : bool disconnectByAddress(const CNetAddr& net_addr) override
249 : : {
250 [ # # ]: 0 : if (m_context->connman) {
251 : 0 : return m_context->connman->DisconnectNode(net_addr);
252 : : }
253 : : return false;
254 : : }
255 : 0 : bool disconnectById(NodeId id) override
256 : : {
257 [ # # ]: 0 : if (m_context->connman) {
258 : 0 : return m_context->connman->DisconnectNode(id);
259 : : }
260 : : return false;
261 : : }
262 : 0 : std::vector<std::unique_ptr<interfaces::ExternalSigner>> listExternalSigners() override
263 : : {
264 : : #ifdef ENABLE_EXTERNAL_SIGNER
265 : 0 : std::vector<ExternalSigner> signers = {};
266 [ # # # # : 0 : const std::string command = args().GetArg("-signer", "");
# # # # ]
267 [ # # ]: 0 : if (command == "") return {};
268 [ # # # # : 0 : ExternalSigner::Enumerate(command, signers, Params().GetChainTypeString());
# # ]
269 : 0 : std::vector<std::unique_ptr<interfaces::ExternalSigner>> result;
270 [ # # ]: 0 : result.reserve(signers.size());
271 [ # # ]: 0 : for (auto& signer : signers) {
272 [ # # # # ]: 0 : result.emplace_back(std::make_unique<ExternalSignerImpl>(std::move(signer)));
273 : : }
274 : 0 : return result;
275 : : #else
276 : : // This result is indistinguishable from a successful call that returns
277 : : // no signers. For the current GUI this doesn't matter, because the wallet
278 : : // creation dialog disables the external signer checkbox in both
279 : : // cases. The return type could be changed to std::optional<std::vector>
280 : : // (or something that also includes error messages) if this distinction
281 : : // becomes important.
282 : : return {};
283 : : #endif // ENABLE_EXTERNAL_SIGNER
284 : 0 : }
285 [ # # ]: 0 : int64_t getTotalBytesRecv() override { return m_context->connman ? m_context->connman->GetTotalBytesRecv() : 0; }
286 [ # # ]: 0 : int64_t getTotalBytesSent() override { return m_context->connman ? m_context->connman->GetTotalBytesSent() : 0; }
287 [ # # ]: 0 : size_t getMempoolSize() override { return m_context->mempool ? m_context->mempool->size() : 0; }
288 [ # # ]: 0 : size_t getMempoolDynamicUsage() override { return m_context->mempool ? m_context->mempool->DynamicMemoryUsage() : 0; }
289 [ # # ]: 0 : size_t getMempoolMaxUsage() override { return m_context->mempool ? m_context->mempool->m_opts.max_size_bytes : 0; }
290 : 0 : bool getHeaderTip(int& height, int64_t& block_time) override
291 : : {
292 : 0 : LOCK(::cs_main);
293 [ # # ]: 0 : auto best_header = chainman().m_best_header;
294 [ # # ]: 0 : if (best_header) {
295 : 0 : height = best_header->nHeight;
296 : 0 : block_time = best_header->GetBlockTime();
297 : 0 : return true;
298 : : }
299 : : return false;
300 : 0 : }
301 : 0 : std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() override
302 : : {
303 [ # # ]: 0 : if (m_context->connman)
304 : 0 : return m_context->connman->getNetLocalAddresses();
305 : : else
306 : 0 : return {};
307 : : }
308 : 0 : int getNumBlocks() override
309 : : {
310 : 0 : LOCK(::cs_main);
311 [ # # # # : 0 : return chainman().ActiveChain().Height();
# # ]
312 : 0 : }
313 : 0 : uint256 getBestBlockHash() override
314 : : {
315 [ # # # # : 0 : const CBlockIndex* tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip());
# # # # ]
316 [ # # ]: 0 : return tip ? tip->GetBlockHash() : chainman().GetParams().GenesisBlock().GetHash();
317 : : }
318 : 0 : int64_t getLastBlockTime() override
319 : : {
320 : 0 : LOCK(::cs_main);
321 [ # # # # : 0 : if (chainman().ActiveChain().Tip()) {
# # # # ]
322 [ # # # # : 0 : return chainman().ActiveChain().Tip()->GetBlockTime();
# # ]
323 : : }
324 [ # # ]: 0 : return chainman().GetParams().GenesisBlock().GetBlockTime(); // Genesis block's time of current network
325 : 0 : }
326 : 0 : double getVerificationProgress() override
327 : : {
328 [ # # # # : 0 : return chainman().GuessVerificationProgress(WITH_LOCK(chainman().GetMutex(), return chainman().ActiveChain().Tip()));
# # # # ]
329 : : }
330 : 0 : bool isInitialBlockDownload() override
331 : : {
332 : 0 : return chainman().IsInitialBlockDownload();
333 : : }
334 : 0 : bool isLoadingBlocks() override { return chainman().m_blockman.LoadingBlocks(); }
335 : 0 : void setNetworkActive(bool active) override
336 : : {
337 [ # # ]: 0 : if (m_context->connman) {
338 : 0 : m_context->connman->SetNetworkActive(active);
339 : : }
340 : 0 : }
341 [ # # # # ]: 0 : bool getNetworkActive() override { return m_context->connman && m_context->connman->GetNetworkActive(); }
342 : 0 : CFeeRate getDustRelayFee() override
343 : : {
344 [ # # ]: 0 : if (!m_context->mempool) return CFeeRate{DUST_RELAY_TX_FEE};
345 : 0 : return m_context->mempool->m_opts.dust_relay_feerate;
346 : : }
347 : 0 : UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override
348 : : {
349 : 0 : JSONRPCRequest req;
350 : 0 : req.context = m_context;
351 [ # # ]: 0 : req.params = params;
352 [ # # ]: 0 : req.strMethod = command;
353 [ # # ]: 0 : req.URI = uri;
354 [ # # ]: 0 : return ::tableRPC.execute(req);
355 : 0 : }
356 : 0 : std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); }
357 : 0 : void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); }
358 : 0 : void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); }
359 : 0 : std::optional<Coin> getUnspentOutput(const COutPoint& output) override
360 : : {
361 : 0 : LOCK(::cs_main);
362 [ # # # # : 0 : return chainman().ActiveChainstate().CoinsTip().GetCoin(output);
# # # # ]
363 : 0 : }
364 : 0 : TransactionError broadcastTransaction(CTransactionRef tx, CAmount max_tx_fee, std::string& err_string) override
365 : : {
366 [ # # # # ]: 0 : return BroadcastTransaction(*m_context, std::move(tx), err_string, max_tx_fee, /*relay=*/ true, /*wait_callback=*/ false);
367 : : }
368 : 0 : WalletLoader& walletLoader() override
369 : : {
370 : 0 : return *Assert(m_context->wallet_loader);
371 : : }
372 : 0 : std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override
373 : : {
374 [ # # # # ]: 0 : return MakeSignalHandler(::uiInterface.InitMessage_connect(fn));
375 : : }
376 : 0 : std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override
377 : : {
378 [ # # # # ]: 0 : return MakeSignalHandler(::uiInterface.ThreadSafeMessageBox_connect(fn));
379 : : }
380 : 0 : std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override
381 : : {
382 [ # # # # ]: 0 : return MakeSignalHandler(::uiInterface.ThreadSafeQuestion_connect(fn));
383 : : }
384 : 0 : std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override
385 : : {
386 [ # # # # ]: 0 : return MakeSignalHandler(::uiInterface.ShowProgress_connect(fn));
387 : : }
388 : 0 : std::unique_ptr<Handler> handleInitWallet(InitWalletFn fn) override
389 : : {
390 [ # # # # ]: 0 : return MakeSignalHandler(::uiInterface.InitWallet_connect(fn));
391 : : }
392 : 0 : std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override
393 : : {
394 [ # # # # ]: 0 : return MakeSignalHandler(::uiInterface.NotifyNumConnectionsChanged_connect(fn));
395 : : }
396 : 0 : std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override
397 : : {
398 [ # # # # ]: 0 : return MakeSignalHandler(::uiInterface.NotifyNetworkActiveChanged_connect(fn));
399 : : }
400 : 0 : std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override
401 : : {
402 [ # # # # ]: 0 : return MakeSignalHandler(::uiInterface.NotifyAlertChanged_connect(fn));
403 : : }
404 : 0 : std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override
405 : : {
406 [ # # # # ]: 0 : return MakeSignalHandler(::uiInterface.BannedListChanged_connect(fn));
407 : : }
408 : 0 : std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override
409 : : {
410 [ # # # # : 0 : return MakeSignalHandler(::uiInterface.NotifyBlockTip_connect([fn, this](SynchronizationState sync_state, const CBlockIndex* block) {
# # ]
411 : 0 : fn(sync_state, BlockTip{block->nHeight, block->GetBlockTime(), block->GetBlockHash()},
412 : 0 : chainman().GuessVerificationProgress(block));
413 [ # # ]: 0 : }));
414 : : }
415 : 0 : std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override
416 : : {
417 : 0 : return MakeSignalHandler(
418 [ # # # # : 0 : ::uiInterface.NotifyHeaderTip_connect([fn](SynchronizationState sync_state, int64_t height, int64_t timestamp, bool presync) {
# # ]
419 : 0 : fn(sync_state, BlockTip{(int)height, timestamp, uint256{}}, presync);
420 [ # # ]: 0 : }));
421 : : }
422 : 0 : NodeContext* context() override { return m_context; }
423 : 0 : void setContext(NodeContext* context) override
424 : : {
425 : 0 : m_context = context;
426 : 0 : }
427 : 0 : ArgsManager& args() { return *Assert(Assert(m_context)->args); }
428 : 0 : ChainstateManager& chainman() { return *Assert(m_context->chainman); }
429 : : NodeContext* m_context{nullptr};
430 : : };
431 : :
432 : : // NOLINTNEXTLINE(misc-no-recursion)
433 : 248580 : bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active, const BlockManager& blockman)
434 : : {
435 [ + + ]: 248580 : if (!index) return false;
436 [ + + ]: 247394 : if (block.m_hash) *block.m_hash = index->GetBlockHash();
437 [ + + ]: 247394 : if (block.m_height) *block.m_height = index->nHeight;
438 [ + + ]: 247394 : if (block.m_time) *block.m_time = index->GetBlockTime();
439 [ + + ]: 247394 : if (block.m_max_time) *block.m_max_time = index->GetBlockTimeMax();
440 [ + + ]: 247394 : if (block.m_mtp_time) *block.m_mtp_time = index->GetMedianTimePast();
441 [ + + + - ]: 401141 : if (block.m_in_active_chain) *block.m_in_active_chain = active[index->nHeight] == index;
442 [ + + ]: 247394 : if (block.m_locator) { *block.m_locator = GetLocator(index); }
443 [ + + + - : 395026 : if (block.m_next_block) FillBlock(active[index->nHeight] == index ? active[index->nHeight + 1] : nullptr, *block.m_next_block, lock, active, blockman);
+ - + - ]
444 [ + + ]: 247394 : if (block.m_data) {
445 : 73274 : REVERSE_LOCK(lock);
446 [ + - + + ]: 73274 : if (!blockman.ReadBlock(*block.m_data, *index)) block.m_data->SetNull();
447 : 73274 : }
448 : 247394 : block.found = true;
449 : 247394 : return true;
450 : : }
451 : :
452 : : class NotificationsProxy : public CValidationInterface
453 : : {
454 : : public:
455 : 791 : explicit NotificationsProxy(std::shared_ptr<Chain::Notifications> notifications)
456 : 791 : : m_notifications(std::move(notifications)) {}
457 [ + - ]: 791 : virtual ~NotificationsProxy() = default;
458 : 4933 : void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t mempool_sequence) override
459 : : {
460 : 4933 : m_notifications->transactionAddedToMempool(tx.info.m_tx);
461 : 4933 : }
462 : 230 : void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
463 : : {
464 : 230 : m_notifications->transactionRemovedFromMempool(tx, reason);
465 : 230 : }
466 : 39487 : void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
467 : : {
468 : 39487 : m_notifications->blockConnected(role, kernel::MakeBlockInfo(index, block.get()));
469 : 39487 : }
470 : 2821 : void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override
471 : : {
472 : 2821 : m_notifications->blockDisconnected(kernel::MakeBlockInfo(index, block.get()));
473 : 2821 : }
474 : 37863 : void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override
475 : : {
476 : 37863 : m_notifications->updatedBlockTip();
477 : 37863 : }
478 : 530 : void ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) override {
479 : 530 : m_notifications->chainStateFlushed(role, locator);
480 : 530 : }
481 : : std::shared_ptr<Chain::Notifications> m_notifications;
482 : : };
483 : :
484 : : class NotificationsHandlerImpl : public Handler
485 : : {
486 : : public:
487 : 791 : explicit NotificationsHandlerImpl(ValidationSignals& signals, std::shared_ptr<Chain::Notifications> notifications)
488 [ + - ]: 791 : : m_signals{signals}, m_proxy{std::make_shared<NotificationsProxy>(std::move(notifications))}
489 : : {
490 [ + - + - ]: 1582 : m_signals.RegisterSharedValidationInterface(m_proxy);
491 [ - - ]: 791 : }
492 [ - + ]: 1582 : ~NotificationsHandlerImpl() override { disconnect(); }
493 : 791 : void disconnect() override
494 : : {
495 [ + - ]: 791 : if (m_proxy) {
496 [ + - + - ]: 1582 : m_signals.UnregisterSharedValidationInterface(m_proxy);
497 : 791 : m_proxy.reset();
498 : : }
499 : 791 : }
500 : : ValidationSignals& m_signals;
501 : : std::shared_ptr<NotificationsProxy> m_proxy;
502 : : };
503 : :
504 : : class RpcHandlerImpl : public Handler
505 : : {
506 : : public:
507 [ + - ]: 27876 : explicit RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command)
508 : : {
509 : 46909 : m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) {
510 [ + - ]: 19033 : if (!m_wrapped_command) return false;
511 : 19033 : try {
512 [ + + ]: 19033 : return m_wrapped_command->actor(request, result, last_handler);
513 [ - + ]: 661 : } catch (const UniValue& e) {
514 : : // If this is not the last handler and a wallet not found
515 : : // exception was thrown, return false so the next handler can
516 : : // try to handle the request. Otherwise, reraise the exception.
517 [ - + ]: 661 : if (!last_handler) {
518 [ - - - - ]: 0 : const UniValue& code = e["code"];
519 [ - - - - : 0 : if (code.isNum() && code.getInt<int>() == RPC_WALLET_NOT_FOUND) {
- - ]
520 : 0 : return false;
521 : : }
522 : : }
523 : 661 : throw;
524 : 661 : }
525 : 27876 : };
526 [ + - ]: 27876 : ::tableRPC.appendCommand(m_command.name, &m_command);
527 : 27876 : }
528 : :
529 : 27876 : void disconnect() final
530 : : {
531 [ + - ]: 27876 : if (m_wrapped_command) {
532 : 27876 : m_wrapped_command = nullptr;
533 : 27876 : ::tableRPC.removeCommand(m_command.name, &m_command);
534 : : }
535 : 27876 : }
536 : :
537 : 55752 : ~RpcHandlerImpl() override { disconnect(); }
538 : :
539 : : CRPCCommand m_command;
540 : : const CRPCCommand* m_wrapped_command;
541 : : };
542 : :
543 : : class ChainImpl : public Chain
544 : : {
545 : : public:
546 : 1771 : explicit ChainImpl(NodeContext& node) : m_node(node) {}
547 : 1545 : std::optional<int> getHeight() override
548 : : {
549 [ + - + - : 4635 : const int height{WITH_LOCK(::cs_main, return chainman().ActiveChain().Height())};
+ - ]
550 [ + + ]: 1545 : return height >= 0 ? std::optional{height} : std::nullopt;
551 : : }
552 : 1630 : uint256 getBlockHash(int height) override
553 : : {
554 : 1630 : LOCK(::cs_main);
555 [ + - + - : 3260 : return Assert(chainman().ActiveChain()[height])->GetBlockHash();
+ - + - +
- ]
556 : 1630 : }
557 : 705 : bool haveBlockOnDisk(int height) override
558 : : {
559 : 705 : LOCK(::cs_main);
560 [ + - + - : 706 : const CBlockIndex* block{chainman().ActiveChain()[height]};
+ - ]
561 [ + - + + : 706 : return block && ((block->nStatus & BLOCK_HAVE_DATA) != 0) && block->nTx > 0;
- + + - ]
562 : 705 : }
563 : 549 : CBlockLocator getTipLocator() override
564 : : {
565 : 549 : LOCK(::cs_main);
566 [ + - + - : 549 : return chainman().ActiveChain().GetLocator();
+ - ]
567 : 549 : }
568 : 2 : CBlockLocator getActiveChainLocator(const uint256& block_hash) override
569 : : {
570 : 2 : LOCK(::cs_main);
571 [ + - + - ]: 2 : const CBlockIndex* index = chainman().m_blockman.LookupBlockIndex(block_hash);
572 [ + - ]: 2 : return GetLocator(index);
573 : 2 : }
574 : 772 : std::optional<int> findLocatorFork(const CBlockLocator& locator) override
575 : : {
576 : 772 : LOCK(::cs_main);
577 [ + - + - : 772 : if (const CBlockIndex* fork = chainman().ActiveChainstate().FindForkInGlobalIndex(locator)) {
+ - + + ]
578 : 764 : return fork->nHeight;
579 : : }
580 : 8 : return std::nullopt;
581 : 772 : }
582 : 646 : bool hasBlockFilterIndex(BlockFilterType filter_type) override
583 : : {
584 : 646 : return GetBlockFilterIndex(filter_type) != nullptr;
585 : : }
586 : 616 : std::optional<bool> blockFilterMatchesAny(BlockFilterType filter_type, const uint256& block_hash, const GCSFilter::ElementSet& filter_set) override
587 : : {
588 : 616 : const BlockFilterIndex* block_filter_index{GetBlockFilterIndex(filter_type)};
589 [ - + ]: 616 : if (!block_filter_index) return std::nullopt;
590 : :
591 : 616 : BlockFilter filter;
592 [ + - + - : 1848 : const CBlockIndex* index{WITH_LOCK(::cs_main, return chainman().m_blockman.LookupBlockIndex(block_hash))};
+ - + - ]
593 [ + - + - : 616 : if (index == nullptr || !block_filter_index->LookupFilter(index, filter)) return std::nullopt;
- + ]
594 [ + - ]: 616 : return filter.GetFilter().MatchAny(filter_set);
595 : 616 : }
596 : 174021 : bool findBlock(const uint256& hash, const FoundBlock& block) override
597 : : {
598 : 174021 : WAIT_LOCK(cs_main, lock);
599 [ + - + - : 174021 : return FillBlock(chainman().m_blockman.LookupBlockIndex(hash), block, lock, chainman().ActiveChain(), chainman().m_blockman);
+ - + - +
- + - +
- ]
600 : 174021 : }
601 : 635 : bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block) override
602 : : {
603 : 635 : WAIT_LOCK(cs_main, lock);
604 [ + - + - ]: 635 : const CChain& active = chainman().ActiveChain();
605 [ + - + - : 635 : return FillBlock(active.FindEarliestAtLeast(min_time, min_height), block, lock, active, chainman().m_blockman);
+ - + - ]
606 : 635 : }
607 : 38 : bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out) override
608 : : {
609 : 38 : WAIT_LOCK(cs_main, lock);
610 [ + - + - ]: 38 : const CChain& active = chainman().ActiveChain();
611 [ + - + - : 38 : if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
+ - ]
612 [ + - + + ]: 38 : if (const CBlockIndex* ancestor = block->GetAncestor(ancestor_height)) {
613 [ + - + - ]: 37 : 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 : 38 : }
618 : 7 : bool findAncestorByHash(const uint256& block_hash, const uint256& ancestor_hash, const FoundBlock& ancestor_out) override
619 : : {
620 : 7 : WAIT_LOCK(cs_main, lock);
621 [ + - + - ]: 7 : const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash);
622 [ + - + - ]: 7 : const CBlockIndex* ancestor = chainman().m_blockman.LookupBlockIndex(ancestor_hash);
623 [ + + + - : 7 : if (block && ancestor && block->GetAncestor(ancestor->nHeight) != ancestor) ancestor = nullptr;
+ + ]
624 [ + - + - : 7 : return FillBlock(ancestor, ancestor_out, lock, chainman().ActiveChain(), chainman().m_blockman);
+ - + - +
- ]
625 : 7 : }
626 : 21 : 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 : 21 : WAIT_LOCK(cs_main, lock);
629 [ + - + - ]: 21 : const CChain& active = chainman().ActiveChain();
630 [ + - + - ]: 21 : const CBlockIndex* block1 = chainman().m_blockman.LookupBlockIndex(block_hash1);
631 [ + - + - ]: 21 : const CBlockIndex* block2 = chainman().m_blockman.LookupBlockIndex(block_hash2);
632 [ + + + - ]: 21 : 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 [ + - + - ]: 21 : return int{FillBlock(ancestor, ancestor_out, lock, active, chainman().m_blockman)} &
637 [ + - + - ]: 21 : int{FillBlock(block1, block1_out, lock, active, chainman().m_blockman)} &
638 [ + - + - : 21 : int{FillBlock(block2, block2_out, lock, active, chainman().m_blockman)};
+ - ]
639 : 21 : }
640 : 883 : void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(m_node, coins); }
641 : 74463 : double guessVerificationProgress(const uint256& block_hash) override
642 : : {
643 : 74463 : LOCK(chainman().GetMutex());
644 [ + - + - : 74463 : return chainman().GuessVerificationProgress(chainman().m_blockman.LookupBlockIndex(block_hash));
+ - + - +
- ]
645 : 74463 : }
646 : 33 : 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 : 33 : LOCK(::cs_main);
656 [ + - + - : 33 : if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) {
+ - ]
657 [ + + + + : 33 : if (max_height && block->nHeight >= *max_height) block = block->GetAncestor(*max_height);
+ - ]
658 [ + + ]: 2974 : for (; block->nStatus & BLOCK_HAVE_DATA; block = block->pprev) {
659 : : // Check pprev to not segfault if min_height is too low
660 [ + + + + ]: 2958 : if (block->nHeight <= min_height || !block->pprev) return true;
661 : : }
662 : : }
663 : : return false;
664 : 33 : }
665 : 642 : RBFTransactionState isRBFOptIn(const CTransaction& tx) override
666 : : {
667 [ - + ]: 642 : if (!m_node.mempool) return IsRBFOptInEmptyMempool(tx);
668 : 642 : LOCK(m_node.mempool->cs);
669 [ + - + - ]: 642 : return IsRBFOptIn(tx, *m_node.mempool);
670 : 642 : }
671 : 17804 : bool isInMempool(const uint256& txid) override
672 : : {
673 [ + - ]: 17804 : if (!m_node.mempool) return false;
674 : 17804 : LOCK(m_node.mempool->cs);
675 [ + - + - ]: 17804 : return m_node.mempool->exists(GenTxid::Txid(txid));
676 : 17804 : }
677 : 221 : bool hasDescendantsInMempool(const uint256& txid) override
678 : : {
679 [ + - ]: 221 : if (!m_node.mempool) return false;
680 : 221 : LOCK(m_node.mempool->cs);
681 [ + - ]: 221 : const auto entry{m_node.mempool->GetEntry(Txid::FromUint256(txid))};
682 [ + + ]: 221 : if (entry == nullptr) return false;
683 : 220 : return entry->GetCountWithDescendants() > 1;
684 : 221 : }
685 : 1578 : bool broadcastTransaction(const CTransactionRef& tx,
686 : : const CAmount& max_tx_fee,
687 : : bool relay,
688 : : std::string& err_string) override
689 : : {
690 [ + - + - : 3156 : const TransactionError err = BroadcastTransaction(m_node, tx, err_string, max_tx_fee, relay, /*wait_callback=*/false);
+ - ]
691 : : // Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures.
692 : : // Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures
693 : : // that Chain clients do not need to know about.
694 : 1578 : return TransactionError::OK == err;
695 : : }
696 : 576339 : void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize, CAmount* ancestorfees) override
697 : : {
698 : 576339 : ancestors = descendants = 0;
699 [ + - ]: 576339 : if (!m_node.mempool) return;
700 : 576339 : m_node.mempool->GetTransactionAncestry(txid, ancestors, descendants, ancestorsize, ancestorfees);
701 : : }
702 : :
703 : 3775 : std::map<COutPoint, CAmount> calculateIndividualBumpFees(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
704 : : {
705 [ - + ]: 3775 : if (!m_node.mempool) {
706 : 0 : std::map<COutPoint, CAmount> bump_fees;
707 [ # # ]: 0 : for (const auto& outpoint : outpoints) {
708 [ # # ]: 0 : bump_fees.emplace(outpoint, 0);
709 : : }
710 : : return bump_fees;
711 : 0 : }
712 [ + - ]: 3775 : return MiniMiner(*m_node.mempool, outpoints).CalculateBumpFees(target_feerate);
713 : : }
714 : :
715 : 8660 : std::optional<CAmount> calculateCombinedBumpFee(const std::vector<COutPoint>& outpoints, const CFeeRate& target_feerate) override
716 : : {
717 [ - + ]: 8660 : if (!m_node.mempool) {
718 : 0 : return 0;
719 : : }
720 [ + - ]: 8660 : return MiniMiner(*m_node.mempool, outpoints).CalculateTotalBumpFees(target_feerate);
721 : : }
722 : 3068 : void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) override
723 : : {
724 : 3068 : const CTxMemPool::Limits default_limits{};
725 : :
726 [ + - ]: 3068 : const CTxMemPool::Limits& limits{m_node.mempool ? m_node.mempool->m_opts.limits : default_limits};
727 : :
728 : 3068 : limit_ancestor_count = limits.ancestor_count;
729 : 3068 : limit_descendant_count = limits.descendant_count;
730 : 3068 : }
731 : 3211 : util::Result<void> checkChainLimits(const CTransactionRef& tx) override
732 : : {
733 [ - + ]: 3211 : if (!m_node.mempool) return {};
734 : 3211 : LockPoints lp;
735 : 3211 : CTxMemPoolEntry entry(tx, 0, 0, 0, 0, false, 0, lp);
736 [ + - ]: 3211 : LOCK(m_node.mempool->cs);
737 [ + - + - : 9633 : return m_node.mempool->CheckPackageLimits({tx}, entry.GetTxSize());
+ + + - -
- - - ]
738 [ + - + - ]: 9633 : }
739 : 5832 : CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc) override
740 : : {
741 [ + + ]: 5832 : if (!m_node.fee_estimator) return {};
742 : 5810 : return m_node.fee_estimator->estimateSmartFee(num_blocks, calc, conservative);
743 : : }
744 : 3394 : unsigned int estimateMaxBlocks() override
745 : : {
746 [ + + ]: 3394 : if (!m_node.fee_estimator) return 0;
747 : 3379 : return m_node.fee_estimator->HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
748 : : }
749 : 2491 : CFeeRate mempoolMinFee() override
750 : : {
751 [ - + ]: 2491 : if (!m_node.mempool) return {};
752 : 2491 : return m_node.mempool->GetMinFee();
753 : : }
754 : 4088 : CFeeRate relayMinFee() override
755 : : {
756 [ - + ]: 4088 : if (!m_node.mempool) return CFeeRate{DEFAULT_MIN_RELAY_TX_FEE};
757 : 4088 : return m_node.mempool->m_opts.min_relay_feerate;
758 : : }
759 : 119 : CFeeRate relayIncrementalFee() override
760 : : {
761 [ - + ]: 119 : if (!m_node.mempool) return CFeeRate{DEFAULT_INCREMENTAL_RELAY_FEE};
762 : 119 : return m_node.mempool->m_opts.incremental_relay_feerate;
763 : : }
764 : 43987 : CFeeRate relayDustFee() override
765 : : {
766 [ - + ]: 43987 : if (!m_node.mempool) return CFeeRate{DUST_RELAY_TX_FEE};
767 : 43987 : return m_node.mempool->m_opts.dust_relay_feerate;
768 : : }
769 : 62 : bool havePruned() override
770 : : {
771 : 62 : LOCK(::cs_main);
772 [ + - + - ]: 62 : return chainman().m_blockman.m_have_pruned;
773 : 62 : }
774 : 1 : std::optional<int> getPruneHeight() override
775 : : {
776 : 1 : LOCK(chainman().GetMutex());
777 [ + - + - : 1 : return GetPruneHeight(chainman().m_blockman, chainman().ActiveChain());
+ - + - ]
778 : 1 : }
779 [ + - + + ]: 172 : bool isReadyToBroadcast() override { return !chainman().m_blockman.LoadingBlocks() && !isInitialBlockDownload(); }
780 : 2768 : bool isInitialBlockDownload() override
781 : : {
782 : 2768 : return chainman().IsInitialBlockDownload();
783 : : }
784 : 74261 : bool shutdownRequested() override { return ShutdownRequested(m_node); }
785 : 1208 : void initMessage(const std::string& message) override { ::uiInterface.InitMessage(message); }
786 : 2 : void initWarning(const bilingual_str& message) override { InitWarning(message); }
787 : 26 : void initError(const bilingual_str& message) override { InitError(message); }
788 : 16 : void showProgress(const std::string& title, int progress, bool resume_possible) override
789 : : {
790 : 16 : ::uiInterface.ShowProgress(title, progress, resume_possible);
791 : 16 : }
792 : 791 : std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) override
793 : : {
794 : 791 : return std::make_unique<NotificationsHandlerImpl>(validation_signals(), std::move(notifications));
795 : : }
796 : 5950 : void waitForNotificationsIfTipChanged(const uint256& old_tip) override
797 : : {
798 [ + + + + : 23788 : if (!old_tip.IsNull() && old_tip == WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()->GetBlockHash())) return;
+ - + - +
- + - ]
799 : 333 : validation_signals().SyncWithValidationInterfaceQueue();
800 : : }
801 : 27876 : std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) override
802 : : {
803 : 27876 : return std::make_unique<RpcHandlerImpl>(command);
804 : : }
805 : 1 : bool rpcEnableDeprecated(const std::string& method) override { return IsDeprecatedRPCEnabled(method); }
806 : 44 : void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) override
807 : : {
808 [ + - ]: 44 : RPCRunLater(name, std::move(fn), seconds);
809 : 44 : }
810 : 0 : common::SettingsValue getSetting(const std::string& name) override
811 : : {
812 : 0 : return args().GetSetting(name);
813 : : }
814 : 723 : std::vector<common::SettingsValue> getSettingsList(const std::string& name) override
815 : : {
816 : 723 : return args().GetSettingsList(name);
817 : : }
818 : 3 : common::SettingsValue getRwSetting(const std::string& name) override
819 : : {
820 [ + - ]: 3 : common::SettingsValue result;
821 [ + - + - ]: 3 : args().LockSettings([&](const common::Settings& settings) {
822 [ + + ]: 3 : if (const common::SettingsValue* value = common::FindKey(settings.rw_settings, name)) {
823 : 2 : result = *value;
824 : : }
825 : 3 : });
826 : 3 : return result;
827 : 0 : }
828 : 193 : bool updateRwSetting(const std::string& name,
829 : : const interfaces::SettingsUpdate& update_settings_func) override
830 : : {
831 : 193 : std::optional<interfaces::SettingsAction> action;
832 : 193 : args().LockSettings([&](common::Settings& settings) {
833 [ + + ]: 193 : if (auto* value = common::FindKey(settings.rw_settings, name)) {
834 : 43 : action = update_settings_func(*value);
835 [ - + ]: 43 : if (value->isNull()) settings.rw_settings.erase(name);
836 : : } else {
837 [ + - ]: 150 : UniValue new_value;
838 [ + - ]: 150 : action = update_settings_func(new_value);
839 [ + + + - ]: 150 : if (!new_value.isNull()) settings.rw_settings[name] = std::move(new_value);
840 : 150 : }
841 : 193 : });
842 [ + - ]: 193 : if (!action) return false;
843 : : // Now dump value to disk if requested
844 [ + + + - ]: 193 : return *action != interfaces::SettingsAction::WRITE || args().WriteSettingsFile();
845 : : }
846 : 1 : bool overwriteRwSetting(const std::string& name, common::SettingsValue value, interfaces::SettingsAction action) override
847 : : {
848 [ + - ]: 1 : return updateRwSetting(name, [&](common::SettingsValue& settings) {
849 : 1 : settings = std::move(value);
850 : 1 : return action;
851 : 1 : });
852 : : }
853 : 0 : bool deleteRwSettings(const std::string& name, interfaces::SettingsAction action) override
854 : : {
855 [ # # ]: 0 : return overwriteRwSetting(name, {}, action);
856 : : }
857 : 1419 : void requestMempoolTransactions(Notifications& notifications) override
858 : : {
859 [ + - ]: 1419 : if (!m_node.mempool) return;
860 [ + - ]: 1419 : LOCK2(::cs_main, m_node.mempool->cs);
861 [ + - + - : 1752 : for (const CTxMemPoolEntry& entry : m_node.mempool->entryAll()) {
+ + ]
862 [ + - + - ]: 999 : notifications.transactionAddedToMempool(entry.GetSharedTx());
863 [ + - ]: 1419 : }
864 [ + - ]: 2838 : }
865 : 58 : bool hasAssumedValidChain() override
866 : : {
867 : 58 : return chainman().IsSnapshotActive();
868 : : }
869 : :
870 : 727 : NodeContext* context() override { return &m_node; }
871 : 1105 : ArgsManager& args() { return *Assert(m_node.args); }
872 : 761851 : ChainstateManager& chainman() { return *Assert(m_node.chainman); }
873 : 1124 : ValidationSignals& validation_signals() { return *Assert(m_node.validation_signals); }
874 : : NodeContext& m_node;
875 : : };
876 : :
877 : : class BlockTemplateImpl : public BlockTemplate
878 : : {
879 : : public:
880 [ - + ]: 38319 : explicit BlockTemplateImpl(std::unique_ptr<CBlockTemplate> block_template, NodeContext& node) : m_block_template(std::move(block_template)), m_node(node)
881 : : {
882 [ - + ]: 38319 : assert(m_block_template);
883 : 38319 : }
884 : :
885 : 0 : CBlockHeader getBlockHeader() override
886 : : {
887 : 0 : return m_block_template->block;
888 : : }
889 : :
890 : 40322 : CBlock getBlock() override
891 : : {
892 : 40322 : return m_block_template->block;
893 : : }
894 : :
895 : 2069 : std::vector<CAmount> getTxFees() override
896 : : {
897 : 2069 : return m_block_template->vTxFees;
898 : : }
899 : :
900 : 2069 : std::vector<int64_t> getTxSigops() override
901 : : {
902 : 2069 : return m_block_template->vTxSigOpsCost;
903 : : }
904 : :
905 : 0 : CTransactionRef getCoinbaseTx() override
906 : : {
907 [ # # ]: 0 : return m_block_template->block.vtx[0];
908 : : }
909 : :
910 : 4138 : std::vector<unsigned char> getCoinbaseCommitment() override
911 : : {
912 : 4138 : return m_block_template->vchCoinbaseCommitment;
913 : : }
914 : :
915 : 0 : int getWitnessCommitmentIndex() override
916 : : {
917 : 0 : return GetWitnessCommitmentIndex(m_block_template->block);
918 : : }
919 : :
920 : 0 : std::vector<uint256> getCoinbaseMerklePath() override
921 : : {
922 : 0 : return TransactionMerklePath(m_block_template->block, 0);
923 : : }
924 : :
925 : 55 : bool submitSolution(uint32_t version, uint32_t timestamp, uint32_t nonce, CTransactionRef coinbase) override
926 : : {
927 : 55 : CBlock block{m_block_template->block};
928 : :
929 [ - + ]: 55 : if (block.vtx.size() == 0) {
930 [ # # ]: 0 : block.vtx.push_back(coinbase);
931 : : } else {
932 : 55 : block.vtx[0] = coinbase;
933 : : }
934 : :
935 : 55 : block.nVersion = version;
936 : 55 : block.nTime = timestamp;
937 : 55 : block.nNonce = nonce;
938 : :
939 [ + - ]: 55 : block.hashMerkleRoot = BlockMerkleRoot(block);
940 : :
941 [ + - ]: 55 : auto block_ptr = std::make_shared<const CBlock>(block);
942 [ + - + - : 55 : return chainman().ProcessNewBlock(block_ptr, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/nullptr);
+ - ]
943 : 55 : }
944 : :
945 : : const std::unique_ptr<CBlockTemplate> m_block_template;
946 : :
947 : 55 : ChainstateManager& chainman() { return *Assert(m_node.chainman); }
948 : : NodeContext& m_node;
949 : : };
950 : :
951 : : class MinerImpl : public Mining
952 : : {
953 : : public:
954 : 1043 : explicit MinerImpl(NodeContext& node) : m_node(node) {}
955 : :
956 : 2070 : bool isTestChain() override
957 : : {
958 : 2070 : return chainman().GetParams().IsTestChain();
959 : : }
960 : :
961 : 0 : bool isInitialBlockDownload() override
962 : : {
963 : 0 : return chainman().IsInitialBlockDownload();
964 : : }
965 : :
966 : 2215 : std::optional<BlockRef> getTip() override
967 : : {
968 : 2215 : LOCK(::cs_main);
969 [ + - + - : 2215 : CBlockIndex* tip{chainman().ActiveChain().Tip()};
+ - ]
970 [ - + ]: 2215 : if (!tip) return {};
971 : 2215 : return BlockRef{tip->GetBlockHash(), tip->nHeight};
972 : 2215 : }
973 : :
974 : 130 : BlockRef waitTipChanged(uint256 current_tip, MillisecondsDouble timeout) override
975 : : {
976 [ + + ]: 130 : if (timeout > std::chrono::years{100}) timeout = std::chrono::years{100}; // Upper bound to avoid UB in std::chrono
977 : 130 : {
978 : 130 : WAIT_LOCK(notifications().m_tip_block_mutex, lock);
979 [ + - + - ]: 130 : notifications().m_tip_block_cv.wait_for(lock, timeout, [&]() EXCLUSIVE_LOCKS_REQUIRED(notifications().m_tip_block_mutex) {
980 : : // We need to wait for m_tip_block to be set AND for the value
981 : : // to differ from the current_tip value.
982 [ + - + + : 150 : return (notifications().TipBlock() && notifications().TipBlock() != current_tip) || chainman().m_interrupt;
+ + ]
983 : : });
984 : 0 : }
985 : : // Must release m_tip_block_mutex before locking cs_main, to avoid deadlocks.
986 : 130 : LOCK(::cs_main);
987 [ + - + - : 390 : return BlockRef{chainman().ActiveChain().Tip()->GetBlockHash(), chainman().ActiveChain().Tip()->nHeight};
+ - + - +
- + - +
- ]
988 : 130 : }
989 : :
990 : 38324 : std::unique_ptr<BlockTemplate> createNewBlock(const BlockCreateOptions& options) override
991 : : {
992 [ + - ]: 38324 : BlockAssembler::Options assemble_options{options};
993 [ + - + - ]: 38324 : ApplyArgsManOptions(*Assert(m_node.args), assemble_options);
994 [ + - + - : 38324 : return std::make_unique<BlockTemplateImpl>(BlockAssembler{chainman().ActiveChainstate(), context()->mempool.get(), assemble_options}.CreateNewBlock(), m_node);
+ - + - +
+ + - ]
995 : 38319 : }
996 : :
997 : 38324 : NodeContext* context() override { return &m_node; }
998 : 42899 : ChainstateManager& chainman() { return *Assert(m_node.chainman); }
999 : 560 : KernelNotifications& notifications() { return *Assert(m_node.notifications); }
1000 : : NodeContext& m_node;
1001 : : };
1002 : : } // namespace
1003 : : } // namespace node
1004 : :
1005 : : namespace interfaces {
1006 : 0 : std::unique_ptr<Node> MakeNode(node::NodeContext& context) { return std::make_unique<node::NodeImpl>(context); }
1007 : 1771 : std::unique_ptr<Chain> MakeChain(node::NodeContext& context) { return std::make_unique<node::ChainImpl>(context); }
1008 : 1043 : std::unique_ptr<Mining> MakeMining(node::NodeContext& context) { return std::make_unique<node::MinerImpl>(context); }
1009 : : } // namespace interfaces
|