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