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