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