Bitcoin Core  0.20.99
P2P Digital Currency
init.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #if defined(HAVE_CONFIG_H)
8 #endif
9 
10 #include <init.h>
11 
12 #include <addrman.h>
13 #include <amount.h>
14 #include <banman.h>
15 #include <blockfilter.h>
16 #include <chain.h>
17 #include <chainparams.h>
18 #include <compat/sanity.h>
19 #include <consensus/validation.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/txindex.h>
26 #include <interfaces/chain.h>
27 #include <interfaces/node.h>
28 #include <key.h>
29 #include <miner.h>
30 #include <net.h>
31 #include <net_permissions.h>
32 #include <net_processing.h>
33 #include <netbase.h>
34 #include <node/context.h>
35 #include <node/ui_interface.h>
36 #include <policy/feerate.h>
37 #include <policy/fees.h>
38 #include <policy/policy.h>
39 #include <policy/settings.h>
40 #include <protocol.h>
41 #include <rpc/blockchain.h>
42 #include <rpc/register.h>
43 #include <rpc/server.h>
44 #include <rpc/util.h>
45 #include <scheduler.h>
46 #include <script/sigcache.h>
47 #include <script/standard.h>
48 #include <shutdown.h>
49 #include <sync.h>
50 #include <timedata.h>
51 #include <torcontrol.h>
52 #include <txdb.h>
53 #include <txmempool.h>
54 #include <util/asmap.h>
55 #include <util/check.h>
56 #include <util/moneystr.h>
57 #include <util/string.h>
58 #include <util/system.h>
59 #include <util/threadnames.h>
60 #include <util/translation.h>
61 #include <validation.h>
62 
63 #include <validationinterface.h>
64 #include <walletinitinterface.h>
65 
66 #include <functional>
67 #include <set>
68 #include <stdint.h>
69 #include <stdio.h>
70 
71 #ifndef WIN32
72 #include <attributes.h>
73 #include <cerrno>
74 #include <signal.h>
75 #include <sys/stat.h>
76 #endif
77 
78 #include <boost/algorithm/string/replace.hpp>
79 #include <boost/signals2/signal.hpp>
80 #include <boost/thread/thread.hpp>
81 
82 #if ENABLE_ZMQ
85 #include <zmq/zmqrpc.h>
86 #endif
87 
88 static bool fFeeEstimatesInitialized = false;
89 static const bool DEFAULT_PROXYRANDOMIZE = true;
90 static const bool DEFAULT_REST_ENABLE = false;
91 static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
92 
93 #ifdef WIN32
94 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
95 // accessing block files don't count towards the fd_set size limit
96 // anyway.
97 #define MIN_CORE_FILEDESCRIPTORS 0
98 #else
99 #define MIN_CORE_FILEDESCRIPTORS 150
100 #endif
101 
102 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
103 
104 static const char* DEFAULT_ASMAP_FILENAME="ip_asn.map";
105 
109 static const char* BITCOIN_PID_FILENAME = "bitcoind.pid";
110 
111 static fs::path GetPidFile(const ArgsManager& args)
112 {
113  return AbsPathForConfigVal(fs::path(args.GetArg("-pid", BITCOIN_PID_FILENAME)));
114 }
115 
116 NODISCARD static bool CreatePidFile(const ArgsManager& args)
117 {
118  fsbridge::ofstream file{GetPidFile(args)};
119  if (file) {
120 #ifdef WIN32
121  tfm::format(file, "%d\n", GetCurrentProcessId());
122 #else
123  tfm::format(file, "%d\n", getpid());
124 #endif
125  return true;
126  } else {
127  return InitError(strprintf(_("Unable to create the PID file '%s': %s"), GetPidFile(args).string(), std::strerror(errno)));
128  }
129 }
130 
132 //
133 // Shutdown
134 //
135 
136 //
137 // Thread management and startup/shutdown:
138 //
139 // The network-processing threads are all part of a thread group
140 // created by AppInit() or the Qt main() function.
141 //
142 // A clean exit happens when StartShutdown() or the SIGTERM
143 // signal handler sets ShutdownRequested(), which makes main thread's
144 // WaitForShutdown() interrupts the thread group.
145 // And then, WaitForShutdown() makes all other on-going threads
146 // in the thread group join the main thread.
147 // Shutdown() is then called to clean up database connections, and stop other
148 // threads that should only be stopped after the main network-processing
149 // threads have exited.
150 //
151 // Shutdown for Qt is very similar, only it uses a QTimer to detect
152 // ShutdownRequested() getting set, and then does the normal Qt
153 // shutdown thing.
154 //
155 
156 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
157 
158 static std::thread g_load_block;
159 
160 static boost::thread_group threadGroup;
161 
163 {
166  InterruptRPC();
167  InterruptREST();
170  if (node.connman)
171  node.connman->Interrupt();
172  if (g_txindex) {
173  g_txindex->Interrupt();
174  }
175  ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Interrupt(); });
176 }
177 
179 {
180  static Mutex g_shutdown_mutex;
181  TRY_LOCK(g_shutdown_mutex, lock_shutdown);
182  if (!lock_shutdown) return;
183  LogPrintf("%s: In progress...\n", __func__);
184  Assert(node.args);
185 
190  util::ThreadRename("shutoff");
191  if (node.mempool) node.mempool->AddTransactionsUpdated(1);
192 
193  StopHTTPRPC();
194  StopREST();
195  StopRPC();
196  StopHTTPServer();
197  for (const auto& client : node.chain_clients) {
198  client->flush();
199  }
200  StopMapPort();
201 
202  // Because these depend on each-other, we make sure that neither can be
203  // using the other before destroying them.
204  if (node.peerman) UnregisterValidationInterface(node.peerman.get());
205  // Follow the lock order requirements:
206  // * CheckForStaleTipAndEvictPeers locks cs_main before indirectly calling GetExtraOutboundCount
207  // which locks cs_vNodes.
208  // * ProcessMessage locks cs_main and g_cs_orphans before indirectly calling ForEachNode which
209  // locks cs_vNodes.
210  // * CConnman::Stop calls DeleteNode, which calls FinalizeNode, which locks cs_main and calls
211  // EraseOrphansFor, which locks g_cs_orphans.
212  //
213  // Thus the implicit locking order requirement is: (1) cs_main, (2) g_cs_orphans, (3) cs_vNodes.
214  if (node.connman) {
215  node.connman->StopThreads();
216  LOCK2(::cs_main, ::g_cs_orphans);
217  node.connman->StopNodes();
218  }
219 
220  StopTorControl();
221 
222  // After everything has been shut down, but before things get flushed, stop the
223  // CScheduler/checkqueue, threadGroup and load block thread.
224  if (node.scheduler) node.scheduler->stop();
225  if (g_load_block.joinable()) g_load_block.join();
226  threadGroup.interrupt_all();
227  threadGroup.join_all();
228 
229  // After the threads that potentially access these pointers have been stopped,
230  // destruct and reset all to nullptr.
231  node.peerman.reset();
232  node.connman.reset();
233  node.banman.reset();
234 
235  if (node.mempool && node.mempool->IsLoaded() && node.args->GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
236  DumpMempool(*node.mempool);
237  }
238 
240  {
242  fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
243  CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
244  if (!est_fileout.IsNull())
245  ::feeEstimator.Write(est_fileout);
246  else
247  LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
248  fFeeEstimatesInitialized = false;
249  }
250 
251  // FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing
252  if (node.chainman) {
253  LOCK(cs_main);
254  for (CChainState* chainstate : node.chainman->GetAll()) {
255  if (chainstate->CanFlushToDisk()) {
256  chainstate->ForceFlushStateToDisk();
257  }
258  }
259  }
260 
261  // After there are no more peers/RPC left to give us new data which may generate
262  // CValidationInterface callbacks, flush them...
264 
265  // Stop and delete all indexes only after flushing background callbacks.
266  if (g_txindex) {
267  g_txindex->Stop();
268  g_txindex.reset();
269  }
270  ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Stop(); });
272 
273  // Any future callbacks will be dropped. This should absolutely be safe - if
274  // missing a callback results in an unrecoverable situation, unclean shutdown
275  // would too. The only reason to do the above flushes is to let the wallet catch
276  // up with our current chain to avoid any strange pruning edge cases and make
277  // next startup faster by avoiding rescan.
278 
279  if (node.chainman) {
280  LOCK(cs_main);
281  for (CChainState* chainstate : node.chainman->GetAll()) {
282  if (chainstate->CanFlushToDisk()) {
283  chainstate->ForceFlushStateToDisk();
284  chainstate->ResetCoinsViews();
285  }
286  }
287  pblocktree.reset();
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();
304  globalVerifyHandle.reset();
305  ECC_Stop();
306  node.mempool.reset();
307  node.chainman = nullptr;
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 {
365  rpc_notify_block_change_connection.disconnect();
366  RPCNotifyBlockChange(nullptr);
367  g_best_block_cv.notify_all();
368  LogPrint(BCLog::RPC, "RPC stopped.\n");
369 }
370 
372 {
373  assert(!node.args);
374  node.args = &gArgs;
375  ArgsManager& argsman = *node.args;
376 
377  SetupHelpOptions(argsman);
378  argsman.AddArg("-help-debug", "Print help message with debugging options and exit", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); // server-only for now
379 
380  const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
381  const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
382  const auto signetBaseParams = CreateBaseChainParams(CBaseChainParams::SIGNET);
383  const auto regtestBaseParams = CreateBaseChainParams(CBaseChainParams::REGTEST);
384  const auto defaultChainParams = CreateChainParams(argsman, CBaseChainParams::MAIN);
385  const auto testnetChainParams = CreateChainParams(argsman, CBaseChainParams::TESTNET);
386  const auto signetChainParams = CreateChainParams(argsman, CBaseChainParams::SIGNET);
387  const auto regtestChainParams = CreateChainParams(argsman, CBaseChainParams::REGTEST);
388 
389  // Hidden Options
390  std::vector<std::string> hidden_args = {
391  "-dbcrashratio", "-forcecompactdb",
392  // GUI args. These will be overwritten by SetupUIArgs for the GUI
393  "-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-splash", "-uiplatform"};
394 
395  argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
396 #if HAVE_SYSTEM
397  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);
398 #endif
399  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);
400  argsman.AddArg("-blocksdir=<dir>", "Specify directory to hold blocks subdirectory for *.dat files (default: <datadir>)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
401 #if HAVE_SYSTEM
402  argsman.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
403 #endif
404  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);
405  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);
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("-debuglogfile=<file>", strprintf("Specify location of debug log file. Relative paths will be prefixed by a net-specific datadir location. (-nodebuglogfile to disable; default: %s)", DEFAULT_DEBUGLOGFILE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
411  argsman.AddArg("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
412  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);
413  argsman.AddArg("-loadblock=<file>", "Imports blocks from external file on startup", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
414  argsman.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
415  argsman.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
416  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);
417  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);
418  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)",
420  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);
421  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);
422  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 -rescan. "
423  "Warning: Reverting this setting requires re-downloading the entire blockchain. "
424  "(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);
425  argsman.AddArg("-reindex", "Rebuild chain state and block index from the blk*.dat files on disk", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
426  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);
427  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);
428 #if HAVE_SYSTEM
429  argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
430 #endif
431 #ifndef WIN32
432  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);
433 #else
434  hidden_args.emplace_back("-sysperms");
435 #endif
436  argsman.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
437  argsman.AddArg("-blockfilterindex=<type>",
438  strprintf("Maintain an index of compact filters by block (default: %s, values: %s).", DEFAULT_BLOCKFILTERINDEX, ListBlockFilterTypes()) +
439  " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
441 
442  argsman.AddArg("-addnode=<ip>", "Add a node to connect to and attempt to keep the connection open (see the `addnode` RPC command help for more info). This option can be specified multiple times to add multiple nodes.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
443  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);
444  argsman.AddArg("-bantime=<n>", strprintf("Default duration (in seconds) of manually configured bans (default: %u)", DEFAULT_MISBEHAVING_BANTIME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
445  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);
446  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);
447  argsman.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
448  argsman.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
449  argsman.AddArg("-dnsseed", "Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
450  argsman.AddArg("-externalip=<ip>", "Specify your own public address", 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)", DEFAULT_MAX_PEER_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 (in MiB per 24h). Limit does not apply to peers with 'download' permission. 0 = no limit (default: %d)", DEFAULT_MAX_UPLOAD_TARGET), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
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("-onlynet=<net>", "Make outgoing connections only through network <net> (ipv4, ipv6 or onion). Incoming connections are not affected by this option. This option can be specified multiple times to allow multiple networks.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
461  argsman.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
462  argsman.AddArg("-peerblockfilters", strprintf("Serve compact block filters to peers per BIP 157 (default: %u)", DEFAULT_PEERBLOCKFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
463  argsman.AddArg("-permitbaremultisig", strprintf("Relay non-P2SH multisig (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
464  argsman.AddArg("-port=<port>", strprintf("Listen for connections on <port> (default: %u, testnet: %u signet: %u, regtest: %u)", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
465  argsman.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
466  argsman.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
467  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);
468  argsman.AddArg("-networkactive", "Enable all P2P network activity (default: 1). Can be changed by the setnetworkactive RPC command", ArgsManager::ALLOW_BOOL, OptionsCategory::CONNECTION);
469  argsman.AddArg("-timeout=<n>", strprintf("Specify connection timeout in milliseconds (minimum: 1, default: %d)", DEFAULT_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
470  argsman.AddArg("-peertimeout=<n>", strprintf("Specify p2p connection timeout in seconds. This option determines the amount of time a peer may be inactive before the connection to it is dropped. (minimum: 1, default: %d)", DEFAULT_PEER_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
471  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);
472  argsman.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::CONNECTION);
473 #ifdef USE_UPNP
474 #if USE_UPNP
475  argsman.AddArg("-upnp", "Use UPnP to map the listening port (default: 1 when listening and no -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
476 #else
477  argsman.AddArg("-upnp", strprintf("Use UPnP to map the listening port (default: %u)", 0), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
478 #endif
479 #else
480  hidden_args.emplace_back("-upnp");
481 #endif
482  argsman.AddArg("-whitebind=<[permissions@]addr>", "Bind to the given address and add permission flags to the peers connecting to it. "
483  "Use [host]:port notation for IPv6. Allowed permissions: " + Join(NET_PERMISSIONS_DOC, ", ") + ". "
484  "Specify multiple permissions separated by commas (default: download,noban,mempool,relay). Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
485 
486  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 "
487  "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as "
488  "-whitebind. Can be specified multiple times." , ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
489 
491 
492 #if ENABLE_ZMQ
493  argsman.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
494  argsman.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
495  argsman.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
496  argsman.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
497  argsman.AddArg("-zmqpubsequence=<address>", "Enable publish hash block and tx sequence in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
498  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);
499  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);
500  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);
501  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);
502  argsman.AddArg("-zmqpubsequencehwm=<n>", strprintf("Set publish hash sequence message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
503 #else
504  hidden_args.emplace_back("-zmqpubhashblock=<address>");
505  hidden_args.emplace_back("-zmqpubhashtx=<address>");
506  hidden_args.emplace_back("-zmqpubrawblock=<address>");
507  hidden_args.emplace_back("-zmqpubrawtx=<address>");
508  hidden_args.emplace_back("-zmqpubsequence=<n>");
509  hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
510  hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
511  hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
512  hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
513  hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
514 #endif
515 
516  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);
517  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);
518  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);
519  argsman.AddArg("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
520  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);
521  argsman.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
522  argsman.AddArg("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
523  argsman.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
524  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);
525  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);
526  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);
527  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);
528  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);
529  argsman.AddArg("-addrmantest", "Allows to test address relay on localhost", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
530  argsman.AddArg("-debug=<category>", "Output debugging information (default: -nodebug, supplying <category> is optional). "
531  "If <category> is not supplied or if <category> = 1, output all debugging information. <category> can be: " + LogInstance().LogCategoriesString() + ".",
533  argsman.AddArg("-debugexclude=<category>", strprintf("Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except one or more specified categories."), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
534  argsman.AddArg("-logips", strprintf("Include IP addresses in debug output (default: %u)", DEFAULT_LOGIPS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
535  argsman.AddArg("-logtimestamps", strprintf("Prepend debug output with timestamp (default: %u)", DEFAULT_LOGTIMESTAMPS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
536 #ifdef HAVE_THREAD_LOCAL
537  argsman.AddArg("-logthreadnames", strprintf("Prepend debug output with name of the originating thread (only available on platforms supporting thread_local) (default: %u)", DEFAULT_LOGTHREADNAMES), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
538 #else
539  hidden_args.emplace_back("-logthreadnames");
540 #endif
541  argsman.AddArg("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
542  argsman.AddArg("-mocktime=<n>", "Replace actual time with " + UNIX_EPOCH_TIME + " (default: 0)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
543  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);
544  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);
545  argsman.AddArg("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
546  argsman.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -daemon. To disable logging to file, set -nodebuglogfile)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
547  argsman.AddArg("-shrinkdebugfile", "Shrink debug.log file on client startup (default: 1 when no -debug)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
548  argsman.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
549 
551 
552  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);
553  argsman.AddArg("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kB) 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);
554  argsman.AddArg("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) 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);
555  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);
556  argsman.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
557  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);
558  argsman.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
560  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);
561  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);
562 
563 
564  argsman.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
565  argsman.AddArg("-blockmintxfee=<amt>", strprintf("Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
566  argsman.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::BLOCK_CREATION);
567 
568  argsman.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
569  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);
570  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);
571  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);
572  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);
573  argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
574  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);
575  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);
576  argsman.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
577  argsman.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
578  argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
579  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);
580  argsman.AddArg("-rpcwhitelistdefault", "Sets default behavior for rpc whitelisting. Unless rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc server acts as if all rpc users are subject to empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault is set to 1 and no -rpcwhitelist is set, rpc server acts as if all rpc users are subject to empty whitelists.", ArgsManager::ALLOW_BOOL, OptionsCategory::RPC);
581  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);
582  argsman.AddArg("-server", "Accept command line and JSON-RPC commands", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
583 
584 #if HAVE_DECL_DAEMON
585  argsman.AddArg("-daemon", "Run in the background as a daemon and accept commands", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
586 #else
587  hidden_args.emplace_back("-daemon");
588 #endif
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  {
621  LOCK(g_genesis_wait_mutex);
622  fHaveGenesis = true;
623  }
624  g_genesis_wait_cv.notify_all();
625  }
626 }
627 
629 {
631  assert(fImporting == false);
632  fImporting = true;
633  }
634 
636  assert(fImporting == true);
637  fImporting = false;
638  }
639 };
640 
641 
642 // If we're using -prune with -reindex, then delete block files that will be ignored by the
643 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
644 // is missing, do the same here to delete any later block files after a gap. Also delete all
645 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
646 // is in sync with what's actually on disk by the time we start downloading, so that pruning
647 // works correctly.
648 static void CleanupBlockRevFiles()
649 {
650  std::map<std::string, fs::path> mapBlockFiles;
651 
652  // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
653  // Remove the rev files immediately and insert the blk file paths into an
654  // ordered map keyed by block file index.
655  LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
656  fs::path blocksdir = GetBlocksDir();
657  for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
658  if (fs::is_regular_file(*it) &&
659  it->path().filename().string().length() == 12 &&
660  it->path().filename().string().substr(8,4) == ".dat")
661  {
662  if (it->path().filename().string().substr(0,3) == "blk")
663  mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
664  else if (it->path().filename().string().substr(0,3) == "rev")
665  remove(it->path());
666  }
667  }
668 
669  // Remove all block files that aren't part of a contiguous set starting at
670  // zero by walking the ordered map (keys are block file indices) by
671  // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
672  // start removing block files.
673  int nContigCounter = 0;
674  for (const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
675  if (atoi(item.first) == nContigCounter) {
676  nContigCounter++;
677  continue;
678  }
679  remove(item.second);
680  }
681 }
682 
683 #if HAVE_SYSTEM
684 static void StartupNotify(const ArgsManager& args)
685 {
686  std::string cmd = args.GetArg("-startupnotify", "");
687  if (!cmd.empty()) {
688  std::thread t(runCommand, cmd);
689  t.detach(); // thread runs free
690  }
691 }
692 #endif
693 
694 static void ThreadImport(ChainstateManager& chainman, std::vector<fs::path> vImportFiles, const ArgsManager& args)
695 {
696  const CChainParams& chainparams = Params();
698 
699  {
700  CImportingNow imp;
701 
702  // -reindex
703  if (fReindex) {
704  int nFile = 0;
705  while (true) {
706  FlatFilePos pos(nFile, 0);
707  if (!fs::exists(GetBlockPosFilename(pos)))
708  break; // No block files left to reindex
709  FILE *file = OpenBlockFile(pos, true);
710  if (!file)
711  break; // This error is logged in OpenBlockFile
712  LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
713  LoadExternalBlockFile(chainparams, file, &pos);
714  if (ShutdownRequested()) {
715  LogPrintf("Shutdown requested. Exit %s\n", __func__);
716  return;
717  }
718  nFile++;
719  }
720  pblocktree->WriteReindexing(false);
721  fReindex = false;
722  LogPrintf("Reindexing finished\n");
723  // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
724  LoadGenesisBlock(chainparams);
725  }
726 
727  // -loadblock=
728  for (const fs::path& path : vImportFiles) {
729  FILE *file = fsbridge::fopen(path, "rb");
730  if (file) {
731  LogPrintf("Importing blocks file %s...\n", path.string());
732  LoadExternalBlockFile(chainparams, file);
733  if (ShutdownRequested()) {
734  LogPrintf("Shutdown requested. Exit %s\n", __func__);
735  return;
736  }
737  } else {
738  LogPrintf("Warning: Could not open blocks file %s\n", path.string());
739  }
740  }
741 
742  // scan for better chains in the block chain database, that are not yet connected in the active best chain
743 
744  // We can't hold cs_main during ActivateBestChain even though we're accessing
745  // the chainman unique_ptrs since ABC requires us not to be holding cs_main, so retrieve
746  // the relevant pointers before the ABC call.
747  for (CChainState* chainstate : WITH_LOCK(::cs_main, return chainman.GetAll())) {
748  BlockValidationState state;
749  if (!chainstate->ActivateBestChain(state, chainparams, nullptr)) {
750  LogPrintf("Failed to connect best block (%s)\n", state.ToString());
751  StartShutdown();
752  return;
753  }
754  }
755 
756  if (args.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
757  LogPrintf("Stopping after block import\n");
758  StartShutdown();
759  return;
760  }
761  } // End scope of CImportingNow
762  chainman.ActiveChainstate().LoadMempool(args);
763 }
764 
769 static bool InitSanityCheck()
770 {
771  if (!ECC_InitSanityCheck()) {
772  return InitError(Untranslated("Elliptic curve cryptography sanity check failure. Aborting."));
773  }
774 
776  return false;
777 
778  if (!Random_SanityCheck()) {
779  return InitError(Untranslated("OS cryptographic RNG sanity check failure. Aborting."));
780  }
781 
782  return true;
783 }
784 
785 static bool AppInitServers(const util::Ref& context, NodeContext& node)
786 {
787  const ArgsManager& args = *Assert(node.args);
790  if (!InitHTTPServer())
791  return false;
792  StartRPC();
794  if (!StartHTTPRPC(context))
795  return false;
796  if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) StartREST(context);
797  StartHTTPServer();
798  return true;
799 }
800 
801 // Parameter interaction based on rules
803 {
804  // when specifying an explicit binding address, you want to listen on it
805  // even when -connect or -proxy is specified
806  if (args.IsArgSet("-bind")) {
807  if (args.SoftSetBoolArg("-listen", true))
808  LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
809  }
810  if (args.IsArgSet("-whitebind")) {
811  if (args.SoftSetBoolArg("-listen", true))
812  LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
813  }
814 
815  if (args.IsArgSet("-connect")) {
816  // when only connecting to trusted nodes, do not seed via DNS, or listen by default
817  if (args.SoftSetBoolArg("-dnsseed", false))
818  LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
819  if (args.SoftSetBoolArg("-listen", false))
820  LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
821  }
822 
823  if (args.IsArgSet("-proxy")) {
824  // to protect privacy, do not listen by default if a default proxy server is specified
825  if (args.SoftSetBoolArg("-listen", false))
826  LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
827  // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
828  // to listen locally, so don't rely on this happening through -listen below.
829  if (args.SoftSetBoolArg("-upnp", false))
830  LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
831  // to protect privacy, do not discover addresses by default
832  if (args.SoftSetBoolArg("-discover", false))
833  LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
834  }
835 
836  if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
837  // do not map ports or try to retrieve public IP when not listening (pointless)
838  if (args.SoftSetBoolArg("-upnp", false))
839  LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
840  if (args.SoftSetBoolArg("-discover", false))
841  LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
842  if (args.SoftSetBoolArg("-listenonion", false))
843  LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
844  }
845 
846  if (args.IsArgSet("-externalip")) {
847  // if an explicit public IP is specified, do not try to find others
848  if (args.SoftSetBoolArg("-discover", false))
849  LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
850  }
851 
852  // disable whitelistrelay in blocksonly mode
853  if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
854  if (args.SoftSetBoolArg("-whitelistrelay", false))
855  LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
856  }
857 
858  // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
859  if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
860  if (args.SoftSetBoolArg("-whitelistrelay", true))
861  LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
862  }
863 }
864 
871 void InitLogging(const ArgsManager& args)
872 {
873  LogInstance().m_print_to_file = !args.IsArgNegated("-debuglogfile");
875  LogInstance().m_print_to_console = args.GetBoolArg("-printtoconsole", !args.GetBoolArg("-daemon", false));
876  LogInstance().m_log_timestamps = args.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
878 #ifdef HAVE_THREAD_LOCAL
879  LogInstance().m_log_threadnames = args.GetBoolArg("-logthreadnames", DEFAULT_LOGTHREADNAMES);
880 #endif
881 
882  fLogIPs = args.GetBoolArg("-logips", DEFAULT_LOGIPS);
883 
884  std::string version_string = FormatFullVersion();
885 #ifdef DEBUG
886  version_string += " (debug build)";
887 #else
888  version_string += " (release build)";
889 #endif
890  LogPrintf(PACKAGE_NAME " version %s\n", version_string);
891 }
892 
893 namespace { // Variables internal to initialization process only
894 
895 int nMaxConnections;
896 int nUserMaxConnections;
897 int nFD;
899 int64_t peer_connect_timeout;
900 std::set<BlockFilterType> g_enabled_filter_types;
901 
902 } // namespace
903 
904 [[noreturn]] static void new_handler_terminate()
905 {
906  // Rather than throwing std::bad-alloc if allocation fails, terminate
907  // immediately to (try to) avoid chain corruption.
908  // Since LogPrintf may itself allocate memory, set the handler directly
909  // to terminate first.
910  std::set_new_handler(std::terminate);
911  LogPrintf("Error: Out of memory. Terminating.\n");
912 
913  // The log was successful, terminate now.
914  std::terminate();
915 };
916 
918 {
919  // ********************************************************* Step 1: setup
920 #ifdef _MSC_VER
921  // Turn off Microsoft heap dump noise
922  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
923  _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
924  // Disable confusing "helpful" text message on abort, Ctrl-C
925  _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
926 #endif
927 #ifdef WIN32
928  // Enable heap terminate-on-corruption
929  HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0);
930 #endif
931 
932  if (!SetupNetworking()) {
933  return InitError(Untranslated("Initializing networking failed."));
934  }
935 
936 #ifndef WIN32
937  if (!args.GetBoolArg("-sysperms", false)) {
938  umask(077);
939  }
940 
941  // Clean shutdown on SIGTERM
944 
945  // Reopen debug.log on SIGHUP
947 
948  // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
949  signal(SIGPIPE, SIG_IGN);
950 #else
951  SetConsoleCtrlHandler(consoleCtrlHandler, true);
952 #endif
953 
954  std::set_new_handler(new_handler_terminate);
955 
956  return true;
957 }
958 
960 {
961  const CChainParams& chainparams = Params();
962  // ********************************************************* Step 2: parameter interactions
963 
964  // also see: InitParameterInteraction()
965 
966  // Error if network-specific options (-addnode, -connect, etc) are
967  // specified in default section of config file, but not overridden
968  // on the command line or in this network's section of the config file.
969  std::string network = args.GetChainName();
970  if (network == CBaseChainParams::SIGNET) {
971  LogPrintf("Signet derived magic (message start): %s\n", HexStr(chainparams.MessageStart()));
972  }
973  bilingual_str errors;
974  for (const auto& arg : args.GetUnsuitableSectionOnlyArgs()) {
975  errors += strprintf(_("Config setting for %s only applied on %s network when in [%s] section.") + Untranslated("\n"), arg, network, network);
976  }
977 
978  if (!errors.empty()) {
979  return InitError(errors);
980  }
981 
982  // Warn if unrecognized section name are present in the config file.
983  bilingual_str warnings;
984  for (const auto& section : args.GetUnrecognizedSections()) {
985  warnings += strprintf(Untranslated("%s:%i ") + _("Section [%s] is not recognized.") + Untranslated("\n"), section.m_file, section.m_line, section.m_name);
986  }
987 
988  if (!warnings.empty()) {
989  InitWarning(warnings);
990  }
991 
992  if (!fs::is_directory(GetBlocksDir())) {
993  return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist."), args.GetArg("-blocksdir", "")));
994  }
995 
996  // parse and validate enabled filter types
997  std::string blockfilterindex_value = args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
998  if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
999  g_enabled_filter_types = AllBlockFilterTypes();
1000  } else if (blockfilterindex_value != "0") {
1001  const std::vector<std::string> names = args.GetArgs("-blockfilterindex");
1002  for (const auto& name : names) {
1003  BlockFilterType filter_type;
1004  if (!BlockFilterTypeByName(name, filter_type)) {
1005  return InitError(strprintf(_("Unknown -blockfilterindex value %s."), name));
1006  }
1007  g_enabled_filter_types.insert(filter_type);
1008  }
1009  }
1010 
1011  // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index are both enabled.
1012  if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
1013  if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
1014  return InitError(_("Cannot set -peerblockfilters without -blockfilterindex."));
1015  }
1016 
1017  nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS);
1018  }
1019 
1020  // if using block pruning, then disallow txindex
1021  if (args.GetArg("-prune", 0)) {
1022  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX))
1023  return InitError(_("Prune mode is incompatible with -txindex."));
1024  if (!g_enabled_filter_types.empty()) {
1025  return InitError(_("Prune mode is incompatible with -blockfilterindex."));
1026  }
1027  }
1028 
1029  // -bind and -whitebind can't be set when not listening
1030  size_t nUserBind = args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
1031  if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1032  return InitError(Untranslated("Cannot set -bind or -whitebind together with -listen=0"));
1033  }
1034 
1035  // Make sure enough file descriptors are available
1036  int nBind = std::max(nUserBind, size_t(1));
1037  nUserMaxConnections = args.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1038  nMaxConnections = std::max(nUserMaxConnections, 0);
1039 
1040  // Trim requested connection counts, to fit into system limitations
1041  // <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695
1043 #ifdef USE_POLL
1044  int fd_max = nFD;
1045 #else
1046  int fd_max = FD_SETSIZE;
1047 #endif
1048  nMaxConnections = std::max(std::min<int>(nMaxConnections, fd_max - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS), 0);
1049  if (nFD < MIN_CORE_FILEDESCRIPTORS)
1050  return InitError(_("Not enough file descriptors available."));
1051  nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
1052 
1053  if (nMaxConnections < nUserMaxConnections)
1054  InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
1055 
1056  // ********************************************************* Step 3: parameter-to-internal-flags
1057  if (args.IsArgSet("-debug")) {
1058  // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
1059  const std::vector<std::string> categories = args.GetArgs("-debug");
1060 
1061  if (std::none_of(categories.begin(), categories.end(),
1062  [](std::string cat){return cat == "0" || cat == "none";})) {
1063  for (const auto& cat : categories) {
1064  if (!LogInstance().EnableCategory(cat)) {
1065  InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
1066  }
1067  }
1068  }
1069  }
1070 
1071  // Now remove the logging categories which were explicitly excluded
1072  for (const std::string& cat : args.GetArgs("-debugexclude")) {
1073  if (!LogInstance().DisableCategory(cat)) {
1074  InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
1075  }
1076  }
1077 
1078  fCheckBlockIndex = args.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
1080 
1081  hashAssumeValid = uint256S(args.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
1082  if (!hashAssumeValid.IsNull())
1083  LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
1084  else
1085  LogPrintf("Validating signatures for all blocks.\n");
1086 
1087  if (args.IsArgSet("-minimumchainwork")) {
1088  const std::string minChainWorkStr = args.GetArg("-minimumchainwork", "");
1089  if (!IsHexNumber(minChainWorkStr)) {
1090  return InitError(strprintf(Untranslated("Invalid non-hex (%s) minimum chain work value specified"), minChainWorkStr));
1091  }
1092  nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
1093  } else {
1095  }
1096  LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
1098  LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex());
1099  }
1100 
1101  // mempool limits
1102  int64_t nMempoolSizeMax = args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1103  int64_t nMempoolSizeMin = args.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
1104  if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
1105  return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
1106  // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
1107  // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
1108  if (args.IsArgSet("-incrementalrelayfee")) {
1109  CAmount n = 0;
1110  if (!ParseMoney(args.GetArg("-incrementalrelayfee", ""), n))
1111  return InitError(AmountErrMsg("incrementalrelayfee", args.GetArg("-incrementalrelayfee", "")));
1113  }
1114 
1115  // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
1116  int64_t nPruneArg = args.GetArg("-prune", 0);
1117  if (nPruneArg < 0) {
1118  return InitError(_("Prune cannot be configured with a negative value."));
1119  }
1120  nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
1121  if (nPruneArg == 1) { // manual pruning: -prune=1
1122  LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1123  nPruneTarget = std::numeric_limits<uint64_t>::max();
1124  fPruneMode = true;
1125  } else if (nPruneTarget) {
1127  return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1128  }
1129  LogPrintf("Prune configured to target %u MiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1130  fPruneMode = true;
1131  }
1132 
1133  nConnectTimeout = args.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1134  if (nConnectTimeout <= 0) {
1136  }
1137 
1138  peer_connect_timeout = args.GetArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
1139  if (peer_connect_timeout <= 0) {
1140  return InitError(Untranslated("peertimeout cannot be configured with a negative value."));
1141  }
1142 
1143  if (args.IsArgSet("-minrelaytxfee")) {
1144  CAmount n = 0;
1145  if (!ParseMoney(args.GetArg("-minrelaytxfee", ""), n)) {
1146  return InitError(AmountErrMsg("minrelaytxfee", args.GetArg("-minrelaytxfee", "")));
1147  }
1148  // High fee check is done afterward in CWallet::CreateWalletFromFile()
1150  } else if (incrementalRelayFee > ::minRelayTxFee) {
1151  // Allow only setting incrementalRelayFee to control both
1153  LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1154  }
1155 
1156  // Sanity check argument for min fee for including tx in block
1157  // TODO: Harmonize which arguments need sanity checking and where that happens
1158  if (args.IsArgSet("-blockmintxfee")) {
1159  CAmount n = 0;
1160  if (!ParseMoney(args.GetArg("-blockmintxfee", ""), n))
1161  return InitError(AmountErrMsg("blockmintxfee", args.GetArg("-blockmintxfee", "")));
1162  }
1163 
1164  // Feerate used to define dust. Shouldn't be changed lightly as old
1165  // implementations may inadvertently create non-standard transactions
1166  if (args.IsArgSet("-dustrelayfee")) {
1167  CAmount n = 0;
1168  if (!ParseMoney(args.GetArg("-dustrelayfee", ""), n))
1169  return InitError(AmountErrMsg("dustrelayfee", args.GetArg("-dustrelayfee", "")));
1170  dustRelayFee = CFeeRate(n);
1171  }
1172 
1173  fRequireStandard = !args.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1174  if (!chainparams.IsTestChain() && !fRequireStandard) {
1175  return InitError(strprintf(Untranslated("acceptnonstdtxn is not currently supported for %s chain"), chainparams.NetworkIDString()));
1176  }
1177  nBytesPerSigOp = args.GetArg("-bytespersigop", nBytesPerSigOp);
1178 
1179  if (!g_wallet_init_interface.ParameterInteraction()) return false;
1180 
1181  fIsBareMultisigStd = args.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1183  nMaxDatacarrierBytes = args.GetArg("-datacarriersize", nMaxDatacarrierBytes);
1184 
1185  // Option to startup with mocktime set (used for regression testing):
1186  SetMockTime(args.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1187 
1188  if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1189  nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1190 
1191  if (args.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1192  return InitError(Untranslated("rpcserialversion must be non-negative."));
1193 
1194  if (args.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1195  return InitError(Untranslated("Unknown rpcserialversion requested."));
1196 
1197  nMaxTipAge = args.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1198 
1199  if (args.IsArgSet("-proxy") && args.GetArg("-proxy", "").empty()) {
1200  return InitError(_("No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
1201  }
1202 
1203  return true;
1204 }
1205 
1206 static bool LockDataDirectory(bool probeOnly)
1207 {
1208  // Make sure only a single Bitcoin process is using the data directory.
1209  fs::path datadir = GetDataDir();
1210  if (!DirIsWritable(datadir)) {
1211  return InitError(strprintf(_("Cannot write to data directory '%s'; check permissions."), datadir.string()));
1212  }
1213  if (!LockDirectory(datadir, ".lock", probeOnly)) {
1214  return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), datadir.string(), PACKAGE_NAME));
1215  }
1216  return true;
1217 }
1218 
1220 {
1221  // ********************************************************* Step 4: sanity checks
1222 
1223  // Initialize elliptic curve code
1224  std::string sha256_algo = SHA256AutoDetect();
1225  LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
1226  RandomInit();
1227  ECC_Start();
1228  globalVerifyHandle.reset(new ECCVerifyHandle());
1229 
1230  // Sanity check
1231  if (!InitSanityCheck())
1232  return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), PACKAGE_NAME));
1233 
1234  // Probe the data directory lock to give an early error message, if possible
1235  // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened,
1236  // and a fork will cause weird behavior to it.
1237  return LockDataDirectory(true);
1238 }
1239 
1241 {
1242  // After daemonization get the data directory lock again and hold on to it until exit
1243  // This creates a slight window for a race condition to happen, however this condition is harmless: it
1244  // will at most make us exit without printing a message to console.
1245  if (!LockDataDirectory(false)) {
1246  // Detailed error printed inside LockDataDirectory
1247  return false;
1248  }
1249  return true;
1250 }
1251 
1253 {
1254  node.chain = interfaces::MakeChain(node);
1255  // Create client interfaces for wallets that are supposed to be loaded
1256  // according to -wallet and -disablewallet options. This only constructs
1257  // the interfaces, it doesn't load wallet data. Wallets actually get loaded
1258  // when load() and start() interface methods are called below.
1260  return true;
1261 }
1262 
1264 {
1265  const ArgsManager& args = *Assert(node.args);
1266  const CChainParams& chainparams = Params();
1267  // ********************************************************* Step 4a: application initialization
1268  if (!CreatePidFile(args)) {
1269  // Detailed error printed inside CreatePidFile().
1270  return false;
1271  }
1272  if (LogInstance().m_print_to_file) {
1273  if (args.GetBoolArg("-shrinkdebugfile", LogInstance().DefaultShrinkDebugFile())) {
1274  // Do this first since it both loads a bunch of debug.log into memory,
1275  // and because this needs to happen before any other debug.log printing
1277  }
1278  }
1279  if (!LogInstance().StartLogging()) {
1280  return InitError(strprintf(Untranslated("Could not open debug log file %s"),
1281  LogInstance().m_file_path.string()));
1282  }
1283 
1284  if (!LogInstance().m_log_timestamps)
1285  LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
1286  LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1287  LogPrintf("Using data directory %s\n", GetDataDir().string());
1288 
1289  // Only log conf file usage message if conf file actually exists.
1290  fs::path config_file_path = GetConfigFile(args.GetArg("-conf", BITCOIN_CONF_FILENAME));
1291  if (fs::exists(config_file_path)) {
1292  LogPrintf("Config file: %s\n", config_file_path.string());
1293  } else if (args.IsArgSet("-conf")) {
1294  // Warn if no conf file exists at path provided by user
1295  InitWarning(strprintf(_("The specified config file %s does not exist\n"), config_file_path.string()));
1296  } else {
1297  // Not categorizing as "Warning" because it's the default behavior
1298  LogPrintf("Config file: %s (not found, skipping)\n", config_file_path.string());
1299  }
1300 
1301  // Log the config arguments to debug.log
1302  args.LogArgs();
1303 
1304  LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1305 
1306  // Warn about relative -datadir path.
1307  if (args.IsArgSet("-datadir") && !fs::path(args.GetArg("-datadir", "")).is_absolute()) {
1308  LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " /* Continued */
1309  "current working directory '%s'. This is fragile, because if bitcoin is started in the future "
1310  "from a different location, it will be unable to locate the current data files. There could "
1311  "also be data loss if bitcoin is started while in a temporary directory.\n",
1312  args.GetArg("-datadir", ""), fs::current_path().string());
1313  }
1314 
1317 
1318  int script_threads = args.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
1319  if (script_threads <= 0) {
1320  // -par=0 means autodetect (number of cores - 1 script threads)
1321  // -par=-n means "leave n cores free" (number of cores - n - 1 script threads)
1322  script_threads += GetNumCores();
1323  }
1324 
1325  // Subtract 1 because the main thread counts towards the par threads
1326  script_threads = std::max(script_threads - 1, 0);
1327 
1328  // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
1329  script_threads = std::min(script_threads, MAX_SCRIPTCHECK_THREADS);
1330 
1331  LogPrintf("Script verification uses %d additional threads\n", script_threads);
1332  if (script_threads >= 1) {
1333  g_parallel_script_checks = true;
1334  for (int i = 0; i < script_threads; ++i) {
1335  threadGroup.create_thread([i]() { return ThreadScriptCheck(i); });
1336  }
1337  }
1338 
1339  assert(!node.scheduler);
1340  node.scheduler = MakeUnique<CScheduler>();
1341 
1342  // Start the lightweight task scheduler thread
1343  threadGroup.create_thread([&] { TraceThread("scheduler", [&] { node.scheduler->serviceQueue(); }); });
1344 
1345  // Gather some entropy once per minute.
1346  node.scheduler->scheduleEvery([]{
1347  RandAddPeriodic();
1348  }, std::chrono::minutes{1});
1349 
1351 
1352  /* Register RPC commands regardless of -server setting so they will be
1353  * available in the GUI RPC console even if external calls are disabled.
1354  */
1356  for (const auto& client : node.chain_clients) {
1357  client->registerRpcs();
1358  }
1359 #if ENABLE_ZMQ
1361 #endif
1362 
1363  /* Start the RPC server already. It will be started in "warmup" mode
1364  * and not really process calls already (but it will signify connections
1365  * that the server is there and will be ready later). Warmup mode will
1366  * be disabled when initialisation is finished.
1367  */
1368  if (args.GetBoolArg("-server", false)) {
1369  uiInterface.InitMessage_connect(SetRPCWarmupStatus);
1370  if (!AppInitServers(context, node))
1371  return InitError(_("Unable to start HTTP server. See debug log for details."));
1372  }
1373 
1374  // ********************************************************* Step 5: verify wallet database integrity
1375  for (const auto& client : node.chain_clients) {
1376  if (!client->verify()) {
1377  return false;
1378  }
1379  }
1380 
1381  // ********************************************************* Step 6: network initialization
1382  // Note that we absolutely cannot open any actual connections
1383  // until the very end ("start node") as the UTXO/block state
1384  // is not yet setup and may end up being set up twice if we
1385  // need to reindex later.
1386 
1387  assert(!node.banman);
1388  node.banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", &uiInterface, args.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
1389  assert(!node.connman);
1390  node.connman = MakeUnique<CConnman>(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max()), args.GetBoolArg("-networkactive", true));
1391 
1392  // Make mempool generally available in the node context. For example the connection manager, wallet, or RPC threads,
1393  // which are all started after this, may use it from the node context.
1394  assert(!node.mempool);
1395  node.mempool = MakeUnique<CTxMemPool>(&::feeEstimator);
1396  if (node.mempool) {
1397  int ratio = std::min<int>(std::max<int>(args.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
1398  if (ratio != 0) {
1399  node.mempool->setSanityCheck(1.0 / ratio);
1400  }
1401  }
1402 
1403  assert(!node.chainman);
1404  node.chainman = &g_chainman;
1405  ChainstateManager& chainman = *Assert(node.chainman);
1406 
1407  node.peerman.reset(new PeerManager(chainparams, *node.connman, node.banman.get(), *node.scheduler, chainman, *node.mempool));
1409 
1410  // sanitize comments per BIP-0014, format user agent and check total size
1411  std::vector<std::string> uacomments;
1412  for (const std::string& cmt : args.GetArgs("-uacomment")) {
1413  if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1414  return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1415  uacomments.push_back(cmt);
1416  }
1418  if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1419  return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1421  }
1422 
1423  if (args.IsArgSet("-onlynet")) {
1424  std::set<enum Network> nets;
1425  for (const std::string& snet : args.GetArgs("-onlynet")) {
1426  enum Network net = ParseNetwork(snet);
1427  if (net == NET_UNROUTABLE)
1428  return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1429  nets.insert(net);
1430  }
1431  for (int n = 0; n < NET_MAX; n++) {
1432  enum Network net = (enum Network)n;
1433  if (!nets.count(net))
1434  SetReachable(net, false);
1435  }
1436  }
1437 
1438  // Check for host lookup allowed before parsing any network related parameters
1439  fNameLookup = args.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1440 
1441  bool proxyRandomize = args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1442  // -proxy sets a proxy for all outgoing network traffic
1443  // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1444  std::string proxyArg = args.GetArg("-proxy", "");
1445  SetReachable(NET_ONION, false);
1446  if (proxyArg != "" && proxyArg != "0") {
1447  CService proxyAddr;
1448  if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) {
1449  return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1450  }
1451 
1452  proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1453  if (!addrProxy.IsValid())
1454  return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1455 
1456  SetProxy(NET_IPV4, addrProxy);
1457  SetProxy(NET_IPV6, addrProxy);
1458  SetProxy(NET_ONION, addrProxy);
1459  SetNameProxy(addrProxy);
1460  SetReachable(NET_ONION, true); // by default, -proxy sets onion as reachable, unless -noonion later
1461  }
1462 
1463  // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1464  // -noonion (or -onion=0) disables connecting to .onion entirely
1465  // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1466  std::string onionArg = args.GetArg("-onion", "");
1467  if (onionArg != "") {
1468  if (onionArg == "0") { // Handle -noonion/-onion=0
1469  SetReachable(NET_ONION, false);
1470  } else {
1471  CService onionProxy;
1472  if (!Lookup(onionArg, onionProxy, 9050, fNameLookup)) {
1473  return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1474  }
1475  proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1476  if (!addrOnion.IsValid())
1477  return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1478  SetProxy(NET_ONION, addrOnion);
1479  SetReachable(NET_ONION, true);
1480  }
1481  }
1482 
1483  // see Step 2: parameter interactions for more information about these
1484  fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
1485  fDiscover = args.GetBoolArg("-discover", true);
1486  g_relay_txes = !args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1487 
1488  for (const std::string& strAddr : args.GetArgs("-externalip")) {
1489  CService addrLocal;
1490  if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1491  AddLocal(addrLocal, LOCAL_MANUAL);
1492  else
1493  return InitError(ResolveErrMsg("externalip", strAddr));
1494  }
1495 
1496  // Read asmap file if configured
1497  if (args.IsArgSet("-asmap")) {
1498  fs::path asmap_path = fs::path(args.GetArg("-asmap", ""));
1499  if (asmap_path.empty()) {
1500  asmap_path = DEFAULT_ASMAP_FILENAME;
1501  }
1502  if (!asmap_path.is_absolute()) {
1503  asmap_path = GetDataDir() / asmap_path;
1504  }
1505  if (!fs::exists(asmap_path)) {
1506  InitError(strprintf(_("Could not find asmap file %s"), asmap_path));
1507  return false;
1508  }
1509  std::vector<bool> asmap = CAddrMan::DecodeAsmap(asmap_path);
1510  if (asmap.size() == 0) {
1511  InitError(strprintf(_("Could not parse asmap file %s"), asmap_path));
1512  return false;
1513  }
1514  const uint256 asmap_version = SerializeHash(asmap);
1515  node.connman->SetAsmap(std::move(asmap));
1516  LogPrintf("Using asmap version %s for IP bucketing\n", asmap_version.ToString());
1517  } else {
1518  LogPrintf("Using /16 prefix for IP bucketing\n");
1519  }
1520 
1521 #if ENABLE_ZMQ
1523 
1526  }
1527 #endif
1528  uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1529  uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1530 
1531  if (args.IsArgSet("-maxuploadtarget")) {
1532  nMaxOutboundLimit = args.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET) * 1024 * 1024;
1533  }
1534 
1535  // ********************************************************* Step 7: load block chain
1536 
1537  fReindex = args.GetBoolArg("-reindex", false);
1538  bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
1539 
1540  // cache size calculations
1541  int64_t nTotalCache = (args.GetArg("-dbcache", nDefaultDbCache) << 20);
1542  nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1543  nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1544  int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20);
1545  nTotalCache -= nBlockTreeDBCache;
1546  int64_t nTxIndexCache = std::min(nTotalCache / 8, args.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0);
1547  nTotalCache -= nTxIndexCache;
1548  int64_t filter_index_cache = 0;
1549  if (!g_enabled_filter_types.empty()) {
1550  size_t n_indexes = g_enabled_filter_types.size();
1551  int64_t max_cache = std::min(nTotalCache / 8, max_filter_index_cache << 20);
1552  filter_index_cache = max_cache / n_indexes;
1553  nTotalCache -= filter_index_cache * n_indexes;
1554  }
1555  int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1556  nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1557  nTotalCache -= nCoinDBCache;
1558  int64_t nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1559  int64_t nMempoolSizeMax = args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1560  LogPrintf("Cache configuration:\n");
1561  LogPrintf("* Using %.1f MiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1562  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1563  LogPrintf("* Using %.1f MiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
1564  }
1565  for (BlockFilterType filter_type : g_enabled_filter_types) {
1566  LogPrintf("* Using %.1f MiB for %s block filter index database\n",
1567  filter_index_cache * (1.0 / 1024 / 1024), BlockFilterTypeName(filter_type));
1568  }
1569  LogPrintf("* Using %.1f MiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1570  LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
1571 
1572  bool fLoaded = false;
1573  while (!fLoaded && !ShutdownRequested()) {
1574  bool fReset = fReindex;
1575  auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
1576  return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull();
1577  };
1578  bilingual_str strLoadError;
1579 
1580  uiInterface.InitMessage(_("Loading block index...").translated);
1581 
1582  do {
1583  const int64_t load_block_index_start_time = GetTimeMillis();
1584  try {
1585  LOCK(cs_main);
1586  chainman.InitializeChainstate(*Assert(node.mempool));
1587  chainman.m_total_coinstip_cache = nCoinCacheUsage;
1588  chainman.m_total_coinsdb_cache = nCoinDBCache;
1589 
1590  UnloadBlockIndex(node.mempool.get(), chainman);
1591 
1592  // new CBlockTreeDB tries to delete the existing file, which
1593  // fails if it's still open from the previous loop. Close it first:
1594  pblocktree.reset();
1595  pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
1596 
1597  if (fReset) {
1598  pblocktree->WriteReindexing(true);
1599  //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1600  if (fPruneMode)
1602  }
1603 
1604  if (ShutdownRequested()) break;
1605 
1606  // LoadBlockIndex will load fHavePruned if we've ever removed a
1607  // block file from disk.
1608  // Note that it also sets fReindex based on the disk flag!
1609  // From here on out fReindex and fReset mean something different!
1610  if (!chainman.LoadBlockIndex(chainparams)) {
1611  if (ShutdownRequested()) break;
1612  strLoadError = _("Error loading block database");
1613  break;
1614  }
1615 
1616  // If the loaded chain has a wrong genesis, bail out immediately
1617  // (we're likely using a testnet datadir, or the other way around).
1618  if (!chainman.BlockIndex().empty() &&
1620  return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1621  }
1622 
1623  // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1624  // in the past, but is now trying to run unpruned.
1625  if (fHavePruned && !fPruneMode) {
1626  strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1627  break;
1628  }
1629 
1630  // At this point blocktree args are consistent with what's on disk.
1631  // If we're not mid-reindex (based on disk + args), add a genesis block on disk
1632  // (otherwise we use the one already on disk).
1633  // This is called again in ThreadImport after the reindex completes.
1634  if (!fReindex && !LoadGenesisBlock(chainparams)) {
1635  strLoadError = _("Error initializing block database");
1636  break;
1637  }
1638 
1639  // At this point we're either in reindex or we've loaded a useful
1640  // block tree into BlockIndex()!
1641 
1642  bool failed_chainstate_init = false;
1643 
1644  for (CChainState* chainstate : chainman.GetAll()) {
1645  chainstate->InitCoinsDB(
1646  /* cache_size_bytes */ nCoinDBCache,
1647  /* in_memory */ false,
1648  /* should_wipe */ fReset || fReindexChainState);
1649 
1650  chainstate->CoinsErrorCatcher().AddReadErrCallback([]() {
1651  uiInterface.ThreadSafeMessageBox(
1652  _("Error reading from database, shutting down."),
1654  });
1655 
1656  // If necessary, upgrade from older database format.
1657  // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1658  if (!chainstate->CoinsDB().Upgrade()) {
1659  strLoadError = _("Error upgrading chainstate database");
1660  failed_chainstate_init = true;
1661  break;
1662  }
1663 
1664  // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1665  if (!chainstate->ReplayBlocks(chainparams)) {
1666  strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1667  failed_chainstate_init = true;
1668  break;
1669  }
1670 
1671  // The on-disk coinsdb is now in a good state, create the cache
1672  chainstate->InitCoinsCache(nCoinCacheUsage);
1673  assert(chainstate->CanFlushToDisk());
1674 
1675  if (!is_coinsview_empty(chainstate)) {
1676  // LoadChainTip initializes the chain based on CoinsTip()'s best block
1677  if (!chainstate->LoadChainTip(chainparams)) {
1678  strLoadError = _("Error initializing block database");
1679  failed_chainstate_init = true;
1680  break; // out of the per-chainstate loop
1681  }
1682  assert(chainstate->m_chain.Tip() != nullptr);
1683  }
1684  }
1685 
1686  if (failed_chainstate_init) {
1687  break; // out of the chainstate activation do-while
1688  }
1689  } catch (const std::exception& e) {
1690  LogPrintf("%s\n", e.what());
1691  strLoadError = _("Error opening block database");
1692  break;
1693  }
1694 
1695  bool failed_rewind{false};
1696  // Can't hold cs_main while calling RewindBlockIndex, so retrieve the relevant
1697  // chainstates beforehand.
1698  for (CChainState* chainstate : WITH_LOCK(::cs_main, return chainman.GetAll())) {
1699  if (!fReset) {
1700  // Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate.
1701  // It both disconnects blocks based on the chainstate, and drops block data in
1702  // BlockIndex() based on lack of available witness data.
1703  uiInterface.InitMessage(_("Rewinding blocks...").translated);
1704  if (!chainstate->RewindBlockIndex(chainparams)) {
1705  strLoadError = _(
1706  "Unable to rewind the database to a pre-fork state. "
1707  "You will need to redownload the blockchain");
1708  failed_rewind = true;
1709  break; // out of the per-chainstate loop
1710  }
1711  }
1712  }
1713 
1714  if (failed_rewind) {
1715  break; // out of the chainstate activation do-while
1716  }
1717 
1718  bool failed_verification = false;
1719 
1720  try {
1721  LOCK(cs_main);
1722 
1723  for (CChainState* chainstate : chainman.GetAll()) {
1724  if (!is_coinsview_empty(chainstate)) {
1725  uiInterface.InitMessage(_("Verifying blocks...").translated);
1726  if (fHavePruned && args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1727  LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
1729  }
1730 
1731  const CBlockIndex* tip = chainstate->m_chain.Tip();
1732  RPCNotifyBlockChange(tip);
1733  if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1734  strLoadError = _("The block database contains a block which appears to be from the future. "
1735  "This may be due to your computer's date and time being set incorrectly. "
1736  "Only rebuild the block database if you are sure that your computer's date and time are correct");
1737  failed_verification = true;
1738  break;
1739  }
1740 
1741  // Only verify the DB of the active chainstate. This is fixed in later
1742  // work when we allow VerifyDB to be parameterized by chainstate.
1743  if (&::ChainstateActive() == chainstate &&
1744  !CVerifyDB().VerifyDB(
1745  chainparams, &chainstate->CoinsDB(),
1746  args.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1747  args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1748  strLoadError = _("Corrupted block database detected");
1749  failed_verification = true;
1750  break;
1751  }
1752  }
1753  }
1754  } catch (const std::exception& e) {
1755  LogPrintf("%s\n", e.what());
1756  strLoadError = _("Error opening block database");
1757  failed_verification = true;
1758  break;
1759  }
1760 
1761  if (!failed_verification) {
1762  fLoaded = true;
1763  LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time);
1764  }
1765  } while(false);
1766 
1767  if (!fLoaded && !ShutdownRequested()) {
1768  // first suggest a reindex
1769  if (!fReset) {
1770  bool fRet = uiInterface.ThreadSafeQuestion(
1771  strLoadError + Untranslated(".\n\n") + _("Do you want to rebuild the block database now?"),
1772  strLoadError.original + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1774  if (fRet) {
1775  fReindex = true;
1776  AbortShutdown();
1777  } else {
1778  LogPrintf("Aborted block database rebuild. Exiting.\n");
1779  return false;
1780  }
1781  } else {
1782  return InitError(strLoadError);
1783  }
1784  }
1785  }
1786 
1787  // As LoadBlockIndex can take several minutes, it's possible the user
1788  // requested to kill the GUI during the last operation. If so, exit.
1789  // As the program has not fully started yet, Shutdown() is possibly overkill.
1790  if (ShutdownRequested()) {
1791  LogPrintf("Shutdown requested. Exiting.\n");
1792  return false;
1793  }
1794 
1795  fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1796  CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
1797  // Allowed to fail as this file IS missing on first startup.
1798  if (!est_filein.IsNull())
1799  ::feeEstimator.Read(est_filein);
1800  fFeeEstimatesInitialized = true;
1801 
1802  // ********************************************************* Step 8: start indexers
1803  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1804  g_txindex = MakeUnique<TxIndex>(nTxIndexCache, false, fReindex);
1805  g_txindex->Start();
1806  }
1807 
1808  for (const auto& filter_type : g_enabled_filter_types) {
1809  InitBlockFilterIndex(filter_type, filter_index_cache, false, fReindex);
1810  GetBlockFilterIndex(filter_type)->Start();
1811  }
1812 
1813  // ********************************************************* Step 9: load wallet
1814  for (const auto& client : node.chain_clients) {
1815  if (!client->load()) {
1816  return false;
1817  }
1818  }
1819 
1820  // ********************************************************* Step 10: data directory maintenance
1821 
1822  // if pruning, unset the service bit and perform the initial blockstore prune
1823  // after any wallet rescanning has taken place.
1824  if (fPruneMode) {
1825  LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1826  nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1827  if (!fReindex) {
1828  LOCK(cs_main);
1829  for (CChainState* chainstate : chainman.GetAll()) {
1830  uiInterface.InitMessage(_("Pruning blockstore...").translated);
1831  chainstate->PruneAndFlush();
1832  }
1833  }
1834  }
1835 
1836  if (chainparams.GetConsensus().SegwitHeight != std::numeric_limits<int>::max()) {
1837  // Advertise witness capabilities.
1838  // The option to not set NODE_WITNESS is only used in the tests and should be removed.
1839  nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1840  }
1841 
1842  // ********************************************************* Step 11: import blocks
1843 
1844  if (!CheckDiskSpace(GetDataDir())) {
1845  InitError(strprintf(_("Error: Disk space is low for %s"), GetDataDir()));
1846  return false;
1847  }
1848  if (!CheckDiskSpace(GetBlocksDir())) {
1849  InitError(strprintf(_("Error: Disk space is low for %s"), GetBlocksDir()));
1850  return false;
1851  }
1852 
1853  // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1854  // No locking, as this happens before any background thread is started.
1855  boost::signals2::connection block_notify_genesis_wait_connection;
1856  if (::ChainActive().Tip() == nullptr) {
1857  block_notify_genesis_wait_connection = uiInterface.NotifyBlockTip_connect(std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
1858  } else {
1859  fHaveGenesis = true;
1860  }
1861 
1862 #if HAVE_SYSTEM
1863  const std::string block_notify = args.GetArg("-blocknotify", "");
1864  if (!block_notify.empty()) {
1865  uiInterface.NotifyBlockTip_connect([block_notify](SynchronizationState sync_state, const CBlockIndex* pBlockIndex) {
1866  if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) return;
1867  std::string command = block_notify;
1868  boost::replace_all(command, "%s", pBlockIndex->GetBlockHash().GetHex());
1869  std::thread t(runCommand, command);
1870  t.detach(); // thread runs free
1871  });
1872  }
1873 #endif
1874 
1875  std::vector<fs::path> vImportFiles;
1876  for (const std::string& strFile : args.GetArgs("-loadblock")) {
1877  vImportFiles.push_back(strFile);
1878  }
1879 
1880  g_load_block = std::thread(&TraceThread<std::function<void()>>, "loadblk", [=, &chainman, &args] {
1881  ThreadImport(chainman, vImportFiles, args);
1882  });
1883 
1884  // Wait for genesis block to be processed
1885  {
1886  WAIT_LOCK(g_genesis_wait_mutex, lock);
1887  // We previously could hang here if StartShutdown() is called prior to
1888  // ThreadImport getting started, so instead we just wait on a timer to
1889  // check ShutdownRequested() regularly.
1890  while (!fHaveGenesis && !ShutdownRequested()) {
1891  g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
1892  }
1893  block_notify_genesis_wait_connection.disconnect();
1894  }
1895 
1896  if (ShutdownRequested()) {
1897  return false;
1898  }
1899 
1900  // ********************************************************* Step 12: start node
1901 
1902  int chain_active_height;
1903 
1905  {
1906  LOCK(cs_main);
1907  LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
1908  chain_active_height = chainman.ActiveChain().Height();
1909  if (tip_info) {
1910  tip_info->block_height = chain_active_height;
1911  tip_info->block_time = chainman.ActiveChain().Tip() ? chainman.ActiveChain().Tip()->GetBlockTime() : Params().GenesisBlock().GetBlockTime();
1912  tip_info->verification_progress = GuessVerificationProgress(Params().TxData(), chainman.ActiveChain().Tip());
1913  }
1914  if (tip_info && ::pindexBestHeader) {
1917  }
1918  }
1919  LogPrintf("nBestHeight = %d\n", chain_active_height);
1920 
1921  Discover();
1922 
1923  // Map ports with UPnP
1924  if (args.GetBoolArg("-upnp", DEFAULT_UPNP)) {
1925  StartMapPort();
1926  }
1927 
1928  CConnman::Options connOptions;
1929  connOptions.nLocalServices = nLocalServices;
1930  connOptions.nMaxConnections = nMaxConnections;
1933  connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1934  connOptions.nMaxFeeler = MAX_FEELER_CONNECTIONS;
1935  connOptions.nBestHeight = chain_active_height;
1936  connOptions.uiInterface = &uiInterface;
1937  connOptions.m_banman = node.banman.get();
1938  connOptions.m_msgproc = node.peerman.get();
1939  connOptions.nSendBufferMaxSize = 1000 * args.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1940  connOptions.nReceiveFloodSize = 1000 * args.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1941  connOptions.m_added_nodes = args.GetArgs("-addnode");
1942 
1943  connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1944  connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1945  connOptions.m_peer_connect_timeout = peer_connect_timeout;
1946 
1947  for (const std::string& bind_arg : args.GetArgs("-bind")) {
1948  CService bind_addr;
1949  const size_t index = bind_arg.rfind('=');
1950  if (index == std::string::npos) {
1951  if (Lookup(bind_arg, bind_addr, GetListenPort(), false)) {
1952  connOptions.vBinds.push_back(bind_addr);
1953  continue;
1954  }
1955  } else {
1956  const std::string network_type = bind_arg.substr(index + 1);
1957  if (network_type == "onion") {
1958  const std::string truncated_bind_arg = bind_arg.substr(0, index);
1959  if (Lookup(truncated_bind_arg, bind_addr, BaseParams().OnionServiceTargetPort(), false)) {
1960  connOptions.onion_binds.push_back(bind_addr);
1961  continue;
1962  }
1963  }
1964  }
1965  return InitError(ResolveErrMsg("bind", bind_arg));
1966  }
1967 
1968  if (connOptions.onion_binds.empty()) {
1969  connOptions.onion_binds.push_back(DefaultOnionServiceTarget());
1970  }
1971 
1972  if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
1973  const auto bind_addr = connOptions.onion_binds.front();
1974  if (connOptions.onion_binds.size() > 1) {
1975  InitWarning(strprintf(_("More than one onion bind address is provided. Using %s for the automatically created Tor onion service."), bind_addr.ToStringIPPort()));
1976  }
1977  StartTorControl(bind_addr);
1978  }
1979 
1980  for (const std::string& strBind : args.GetArgs("-whitebind")) {
1981  NetWhitebindPermissions whitebind;
1983  if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) return InitError(error);
1984  connOptions.vWhiteBinds.push_back(whitebind);
1985  }
1986 
1987  for (const auto& net : args.GetArgs("-whitelist")) {
1988  NetWhitelistPermissions subnet;
1990  if (!NetWhitelistPermissions::TryParse(net, subnet, error)) return InitError(error);
1991  connOptions.vWhitelistedRange.push_back(subnet);
1992  }
1993 
1994  connOptions.vSeedNodes = args.GetArgs("-seednode");
1995 
1996  // Initiate outbound connections unless connect=0
1997  connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect");
1998  if (!connOptions.m_use_addrman_outgoing) {
1999  const auto connect = args.GetArgs("-connect");
2000  if (connect.size() != 1 || connect[0] != "0") {
2001  connOptions.m_specified_outgoing = connect;
2002  }
2003  }
2004  if (!node.connman->Start(*node.scheduler, connOptions)) {
2005  return false;
2006  }
2007 
2008  // ********************************************************* Step 13: finished
2009 
2011  uiInterface.InitMessage(_("Done loading").translated);
2012 
2013  for (const auto& client : node.chain_clients) {
2014  client->start(*node.scheduler);
2015  }
2016 
2017  BanMan* banman = node.banman.get();
2018  node.scheduler->scheduleEvery([banman]{
2019  banman->DumpBanlist();
2020  }, DUMP_BANS_INTERVAL);
2021 
2022 #if HAVE_SYSTEM
2023  StartupNotify(args);
2024 #endif
2025 
2026  return true;
2027 }
std::vector< CService > vBinds
Definition: net.h:218
int m_max_outbound_full_relay
Definition: net.h:202
bool fIsBareMultisigStd
Definition: settings.cpp:11
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
void EnableCategory(LogFlags flag)
Definition: logging.cpp:90
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:66
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
Definition: random.cpp:711
#define COPYRIGHT_YEAR
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:60
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
Definition: init.cpp:617
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:72
std::string NetworkIDString() const
Return the network string.
Definition: chainparams.h:86
void ECC_Start()
Initialize the elliptic curve support.
Definition: key.cpp:348
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument &#39;checklevel&#39;.
Definition: validation.cpp:77
bool(* handler)(const util::Ref &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:671
std::vector< std::unique_ptr< interfaces::ChainClient > > chain_clients
List of all chain clients (wallet processes or other client) connected to node.
Definition: context.h:45
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:370
bool ShutdownRequested()
Definition: shutdown.cpp:20
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:592
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
Definition: error.cpp:39
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:62
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:139
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
std::deque< CInv >::iterator it
static void CleanupBlockRevFiles()
Definition: init.cpp:648
const std::vector< std::string > NET_PERMISSIONS_DOC
std::condition_variable g_best_block_cv
Definition: validation.cpp:133
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:871
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:106
BCLog::Logger & LogInstance()
Definition: logging.cpp:14
Definition: banman.h:57
ServiceFlags
nServices flags
Definition: protocol.h:269
const char *const BITCOIN_SETTINGS_FILENAME
Definition: system.cpp:74
static const uint64_t MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
Definition: net.h:82
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: error.cpp:49
#define LogPrint(category,...)
Definition: logging.h:182
int64_t GetBlockTime() const
Definition: chain.h:247
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:123
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:236
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:24
int m_max_outbound_block_relay
Definition: net.h:203
fs::path GetDefaultDataDir()
Definition: system.cpp:650
static const int DEFAULT_HTTP_SERVER_TIMEOUT
Definition: httpserver.h:13
static const int64_t nMaxTxIndexCache
Max memory allocated to block tree DB specific cache, if -txindex (MiB)
Definition: txdb.h:36
#define TRY_LOCK(cs, name)
Definition: sync.h:234
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:68
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
Definition: standard.h:101
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: system.cpp:492
void Shutdown(NodeContext &node)
Definition: init.cpp:178
static const std::string REGTEST
Bilingual messages:
Definition: translation.h:16
RecursiveMutex g_cs_orphans
Guards orphan transactions and extra txs for compact blocks.
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:325
static const unsigned int DEFAULT_RPC_SERIALIZE_VERSION
Definition: server.h:20
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:57
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:113
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1262
BanMan * m_banman
Definition: net.h:209
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:17
fs::path m_file_path
Definition: logging.h:94
static boost::signals2::connection rpc_notify_block_change_connection
Definition: init.cpp:357
std::unique_ptr< BanMan > banman
Definition: context.h:41
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:36
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:88
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:32
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:781
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:38
bool empty() const
Definition: translation.h:27
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
static const int DEFAULT_HTTP_WORKQUEUE
Definition: httpserver.h:12
static void RegisterAllCoreRPCCommands(CRPCTable &t)
Definition: register.h:23
IPv4.
Definition: netaddress.h:49
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:138
static void OnRPCStarted()
Definition: init.cpp:358
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:73
void InitWarning(const bilingual_str &str)
Show warning message.
~CImportingNow()
Definition: init.cpp:635
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
Definition: init.cpp:328
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KB) const
Definition: feerate.cpp:38
static const bool DEFAULT_ACCEPT_DATACARRIER
Definition: standard.h:17
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:40
bool Write(CAutoFile &fileout) const
Write estimation data to a file.
Definition: fees.cpp:860
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ChainActive().Tip() will not be pr...
Definition: validation.h:84
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:58
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
Definition: util.cpp:20
void FlushUnconfirmed()
Empty mempool transactions on shutdown to record failure to confirm for txs still in mempool...
Definition: fees.cpp:945
unsigned int nReceiveFloodSize
Definition: net.h:211
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: system.cpp:525
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:24
CClientUIInterface * uiInterface
Definition: net.h:207
int Height() const
Return the maximal height in the chain.
Definition: chain.h:415
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
Definition: standard.cpp:16
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name...
Definition: threadnames.cpp:57
void StopTorControl()
Definition: torcontrol.cpp:776
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:43
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:696
void OnStopped(std::function< void()> slot)
Definition: server.cpp:74
static const unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or BIP...
Definition: policy.h:34
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:70
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:21
std::atomic< bool > m_reopen_file
Definition: logging.h:95
CChainState stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:506
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1267
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:64
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
static void OnRPCStopped()
Definition: init.cpp:363
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:147
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
#define PACKAGE_NAME
void InterruptRPC()
Definition: server.cpp:291
const std::set< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:78
bool m_print_to_console
Definition: logging.h:87
bool fDiscover
Definition: net.cpp:112
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
Definition: chainparams.h:71
void Discover()
Definition: net.cpp:2296
int nMaxConnections
Definition: net.h:201
const CBlock & GenesisBlock() const
Definition: chainparams.h:69
static std::unique_ptr< ECCVerifyHandle > globalVerifyHandle
Definition: init.cpp:156
const fs::path & GetBlocksDir()
Definition: system.cpp:681
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:52
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
std::string translated
Definition: translation.h:18
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:1068
uint32_t nTime
Definition: chain.h:179
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:478
static const int64_t nMinDbCache
min. -dbcache (MiB)
Definition: txdb.h:30
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
Definition: sha256.cpp:562
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
Definition: random.cpp:587
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:12
bool InitBlockFilterIndex(BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe)
Initialize a block filter index for the given type if one does not already exist. ...
static const int64_t max_filter_index_cache
Max memory allocated to all block filter index caches combined in MiB.
Definition: txdb.h:38
virtual void Construct(NodeContext &node) const =0
Add wallets that should be opened to list of chain clients.
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:305
bool ParseMoney(const std::string &money_string, CAmount &nRet)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:34
static void HandleSIGHUP(int)
Definition: init.cpp:333
fs::ofstream ofstream
Definition: fs.h:91
static const bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
Definition: policy.h:38
static boost::thread_group threadGroup
Definition: init.cpp:160
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: system.cpp:136
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:73
bool SetupNetworking()
Definition: system.cpp:1250
std::string LicenseInfo()
Returns licensing information (for -version)
Definition: init.cpp:594
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:747
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:439
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:371
uint64_t nPruneTarget
Number of MiB of block files that we&#39;re trying to stay below.
Definition: validation.cpp:143
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition: netbase.cpp:746
void ThreadScriptCheck(int worker_num)
Run an instance of the script checking thread.
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:274
bool IsNull() const
Definition: uint256.h:31
static const bool DEFAULT_STOPAFTERBLOCKIMPORT
Definition: init.cpp:91
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:231
void Stop()
Stops the instance from staying in sync with blockchain updates.
Definition: base.cpp:314
std::unique_ptr< Chain > MakeChain(NodeContext &node)
Return implementation of Chain interface.
Definition: chain.cpp:415
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:647
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:68
arith_uint256 UintToArith256(const uint256 &a)
bool m_print_to_file
Definition: logging.h:88
std::function< void()> rpc_interruption_point
Definition: context.h:50
static const std::string MAIN
Chain name strings.
static const bool DEFAULT_PEERBLOCKFILTERS
bool IsValid() const
Definition: netaddress.cpp:428
void LoadMempool(const ArgsManager &args)
Load the persisted mempool from disk.
bool Lookup(const std::string &name, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:207
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
uint256 GetBlockHash() const
Definition: chain.h:233
void SetMockTime(int64_t nMockTimeIn)
For testing.
Definition: time.cpp:47
void SetRPCWarmupFinished()
Definition: server.cpp:331
uint256 SerializeHash(const T &obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
Compute the 256-bit hash of an object&#39;s serialization.
Definition: hash.h:192
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:89
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:151
BlockFilterType
Definition: blockfilter.h:88
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: system.cpp:87
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:78
#define LOCK2(cs1, cs2)
Definition: sync.h:231
void StopMapPort()
Definition: net.cpp:1672
bool glibc_sanity_test()
CRPCTable tableRPC
Definition: server.cpp:517
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:359
void Interrupt()
Definition: base.cpp:295
Users of this module must hold an ECCVerifyHandle.
Definition: pubkey.h:259
bool fCheckpointsEnabled
Definition: validation.cpp:142
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1219
bool LoadBlockIndex(const CChainParams &chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we&#39;re running with -reindex...
ChainstateManager * chainman
Definition: context.h:40
uint16_t GetListenPort()
Definition: net.cpp:126
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: system.cpp:461
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
static CZMQNotificationInterface * Create()
NodeContext struct containing references to chain state and connection state.
Definition: context.h:36
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:34
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
std::unique_ptr< CConnman > connman
Definition: context.h:37
Access to the block database (blocks/index/)
Definition: txdb.h:96
bool m_log_threadnames
Definition: logging.h:92
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:450
static std::condition_variable g_genesis_wait_cv
Definition: init.cpp:615
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:162
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:149
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:131
bool m_log_time_micros
Definition: logging.h:91
#define NODISCARD
Definition: attributes.h:18
#define LOCK(cs)
Definition: sync.h:230
const char * name
Definition: rest.cpp:41
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition: key.cpp:365
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:17
std::string ToString() const
Definition: validation.h:125
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:57
NetEventsInterface * m_msgproc
Definition: net.h:208
CImportingNow()
Definition: init.cpp:630
static const unsigned int DEFAULT_BLOCK_MIN_TX_FEE
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
Definition: policy.h:22
static bool AppInitServers(const util::Ref &context, NodeContext &node)
Definition: init.cpp:785
int atoi(const std::string &str)
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:501
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
bool g_relay_txes
Definition: net.cpp:114
std::vector< std::string > vSeedNodes
Definition: net.h:215
uint256 uint256S(const char *str)
Definition: uint256.h:137
std::vector< std::string > m_specified_outgoing
Definition: net.h:221
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:314
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:506
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:706
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:56
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:129
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:64
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:66
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:82
void InitSignatureCache()
Definition: sigcache.cpp:91
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
Definition: banman.h:21
const std::string CURRENCY_UNIT
Definition: feerate.h:14
int nMaxFeeler
Definition: net.h:205
CMainSignals & GetMainSignals()
static const int64_t nDefaultDbCache
-dbcache default (MiB)
Definition: txdb.h:24
void DisableCategory(LogFlags flag)
Definition: logging.cpp:103
Network
A network type.
Definition: netaddress.h:43
void Start()
Start initializes the sync state and registers the instance as a ValidationInterface so that it stays...
Definition: base.cpp:300
static const bool DEFAULT_FEEFILTER
Default for using fee filter.
Definition: validation.h:80
Block and header tip information.
Definition: node.h:42
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:66
bool InitError(const bilingual_str &str)
Show error message.
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:78
ChainstateManager g_chainman
Definition: validation.cpp:104
#define WAIT_LOCK(cs, name)
Definition: sync.h:235
std::atomic_bool fImporting
static const int64_t nDefaultDbBatchSize
-dbbatchsize default (bytes)
Definition: txdb.h:26
std::string ToString() const
Definition: uint256.cpp:64
void StartRPC()
Definition: server.cpp:284
static fs::path GetPidFile(const ArgsManager &args)
Definition: init.cpp:111
int64_t GetBlockTime() const
Definition: block.h:55
const std::string CLIENT_NAME
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:118
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:26
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:1285
void TraceThread(const char *name, Callable func)
Definition: system.h:432
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:76
int nConnectTimeout
Definition: netbase.cpp:36
static const int DEFAULT_ZMQ_SNDHWM
static NODISCARD bool CreatePidFile(const ArgsManager &args)
Definition: init.cpp:116
static const bool DEFAULT_PROXYRANDOMIZE
Definition: init.cpp:89
bool IsHexNumber(const std::string &str)
Return true if the string is a hex number, optionally prefixed with "0x".
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:257
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:144
void DumpBanlist()
Definition: banman.cpp:42
std::string FormatFullVersion()
std::unique_ptr< PeerManager > peerman
Definition: context.h:39
CFeeRate incrementalRelayFee
Definition: settings.cpp:12
virtual void AddWalletOptions(ArgsManager &argsman) const =0
Get wallet help string.
Type-safe dynamic reference.
Definition: ref.h:21
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:146
static const int64_t nMaxBlockDBCache
Max memory allocated to block tree DB specific cache, if no -txindex (MiB)
Definition: txdb.h:32
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
Definition: validation.h:844
static void ThreadImport(ChainstateManager &chainman, std::vector< fs::path > vImportFiles, const ArgsManager &args)
Definition: init.cpp:694
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:712
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:310
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:43
void StartREST(const util::Ref &context)
Start HTTP REST subsystem.
Definition: rest.cpp:684
uint64_t nMaxOutboundTimeframe
Definition: net.h:212
void LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, FlatFilePos *dbp)
Import blocks from an external file.
std::atomic_bool fReindex
#define PACKAGE_URL
CBlockIndex * LookupBlockIndex(const uint256 &hash)
Definition: validation.cpp:173
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once) ...
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:131
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
bool glibcxx_sanity_test()
256-bit opaque blob.
Definition: uint256.h:124
bool fCheckBlockIndex
Definition: validation.cpp:141
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:216
std::vector< CService > onion_binds
Definition: net.h:219
ArgsManager * args
Definition: context.h:42
static bool fFeeEstimatesInitialized
Definition: init.cpp:88
bool StartHTTPRPC(const util::Ref &context)
Start HTTP RPC subsystem.
Definition: httprpc.cpp:287
static const bool DEFAULT_PEERBLOOMFILTERS
void RegisterZMQRPCCommands(CRPCTable &t)
Definition: zmqrpc.cpp:62
uint256 nMinimumChainWork
The best chain should have at least this much work.
Definition: params.h:83
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
Definition: chainparams.h:73
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
Definition: validation.cpp:135
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
Definition: validation.cpp:106
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:74
const WalletInitInterface & g_wallet_init_interface
Definition: init.cpp:38
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition: banman.h:19
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:49
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:75
unsigned int nBytesPerSigOp
Definition: settings.cpp:14
void StopRPC()
Definition: server.cpp:302
int nMaxAddnode
Definition: net.h:204
static const unsigned int DEFAULT_BYTES_PER_SIGOP
Default for -bytespersigop.
Definition: policy.h:36
bool IsValid() const
Definition: netbase.h:34
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:959
static const char * DEFAULT_ASMAP_FILENAME
Definition: init.cpp:104
uint256 defaultAssumeValid
By default assume that the signatures in ancestors of this block are valid.
Definition: params.h:85
bool fRequireStandard
Definition: validation.cpp:140
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:90
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
std::string original
Definition: translation.h:17
static void new_handler_terminate()
Definition: init.cpp:904
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:751
static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:80
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:137
const CChainParams & Params()
Return the currently selected parameters.
static bool TryParse(const std::string str, NetWhitebindPermissions &output, bilingual_str &error)
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
static const char * FEE_ESTIMATES_FILENAME
Definition: init.cpp:102
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:85
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
Definition: server.cpp:320
static const int64_t nMaxCoinsDBCache
Max memory allocated to coin DB specific cache (MiB)
Definition: txdb.h:40
void InitScriptExecutionCache()
Initializes the script-execution cache.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of orphan+recently-replaced txn to keep around for block reconstruction.
static const unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
Definition: policy.h:52
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:466
bool Read(CAutoFile &filein)
Read estimation data from a file.
Definition: fees.cpp:885
ServiceFlags nLocalServices
Definition: net.h:200
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:692
bool fLogIPs
Definition: logging.cpp:35
int64_t GetAdjustedTime()
Definition: timedata.cpp:34
uint64_t nMaxOutboundLimit
Definition: net.h:213
std::vector< std::string > m_added_nodes
Definition: net.h:222
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:24
bool AppInitBasicSetup(ArgsManager &args)
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:917
static const int64_t nMaxDbCache
max. -dbcache (MiB)
Definition: txdb.h:28
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:390
std::string FormatSubVersion(const std::string &name, int nClientVersion, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip...
IPv6.
Definition: netaddress.h:52
CChainState &InitializeChainstate(CTxMemPool &mempool, const uint256 &snapshot_blockhash=uint256()) 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:861
std::string GetHex() const
Definition: uint256.cpp:20
TOR (v2 or v3)
Definition: netaddress.h:55
void AbortShutdown()
Definition: shutdown.cpp:16
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
ArgsManager gArgs
Definition: system.cpp:76
bool fListen
Definition: net.cpp:113
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: system.cpp:981
static Mutex g_genesis_wait_mutex
Definition: init.cpp:614
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:606
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:199
CService DefaultOnionServiceTarget()
Definition: torcontrol.cpp:785
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:60
static const bool DEFAULT_UPNP
-upnp default
Definition: net.h:75
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:86
void StartShutdown()
Definition: shutdown.cpp:12
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:84
static const std::string TESTNET
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
static std::vector< bool > DecodeAsmap(fs::path path)
Definition: addrman.cpp:631
unsigned int nSendBufferMaxSize
Definition: net.h:210
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:427
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:917
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: system.cpp:261
static std::thread g_load_block
Definition: init.cpp:158
CChainState & ActiveChainstate() const
The most-work chain.
void InterruptTorControl()
Definition: torcontrol.cpp:766
int SegwitHeight
Block height at which Segwit (BIP141, BIP143 and BIP147) becomes active.
Definition: params.h:63
bool m_log_timestamps
Definition: logging.h:90
void OnStarted(std::function< void()> slot)
Definition: server.cpp:69
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:1252
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:47
std::string GetHex() const
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1240
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
static bool InitSanityCheck()
Sanity checks Ensure that Bitcoin is running in a usable environment with all necessary library suppo...
Definition: init.cpp:769
bool AppInitMain(const util::Ref &context, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
Definition: init.cpp:1263
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we&#39;ll relay everything (blocks, tx, addrs, etc)
Definition: net.h:62
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1293
static const bool DEFAULT_LOGIPS
Definition: logging.h:22
CClientUIInterface uiInterface
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:150
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:341
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
Definition: init.cpp:109
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:65
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:848
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:26
static void registerSignalHandler(int signal, void(*handler)(int))
Definition: init.cpp:347
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:95
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:361
static const unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create...
Definition: policy.h:20
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:99
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:23
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:12
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
static const bool DEFAULT_LISTEN_ONION
Definition: torcontrol.h:16
bool m_use_addrman_outgoing
Definition: net.h:220
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:217
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:241
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:642
BIP-0014 subset.
Definition: strencodings.h:26
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:23
static const std::string SIGNET
static const bool DEFAULT_TXINDEX
Definition: validation.h:75
CFeeRate dustRelayFee
Definition: settings.cpp:13
static const int DEFAULT_HTTP_THREADS
Definition: httpserver.h:11
static const bool DEFAULT_REST_ENABLE
Definition: init.cpp:90
static bool TryParse(const std::string str, NetWhitelistPermissions &output, bilingual_str &error)
unsigned nMaxDatacarrierBytes
Maximum size of TxoutType::NULL_DATA scripts that this node considers standard.
Definition: standard.cpp:17
bool fNameLookup
Definition: netbase.cpp:37
void StartMapPort()
Definition: net.cpp:1664
CChain & ActiveChain() const
Definition: validation.h:865
uint256 hashGenesisBlock
Definition: params.h:47
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:802
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
Definition: timedata.h:13
void InterruptMapPort()
Definition: net.cpp:1668
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:86
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:602
int nBestHeight
Definition: net.h:206
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:70
#define Assert(val)
Identity function.
Definition: check.h:57
void ShrinkDebugFile()
Definition: logging.cpp:283
CZMQNotificationInterface * g_zmq_notification_interface
static bool LockDataDirectory(bool probeOnly)
Definition: init.cpp:1206
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
static bool fHaveGenesis
Definition: init.cpp:613
std::unique_ptr< CScheduler > scheduler
Definition: context.h:49
int64_t m_peer_connect_timeout
Definition: net.h:214
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.
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:869
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:46