Bitcoin Core 22.99.0
P2P Digital Currency
init.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2020 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#if defined(HAVE_CONFIG_H)
8#endif
9
10#include <init.h>
11
12#include <addrman.h>
13#include <banman.h>
14#include <blockfilter.h>
15#include <chain.h>
16#include <chainparams.h>
17#include <compat/sanity.h>
18#include <consensus/amount.h>
19#include <deploymentstatus.h>
20#include <fs.h>
21#include <hash.h>
22#include <httprpc.h>
23#include <httpserver.h>
26#include <index/txindex.h>
27#include <init/common.h>
28#include <interfaces/chain.h>
29#include <interfaces/init.h>
30#include <interfaces/node.h>
31#include <mapport.h>
32#include <miner.h>
33#include <net.h>
34#include <net_permissions.h>
35#include <net_processing.h>
36#include <netbase.h>
37#include <node/blockstorage.h>
38#include <node/context.h>
39#include <node/ui_interface.h>
40#include <policy/feerate.h>
41#include <policy/fees.h>
42#include <policy/policy.h>
43#include <policy/settings.h>
44#include <protocol.h>
45#include <rpc/blockchain.h>
46#include <rpc/register.h>
47#include <rpc/server.h>
48#include <rpc/util.h>
49#include <scheduler.h>
50#include <script/sigcache.h>
51#include <script/standard.h>
52#include <shutdown.h>
53#include <sync.h>
54#include <timedata.h>
55#include <torcontrol.h>
56#include <txdb.h>
57#include <txmempool.h>
58#include <txorphanage.h>
59#include <util/asmap.h>
60#include <util/check.h>
61#include <util/moneystr.h>
62#include <util/string.h>
64#include <util/system.h>
65#include <util/thread.h>
66#include <util/threadnames.h>
67#include <util/translation.h>
68#include <validation.h>
69#include <validationinterface.h>
70#include <walletinitinterface.h>
71
72#include <functional>
73#include <set>
74#include <stdint.h>
75#include <stdio.h>
76#include <thread>
77#include <vector>
78
79#ifndef WIN32
80#include <attributes.h>
81#include <cerrno>
82#include <signal.h>
83#include <sys/stat.h>
84#endif
85
86#include <boost/algorithm/string/replace.hpp>
87#include <boost/signals2/signal.hpp>
88
89#if ENABLE_ZMQ
92#include <zmq/zmqrpc.h>
93#endif
94
95static const bool DEFAULT_PROXYRANDOMIZE = true;
96static const bool DEFAULT_REST_ENABLE = false;
97
98#ifdef WIN32
99// Win32 LevelDB doesn't use filedescriptors, and the ones used for
100// accessing block files don't count towards the fd_set size limit
101// anyway.
102#define MIN_CORE_FILEDESCRIPTORS 0
103#else
104#define MIN_CORE_FILEDESCRIPTORS 150
105#endif
106
107static const char* DEFAULT_ASMAP_FILENAME="ip_asn.map";
108
112static const char* BITCOIN_PID_FILENAME = "bitcoind.pid";
113
114static fs::path GetPidFile(const ArgsManager& args)
115{
117}
118
119[[nodiscard]] static bool CreatePidFile(const ArgsManager& args)
120{
121 fsbridge::ofstream file{GetPidFile(args)};
122 if (file) {
123#ifdef WIN32
124 tfm::format(file, "%d\n", GetCurrentProcessId());
125#else
126 tfm::format(file, "%d\n", getpid());
127#endif
128 return true;
129 } else {
130 return InitError(strprintf(_("Unable to create the PID file '%s': %s"), fs::PathToString(GetPidFile(args)), std::strerror(errno)));
131 }
132}
133
135//
136// Shutdown
137//
138
139//
140// Thread management and startup/shutdown:
141//
142// The network-processing threads are all part of a thread group
143// created by AppInit() or the Qt main() function.
144//
145// A clean exit happens when StartShutdown() or the SIGTERM
146// signal handler sets ShutdownRequested(), which makes main thread's
147// WaitForShutdown() interrupts the thread group.
148// And then, WaitForShutdown() makes all other on-going threads
149// in the thread group join the main thread.
150// Shutdown() is then called to clean up database connections, and stop other
151// threads that should only be stopped after the main network-processing
152// threads have exited.
153//
154// Shutdown for Qt is very similar, only it uses a QTimer to detect
155// ShutdownRequested() getting set, and then does the normal Qt
156// shutdown thing.
157//
158
160{
163 InterruptRPC();
167 if (node.connman)
168 node.connman->Interrupt();
169 if (g_txindex) {
170 g_txindex->Interrupt();
171 }
172 ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Interrupt(); });
173 if (g_coin_stats_index) {
174 g_coin_stats_index->Interrupt();
175 }
176}
177
179{
180 static Mutex g_shutdown_mutex;
181 TRY_LOCK(g_shutdown_mutex, lock_shutdown);
182 if (!lock_shutdown) return;
183 LogPrintf("%s: In progress...\n", __func__);
184 Assert(node.args);
185
190 util::ThreadRename("shutoff");
191 if (node.mempool) node.mempool->AddTransactionsUpdated(1);
192
193 StopHTTPRPC();
194 StopREST();
195 StopRPC();
197 for (const auto& client : node.chain_clients) {
198 client->flush();
199 }
200 StopMapPort();
201
202 // Because these depend on each-other, we make sure that neither can be
203 // using the other before destroying them.
204 if (node.peerman) UnregisterValidationInterface(node.peerman.get());
205 if (node.connman) node.connman->Stop();
206
208
209 // After everything has been shut down, but before things get flushed, stop the
210 // CScheduler/checkqueue, scheduler and load block thread.
211 if (node.scheduler) node.scheduler->stop();
212 if (node.chainman && node.chainman->m_load_block.joinable()) node.chainman->m_load_block.join();
214
215 // After the threads that potentially access these pointers have been stopped,
216 // destruct and reset all to nullptr.
217 node.peerman.reset();
218 node.connman.reset();
219 node.banman.reset();
220 node.addrman.reset();
221
222 if (node.mempool && node.mempool->IsLoaded() && node.args->GetBoolArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
223 DumpMempool(*node.mempool);
224 }
225
226 // Drop transactions we were still watching, and record fee estimations.
227 if (node.fee_estimator) node.fee_estimator->Flush();
228
229 // FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing
230 if (node.chainman) {
231 LOCK(cs_main);
232 for (CChainState* chainstate : node.chainman->GetAll()) {
233 if (chainstate->CanFlushToDisk()) {
234 chainstate->ForceFlushStateToDisk();
235 }
236 }
237 }
238
239 // After there are no more peers/RPC left to give us new data which may generate
240 // CValidationInterface callbacks, flush them...
242
243 // Stop and delete all indexes only after flushing background callbacks.
244 if (g_txindex) {
245 g_txindex->Stop();
246 g_txindex.reset();
247 }
248 if (g_coin_stats_index) {
249 g_coin_stats_index->Stop();
250 g_coin_stats_index.reset();
251 }
252 ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Stop(); });
254
255 // Any future callbacks will be dropped. This should absolutely be safe - if
256 // missing a callback results in an unrecoverable situation, unclean shutdown
257 // would too. The only reason to do the above flushes is to let the wallet catch
258 // up with our current chain to avoid any strange pruning edge cases and make
259 // next startup faster by avoiding rescan.
260
261 if (node.chainman) {
262 LOCK(cs_main);
263 for (CChainState* chainstate : node.chainman->GetAll()) {
264 if (chainstate->CanFlushToDisk()) {
265 chainstate->ForceFlushStateToDisk();
266 chainstate->ResetCoinsViews();
267 }
268 }
269 }
270 for (const auto& client : node.chain_clients) {
271 client->stop();
272 }
273
274#if ENABLE_ZMQ
279 }
280#endif
281
282 node.chain_clients.clear();
286 node.mempool.reset();
287 node.fee_estimator.reset();
288 node.chainman.reset();
289 node.scheduler.reset();
290
291 try {
292 if (!fs::remove(GetPidFile(*node.args))) {
293 LogPrintf("%s: Unable to remove PID file: File does not exist\n", __func__);
294 }
295 } catch (const fs::filesystem_error& e) {
296 LogPrintf("%s: Unable to remove PID file: %s\n", __func__, fsbridge::get_filesystem_error_message(e));
297 }
298
299 node.args = nullptr;
300 LogPrintf("%s: done\n", __func__);
301}
302
308#ifndef WIN32
309static void HandleSIGTERM(int)
310{
312}
313
314static void HandleSIGHUP(int)
315{
316 LogInstance().m_reopen_file = true;
317}
318#else
319static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
320{
322 Sleep(INFINITE);
323 return true;
324}
325#endif
326
327#ifndef WIN32
328static void registerSignalHandler(int signal, void(*handler)(int))
329{
330 struct sigaction sa;
331 sa.sa_handler = handler;
332 sigemptyset(&sa.sa_mask);
333 sa.sa_flags = 0;
334 sigaction(signal, &sa, nullptr);
335}
336#endif
337
338static boost::signals2::connection rpc_notify_block_change_connection;
339static void OnRPCStarted()
340{
341 rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(std::bind(RPCNotifyBlockChange, std::placeholders::_2));
342}
343
344static void OnRPCStopped()
345{
347 RPCNotifyBlockChange(nullptr);
348 g_best_block_cv.notify_all();
349 LogPrint(BCLog::RPC, "RPC stopped.\n");
350}
351
353{
354 SetupHelpOptions(argsman);
355 argsman.AddArg("-help-debug", "Print help message with debugging options and exit", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); // server-only for now
356
357 init::AddLoggingArgs(argsman);
358
359 const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
360 const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
361 const auto signetBaseParams = CreateBaseChainParams(CBaseChainParams::SIGNET);
362 const auto regtestBaseParams = CreateBaseChainParams(CBaseChainParams::REGTEST);
363 const auto defaultChainParams = CreateChainParams(argsman, CBaseChainParams::MAIN);
364 const auto testnetChainParams = CreateChainParams(argsman, CBaseChainParams::TESTNET);
365 const auto signetChainParams = CreateChainParams(argsman, CBaseChainParams::SIGNET);
366 const auto regtestChainParams = CreateChainParams(argsman, CBaseChainParams::REGTEST);
367
368 // Hidden Options
369 std::vector<std::string> hidden_args = {
370 "-dbcrashratio", "-forcecompactdb",
371 // GUI args. These will be overwritten by SetupUIArgs for the GUI
372 "-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-splash", "-uiplatform"};
373
374 argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
375#if HAVE_SYSTEM
376 argsman.AddArg("-alertnotify=<cmd>", "Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
377#endif
378 argsman.AddArg("-assumevalid=<hex>", strprintf("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s, signet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex(), signetChainParams->GetConsensus().defaultAssumeValid.GetHex()), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
379 argsman.AddArg("-blocksdir=<dir>", "Specify directory to hold blocks subdirectory for *.dat files (default: <datadir>)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
380 argsman.AddArg("-fastprune", "Use smaller block files and lower minimum prune height for testing purposes", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
381#if HAVE_SYSTEM
382 argsman.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
383#endif
384 argsman.AddArg("-blockreconstructionextratxn=<n>", strprintf("Extra transactions to keep in memory for compact block reconstructions (default: %u)", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
385 argsman.AddArg("-blocksonly", strprintf("Whether to reject transactions from network peers. Automatic broadcast and rebroadcast of any transactions from inbound peers is disabled, unless the peer has the 'forcerelay' permission. RPC transactions are not affected. (default: %u)", DEFAULT_BLOCKSONLY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
386 argsman.AddArg("-coinstatsindex", strprintf("Maintain coinstats index used by the gettxoutsetinfo RPC (default: %u)", DEFAULT_COINSTATSINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
387 argsman.AddArg("-conf=<file>", strprintf("Specify path to read-only configuration file. Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
388 argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
389 argsman.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
390 argsman.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (%d to %d, default: %d). In addition, unused mempool memory is shared for this cache (see -maxmempool).", nMinDbCache, nMaxDbCache, nDefaultDbCache), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
391 argsman.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
392 argsman.AddArg("-loadblock=<file>", "Imports blocks from external file on startup", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
393 argsman.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
394 argsman.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
395 argsman.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
396 argsman.AddArg("-minimumchainwork=<hex>", strprintf("Minimum work assumed to exist on a valid chain in hex (default: %s, testnet: %s, signet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex(), signetChainParams->GetConsensus().nMinimumChainWork.GetHex()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
397 argsman.AddArg("-par=<n>", strprintf("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)",
399 argsman.AddArg("-persistmempool", strprintf("Whether to save the mempool on shutdown and load on restart (default: %u)", DEFAULT_PERSIST_MEMPOOL), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
400 argsman.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
401 argsman.AddArg("-prune=<n>", strprintf("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex and -coinstatsindex. "
402 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
403 "(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
404 argsman.AddArg("-reindex", "Rebuild chain state and block index from the blk*.dat files on disk", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
405 argsman.AddArg("-reindex-chainstate", "Rebuild chain state from the currently indexed blocks. When in pruning mode or if blocks on disk might be corrupted, use full -reindex instead.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
406 argsman.AddArg("-settings=<file>", strprintf("Specify path to dynamic settings data file. Can be disabled with -nosettings. File is written at runtime and not meant to be edited by users (use %s instead for custom settings). Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME, BITCOIN_SETTINGS_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
407#if HAVE_SYSTEM
408 argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
409#endif
410#ifndef WIN32
411 argsman.AddArg("-sysperms", "Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
412#else
413 hidden_args.emplace_back("-sysperms");
414#endif
415 argsman.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
416 argsman.AddArg("-blockfilterindex=<type>",
417 strprintf("Maintain an index of compact filters by block (default: %s, values: %s).", DEFAULT_BLOCKFILTERINDEX, ListBlockFilterTypes()) +
418 " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
420
421 argsman.AddArg("-addnode=<ip>", strprintf("Add a node to connect to and attempt to keep the connection open (see the addnode RPC help for more info). This option can be specified multiple times to add multiple nodes; connections are limited to %u at a time and are counted separately from the -maxconnections limit.", MAX_ADDNODE_CONNECTIONS), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
422 argsman.AddArg("-asmap=<file>", strprintf("Specify asn mapping used for bucketing of the peers (default: %s). Relative paths will be prefixed by the net-specific datadir location.", DEFAULT_ASMAP_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
423 argsman.AddArg("-bantime=<n>", strprintf("Default duration (in seconds) of manually configured bans (default: %u)", DEFAULT_MISBEHAVING_BANTIME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
424 argsman.AddArg("-bind=<addr>[:<port>][=onion]", strprintf("Bind to given address and always listen on it (default: 0.0.0.0). Use [host]:port notation for IPv6. Append =onion to tag any incoming connections to that address and port as incoming Tor connections (default: 127.0.0.1:%u=onion, testnet: 127.0.0.1:%u=onion, signet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)", defaultBaseParams->OnionServiceTargetPort(), testnetBaseParams->OnionServiceTargetPort(), signetBaseParams->OnionServiceTargetPort(), regtestBaseParams->OnionServiceTargetPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
425 argsman.AddArg("-cjdnsreachable", "If set then this host is configured for CJDNS (connecting to fc00::/8 addresses would lead us to the CJDNS network) (default: 0)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
426 argsman.AddArg("-connect=<ip>", "Connect only to the specified node; -noconnect disables automatic connections (the rules for this peer are the same as for -addnode). This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
427 argsman.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
428 argsman.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
429 argsman.AddArg("-dnsseed", strprintf("Query for peer addresses via DNS lookup, if low on addresses (default: %u unless -connect used)", DEFAULT_DNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
430 argsman.AddArg("-externalip=<ip>", "Specify your own public address", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
431 argsman.AddArg("-fixedseeds", strprintf("Allow fixed seeds if DNS seeds don't provide peers (default: %u)", DEFAULT_FIXEDSEEDS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
432 argsman.AddArg("-forcednsseed", strprintf("Always query for peer addresses via DNS lookup (default: %u)", DEFAULT_FORCEDNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
433 argsman.AddArg("-listen", "Accept connections from outside (default: 1 if no -proxy or -connect)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
434 argsman.AddArg("-listenonion", strprintf("Automatically create Tor onion service (default: %d)", DEFAULT_LISTEN_ONION), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
435 argsman.AddArg("-maxconnections=<n>", strprintf("Maintain at most <n> connections to peers (default: %u). This limit does not apply to connections manually added via -addnode or the addnode RPC, which have a separate limit of %u.", DEFAULT_MAX_PEER_CONNECTIONS, MAX_ADDNODE_CONNECTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
436 argsman.AddArg("-maxreceivebuffer=<n>", strprintf("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXRECEIVEBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
437 argsman.AddArg("-maxsendbuffer=<n>", strprintf("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXSENDBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
438 argsman.AddArg("-maxtimeadjustment", strprintf("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)", DEFAULT_MAX_TIME_ADJUSTMENT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
439 argsman.AddArg("-maxuploadtarget=<n>", strprintf("Tries to keep outbound traffic under the given target (in MiB per 24h). Limit does not apply to peers with 'download' permission. 0 = no limit (default: %d)", DEFAULT_MAX_UPLOAD_TARGET), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
440 argsman.AddArg("-onion=<ip:port>", "Use separate SOCKS5 proxy to reach peers via Tor onion services, set -noonion to disable (default: -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
441 argsman.AddArg("-i2psam=<ip:port>", "I2P SAM proxy to reach I2P peers and accept I2P connections (default: none)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
442 argsman.AddArg("-i2pacceptincoming", "If set and -i2psam is also set then incoming I2P connections are accepted via the SAM proxy. If this is not set but -i2psam is set then only outgoing connections will be made to the I2P network. Ignored if -i2psam is not set. Listening for incoming I2P connections is done through the SAM proxy, not by binding to a local address and port (default: 1)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
443 argsman.AddArg("-onlynet=<net>", "Make outgoing connections only through network <net> (" + Join(GetNetworkNames(), ", ") + "). Incoming connections are not affected by this option. This option can be specified multiple times to allow multiple networks. Warning: if it is used with non-onion networks and the -onion or -proxy option is set, then outbound onion connections will still be made; use -noonion or -onion=0 to disable outbound onion connections in this case.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
444 argsman.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
445 argsman.AddArg("-peerblockfilters", strprintf("Serve compact block filters to peers per BIP 157 (default: %u)", DEFAULT_PEERBLOCKFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
446 argsman.AddArg("-permitbaremultisig", strprintf("Relay non-P2SH multisig (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
447 argsman.AddArg("-port=<port>", strprintf("Listen for connections on <port>. Nodes not using the default ports (default: %u, testnet: %u, signet: %u, regtest: %u) are unlikely to get incoming connections. Not relevant for I2P (see doc/i2p.md).", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
448 argsman.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
449 argsman.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
450 argsman.AddArg("-seednode=<ip>", "Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
451 argsman.AddArg("-networkactive", "Enable all P2P network activity (default: 1). Can be changed by the setnetworkactive RPC command", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
452 argsman.AddArg("-timeout=<n>", strprintf("Specify socket connection timeout in milliseconds. If an initial attempt to connect is unsuccessful after this amount of time, drop it (minimum: 1, default: %d)", DEFAULT_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
453 argsman.AddArg("-peertimeout=<n>", strprintf("Specify a p2p connection timeout delay in seconds. After connecting to a peer, wait this amount of time before considering disconnection based on inactivity (minimum: 1, default: %d)", DEFAULT_PEER_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
454 argsman.AddArg("-torcontrol=<ip>:<port>", strprintf("Tor control port to use if onion listening enabled (default: %s)", DEFAULT_TOR_CONTROL), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
455 argsman.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::CONNECTION);
456#ifdef USE_UPNP
457#if USE_UPNP
458 argsman.AddArg("-upnp", "Use UPnP to map the listening port (default: 1 when listening and no -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
459#else
460 argsman.AddArg("-upnp", strprintf("Use UPnP to map the listening port (default: %u)", 0), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
461#endif
462#else
463 hidden_args.emplace_back("-upnp");
464#endif
465#ifdef USE_NATPMP
466 argsman.AddArg("-natpmp", strprintf("Use NAT-PMP to map the listening port (default: %s)", DEFAULT_NATPMP ? "1 when listening and no -proxy" : "0"), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
467#else
468 hidden_args.emplace_back("-natpmp");
469#endif // USE_NATPMP
470 argsman.AddArg("-whitebind=<[permissions@]addr>", "Bind to the given address and add permission flags to the peers connecting to it. "
471 "Use [host]:port notation for IPv6. Allowed permissions: " + Join(NET_PERMISSIONS_DOC, ", ") + ". "
472 "Specify multiple permissions separated by commas (default: download,noban,mempool,relay). Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
473
474 argsman.AddArg("-whitelist=<[permissions@]IP address or network>", "Add permission flags to the peers connecting from the given IP address (e.g. 1.2.3.4) or "
475 "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as "
476 "-whitebind. Can be specified multiple times." , ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
477
479
480#if ENABLE_ZMQ
481 argsman.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
482 argsman.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
483 argsman.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
484 argsman.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
485 argsman.AddArg("-zmqpubsequence=<address>", "Enable publish hash block and tx sequence in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
486 argsman.AddArg("-zmqpubhashblockhwm=<n>", strprintf("Set publish hash block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
487 argsman.AddArg("-zmqpubhashtxhwm=<n>", strprintf("Set publish hash transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
488 argsman.AddArg("-zmqpubrawblockhwm=<n>", strprintf("Set publish raw block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
489 argsman.AddArg("-zmqpubrawtxhwm=<n>", strprintf("Set publish raw transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
490 argsman.AddArg("-zmqpubsequencehwm=<n>", strprintf("Set publish hash sequence message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
491#else
492 hidden_args.emplace_back("-zmqpubhashblock=<address>");
493 hidden_args.emplace_back("-zmqpubhashtx=<address>");
494 hidden_args.emplace_back("-zmqpubrawblock=<address>");
495 hidden_args.emplace_back("-zmqpubrawtx=<address>");
496 hidden_args.emplace_back("-zmqpubsequence=<n>");
497 hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
498 hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
499 hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
500 hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
501 hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
502#endif
503
504 argsman.AddArg("-checkblocks=<n>", strprintf("How many blocks to check at startup (default: %u, 0 = all)", DEFAULT_CHECKBLOCKS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
505 argsman.AddArg("-checklevel=<n>", strprintf("How thorough the block verification of -checkblocks is: %s (0-4, default: %u)", Join(CHECKLEVEL_DOC, ", "), DEFAULT_CHECKLEVEL), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
506 argsman.AddArg("-checkblockindex", strprintf("Do a consistency check for the block tree, chainstate, and other validation data structures occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
507 argsman.AddArg("-checkaddrman=<n>", strprintf("Run addrman consistency checks every <n> operations. Use 0 to disable. (default: %u)", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
508 argsman.AddArg("-checkmempool=<n>", strprintf("Run mempool consistency checks every <n> transactions. Use 0 to disable. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
509 argsman.AddArg("-checkpoints", strprintf("Enable rejection of any forks from the known historical chain until block %s (default: %u)", defaultChainParams->Checkpoints().GetHeight(), DEFAULT_CHECKPOINTS_ENABLED), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
510 argsman.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
511 argsman.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
512 argsman.AddArg("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
513 argsman.AddArg("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
514 argsman.AddArg("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
515 argsman.AddArg("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
516 argsman.AddArg("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
517 argsman.AddArg("-addrmantest", "Allows to test address relay on localhost", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
518 argsman.AddArg("-capturemessages", "Capture all P2P messages to disk", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
519 argsman.AddArg("-mocktime=<n>", "Replace actual time with " + UNIX_EPOCH_TIME + " (default: 0)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
520 argsman.AddArg("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
521 argsman.AddArg("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
522 argsman.AddArg("-printpriority", strprintf("Log transaction fee rate in " + CURRENCY_UNIT + "/kvB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
523 argsman.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
524
526
527 argsman.AddArg("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
528 argsman.AddArg("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kvB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
529 argsman.AddArg("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kvB) used to define dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
530 argsman.AddArg("-bytespersigop", strprintf("Equivalent bytes per sigop in transactions for relay and mining (default: %u)", DEFAULT_BYTES_PER_SIGOP), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
531 argsman.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
532 argsman.AddArg("-datacarriersize", strprintf("Maximum size of data in data carrier transactions we relay and mine (default: %u)", MAX_OP_RETURN_RELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
533 argsman.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kvB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
535 argsman.AddArg("-whitelistforcerelay", strprintf("Add 'forcerelay' permission to whitelisted inbound peers with default permissions. This will relay transactions even if the transactions were already in the mempool. (default: %d)", DEFAULT_WHITELISTFORCERELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
536 argsman.AddArg("-whitelistrelay", strprintf("Add 'relay' permission to whitelisted inbound peers with default permissions. This will accept relayed transactions even when not relaying transactions (default: %d)", DEFAULT_WHITELISTRELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
537
538
539 argsman.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
540 argsman.AddArg("-blockmintxfee=<amt>", strprintf("Set lowest fee rate (in %s/kvB) for transactions to be included in block creation. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
541 argsman.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::BLOCK_CREATION);
542
543 argsman.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
544 argsman.AddArg("-rpcallowip=<ip>", "Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
545 argsman.AddArg("-rpcauth=<userpw>", "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcauth. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
546 argsman.AddArg("-rpcbind=<addr>[:port]", "Bind to given address to listen for JSON-RPC connections. Do not expose the RPC server to untrusted networks such as the public internet! This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
547 argsman.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
548 argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
549 argsman.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u, testnet: %u, signet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), signetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC);
550 argsman.AddArg("-rpcserialversion", strprintf("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)", DEFAULT_RPC_SERIALIZE_VERSION), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
551 argsman.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
552 argsman.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
553 argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
554 argsman.AddArg("-rpcwhitelist=<whitelist>", "Set a whitelist to filter incoming RPC calls for a specific user. The field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc 2>,...,<rpc n>. If multiple whitelists are set for a given user, they are set-intersected. See -rpcwhitelistdefault documentation for information on default whitelist behavior.", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
555 argsman.AddArg("-rpcwhitelistdefault", "Sets default behavior for rpc whitelisting. Unless rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc server acts as if all rpc users are subject to empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault is set to 1 and no -rpcwhitelist is set, rpc server acts as if all rpc users are subject to empty whitelists.", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
556 argsman.AddArg("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
557 argsman.AddArg("-server", "Accept command line and JSON-RPC commands", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
558
559#if HAVE_DECL_FORK
560 argsman.AddArg("-daemon", strprintf("Run in the background as a daemon and accept commands (default: %d)", DEFAULT_DAEMON), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
561 argsman.AddArg("-daemonwait", strprintf("Wait for initialization to be finished before exiting. This implies -daemon (default: %d)", DEFAULT_DAEMONWAIT), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
562#else
563 hidden_args.emplace_back("-daemon");
564 hidden_args.emplace_back("-daemonwait");
565#endif
566
567#if defined(USE_SYSCALL_SANDBOX)
568 argsman.AddArg("-sandbox=<mode>", "Use the experimental syscall sandbox in the specified mode (-sandbox=log-and-abort or -sandbox=abort). Allow only expected syscalls to be used by bitcoind. Note that this is an experimental new feature that may cause bitcoind to exit or crash unexpectedly: use with caution. In the \"log-and-abort\" mode the invocation of an unexpected syscall results in a debug handler being invoked which will log the incident and terminate the program (without executing the unexpected syscall). In the \"abort\" mode the invocation of an unexpected syscall results in the entire process being killed immediately by the kernel without executing the unexpected syscall.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
569#endif // USE_SYSCALL_SANDBOX
570
571 // Add the hidden options
572 argsman.AddHiddenArgs(hidden_args);
573}
574
575std::string LicenseInfo()
576{
577 const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
578
579 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i").translated, 2009, COPYRIGHT_YEAR) + " ") + "\n" +
580 "\n" +
581 strprintf(_("Please contribute if you find %s useful. "
582 "Visit %s for further information about the software.").translated,
583 PACKAGE_NAME, "<" PACKAGE_URL ">") +
584 "\n" +
585 strprintf(_("The source code is available from %s.").translated,
586 URL_SOURCE_CODE) +
587 "\n" +
588 "\n" +
589 _("This is experimental software.").translated + "\n" +
590 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s").translated, "COPYING", "<https://opensource.org/licenses/MIT>") +
591 "\n";
592}
593
594static bool fHaveGenesis = false;
596static std::condition_variable g_genesis_wait_cv;
597
598static void BlockNotifyGenesisWait(const CBlockIndex* pBlockIndex)
599{
600 if (pBlockIndex != nullptr) {
601 {
603 fHaveGenesis = true;
604 }
605 g_genesis_wait_cv.notify_all();
606 }
607}
608
609#if HAVE_SYSTEM
610static void StartupNotify(const ArgsManager& args)
611{
612 std::string cmd = args.GetArg("-startupnotify", "");
613 if (!cmd.empty()) {
614 std::thread t(runCommand, cmd);
615 t.detach(); // thread runs free
616 }
617}
618#endif
619
621{
622 const ArgsManager& args = *Assert(node.args);
625 if (!InitHTTPServer())
626 return false;
627 StartRPC();
628 node.rpc_interruption_point = RpcInterruptionPoint;
629 if (!StartHTTPRPC(&node))
630 return false;
631 if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) StartREST(&node);
633 return true;
634}
635
636// Parameter interaction based on rules
638{
639 // when specifying an explicit binding address, you want to listen on it
640 // even when -connect or -proxy is specified
641 if (args.IsArgSet("-bind")) {
642 if (args.SoftSetBoolArg("-listen", true))
643 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
644 }
645 if (args.IsArgSet("-whitebind")) {
646 if (args.SoftSetBoolArg("-listen", true))
647 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
648 }
649
650 if (args.IsArgSet("-connect")) {
651 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
652 if (args.SoftSetBoolArg("-dnsseed", false))
653 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
654 if (args.SoftSetBoolArg("-listen", false))
655 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
656 }
657
658 if (args.IsArgSet("-proxy")) {
659 // to protect privacy, do not listen by default if a default proxy server is specified
660 if (args.SoftSetBoolArg("-listen", false))
661 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
662 // to protect privacy, do not map ports when a proxy is set. The user may still specify -listen=1
663 // to listen locally, so don't rely on this happening through -listen below.
664 if (args.SoftSetBoolArg("-upnp", false))
665 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
666 if (args.SoftSetBoolArg("-natpmp", false)) {
667 LogPrintf("%s: parameter interaction: -proxy set -> setting -natpmp=0\n", __func__);
668 }
669 // to protect privacy, do not discover addresses by default
670 if (args.SoftSetBoolArg("-discover", false))
671 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
672 }
673
674 if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
675 // do not map ports or try to retrieve public IP when not listening (pointless)
676 if (args.SoftSetBoolArg("-upnp", false))
677 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
678 if (args.SoftSetBoolArg("-natpmp", false)) {
679 LogPrintf("%s: parameter interaction: -listen=0 -> setting -natpmp=0\n", __func__);
680 }
681 if (args.SoftSetBoolArg("-discover", false))
682 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
683 if (args.SoftSetBoolArg("-listenonion", false))
684 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
685 if (args.SoftSetBoolArg("-i2pacceptincoming", false)) {
686 LogPrintf("%s: parameter interaction: -listen=0 -> setting -i2pacceptincoming=0\n", __func__);
687 }
688 }
689
690 if (args.IsArgSet("-externalip")) {
691 // if an explicit public IP is specified, do not try to find others
692 if (args.SoftSetBoolArg("-discover", false))
693 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
694 }
695
696 // disable whitelistrelay in blocksonly mode
697 if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
698 if (args.SoftSetBoolArg("-whitelistrelay", false))
699 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
700 }
701
702 // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
703 if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
704 if (args.SoftSetBoolArg("-whitelistrelay", true))
705 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
706 }
707}
708
715void InitLogging(const ArgsManager& args)
716{
719}
720
721namespace { // Variables internal to initialization process only
722
723int nMaxConnections;
724int nUserMaxConnections;
725int nFD;
727int64_t peer_connect_timeout;
728std::set<BlockFilterType> g_enabled_filter_types;
729
730} // namespace
731
732[[noreturn]] static void new_handler_terminate()
733{
734 // Rather than throwing std::bad-alloc if allocation fails, terminate
735 // immediately to (try to) avoid chain corruption.
736 // Since LogPrintf may itself allocate memory, set the handler directly
737 // to terminate first.
738 std::set_new_handler(std::terminate);
739 LogPrintf("Error: Out of memory. Terminating.\n");
740
741 // The log was successful, terminate now.
742 std::terminate();
743};
744
746{
747 // ********************************************************* Step 1: setup
748#ifdef _MSC_VER
749 // Turn off Microsoft heap dump noise
750 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
751 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
752 // Disable confusing "helpful" text message on abort, Ctrl-C
753 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
754#endif
755#ifdef WIN32
756 // Enable heap terminate-on-corruption
757 HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0);
758#endif
759 if (!InitShutdownState()) {
760 return InitError(Untranslated("Initializing wait-for-shutdown state failed."));
761 }
762
763 if (!SetupNetworking()) {
764 return InitError(Untranslated("Initializing networking failed."));
765 }
766
767#ifndef WIN32
768 if (!args.GetBoolArg("-sysperms", false)) {
769 umask(077);
770 }
771
772 // Clean shutdown on SIGTERM
775
776 // Reopen debug.log on SIGHUP
778
779 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
780 signal(SIGPIPE, SIG_IGN);
781#else
782 SetConsoleCtrlHandler(consoleCtrlHandler, true);
783#endif
784
785 std::set_new_handler(new_handler_terminate);
786
787 return true;
788}
789
791{
792 const CChainParams& chainparams = Params();
793 // ********************************************************* Step 2: parameter interactions
794
795 // also see: InitParameterInteraction()
796
797 // Error if network-specific options (-addnode, -connect, etc) are
798 // specified in default section of config file, but not overridden
799 // on the command line or in this network's section of the config file.
800 std::string network = args.GetChainName();
801 if (network == CBaseChainParams::SIGNET) {
802 LogPrintf("Signet derived magic (message start): %s\n", HexStr(chainparams.MessageStart()));
803 }
804 bilingual_str errors;
805 for (const auto& arg : args.GetUnsuitableSectionOnlyArgs()) {
806 errors += strprintf(_("Config setting for %s only applied on %s network when in [%s] section.") + Untranslated("\n"), arg, network, network);
807 }
808
809 if (!errors.empty()) {
810 return InitError(errors);
811 }
812
813 // Warn if unrecognized section name are present in the config file.
814 bilingual_str warnings;
815 for (const auto& section : args.GetUnrecognizedSections()) {
816 warnings += strprintf(Untranslated("%s:%i ") + _("Section [%s] is not recognized.") + Untranslated("\n"), section.m_file, section.m_line, section.m_name);
817 }
818
819 if (!warnings.empty()) {
820 InitWarning(warnings);
821 }
822
823 if (!fs::is_directory(gArgs.GetBlocksDirPath())) {
824 return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist."), args.GetArg("-blocksdir", "")));
825 }
826
827 // parse and validate enabled filter types
828 std::string blockfilterindex_value = args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
829 if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
830 g_enabled_filter_types = AllBlockFilterTypes();
831 } else if (blockfilterindex_value != "0") {
832 const std::vector<std::string> names = args.GetArgs("-blockfilterindex");
833 for (const auto& name : names) {
834 BlockFilterType filter_type;
835 if (!BlockFilterTypeByName(name, filter_type)) {
836 return InitError(strprintf(_("Unknown -blockfilterindex value %s."), name));
837 }
838 g_enabled_filter_types.insert(filter_type);
839 }
840 }
841
842 // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index are both enabled.
843 if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
844 if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
845 return InitError(_("Cannot set -peerblockfilters without -blockfilterindex."));
846 }
847
848 nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS);
849 }
850
851 // if using block pruning, then disallow txindex and coinstatsindex
852 if (args.GetIntArg("-prune", 0)) {
853 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX))
854 return InitError(_("Prune mode is incompatible with -txindex."));
855 if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX))
856 return InitError(_("Prune mode is incompatible with -coinstatsindex."));
857 }
858
859 // If -forcednsseed is set to true, ensure -dnsseed has not been set to false
860 if (args.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED) && !args.GetBoolArg("-dnsseed", DEFAULT_DNSSEED)){
861 return InitError(_("Cannot set -forcednsseed to true when setting -dnsseed to false."));
862 }
863
864 // -bind and -whitebind can't be set when not listening
865 size_t nUserBind = args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
866 if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
867 return InitError(Untranslated("Cannot set -bind or -whitebind together with -listen=0"));
868 }
869
870 // if listen=0, then disallow listenonion=1
871 if (!args.GetBoolArg("-listen", DEFAULT_LISTEN) && args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
872 return InitError(Untranslated("Cannot set -listen=0 together with -listenonion=1"));
873 }
874
875 // Make sure enough file descriptors are available
876 int nBind = std::max(nUserBind, size_t(1));
877 nUserMaxConnections = args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
878 nMaxConnections = std::max(nUserMaxConnections, 0);
879
881
882#ifdef USE_POLL
883 int fd_max = nFD;
884#else
885 int fd_max = FD_SETSIZE;
886#endif
887 // Trim requested connection counts, to fit into system limitations
888 // <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695
889 nMaxConnections = std::max(std::min<int>(nMaxConnections, fd_max - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS - NUM_FDS_MESSAGE_CAPTURE), 0);
890 if (nFD < MIN_CORE_FILEDESCRIPTORS)
891 return InitError(_("Not enough file descriptors available."));
892 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS - NUM_FDS_MESSAGE_CAPTURE, nMaxConnections);
893
894 if (nMaxConnections < nUserMaxConnections)
895 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
896
897 // ********************************************************* Step 3: parameter-to-internal-flags
899
900 fCheckBlockIndex = args.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
902
903 hashAssumeValid = uint256S(args.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
904 if (!hashAssumeValid.IsNull())
905 LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
906 else
907 LogPrintf("Validating signatures for all blocks.\n");
908
909 if (args.IsArgSet("-minimumchainwork")) {
910 const std::string minChainWorkStr = args.GetArg("-minimumchainwork", "");
911 if (!IsHexNumber(minChainWorkStr)) {
912 return InitError(strprintf(Untranslated("Invalid non-hex (%s) minimum chain work value specified"), minChainWorkStr));
913 }
914 nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
915 } else {
917 }
918 LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
920 LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex());
921 }
922
923 // mempool limits
924 int64_t nMempoolSizeMax = args.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
925 int64_t nMempoolSizeMin = args.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
926 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
927 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
928 // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
929 // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
930 if (args.IsArgSet("-incrementalrelayfee")) {
931 if (std::optional<CAmount> inc_relay_fee = ParseMoney(args.GetArg("-incrementalrelayfee", ""))) {
932 ::incrementalRelayFee = CFeeRate{inc_relay_fee.value()};
933 } else {
934 return InitError(AmountErrMsg("incrementalrelayfee", args.GetArg("-incrementalrelayfee", "")));
935 }
936 }
937
938 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
939 int64_t nPruneArg = args.GetIntArg("-prune", 0);
940 if (nPruneArg < 0) {
941 return InitError(_("Prune cannot be configured with a negative value."));
942 }
943 nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
944 if (nPruneArg == 1) { // manual pruning: -prune=1
945 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
946 nPruneTarget = std::numeric_limits<uint64_t>::max();
947 fPruneMode = true;
948 } else if (nPruneTarget) {
950 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
951 }
952 LogPrintf("Prune configured to target %u MiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
953 fPruneMode = true;
954 }
955
957 if (nConnectTimeout <= 0) {
959 }
960
961 peer_connect_timeout = args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
962 if (peer_connect_timeout <= 0) {
963 return InitError(Untranslated("peertimeout cannot be configured with a negative value."));
964 }
965
966 if (args.IsArgSet("-minrelaytxfee")) {
967 if (std::optional<CAmount> min_relay_fee = ParseMoney(args.GetArg("-minrelaytxfee", ""))) {
968 // High fee check is done afterward in CWallet::Create()
969 ::minRelayTxFee = CFeeRate{min_relay_fee.value()};
970 } else {
971 return InitError(AmountErrMsg("minrelaytxfee", args.GetArg("-minrelaytxfee", "")));
972 }
973 } else if (incrementalRelayFee > ::minRelayTxFee) {
974 // Allow only setting incrementalRelayFee to control both
976 LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
977 }
978
979 // Sanity check argument for min fee for including tx in block
980 // TODO: Harmonize which arguments need sanity checking and where that happens
981 if (args.IsArgSet("-blockmintxfee")) {
982 if (!ParseMoney(args.GetArg("-blockmintxfee", ""))) {
983 return InitError(AmountErrMsg("blockmintxfee", args.GetArg("-blockmintxfee", "")));
984 }
985 }
986
987 // Feerate used to define dust. Shouldn't be changed lightly as old
988 // implementations may inadvertently create non-standard transactions
989 if (args.IsArgSet("-dustrelayfee")) {
990 if (std::optional<CAmount> parsed = ParseMoney(args.GetArg("-dustrelayfee", ""))) {
991 dustRelayFee = CFeeRate{parsed.value()};
992 } else {
993 return InitError(AmountErrMsg("dustrelayfee", args.GetArg("-dustrelayfee", "")));
994 }
995 }
996
997 fRequireStandard = !args.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
998 if (!chainparams.IsTestChain() && !fRequireStandard) {
999 return InitError(strprintf(Untranslated("acceptnonstdtxn is not currently supported for %s chain"), chainparams.NetworkIDString()));
1000 }
1001 nBytesPerSigOp = args.GetIntArg("-bytespersigop", nBytesPerSigOp);
1002
1003 if (!g_wallet_init_interface.ParameterInteraction()) return false;
1004
1005 fIsBareMultisigStd = args.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1007 nMaxDatacarrierBytes = args.GetIntArg("-datacarriersize", nMaxDatacarrierBytes);
1008
1009 // Option to startup with mocktime set (used for regression testing):
1010 SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1011
1012 if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1013 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1014
1015 if (args.GetIntArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1016 return InitError(Untranslated("rpcserialversion must be non-negative."));
1017
1018 if (args.GetIntArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1019 return InitError(Untranslated("Unknown rpcserialversion requested."));
1020
1021 nMaxTipAge = args.GetIntArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1022
1023 if (args.IsArgSet("-proxy") && args.GetArg("-proxy", "").empty()) {
1024 return InitError(_("No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
1025 }
1026
1027#if defined(USE_SYSCALL_SANDBOX)
1028 if (args.IsArgSet("-sandbox") && !args.IsArgNegated("-sandbox")) {
1029 const std::string sandbox_arg{args.GetArg("-sandbox", "")};
1030 bool log_syscall_violation_before_terminating{false};
1031 if (sandbox_arg == "log-and-abort") {
1032 log_syscall_violation_before_terminating = true;
1033 } else if (sandbox_arg == "abort") {
1034 // log_syscall_violation_before_terminating is false by default.
1035 } else {
1036 return InitError(Untranslated("Unknown syscall sandbox mode (-sandbox=<mode>). Available modes are \"log-and-abort\" and \"abort\"."));
1037 }
1038 // execve(...) is not allowed by the syscall sandbox.
1039 const std::vector<std::string> features_using_execve{
1040 "-alertnotify",
1041 "-blocknotify",
1042 "-signer",
1043 "-startupnotify",
1044 "-walletnotify",
1045 };
1046 for (const std::string& feature_using_execve : features_using_execve) {
1047 if (!args.GetArg(feature_using_execve, "").empty()) {
1048 return InitError(Untranslated(strprintf("The experimental syscall sandbox feature (-sandbox=<mode>) is incompatible with %s (which uses execve).", feature_using_execve)));
1049 }
1050 }
1051 if (!SetupSyscallSandbox(log_syscall_violation_before_terminating)) {
1052 return InitError(Untranslated("Installation of the syscall sandbox failed."));
1053 }
1054 LogPrintf("Experimental syscall sandbox enabled (-sandbox=%s): bitcoind will terminate if an unexpected (not allowlisted) syscall is invoked.\n", sandbox_arg);
1055 }
1056#endif // USE_SYSCALL_SANDBOX
1057
1058 return true;
1059}
1060
1061static bool LockDataDirectory(bool probeOnly)
1062{
1063 // Make sure only a single Bitcoin process is using the data directory.
1064 fs::path datadir = gArgs.GetDataDirNet();
1065 if (!DirIsWritable(datadir)) {
1066 return InitError(strprintf(_("Cannot write to data directory '%s'; check permissions."), fs::PathToString(datadir)));
1067 }
1068 if (!LockDirectory(datadir, ".lock", probeOnly)) {
1069 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), fs::PathToString(datadir), PACKAGE_NAME));
1070 }
1071 return true;
1072}
1073
1075{
1076 // ********************************************************* Step 4: sanity checks
1077
1079
1080 if (!init::SanityChecks()) {
1081 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), PACKAGE_NAME));
1082 }
1083
1084 // Probe the data directory lock to give an early error message, if possible
1085 // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened,
1086 // and a fork will cause weird behavior to it.
1087 return LockDataDirectory(true);
1088}
1089
1091{
1092 // After daemonization get the data directory lock again and hold on to it until exit
1093 // This creates a slight window for a race condition to happen, however this condition is harmless: it
1094 // will at most make us exit without printing a message to console.
1095 if (!LockDataDirectory(false)) {
1096 // Detailed error printed inside LockDataDirectory
1097 return false;
1098 }
1099 return true;
1100}
1101
1103{
1104 node.chain = node.init->makeChain();
1105 // Create client interfaces for wallets that are supposed to be loaded
1106 // according to -wallet and -disablewallet options. This only constructs
1107 // the interfaces, it doesn't load wallet data. Wallets actually get loaded
1108 // when load() and start() interface methods are called below.
1110 return true;
1111}
1112
1114{
1115 const ArgsManager& args = *Assert(node.args);
1116 const CChainParams& chainparams = Params();
1117 // ********************************************************* Step 4a: application initialization
1118 if (!CreatePidFile(args)) {
1119 // Detailed error printed inside CreatePidFile().
1120 return false;
1121 }
1122 if (!init::StartLogging(args)) {
1123 // Detailed error printed inside StartLogging().
1124 return false;
1125 }
1126
1127 LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1128
1129 // Warn about relative -datadir path.
1130 if (args.IsArgSet("-datadir") && !fs::PathFromString(args.GetArg("-datadir", "")).is_absolute()) {
1131 LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " /* Continued */
1132 "current working directory '%s'. This is fragile, because if bitcoin is started in the future "
1133 "from a different location, it will be unable to locate the current data files. There could "
1134 "also be data loss if bitcoin is started while in a temporary directory.\n",
1135 args.GetArg("-datadir", ""), fs::PathToString(fs::current_path()));
1136 }
1137
1140
1141 int script_threads = args.GetIntArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
1142 if (script_threads <= 0) {
1143 // -par=0 means autodetect (number of cores - 1 script threads)
1144 // -par=-n means "leave n cores free" (number of cores - n - 1 script threads)
1145 script_threads += GetNumCores();
1146 }
1147
1148 // Subtract 1 because the main thread counts towards the par threads
1149 script_threads = std::max(script_threads - 1, 0);
1150
1151 // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
1152 script_threads = std::min(script_threads, MAX_SCRIPTCHECK_THREADS);
1153
1154 LogPrintf("Script verification uses %d additional threads\n", script_threads);
1155 if (script_threads >= 1) {
1157 StartScriptCheckWorkerThreads(script_threads);
1158 }
1159
1160 assert(!node.scheduler);
1161 node.scheduler = std::make_unique<CScheduler>();
1162
1163 // Start the lightweight task scheduler thread
1164 node.scheduler->m_service_thread = std::thread(util::TraceThread, "scheduler", [&] { node.scheduler->serviceQueue(); });
1165
1166 // Gather some entropy once per minute.
1167 node.scheduler->scheduleEvery([]{
1169 }, std::chrono::minutes{1});
1170
1172
1173 /* Register RPC commands regardless of -server setting so they will be
1174 * available in the GUI RPC console even if external calls are disabled.
1175 */
1177 for (const auto& client : node.chain_clients) {
1178 client->registerRpcs();
1179 }
1180#if ENABLE_ZMQ
1182#endif
1183
1184 /* Start the RPC server already. It will be started in "warmup" mode
1185 * and not really process calls already (but it will signify connections
1186 * that the server is there and will be ready later). Warmup mode will
1187 * be disabled when initialisation is finished.
1188 */
1189 if (args.GetBoolArg("-server", false)) {
1190 uiInterface.InitMessage_connect(SetRPCWarmupStatus);
1191 if (!AppInitServers(node))
1192 return InitError(_("Unable to start HTTP server. See debug log for details."));
1193 }
1194
1195 // ********************************************************* Step 5: verify wallet database integrity
1196 for (const auto& client : node.chain_clients) {
1197 if (!client->verify()) {
1198 return false;
1199 }
1200 }
1201
1202 // ********************************************************* Step 6: network initialization
1203 // Note that we absolutely cannot open any actual connections
1204 // until the very end ("start node") as the UTXO/block state
1205 // is not yet setup and may end up being set up twice if we
1206 // need to reindex later.
1207
1208 fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
1209 fDiscover = args.GetBoolArg("-discover", true);
1210 const bool ignores_incoming_txs{args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)};
1211
1212 {
1213 // Initialize addrman
1214 assert(!node.addrman);
1215
1216 // Read asmap file if configured
1217 std::vector<bool> asmap;
1218 if (args.IsArgSet("-asmap")) {
1219 fs::path asmap_path = fs::PathFromString(args.GetArg("-asmap", ""));
1220 if (asmap_path.empty()) {
1222 }
1223 if (!asmap_path.is_absolute()) {
1224 asmap_path = gArgs.GetDataDirNet() / asmap_path;
1225 }
1226 if (!fs::exists(asmap_path)) {
1227 InitError(strprintf(_("Could not find asmap file %s"), fs::quoted(fs::PathToString(asmap_path))));
1228 return false;
1229 }
1230 asmap = DecodeAsmap(asmap_path);
1231 if (asmap.size() == 0) {
1232 InitError(strprintf(_("Could not parse asmap file %s"), fs::quoted(fs::PathToString(asmap_path))));
1233 return false;
1234 }
1235 const uint256 asmap_version = SerializeHash(asmap);
1236 LogPrintf("Using asmap version %s for IP bucketing\n", asmap_version.ToString());
1237 } else {
1238 LogPrintf("Using /16 prefix for IP bucketing\n");
1239 }
1240
1241 uiInterface.InitMessage(_("Loading P2P addresses…").translated);
1242 if (const auto error{LoadAddrman(asmap, args, node.addrman)}) {
1243 return InitError(*error);
1244 }
1245 }
1246
1247 assert(!node.banman);
1248 node.banman = std::make_unique<BanMan>(gArgs.GetDataDirNet() / "banlist", &uiInterface, args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
1249 assert(!node.connman);
1250 node.connman = std::make_unique<CConnman>(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max()), *node.addrman, args.GetBoolArg("-networkactive", true));
1251
1252 assert(!node.fee_estimator);
1253 // Don't initialize fee estimation with old data if we don't relay transactions,
1254 // as they would never get updated.
1255 if (!ignores_incoming_txs) node.fee_estimator = std::make_unique<CBlockPolicyEstimator>();
1256
1257 assert(!node.mempool);
1258 int check_ratio = std::min<int>(std::max<int>(args.GetIntArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
1259 node.mempool = std::make_unique<CTxMemPool>(node.fee_estimator.get(), check_ratio);
1260
1261 assert(!node.chainman);
1262 node.chainman = std::make_unique<ChainstateManager>();
1263 ChainstateManager& chainman = *node.chainman;
1264
1265 assert(!node.peerman);
1266 node.peerman = PeerManager::make(chainparams, *node.connman, *node.addrman, node.banman.get(),
1267 chainman, *node.mempool, ignores_incoming_txs);
1268 RegisterValidationInterface(node.peerman.get());
1269
1270 // sanitize comments per BIP-0014, format user agent and check total size
1271 std::vector<std::string> uacomments;
1272 for (const std::string& cmt : args.GetArgs("-uacomment")) {
1273 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1274 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1275 uacomments.push_back(cmt);
1276 }
1278 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1279 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1281 }
1282
1283 if (args.IsArgSet("-onlynet")) {
1284 std::set<enum Network> nets;
1285 for (const std::string& snet : args.GetArgs("-onlynet")) {
1286 enum Network net = ParseNetwork(snet);
1287 if (net == NET_UNROUTABLE)
1288 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1289 nets.insert(net);
1290 }
1291 for (int n = 0; n < NET_MAX; n++) {
1292 enum Network net = (enum Network)n;
1293 if (!nets.count(net))
1294 SetReachable(net, false);
1295 }
1296 }
1297
1298 if (!args.IsArgSet("-cjdnsreachable")) {
1299 SetReachable(NET_CJDNS, false);
1300 }
1301 // Now IsReachable(NET_CJDNS) is true if:
1302 // 1. -cjdnsreachable is given and
1303 // 2.1. -onlynet is not given or
1304 // 2.2. -onlynet=cjdns is given
1305
1306 // Check for host lookup allowed before parsing any network related parameters
1308
1309 bool proxyRandomize = args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1310 // -proxy sets a proxy for all outgoing network traffic
1311 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1312 std::string proxyArg = args.GetArg("-proxy", "");
1313 SetReachable(NET_ONION, false);
1314 if (proxyArg != "" && proxyArg != "0") {
1315 CService proxyAddr;
1316 if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) {
1317 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1318 }
1319
1320 proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1321 if (!addrProxy.IsValid())
1322 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1323
1324 SetProxy(NET_IPV4, addrProxy);
1325 SetProxy(NET_IPV6, addrProxy);
1326 SetProxy(NET_ONION, addrProxy);
1327 SetProxy(NET_CJDNS, addrProxy);
1328 SetNameProxy(addrProxy);
1329 SetReachable(NET_ONION, true); // by default, -proxy sets onion as reachable, unless -noonion later
1330 }
1331
1332 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1333 // -noonion (or -onion=0) disables connecting to .onion entirely
1334 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1335 std::string onionArg = args.GetArg("-onion", "");
1336 if (onionArg != "") {
1337 if (onionArg == "0") { // Handle -noonion/-onion=0
1338 SetReachable(NET_ONION, false);
1339 } else {
1340 CService onionProxy;
1341 if (!Lookup(onionArg, onionProxy, 9050, fNameLookup)) {
1342 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1343 }
1344 proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1345 if (!addrOnion.IsValid())
1346 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1347 SetProxy(NET_ONION, addrOnion);
1348 SetReachable(NET_ONION, true);
1349 }
1350 }
1351
1352 for (const std::string& strAddr : args.GetArgs("-externalip")) {
1353 CService addrLocal;
1354 if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1355 AddLocal(addrLocal, LOCAL_MANUAL);
1356 else
1357 return InitError(ResolveErrMsg("externalip", strAddr));
1358 }
1359
1360#if ENABLE_ZMQ
1362
1365 }
1366#endif
1367
1368 // ********************************************************* Step 7: load block chain
1369
1370 fReindex = args.GetBoolArg("-reindex", false);
1371 bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
1372
1373 // cache size calculations
1374 int64_t nTotalCache = (args.GetIntArg("-dbcache", nDefaultDbCache) << 20);
1375 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1376 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1377 int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20);
1378 nTotalCache -= nBlockTreeDBCache;
1379 int64_t nTxIndexCache = std::min(nTotalCache / 8, args.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0);
1380 nTotalCache -= nTxIndexCache;
1381 int64_t filter_index_cache = 0;
1382 if (!g_enabled_filter_types.empty()) {
1383 size_t n_indexes = g_enabled_filter_types.size();
1384 int64_t max_cache = std::min(nTotalCache / 8, max_filter_index_cache << 20);
1385 filter_index_cache = max_cache / n_indexes;
1386 nTotalCache -= filter_index_cache * n_indexes;
1387 }
1388 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1389 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1390 nTotalCache -= nCoinDBCache;
1391 int64_t nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1392 int64_t nMempoolSizeMax = args.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1393 LogPrintf("Cache configuration:\n");
1394 LogPrintf("* Using %.1f MiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1395 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1396 LogPrintf("* Using %.1f MiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
1397 }
1398 for (BlockFilterType filter_type : g_enabled_filter_types) {
1399 LogPrintf("* Using %.1f MiB for %s block filter index database\n",
1400 filter_index_cache * (1.0 / 1024 / 1024), BlockFilterTypeName(filter_type));
1401 }
1402 LogPrintf("* Using %.1f MiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1403 LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
1404
1405 bool fLoaded = false;
1406 while (!fLoaded && !ShutdownRequested()) {
1407 const bool fReset = fReindex;
1408 auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
1409 return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull();
1410 };
1411 bilingual_str strLoadError;
1412
1413 uiInterface.InitMessage(_("Loading block index…").translated);
1414
1415 do {
1416 const int64_t load_block_index_start_time = GetTimeMillis();
1417 try {
1418 LOCK(cs_main);
1419 chainman.InitializeChainstate(Assert(node.mempool.get()));
1420 chainman.m_total_coinstip_cache = nCoinCacheUsage;
1421 chainman.m_total_coinsdb_cache = nCoinDBCache;
1422
1423 UnloadBlockIndex(node.mempool.get(), chainman);
1424
1425 auto& pblocktree{chainman.m_blockman.m_block_tree_db};
1426 // new CBlockTreeDB tries to delete the existing file, which
1427 // fails if it's still open from the previous loop. Close it first:
1428 pblocktree.reset();
1429 pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
1430
1431 if (fReset) {
1432 pblocktree->WriteReindexing(true);
1433 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1434 if (fPruneMode)
1436 }
1437
1438 if (ShutdownRequested()) break;
1439
1440 // LoadBlockIndex will load fHavePruned if we've ever removed a
1441 // block file from disk.
1442 // Note that it also sets fReindex based on the disk flag!
1443 // From here on out fReindex and fReset mean something different!
1444 if (!chainman.LoadBlockIndex()) {
1445 if (ShutdownRequested()) break;
1446 strLoadError = _("Error loading block database");
1447 break;
1448 }
1449
1450 // If the loaded chain has a wrong genesis, bail out immediately
1451 // (we're likely using a testnet datadir, or the other way around).
1452 if (!chainman.BlockIndex().empty() &&
1453 !chainman.m_blockman.LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
1454 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1455 }
1456
1457 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1458 // in the past, but is now trying to run unpruned.
1459 if (fHavePruned && !fPruneMode) {
1460 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1461 break;
1462 }
1463
1464 // At this point blocktree args are consistent with what's on disk.
1465 // If we're not mid-reindex (based on disk + args), add a genesis block on disk
1466 // (otherwise we use the one already on disk).
1467 // This is called again in ThreadImport after the reindex completes.
1468 if (!fReindex && !chainman.ActiveChainstate().LoadGenesisBlock()) {
1469 strLoadError = _("Error initializing block database");
1470 break;
1471 }
1472
1473 // At this point we're either in reindex or we've loaded a useful
1474 // block tree into BlockIndex()!
1475
1476 bool failed_chainstate_init = false;
1477
1478 for (CChainState* chainstate : chainman.GetAll()) {
1479 chainstate->InitCoinsDB(
1480 /* cache_size_bytes */ nCoinDBCache,
1481 /* in_memory */ false,
1482 /* should_wipe */ fReset || fReindexChainState);
1483
1484 chainstate->CoinsErrorCatcher().AddReadErrCallback([]() {
1485 uiInterface.ThreadSafeMessageBox(
1486 _("Error reading from database, shutting down."),
1488 });
1489
1490 // If necessary, upgrade from older database format.
1491 // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1492 if (!chainstate->CoinsDB().Upgrade()) {
1493 strLoadError = _("Error upgrading chainstate database");
1494 failed_chainstate_init = true;
1495 break;
1496 }
1497
1498 // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1499 if (!chainstate->ReplayBlocks()) {
1500 strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1501 failed_chainstate_init = true;
1502 break;
1503 }
1504
1505 // The on-disk coinsdb is now in a good state, create the cache
1506 chainstate->InitCoinsCache(nCoinCacheUsage);
1507 assert(chainstate->CanFlushToDisk());
1508
1509 if (!is_coinsview_empty(chainstate)) {
1510 // LoadChainTip initializes the chain based on CoinsTip()'s best block
1511 if (!chainstate->LoadChainTip()) {
1512 strLoadError = _("Error initializing block database");
1513 failed_chainstate_init = true;
1514 break; // out of the per-chainstate loop
1515 }
1516 assert(chainstate->m_chain.Tip() != nullptr);
1517 }
1518 }
1519
1520 if (failed_chainstate_init) {
1521 break; // out of the chainstate activation do-while
1522 }
1523 } catch (const std::exception& e) {
1524 LogPrintf("%s\n", e.what());
1525 strLoadError = _("Error opening block database");
1526 break;
1527 }
1528
1529 if (!fReset) {
1530 LOCK(cs_main);
1531 auto chainstates{chainman.GetAll()};
1532 if (std::any_of(chainstates.begin(), chainstates.end(),
1533 [](const CChainState* cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->NeedsRedownload(); })) {
1534 strLoadError = strprintf(_("Witness data for blocks after height %d requires validation. Please restart with -reindex."),
1535 chainparams.GetConsensus().SegwitHeight);
1536 break;
1537 }
1538 }
1539
1540 bool failed_verification = false;
1541
1542 try {
1543 LOCK(cs_main);
1544
1545 for (CChainState* chainstate : chainman.GetAll()) {
1546 if (!is_coinsview_empty(chainstate)) {
1547 uiInterface.InitMessage(_("Verifying blocks…").translated);
1548 if (fHavePruned && args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1549 LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
1551 }
1552
1553 const CBlockIndex* tip = chainstate->m_chain.Tip();
1555 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1556 strLoadError = _("The block database contains a block which appears to be from the future. "
1557 "This may be due to your computer's date and time being set incorrectly. "
1558 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1559 failed_verification = true;
1560 break;
1561 }
1562
1563 if (!CVerifyDB().VerifyDB(
1564 *chainstate, chainparams, chainstate->CoinsDB(),
1565 args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL),
1566 args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1567 strLoadError = _("Corrupted block database detected");
1568 failed_verification = true;
1569 break;
1570 }
1571 }
1572 }
1573 } catch (const std::exception& e) {
1574 LogPrintf("%s\n", e.what());
1575 strLoadError = _("Error opening block database");
1576 failed_verification = true;
1577 break;
1578 }
1579
1580 if (!failed_verification) {
1581 fLoaded = true;
1582 LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time);
1583 }
1584 } while(false);
1585
1586 if (!fLoaded && !ShutdownRequested()) {
1587 // first suggest a reindex
1588 if (!fReset) {
1589 bool fRet = uiInterface.ThreadSafeQuestion(
1590 strLoadError + Untranslated(".\n\n") + _("Do you want to rebuild the block database now?"),
1591 strLoadError.original + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1593 if (fRet) {
1594 fReindex = true;
1595 AbortShutdown();
1596 } else {
1597 LogPrintf("Aborted block database rebuild. Exiting.\n");
1598 return false;
1599 }
1600 } else {
1601 return InitError(strLoadError);
1602 }
1603 }
1604 }
1605
1606 // As LoadBlockIndex can take several minutes, it's possible the user
1607 // requested to kill the GUI during the last operation. If so, exit.
1608 // As the program has not fully started yet, Shutdown() is possibly overkill.
1609 if (ShutdownRequested()) {
1610 LogPrintf("Shutdown requested. Exiting.\n");
1611 return false;
1612 }
1613
1614 // ********************************************************* Step 8: start indexers
1615 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1616 if (const auto error{CheckLegacyTxindex(*Assert(chainman.m_blockman.m_block_tree_db))}) {
1617 return InitError(*error);
1618 }
1619
1620 g_txindex = std::make_unique<TxIndex>(nTxIndexCache, false, fReindex);
1621 if (!g_txindex->Start(chainman.ActiveChainstate())) {
1622 return false;
1623 }
1624 }
1625
1626 for (const auto& filter_type : g_enabled_filter_types) {
1627 InitBlockFilterIndex(filter_type, filter_index_cache, false, fReindex);
1628 if (!GetBlockFilterIndex(filter_type)->Start(chainman.ActiveChainstate())) {
1629 return false;
1630 }
1631 }
1632
1633 if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
1634 g_coin_stats_index = std::make_unique<CoinStatsIndex>(/* cache size */ 0, false, fReindex);
1635 if (!g_coin_stats_index->Start(chainman.ActiveChainstate())) {
1636 return false;
1637 }
1638 }
1639
1640 // ********************************************************* Step 9: load wallet
1641 for (const auto& client : node.chain_clients) {
1642 if (!client->load()) {
1643 return false;
1644 }
1645 }
1646
1647 // ********************************************************* Step 10: data directory maintenance
1648
1649 // if pruning, unset the service bit and perform the initial blockstore prune
1650 // after any wallet rescanning has taken place.
1651 if (fPruneMode) {
1652 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1653 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1654 if (!fReindex) {
1655 LOCK(cs_main);
1656 for (CChainState* chainstate : chainman.GetAll()) {
1657 uiInterface.InitMessage(_("Pruning blockstore…").translated);
1658 chainstate->PruneAndFlush();
1659 }
1660 }
1661 }
1662
1663 // ********************************************************* Step 11: import blocks
1664
1666 InitError(strprintf(_("Error: Disk space is low for %s"), fs::quoted(fs::PathToString(gArgs.GetDataDirNet()))));
1667 return false;
1668 }
1670 InitError(strprintf(_("Error: Disk space is low for %s"), fs::quoted(fs::PathToString(gArgs.GetBlocksDirPath()))));
1671 return false;
1672 }
1673
1674 // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1675 // No locking, as this happens before any background thread is started.
1676 boost::signals2::connection block_notify_genesis_wait_connection;
1677 if (chainman.ActiveChain().Tip() == nullptr) {
1678 block_notify_genesis_wait_connection = uiInterface.NotifyBlockTip_connect(std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
1679 } else {
1680 fHaveGenesis = true;
1681 }
1682
1683#if HAVE_SYSTEM
1684 const std::string block_notify = args.GetArg("-blocknotify", "");
1685 if (!block_notify.empty()) {
1686 uiInterface.NotifyBlockTip_connect([block_notify](SynchronizationState sync_state, const CBlockIndex* pBlockIndex) {
1687 if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) return;
1688 std::string command = block_notify;
1689 boost::replace_all(command, "%s", pBlockIndex->GetBlockHash().GetHex());
1690 std::thread t(runCommand, command);
1691 t.detach(); // thread runs free
1692 });
1693 }
1694#endif
1695
1696 std::vector<fs::path> vImportFiles;
1697 for (const std::string& strFile : args.GetArgs("-loadblock")) {
1698 vImportFiles.push_back(fs::PathFromString(strFile));
1699 }
1700
1701 chainman.m_load_block = std::thread(&util::TraceThread, "loadblk", [=, &chainman, &args] {
1702 ThreadImport(chainman, vImportFiles, args);
1703 });
1704
1705 // Wait for genesis block to be processed
1706 {
1708 // We previously could hang here if StartShutdown() is called prior to
1709 // ThreadImport getting started, so instead we just wait on a timer to
1710 // check ShutdownRequested() regularly.
1711 while (!fHaveGenesis && !ShutdownRequested()) {
1712 g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
1713 }
1714 block_notify_genesis_wait_connection.disconnect();
1715 }
1716
1717 if (ShutdownRequested()) {
1718 return false;
1719 }
1720
1721 // ********************************************************* Step 12: start node
1722
1723 int chain_active_height;
1724
1726 {
1727 LOCK(cs_main);
1728 LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
1729 chain_active_height = chainman.ActiveChain().Height();
1730 if (tip_info) {
1731 tip_info->block_height = chain_active_height;
1732 tip_info->block_time = chainman.ActiveChain().Tip() ? chainman.ActiveChain().Tip()->GetBlockTime() : Params().GenesisBlock().GetBlockTime();
1733 tip_info->verification_progress = GuessVerificationProgress(Params().TxData(), chainman.ActiveChain().Tip());
1734 }
1735 if (tip_info && ::pindexBestHeader) {
1738 }
1739 }
1740 LogPrintf("nBestHeight = %d\n", chain_active_height);
1741 if (node.peerman) node.peerman->SetBestHeight(chain_active_height);
1742
1743 Discover();
1744
1745 // Map ports with UPnP or NAT-PMP.
1747
1748 CConnman::Options connOptions;
1749 connOptions.nLocalServices = nLocalServices;
1750 connOptions.nMaxConnections = nMaxConnections;
1754 connOptions.nMaxFeeler = MAX_FEELER_CONNECTIONS;
1755 connOptions.uiInterface = &uiInterface;
1756 connOptions.m_banman = node.banman.get();
1757 connOptions.m_msgproc = node.peerman.get();
1758 connOptions.nSendBufferMaxSize = 1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1759 connOptions.nReceiveFloodSize = 1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1760 connOptions.m_added_nodes = args.GetArgs("-addnode");
1761
1762 connOptions.nMaxOutboundLimit = 1024 * 1024 * args.GetIntArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
1763 connOptions.m_peer_connect_timeout = peer_connect_timeout;
1764
1765 for (const std::string& bind_arg : args.GetArgs("-bind")) {
1766 CService bind_addr;
1767 const size_t index = bind_arg.rfind('=');
1768 if (index == std::string::npos) {
1769 if (Lookup(bind_arg, bind_addr, GetListenPort(), false)) {
1770 connOptions.vBinds.push_back(bind_addr);
1771 continue;
1772 }
1773 } else {
1774 const std::string network_type = bind_arg.substr(index + 1);
1775 if (network_type == "onion") {
1776 const std::string truncated_bind_arg = bind_arg.substr(0, index);
1777 if (Lookup(truncated_bind_arg, bind_addr, BaseParams().OnionServiceTargetPort(), false)) {
1778 connOptions.onion_binds.push_back(bind_addr);
1779 continue;
1780 }
1781 }
1782 }
1783 return InitError(ResolveErrMsg("bind", bind_arg));
1784 }
1785
1786 for (const std::string& strBind : args.GetArgs("-whitebind")) {
1787 NetWhitebindPermissions whitebind;
1789 if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) return InitError(error);
1790 connOptions.vWhiteBinds.push_back(whitebind);
1791 }
1792
1793 // If the user did not specify -bind= or -whitebind= then we bind
1794 // on any address - 0.0.0.0 (IPv4) and :: (IPv6).
1795 connOptions.bind_on_any = args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
1796
1797 CService onion_service_target;
1798 if (!connOptions.onion_binds.empty()) {
1799 onion_service_target = connOptions.onion_binds.front();
1800 } else {
1801 onion_service_target = DefaultOnionServiceTarget();
1802 connOptions.onion_binds.push_back(onion_service_target);
1803 }
1804
1805 if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
1806 if (connOptions.onion_binds.size() > 1) {
1807 InitWarning(strprintf(_("More than one onion bind address is provided. Using %s "
1808 "for the automatically created Tor onion service."),
1809 onion_service_target.ToStringIPPort()));
1810 }
1811 StartTorControl(onion_service_target);
1812 }
1813
1814 for (const auto& net : args.GetArgs("-whitelist")) {
1817 if (!NetWhitelistPermissions::TryParse(net, subnet, error)) return InitError(error);
1818 connOptions.vWhitelistedRange.push_back(subnet);
1819 }
1820
1821 connOptions.vSeedNodes = args.GetArgs("-seednode");
1822
1823 // Initiate outbound connections unless connect=0
1824 connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect");
1825 if (!connOptions.m_use_addrman_outgoing) {
1826 const auto connect = args.GetArgs("-connect");
1827 if (connect.size() != 1 || connect[0] != "0") {
1828 connOptions.m_specified_outgoing = connect;
1829 }
1830 }
1831
1832 const std::string& i2psam_arg = args.GetArg("-i2psam", "");
1833 if (!i2psam_arg.empty()) {
1834 CService addr;
1835 if (!Lookup(i2psam_arg, addr, 7656, fNameLookup) || !addr.IsValid()) {
1836 return InitError(strprintf(_("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
1837 }
1838 SetReachable(NET_I2P, true);
1839 SetProxy(NET_I2P, proxyType{addr});
1840 } else {
1841 SetReachable(NET_I2P, false);
1842 }
1843
1844 connOptions.m_i2p_accept_incoming = args.GetBoolArg("-i2pacceptincoming", true);
1845
1846 if (!node.connman->Start(*node.scheduler, connOptions)) {
1847 return false;
1848 }
1849
1850 // ********************************************************* Step 13: finished
1851
1853 uiInterface.InitMessage(_("Done loading").translated);
1854
1855 for (const auto& client : node.chain_clients) {
1856 client->start(*node.scheduler);
1857 }
1858
1859 BanMan* banman = node.banman.get();
1860 node.scheduler->scheduleEvery([banman]{
1861 banman->DumpBanlist();
1863
1864 if (node.peerman) node.peerman->StartScheduledTasks(*node.scheduler);
1865
1866#if HAVE_SYSTEM
1867 StartupNotify(args);
1868#endif
1869
1870 return true;
1871}
std::optional< bilingual_str > LoadAddrman(const std::vector< bool > &asmap, const ArgsManager &args, std::unique_ptr< AddrMan > &addrman)
Returns an error string on failure.
Definition: addrdb.cpp:184
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS
Default for -checkaddrman.
Definition: addrman.h:23
arith_uint256 UintToArith256(const uint256 &a)
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition: banman.h:19
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
How often to dump banned addresses/subnets to disk.
Definition: banman.h:22
#define PACKAGE_NAME
#define COPYRIGHT_YEAR
#define PACKAGE_URL
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:280
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:118
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
const std::set< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
BlockFilterType
Definition: blockfilter.h:89
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
bool InitBlockFilterIndex(BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe)
Initialize a block filter index for the given type if one does not already exist.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
bool fHavePruned
Pruning-related variables and constants.
void ThreadImport(ChainstateManager &chainman, std::vector< fs::path > vImportFiles, const ArgsManager &args)
void CleanupBlockRevFiles()
bool fPruneMode
True if we're running in -prune mode.
std::atomic_bool fReindex
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
Definition: blockstorage.h:29
std::unique_ptr< const CChainParams > CreateChainParams(const ArgsManager &args, const std::string &chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
const CChainParams & Params()
Return the currently selected parameters.
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
#define Assert(val)
Identity function.
Definition: check.h:57
const std::set< std::string > GetUnsuitableSectionOnlyArgs() const
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition: system.cpp:266
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:401
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: system.cpp:585
@ NETWORK_ONLY
Definition: system.h:179
@ ALLOW_ANY
disable validation
Definition: system.h:166
@ DEBUG_ONLY
Definition: system.h:173
@ SENSITIVE
Definition: system.h:181
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:487
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:496
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:288
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:596
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:590
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: system.cpp:616
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:602
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: system.cpp:663
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:642
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: system.cpp:286
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:989
std::atomic< bool > m_reopen_file
Definition: logging.h:102
Definition: banman.h:59
void DumpBanlist()
Definition: banman.cpp:40
void Stop()
Stops the instance from staying in sync with blockchain updates.
Definition: base.cpp:357
bool BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(void Interrupt()
Blocks the current thread until the index is caught up to the current state of the block chain.
Definition: base.cpp:338
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
static const std::string REGTEST
static const std::string TESTNET
static const std::string SIGNET
static const std::string MAIN
Chain name strings.
int64_t GetBlockTime() const
Definition: block.h:55
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:146
uint32_t nTime
Definition: chain.h:200
uint256 GetBlockHash() const
Definition: chain.h:254
int64_t GetBlockTime() const
Definition: chain.h:268
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:158
Access to the block database (blocks/index/)
Definition: txdb.h:78
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:421
int Height() const
Return the maximal height in the chain.
Definition: chain.h:446
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:70
const CBlock & GenesisBlock() const
Definition: chainparams.h:95
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
Definition: chainparams.h:97
std::string NetworkIDString() const
Return the network string.
Definition: chainparams.h:112
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
Definition: chainparams.h:99
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:101
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:83
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:544
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:30
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Definition: feerate.cpp:39
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once)
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
bool IsValid() const
Definition: netaddress.cpp:451
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:523
std::string ToStringIPPort() const
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:333
static const int DEFAULT_ZMQ_SNDHWM
static CZMQNotificationInterface * Create()
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:847
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
Definition: validation.h:906
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:910
CChainState &InitializeChainstate(CTxMemPool *mempool, const std::optional< uint256 > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
Definition: validation.h:925
CChainState & ActiveChainstate() const
The most-work chain.
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:949
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
std::thread m_load_block
Definition: validation.h:899
CChain & ActiveChain() const
Definition: validation.h:945
static bool TryParse(const std::string &str, NetWhitebindPermissions &output, bilingual_str &error)
static bool TryParse(const std::string &str, NetWhitelistPermissions &output, bilingual_str &error)
static std::unique_ptr< PeerManager > make(const CChainParams &chainparams, CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, bool ignore_incoming_txs)
virtual void AddWalletOptions(ArgsManager &argsman) const =0
Get wallet help string.
virtual void Construct(NodeContext &node) const =0
Add wallets that should be opened to list of chain clients.
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
std::string ToString() const
Definition: uint256.cpp:64
bool IsNull() const
Definition: uint256.h:31
std::string GetHex() const
Definition: uint256.cpp:20
std::string GetHex() const
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:34
bool IsValid() const
Definition: netbase.h:54
256-bit opaque blob.
Definition: uint256.h:124
std::string FormatSubVersion(const std::string &name, int nClientVersion, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip...
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:33
const std::string CLIENT_NAME
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: error.cpp:53
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
Definition: error.cpp:43
const std::string CURRENCY_UNIT
Definition: feerate.h:14
uint256 SerializeHash(const T &obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
Compute the 256-bit hash of an object's serialization.
Definition: hash.h:192
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:310
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:315
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
Definition: httprpc.cpp:292
void StartREST(const std::any &context)
Start HTTP REST subsystem.
Definition: rest.cpp:728
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:740
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:736
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:430
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:418
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:350
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:442
static const int DEFAULT_HTTP_SERVER_TIMEOUT
Definition: httpserver.h:13
static const int DEFAULT_HTTP_WORKQUEUE
Definition: httpserver.h:12
static const int DEFAULT_HTTP_THREADS
Definition: httpserver.h:11
Common init functions shared by bitcoin-node, bitcoin-wallet, etc.
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
Definition: init.cpp:112
static bool CreatePidFile(const ArgsManager &args)
Definition: init.cpp:119
static const bool DEFAULT_PROXYRANDOMIZE
Definition: init.cpp:95
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:159
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:715
static bool AppInitServers(NodeContext &node)
Definition: init.cpp:620
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1090
void SetupServerArgs(ArgsManager &argsman)
Register all arguments with the ArgsManager.
Definition: init.cpp:352
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:104
static bool fHaveGenesis
Definition: init.cpp:594
void Shutdown(NodeContext &node)
Definition: init.cpp:178
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
Definition: init.cpp:309
static void OnRPCStarted()
Definition: init.cpp:339
static Mutex g_genesis_wait_mutex
Definition: init.cpp:595
static void HandleSIGHUP(int)
Definition: init.cpp:314
static fs::path GetPidFile(const ArgsManager &args)
Definition: init.cpp:114
static std::condition_variable g_genesis_wait_cv
Definition: init.cpp:596
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:745
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1074
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:790
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:1102
static const char * DEFAULT_ASMAP_FILENAME
Definition: init.cpp:107
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:637
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
Definition: init.cpp:598
static void OnRPCStopped()
Definition: init.cpp:344
static bool LockDataDirectory(bool probeOnly)
Definition: init.cpp:1061
static void registerSignalHandler(int signal, void(*handler)(int))
Definition: init.cpp:328
std::string LicenseInfo()
Returns licensing information (for -version)
Definition: init.cpp:575
bool AppInitMain(NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
Definition: init.cpp:1113
static const bool DEFAULT_REST_ENABLE
Definition: init.cpp:96
static boost::signals2::connection rpc_notify_block_change_connection
Definition: init.cpp:338
static void new_handler_terminate()
Definition: init.cpp:732
static constexpr bool DEFAULT_DAEMON
Default value for -daemon option.
Definition: init.h:14
static constexpr bool DEFAULT_DAEMONWAIT
Default value for -daemonwait option.
Definition: init.h:16
BCLog::Logger & LogInstance()
Definition: logging.cpp:17
#define LogPrint(category,...)
Definition: logging.h:191
#define LogPrintf(...)
Definition: logging.h:187
void StartMapPort(bool use_upnp, bool use_natpmp)
Definition: mapport.cpp:327
void StopMapPort()
Definition: mapport.cpp:335
void InterruptMapPort()
Definition: mapport.cpp:331
static constexpr bool DEFAULT_NATPMP
Definition: mapport.h:17
static constexpr bool DEFAULT_UPNP
Definition: mapport.h:11
static void pool cs
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:26
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:41
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:15
@ RPC
Definition: logging.h:45
void OnStarted(std::function< void()> slot)
Definition: server.cpp:69
void OnStopped(std::function< void()> slot)
Definition: server.cpp:74
static auto quoted(const std::string &s)
Definition: fs.h:83
static bool exists(const path &p)
Definition: fs.h:77
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:120
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:133
fs::ofstream ofstream
Definition: fs.h:225
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:138
void AddLoggingArgs(ArgsManager &argsman)
Definition: common.cpp:61
void SetLoggingCategories(const ArgsManager &args)
Definition: common.cpp:96
bool SanityChecks()
Ensure a usable environment with all necessary library support.
Definition: common.cpp:41
void SetGlobals()
Definition: common.cpp:26
bool StartLogging(const ArgsManager &args)
Definition: common.cpp:120
void SetLoggingOptions(const ArgsManager &args)
Definition: common.cpp:81
void UnsetGlobals()
Definition: common.cpp:35
void LogPackageVersion()
Definition: common.cpp:157
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1062
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:13
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
Definition: threadnames.cpp:57
uint16_t GetListenPort()
Definition: net.cpp:125
bool fDiscover
Definition: net.cpp:112
bool AddLocal(const CService &addr_, int nScore)
Definition: net.cpp:250
bool fListen
Definition: net.cpp:113
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:117
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:290
void Discover()
Definition: net.cpp:2402
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:71
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:59
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:63
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:85
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:79
static constexpr bool DEFAULT_FIXEDSEEDS
Definition: net.h:83
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:75
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:48
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:46
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:73
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:84
static constexpr bool DEFAULT_FORCEDNSSEED
Definition: net.h:81
static constexpr bool DEFAULT_DNSSEED
Definition: net.h:82
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:67
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:69
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:77
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:61
@ LOCAL_MANUAL
Definition: net.h:193
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:65
const std::vector< std::string > NET_PERMISSIONS_DOC
static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of orphan+recently-replaced txn to keep around for block reconstruction.
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
static const bool DEFAULT_PEERBLOCKFILTERS
static const bool DEFAULT_PEERBLOOMFILTERS
Network
A network type.
Definition: netaddress.h:45
@ NET_I2P
I2P.
Definition: netaddress.h:59
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:62
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:69
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:56
@ NET_IPV6
IPv6.
Definition: netaddress.h:53
@ NET_IPV4
IPv4.
Definition: netaddress.h:50
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:47
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:87
bool Lookup(const std::string &name, std::vector< CService > &vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:198
bool fNameLookup
Definition: netbase.cpp:37
int nConnectTimeout
Definition: netbase.cpp:36
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition: netbase.cpp:626
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:608
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition: netbase.cpp:121
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:30
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:28
bool fIsBareMultisigStd
Definition: settings.cpp:11
CFeeRate incrementalRelayFee
Definition: settings.cpp:12
CFeeRate dustRelayFee
Definition: settings.cpp:13
unsigned int nBytesPerSigOp
Definition: settings.cpp:14
static const unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
Definition: policy.h:54
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:32
static const unsigned int DEFAULT_BLOCK_MIN_TX_FEE
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
Definition: policy.h:22
static const unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or BIP...
Definition: policy.h:34
static const bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
Definition: policy.h:38
static const unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create.
Definition: policy.h:20
static const unsigned int DEFAULT_BYTES_PER_SIGOP
Default for -bytespersigop.
Definition: policy.h:36
ServiceFlags
nServices flags
Definition: protocol.h:271
@ NODE_WITNESS
Definition: protocol.h:284
@ NODE_NETWORK_LIMITED
Definition: protocol.h:291
@ NODE_BLOOM
Definition: protocol.h:281
@ NODE_NETWORK
Definition: protocol.h:277
@ NODE_COMPACT_FILTERS
Definition: protocol.h:287
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
Definition: random.cpp:586
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:591
static void RegisterAllCoreRPCCommands(CRPCTable &t)
Definition: register.h:25
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:715
const char * name
Definition: rest.cpp:43
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Definition: util.cpp:21
void SetRPCWarmupFinished()
Definition: server.cpp:337
void StartRPC()
Definition: server.cpp:290
void StopRPC()
Definition: server.cpp:308
void InterruptRPC()
Definition: server.cpp:297
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:331
CRPCTable tableRPC
Definition: server.cpp:548
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
Definition: server.cpp:326
static const unsigned int DEFAULT_RPC_SERIALIZE_VERSION
Definition: server.h:19
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:87
bool InitShutdownState()
Initialize shutdown state.
Definition: shutdown.cpp:45
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:56
void AbortShutdown()
Clear shutdown flag.
Definition: shutdown.cpp:77
void InitSignatureCache()
Definition: sigcache.cpp:95
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:18
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
Definition: standard.cpp:19
unsigned nMaxDatacarrierBytes
Maximum size of TxoutType::NULL_DATA scripts that this node considers standard.
Definition: standard.cpp:20
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
Definition: standard.h:38
static const bool DEFAULT_ACCEPT_DATACARRIER
Definition: standard.h:18
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
bool IsHexNumber(const std::string &str)
Return true if the string is a hex number, optionally prefixed with "0x".
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
Definition: strencodings.h:27
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:44
int m_max_outbound_block_relay
Definition: net.h:749
unsigned int nReceiveFloodSize
Definition: net.h:756
int m_max_outbound_full_relay
Definition: net.h:748
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:761
uint64_t nMaxOutboundLimit
Definition: net.h:757
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:760
CClientUIInterface * uiInterface
Definition: net.h:752
std::vector< CService > onion_binds
Definition: net.h:763
int nMaxFeeler
Definition: net.h:751
std::vector< std::string > m_specified_outgoing
Definition: net.h:768
NetEventsInterface * m_msgproc
Definition: net.h:753
int nMaxConnections
Definition: net.h:747
ServiceFlags nLocalServices
Definition: net.h:746
std::vector< std::string > m_added_nodes
Definition: net.h:769
int64_t m_peer_connect_timeout
Definition: net.h:758
std::vector< CService > vBinds
Definition: net.h:762
unsigned int nSendBufferMaxSize
Definition: net.h:755
bool m_i2p_accept_incoming
Definition: net.h:770
std::vector< std::string > vSeedNodes
Definition: net.h:759
BanMan * m_banman
Definition: net.h:754
bool m_use_addrman_outgoing
Definition: net.h:767
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:766
int nMaxAddnode
Definition: net.h:750
uint256 defaultAssumeValid
By default assume that the signatures in ancestors of this block are valid.
Definition: params.h:109
int SegwitHeight
Block height at which Segwit (BIP141, BIP143 and BIP147) becomes active.
Definition: params.h:87
uint256 hashGenesisBlock
Definition: params.h:71
uint256 nMinimumChainWork
The best chain should have at least this much work.
Definition: params.h:107
NodeContext struct containing references to chain state and connection state.
Definition: context.h:39
Bilingual messages:
Definition: translation.h:16
bool empty() const
Definition: translation.h:27
std::string translated
Definition: translation.h:18
std::string original
Definition: translation.h:17
Block and header tip information.
Definition: node.h:45
#define WAIT_LOCK(cs, name)
Definition: sync.h:231
#define LOCK(cs)
Definition: sync.h:226
#define TRY_LOCK(cs, name)
Definition: sync.h:230
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:117
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:101
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
Definition: timedata.h:13
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
CService DefaultOnionServiceTarget()
Definition: torcontrol.cpp:633
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:40
void InterruptTorControl()
Definition: torcontrol.cpp:614
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:595
void StopTorControl()
Definition: torcontrol.cpp:624
static const bool DEFAULT_LISTEN_ONION
Definition: torcontrol.h:28
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:63
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:46
std::optional< bilingual_str > CheckLegacyTxindex(CBlockTreeDB &block_tree_db)
Definition: txdb.cpp:35
static const int64_t nMinDbCache
min. -dbcache (MiB)
Definition: txdb.h:33
static const int64_t nDefaultDbBatchSize
-dbbatchsize default (bytes)
Definition: txdb.h:29
static const int64_t nMaxCoinsDBCache
Max memory allocated to coin DB specific cache (MiB)
Definition: txdb.h:43
static const int64_t nMaxBlockDBCache
Max memory allocated to block tree DB specific cache, if no -txindex (MiB)
Definition: txdb.h:35
static const int64_t nMaxTxIndexCache
Max memory allocated to block tree DB specific cache, if -txindex (MiB)
Definition: txdb.h:39
static const int64_t nMaxDbCache
max. -dbcache (MiB)
Definition: txdb.h:31
static const int64_t nDefaultDbCache
-dbcache default (MiB)
Definition: txdb.h:27
static const int64_t max_filter_index_cache
Max memory allocated to all block filter index caches combined in MiB.
Definition: txdb.h:41
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:14
CClientUIInterface uiInterface
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
uint256 uint256S(const char *str)
Definition: uint256.h:137
std::vector< bool > DecodeAsmap(fs::path path)
Read asmap from provided binary file.
Definition: asmap.cpp:193
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:744
fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: system.cpp:1368
const char *const BITCOIN_SETTINGS_FILENAME
Definition: system.cpp:83
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1350
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: system.cpp:96
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:132
bool SetupNetworking()
Definition: system.cpp:1333
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:1149
ArgsManager gArgs
Definition: system.cpp:85
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: system.cpp:145
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:82
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1345
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:130
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:131
bool fCheckBlockIndex
Definition: validation.cpp:126
std::condition_variable g_best_block_cv
Definition: validation.cpp:122
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
Definition: validation.cpp:124
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:133
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
void InitScriptExecutionCache()
Initializes the script-execution cache.
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:81
bool fCheckpointsEnabled
Definition: validation.cpp:127
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:120
bool DumpMempool(const CTxMemPool &pool, FopenFn mockable_fopen_function, bool skip_file_commit)
Dump the mempool to disk.
bool fRequireStandard
Definition: validation.cpp:125
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
Definition: validation.cpp:128
assert(!tx.IsCoinBase())
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:70
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:60
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:90
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:62
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:81
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h:79
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:66
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:93
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:54
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:68
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:73
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:64
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:58
static constexpr bool DEFAULT_COINSTATSINDEX
Definition: validation.h:72
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:56
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:69
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:80
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:75
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:77
static const bool DEFAULT_TXINDEX
Definition: validation.h:71
CMainSignals & GetMainSignals()
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
const WalletInitInterface & g_wallet_init_interface
Definition: init.cpp:42
CZMQNotificationInterface * g_zmq_notification_interface
void RegisterZMQRPCCommands(CRPCTable &t)
Definition: zmqrpc.cpp:62