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