BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
init.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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 <chain.h>
15 #include <chainparams.h>
16 #include <checkpoints.h>
17 #include <compat/sanity.h>
18 #include <consensus/validation.h>
19 #include <fs.h>
20 #include <httpserver.h>
21 #include <httprpc.h>
22 #include <index/txindex.h>
23 #include <key.h>
24 #include <validation.h>
25 #include <miner.h>
26 #include <netbase.h>
27 #include <net.h>
28 #include <net_processing.h>
29 #include <policy/feerate.h>
30 #include <policy/fees.h>
31 #include <policy/policy.h>
32 #include <rpc/server.h>
33 #include <rpc/register.h>
34 #include <rpc/blockchain.h>
35 #include <script/standard.h>
36 #include <script/sigcache.h>
37 #include <scheduler.h>
38 #include <shutdown.h>
39 #include <timedata.h>
40 #include <txdb.h>
41 #include <txmempool.h>
42 #include <torcontrol.h>
43 #include <ui_interface.h>
44 #include <util.h>
45 #include <utilmoneystr.h>
46 #include <validationinterface.h>
47 #include <warnings.h>
48 #include <walletinitinterface.h>
49 #include <stdint.h>
50 #include <stdio.h>
51 
52 #ifndef WIN32
53 #include <signal.h>
54 #include <sys/stat.h>
55 #endif
56 
57 #include <boost/algorithm/string/classification.hpp>
58 #include <boost/algorithm/string/replace.hpp>
59 #include <boost/algorithm/string/split.hpp>
60 #include <boost/bind.hpp>
61 #include <boost/thread.hpp>
62 #include <openssl/crypto.h>
63 
64 #if ENABLE_ZMQ
66 #include <zmq/zmqrpc.h>
67 #endif
68 
70 static const bool DEFAULT_PROXYRANDOMIZE = true;
71 static const bool DEFAULT_REST_ENABLE = false;
72 static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
73 
74 std::unique_ptr<CConnman> g_connman;
75 std::unique_ptr<PeerLogicValidation> peerLogic;
76 
77 #ifdef WIN32
78 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
79 // accessing block files don't count towards the fd_set size limit
80 // anyway.
81 #define MIN_CORE_FILEDESCRIPTORS 0
82 #else
83 #define MIN_CORE_FILEDESCRIPTORS 150
84 #endif
85 
86 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
87 
89 //
90 // Shutdown
91 //
92 
93 //
94 // Thread management and startup/shutdown:
95 //
96 // The network-processing threads are all part of a thread group
97 // created by AppInit() or the Qt main() function.
98 //
99 // A clean exit happens when StartShutdown() or the SIGTERM
100 // signal handler sets ShutdownRequested(), which makes main thread's
101 // WaitForShutdown() interrupts the thread group.
102 // And then, WaitForShutdown() makes all other on-going threads
103 // in the thread group join the main thread.
104 // Shutdown() is then called to clean up database connections, and stop other
105 // threads that should only be stopped after the main network-processing
106 // threads have exited.
107 //
108 // Shutdown for Qt is very similar, only it uses a QTimer to detect
109 // ShutdownRequested() getting set, and then does the normal Qt
110 // shutdown thing.
111 //
112 
119 {
120 public:
122  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override {
123  try {
124  return CCoinsViewBacked::GetCoin(outpoint, coin);
125  } catch(const std::runtime_error& e) {
126  uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
127  LogPrintf("Error reading from database: %s\n", e.what());
128  // Starting the shutdown sequence and returning false to the caller would be
129  // interpreted as 'entry not found' (as opposed to unable to read data), and
130  // could lead to invalid interpretation. Just exit immediately, as we can't
131  // continue anyway, and all writes should be atomic.
132  abort();
133  }
134  }
135  // Writes do not need similar protection, as failure to write is handled by the caller.
136 };
137 
138 static std::unique_ptr<CCoinsViewErrorCatcher> pcoinscatcher;
139 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
140 
141 static boost::thread_group threadGroup;
142 static CScheduler scheduler;
143 
144 void Interrupt()
145 {
148  InterruptRPC();
149  InterruptREST();
152  if (g_connman)
153  g_connman->Interrupt();
154  if (g_txindex) {
155  g_txindex->Interrupt();
156  }
157 }
158 
159 void Shutdown()
160 {
161  LogPrintf("%s: In progress...\n", __func__);
162  static CCriticalSection cs_Shutdown;
163  TRY_LOCK(cs_Shutdown, lockShutdown);
164  if (!lockShutdown)
165  return;
166 
171  RenameThread("bsha3-shutoff");
173 
174  StopHTTPRPC();
175  StopREST();
176  StopRPC();
177  StopHTTPServer();
179  StopMapPort();
180 
181  // Because these depend on each-other, we make sure that neither can be
182  // using the other before destroying them.
184  if (g_connman) g_connman->Stop();
185  if (g_txindex) g_txindex->Stop();
186 
187  StopTorControl();
188 
189  // After everything has been shut down, but before things get flushed, stop the
190  // CScheduler/checkqueue threadGroup
191  threadGroup.interrupt_all();
192  threadGroup.join_all();
193 
194  // After the threads that potentially access these pointers have been stopped,
195  // destruct and reset all to nullptr.
196  peerLogic.reset();
197  g_connman.reset();
198  g_txindex.reset();
199 
200  if (g_is_mempool_loaded && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
201  DumpMempool();
202  }
203 
205  {
207  fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
208  CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
209  if (!est_fileout.IsNull())
210  ::feeEstimator.Write(est_fileout);
211  else
212  LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
213  fFeeEstimatesInitialized = false;
214  }
215 
216  // FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing
217  if (pcoinsTip != nullptr) {
219  }
220 
221  // After there are no more peers/RPC left to give us new data which may generate
222  // CValidationInterface callbacks, flush them...
224 
225  // Any future callbacks will be dropped. This should absolutely be safe - if
226  // missing a callback results in an unrecoverable situation, unclean shutdown
227  // would too. The only reason to do the above flushes is to let the wallet catch
228  // up with our current chain to avoid any strange pruning edge cases and make
229  // next startup faster by avoiding rescan.
230 
231  {
232  LOCK(cs_main);
233  if (pcoinsTip != nullptr) {
235  }
236  pcoinsTip.reset();
237  pcoinscatcher.reset();
238  pcoinsdbview.reset();
239  pblocktree.reset();
240  }
242 
243 #if ENABLE_ZMQ
248  }
249 #endif
250 
251 #ifndef WIN32
252  try {
253  fs::remove(GetPidFile());
254  } catch (const fs::filesystem_error& e) {
255  LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
256  }
257 #endif
262  globalVerifyHandle.reset();
263  ECC_Stop();
264  LogPrintf("%s: done\n", __func__);
265 }
266 
272 #ifndef WIN32
273 static void HandleSIGTERM(int)
274 {
275  StartShutdown();
276 }
277 
278 static void HandleSIGHUP(int)
279 {
280  g_logger->m_reopen_file = true;
281 }
282 #else
283 static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
284 {
285  StartShutdown();
286  Sleep(INFINITE);
287  return true;
288 }
289 #endif
290 
291 #ifndef WIN32
292 static void registerSignalHandler(int signal, void(*handler)(int))
293 {
294  struct sigaction sa;
295  sa.sa_handler = handler;
296  sigemptyset(&sa.sa_mask);
297  sa.sa_flags = 0;
298  sigaction(signal, &sa, nullptr);
299 }
300 #endif
301 
302 static void OnRPCStarted()
303 {
304  uiInterface.NotifyBlockTip_connect(&RPCNotifyBlockChange);
305 }
306 
307 static void OnRPCStopped()
308 {
309  uiInterface.NotifyBlockTip_disconnect(&RPCNotifyBlockChange);
310  RPCNotifyBlockChange(false, nullptr);
311  g_best_block_cv.notify_all();
312  LogPrint(BCLog::RPC, "RPC stopped.\n");
313 }
314 
316 {
317  const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
318  const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
319  const auto regtestBaseParams = CreateBaseChainParams(CBaseChainParams::REGTEST);
320  const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
321  const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET);
322  const auto regtestChainParams = CreateChainParams(CBaseChainParams::REGTEST);
323 
324  // Hidden Options
325  std::vector<std::string> hidden_args = {"-h", "-help",
326  "-dbcrashratio", "-forcecompactdb",
327  // GUI args. These will be overwritten by SetupUIArgs for the GUI
328  "-allowselfsignedrootcertificates", "-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-rootcertificates=<file>", "-splash", "-uiplatform"};
329 
330  // Set all of the args and their help
331  // When adding new options to the categories, please keep and ensure alphabetical ordering.
332  gArgs.AddArg("-?", "Print this help message and exit", false, OptionsCategory::OPTIONS);
333  gArgs.AddArg("-version", "Print version and exit", false, OptionsCategory::OPTIONS);
334  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)", false, OptionsCategory::OPTIONS);
335  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()), false, OptionsCategory::OPTIONS);
336  gArgs.AddArg("-blocksdir=<dir>", "Specify blocks directory (default: <datadir>/blocks)", false, OptionsCategory::OPTIONS);
337  gArgs.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", false, OptionsCategory::OPTIONS);
338  gArgs.AddArg("-blockreconstructionextratxn=<n>", strprintf("Extra transactions to keep in memory for compact block reconstructions (default: %u)", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), false, OptionsCategory::OPTIONS);
339  gArgs.AddArg("-blocksonly", strprintf("Whether to operate in a blocks only mode (default: %u)", DEFAULT_BLOCKSONLY), true, OptionsCategory::OPTIONS);
340  gArgs.AddArg("-conf=<file>", strprintf("Specify configuration file. Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME), false, OptionsCategory::OPTIONS);
341  gArgs.AddArg("-datadir=<dir>", "Specify data directory", false, OptionsCategory::OPTIONS);
342  gArgs.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), true, OptionsCategory::OPTIONS);
343  gArgs.AddArg("-dbcache=<n>", strprintf("Set database cache size in megabytes (%d to %d, default: %d)", nMinDbCache, nMaxDbCache, nDefaultDbCache), false, OptionsCategory::OPTIONS);
344  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), false, OptionsCategory::OPTIONS);
345  gArgs.AddArg("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER), true, OptionsCategory::OPTIONS);
346  gArgs.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", false, OptionsCategory::OPTIONS);
347  gArgs.AddArg("-loadblock=<file>", "Imports blocks from external blk000??.dat file on startup", false, OptionsCategory::OPTIONS);
348  gArgs.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE), false, OptionsCategory::OPTIONS);
349  gArgs.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), false, OptionsCategory::OPTIONS);
350  gArgs.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY), false, OptionsCategory::OPTIONS);
351  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()), true, OptionsCategory::OPTIONS);
352  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)",
353  -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), false, OptionsCategory::OPTIONS);
354  gArgs.AddArg("-persistmempool", strprintf("Whether to save the mempool on shutdown and load on restart (default: %u)", DEFAULT_PERSIST_MEMPOOL), false, OptionsCategory::OPTIONS);
355 #ifndef WIN32
356  gArgs.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", BITCOIN_PID_FILENAME), false, OptionsCategory::OPTIONS);
357 #else
358  hidden_args.emplace_back("-pid");
359 #endif
360  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. "
361  "Warning: Reverting this setting requires re-downloading the entire blockchain. "
362  "(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), false, OptionsCategory::OPTIONS);
363  gArgs.AddArg("-reindex", "Rebuild chain state and block index from the blk*.dat files on disk", false, OptionsCategory::OPTIONS);
364  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.", false, OptionsCategory::OPTIONS);
365 #ifndef WIN32
366  gArgs.AddArg("-sysperms", "Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)", false, OptionsCategory::OPTIONS);
367 #else
368  hidden_args.emplace_back("-sysperms");
369 #endif
370  gArgs.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), false, OptionsCategory::OPTIONS);
371 
372  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.", false, OptionsCategory::CONNECTION);
373  gArgs.AddArg("-banscore=<n>", strprintf("Threshold for disconnecting misbehaving peers (default: %u)", DEFAULT_BANSCORE_THRESHOLD), false, OptionsCategory::CONNECTION);
374  gArgs.AddArg("-bantime=<n>", strprintf("Number of seconds to keep misbehaving peers from reconnecting (default: %u)", DEFAULT_MISBEHAVING_BANTIME), false, OptionsCategory::CONNECTION);
375  gArgs.AddArg("-bind=<addr>", "Bind to given address and always listen on it. Use [host]:port notation for IPv6", false, OptionsCategory::CONNECTION);
376  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.", false, OptionsCategory::CONNECTION);
377  gArgs.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", false, OptionsCategory::CONNECTION);
378  gArgs.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), false, OptionsCategory::CONNECTION);
379  gArgs.AddArg("-dnsseed", "Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)", false, OptionsCategory::CONNECTION);
380  gArgs.AddArg("-enablebip61", strprintf("Send reject messages per BIP61 (default: %u)", DEFAULT_ENABLE_BIP61), false, OptionsCategory::CONNECTION);
381  gArgs.AddArg("-externalip=<ip>", "Specify your own public address", false, OptionsCategory::CONNECTION);
382  gArgs.AddArg("-forcednsseed", strprintf("Always query for peer addresses via DNS lookup (default: %u)", DEFAULT_FORCEDNSSEED), false, OptionsCategory::CONNECTION);
383  gArgs.AddArg("-listen", "Accept connections from outside (default: 1 if no -proxy or -connect)", false, OptionsCategory::CONNECTION);
384  gArgs.AddArg("-listenonion", strprintf("Automatically create Tor hidden service (default: %d)", DEFAULT_LISTEN_ONION), false, OptionsCategory::CONNECTION);
385  gArgs.AddArg("-maxconnections=<n>", strprintf("Maintain at most <n> connections to peers (default: %u)", DEFAULT_MAX_PEER_CONNECTIONS), false, OptionsCategory::CONNECTION);
386  gArgs.AddArg("-maxreceivebuffer=<n>", strprintf("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXRECEIVEBUFFER), false, OptionsCategory::CONNECTION);
387  gArgs.AddArg("-maxsendbuffer=<n>", strprintf("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXSENDBUFFER), false, OptionsCategory::CONNECTION);
388  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), false, OptionsCategory::CONNECTION);
389  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), false, OptionsCategory::CONNECTION);
390  gArgs.AddArg("-onion=<ip:port>", "Use separate SOCKS5 proxy to reach peers via Tor hidden services, set -noonion to disable (default: -proxy)", false, OptionsCategory::CONNECTION);
391  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.", false, OptionsCategory::CONNECTION);
392  gArgs.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), false, OptionsCategory::CONNECTION);
393  gArgs.AddArg("-permitbaremultisig", strprintf("Relay non-P2SH multisig (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), false, OptionsCategory::CONNECTION);
394  gArgs.AddArg("-port=<port>", strprintf("Listen for connections on <port> (default: %u, testnet: %u, regtest: %u)", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), false, OptionsCategory::CONNECTION);
395  gArgs.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", false, OptionsCategory::CONNECTION);
396  gArgs.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), false, OptionsCategory::CONNECTION);
397  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.", false, OptionsCategory::CONNECTION);
398  gArgs.AddArg("-timeout=<n>", strprintf("Specify connection timeout in milliseconds (minimum: 1, default: %d)", DEFAULT_CONNECT_TIMEOUT), false, OptionsCategory::CONNECTION);
399  gArgs.AddArg("-torcontrol=<ip>:<port>", strprintf("Tor control port to use if onion listening enabled (default: %s)", DEFAULT_TOR_CONTROL), false, OptionsCategory::CONNECTION);
400  gArgs.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", false, OptionsCategory::CONNECTION);
401 #ifdef USE_UPNP
402 #if USE_UPNP
403  gArgs.AddArg("-upnp", "Use UPnP to map the listening port (default: 1 when listening and no -proxy)", false, OptionsCategory::CONNECTION);
404 #else
405  gArgs.AddArg("-upnp", strprintf("Use UPnP to map the listening port (default: %u)", 0), false, OptionsCategory::CONNECTION);
406 #endif
407 #else
408  hidden_args.emplace_back("-upnp");
409 #endif
410  gArgs.AddArg("-whitebind=<addr>", "Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6", false, OptionsCategory::CONNECTION);
411  gArgs.AddArg("-whitelist=<IP address or network>", "Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR notated network (e.g. 1.2.3.0/24). Can be specified multiple times."
412  " Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway", false, OptionsCategory::CONNECTION);
413 
415 
416 #if ENABLE_ZMQ
417  gArgs.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", false, OptionsCategory::ZMQ);
418  gArgs.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", false, OptionsCategory::ZMQ);
419  gArgs.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", false, OptionsCategory::ZMQ);
420  gArgs.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", false, OptionsCategory::ZMQ);
421 #else
422  hidden_args.emplace_back("-zmqpubhashblock=<address>");
423  hidden_args.emplace_back("-zmqpubhashtx=<address>");
424  hidden_args.emplace_back("-zmqpubrawblock=<address>");
425  hidden_args.emplace_back("-zmqpubrawtx=<address>");
426 #endif
427 
428  gArgs.AddArg("-checkblocks=<n>", strprintf("How many blocks to check at startup (default: %u, 0 = all)", DEFAULT_CHECKBLOCKS), true, OptionsCategory::DEBUG_TEST);
429  gArgs.AddArg("-checklevel=<n>", strprintf("How thorough the block verification of -checkblocks is: "
430  "level 0 reads the blocks from disk, "
431  "level 1 verifies block validity, "
432  "level 2 verifies undo data, "
433  "level 3 checks disconnection of tip blocks, "
434  "and level 4 tries to reconnect the blocks, "
435  "each level includes the checks of the previous levels "
436  "(0-4, default: %u)", DEFAULT_CHECKLEVEL), true, OptionsCategory::DEBUG_TEST);
437  gArgs.AddArg("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST);
438  gArgs.AddArg("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST);
439  gArgs.AddArg("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED), true, OptionsCategory::DEBUG_TEST);
440  gArgs.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", true, OptionsCategory::DEBUG_TEST);
441  gArgs.AddArg("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages", true, OptionsCategory::DEBUG_TEST);
442  gArgs.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), true, OptionsCategory::DEBUG_TEST);
443  gArgs.AddArg("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT), true, OptionsCategory::DEBUG_TEST);
444  gArgs.AddArg("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT), true, OptionsCategory::DEBUG_TEST);
445  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), true, OptionsCategory::DEBUG_TEST);
446  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), true, OptionsCategory::DEBUG_TEST);
447  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), true, OptionsCategory::DEBUG_TEST);
448  gArgs.AddArg("-addrmantest", "Allows to test address relay on localhost", true, OptionsCategory::DEBUG_TEST);
449  gArgs.AddArg("-debug=<category>", "Output debugging information (default: -nodebug, supplying <category> is optional). "
450  "If <category> is not supplied or if <category> = 1, output all debugging information. <category> can be: " + ListLogCategories() + ".", false, OptionsCategory::DEBUG_TEST);
451  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."), false, OptionsCategory::DEBUG_TEST);
452  gArgs.AddArg("-help-debug", "Print help message with debugging options and exit", false, OptionsCategory::DEBUG_TEST);
453  gArgs.AddArg("-logips", strprintf("Include IP addresses in debug output (default: %u)", DEFAULT_LOGIPS), false, OptionsCategory::DEBUG_TEST);
454  gArgs.AddArg("-logtimestamps", strprintf("Prepend debug output with timestamp (default: %u)", DEFAULT_LOGTIMESTAMPS), false, OptionsCategory::DEBUG_TEST);
455  gArgs.AddArg("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS), true, OptionsCategory::DEBUG_TEST);
456  gArgs.AddArg("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)", true, OptionsCategory::DEBUG_TEST);
457  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), true, OptionsCategory::DEBUG_TEST);
458  gArgs.AddArg("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE), true, OptionsCategory::DEBUG_TEST);
459  gArgs.AddArg("-maxtxfee=<amt>", strprintf("Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)",
460  CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)), false, OptionsCategory::DEBUG_TEST);
461  gArgs.AddArg("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY), true, OptionsCategory::DEBUG_TEST);
462  gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -daemon. To disable logging to file, set -nodebuglogfile)", false, OptionsCategory::DEBUG_TEST);
463  gArgs.AddArg("-shrinkdebugfile", "Shrink debug.log file on client startup (default: 1 when no -debug)", false, OptionsCategory::DEBUG_TEST);
464  gArgs.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", false, OptionsCategory::DEBUG_TEST);
465 
467 
468  gArgs.AddArg("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()), true, OptionsCategory::NODE_RELAY);
469  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)), true, OptionsCategory::NODE_RELAY);
470  gArgs.AddArg("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to defined 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)), true, OptionsCategory::NODE_RELAY);
471  gArgs.AddArg("-bytespersigop", strprintf("Equivalent bytes per sigop in transactions for relay and mining (default: %u)", DEFAULT_BYTES_PER_SIGOP), false, OptionsCategory::NODE_RELAY);
472  gArgs.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), false, OptionsCategory::NODE_RELAY);
473  gArgs.AddArg("-datacarriersize", strprintf("Maximum size of data in data carrier transactions we relay and mine (default: %u)", MAX_OP_RETURN_RELAY), false, OptionsCategory::NODE_RELAY);
474  gArgs.AddArg("-mempoolreplacement", strprintf("Enable transaction replacement in the memory pool (default: %u)", DEFAULT_ENABLE_REPLACEMENT), false, OptionsCategory::NODE_RELAY);
475  gArgs.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
476  CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)), false, OptionsCategory::NODE_RELAY);
477  gArgs.AddArg("-whitelistforcerelay", strprintf("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)", DEFAULT_WHITELISTFORCERELAY), false, OptionsCategory::NODE_RELAY);
478  gArgs.AddArg("-whitelistrelay", strprintf("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)", DEFAULT_WHITELISTRELAY), false, OptionsCategory::NODE_RELAY);
479 
480 
481  gArgs.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), false, OptionsCategory::BLOCK_CREATION);
482  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)), false, OptionsCategory::BLOCK_CREATION);
483  gArgs.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", true, OptionsCategory::BLOCK_CREATION);
484 
485  gArgs.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), false, OptionsCategory::RPC);
486  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", false, OptionsCategory::RPC);
487  gArgs.AddArg("-rpcauth=<userpw>", "Username and 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", false, OptionsCategory::RPC);
488  gArgs.AddArg("-rpcbind=<addr>[:port]", "Bind to given address to listen for JSON-RPC connections. 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, or if -rpcallowip has been specified, 0.0.0.0 and :: i.e., all addresses)", false, OptionsCategory::RPC);
489  gArgs.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", false, OptionsCategory::RPC);
490  gArgs.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", false, OptionsCategory::RPC);
491  gArgs.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u, testnet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), false, OptionsCategory::RPC);
492  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), false, OptionsCategory::RPC);
493  gArgs.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), true, OptionsCategory::RPC);
494  gArgs.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), false, OptionsCategory::RPC);
495  gArgs.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", false, OptionsCategory::RPC);
496  gArgs.AddArg("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), true, OptionsCategory::RPC);
497  gArgs.AddArg("-server", "Accept command line and JSON-RPC commands", false, OptionsCategory::RPC);
498 
499 #if HAVE_DECL_DAEMON
500  gArgs.AddArg("-daemon", "Run in the background as a daemon and accept commands", false, OptionsCategory::OPTIONS);
501 #else
502  hidden_args.emplace_back("-daemon");
503 #endif
504 
505  // Add the hidden options
506  gArgs.AddHiddenArgs(hidden_args);
507 }
508 
509 std::string LicenseInfo()
510 {
511  const std::string URL_SOURCE_CODE = "<https://github.com/bsha3/bsha3>";
512  const std::string URL_WEBSITE = "<https://bsha3.org>";
513 
514  return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2018, COPYRIGHT_YEAR) + " ") + "\n" +
515  "\n" +
516  strprintf(_("Please contribute if you find %s useful. "
517  "Visit %s for further information about the software."),
518  PACKAGE_NAME, URL_WEBSITE) +
519  "\n" +
520  strprintf(_("The source code is available from %s."),
521  URL_SOURCE_CODE) +
522  "\n" +
523  "\n" +
524  _("This is experimental software.") + "\n" +
525  strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
526  "\n" +
527  strprintf(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard."), "<https://www.openssl.org>") +
528  "\n";
529 }
530 
531 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
532 {
533  if (initialSync || !pBlockIndex)
534  return;
535 
536  std::string strCmd = gArgs.GetArg("-blocknotify", "");
537  if (!strCmd.empty()) {
538  boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
539  std::thread t(runCommand, strCmd);
540  t.detach(); // thread runs free
541  }
542 }
543 
544 static bool fHaveGenesis = false;
545 static Mutex g_genesis_wait_mutex;
546 static std::condition_variable g_genesis_wait_cv;
547 
548 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
549 {
550  if (pBlockIndex != nullptr) {
551  {
552  LOCK(g_genesis_wait_mutex);
553  fHaveGenesis = true;
554  }
555  g_genesis_wait_cv.notify_all();
556  }
557 }
558 
560 {
562  assert(fImporting == false);
563  fImporting = true;
564  }
565 
567  assert(fImporting == true);
568  fImporting = false;
569  }
570 };
571 
572 
573 // If we're using -prune with -reindex, then delete block files that will be ignored by the
574 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
575 // is missing, do the same here to delete any later block files after a gap. Also delete all
576 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
577 // is in sync with what's actually on disk by the time we start downloading, so that pruning
578 // works correctly.
579 static void CleanupBlockRevFiles()
580 {
581  std::map<std::string, fs::path> mapBlockFiles;
582 
583  // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
584  // Remove the rev files immediately and insert the blk file paths into an
585  // ordered map keyed by block file index.
586  LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
587  fs::path blocksdir = GetBlocksDir();
588  for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
589  if (fs::is_regular_file(*it) &&
590  it->path().filename().string().length() == 12 &&
591  it->path().filename().string().substr(8,4) == ".dat")
592  {
593  if (it->path().filename().string().substr(0,3) == "blk")
594  mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
595  else if (it->path().filename().string().substr(0,3) == "rev")
596  remove(it->path());
597  }
598  }
599 
600  // Remove all block files that aren't part of a contiguous set starting at
601  // zero by walking the ordered map (keys are block file indices) by
602  // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
603  // start removing block files.
604  int nContigCounter = 0;
605  for (const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
606  if (atoi(item.first) == nContigCounter) {
607  nContigCounter++;
608  continue;
609  }
610  remove(item.second);
611  }
612 }
613 
614 static void ThreadImport(std::vector<fs::path> vImportFiles)
615 {
616  const CChainParams& chainparams = Params();
617  RenameThread("bsha3-loadblk");
619 
620  {
621  CImportingNow imp;
622 
623  // -reindex
624  if (fReindex) {
625  int nFile = 0;
626  while (true) {
627  CDiskBlockPos pos(nFile, 0);
628  if (!fs::exists(GetBlockPosFilename(pos, "blk")))
629  break; // No block files left to reindex
630  FILE *file = OpenBlockFile(pos, true);
631  if (!file)
632  break; // This error is logged in OpenBlockFile
633  LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
634  LoadExternalBlockFile(chainparams, file, &pos);
635  nFile++;
636  }
637  pblocktree->WriteReindexing(false);
638  fReindex = false;
639  LogPrintf("Reindexing finished\n");
640  // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
641  LoadGenesisBlock(chainparams);
642  }
643 
644  // hardcoded $DATADIR/bootstrap.dat
645  fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
646  if (fs::exists(pathBootstrap)) {
647  FILE *file = fsbridge::fopen(pathBootstrap, "rb");
648  if (file) {
649  fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
650  LogPrintf("Importing bootstrap.dat...\n");
651  LoadExternalBlockFile(chainparams, file);
652  RenameOver(pathBootstrap, pathBootstrapOld);
653  } else {
654  LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
655  }
656  }
657 
658  // -loadblock=
659  for (const fs::path& path : vImportFiles) {
660  FILE *file = fsbridge::fopen(path, "rb");
661  if (file) {
662  LogPrintf("Importing blocks file %s...\n", path.string());
663  LoadExternalBlockFile(chainparams, file);
664  } else {
665  LogPrintf("Warning: Could not open blocks file %s\n", path.string());
666  }
667  }
668 
669  // scan for better chains in the block chain database, that are not yet connected in the active best chain
670  CValidationState state;
671  if (!ActivateBestChain(state, chainparams)) {
672  LogPrintf("Failed to connect best block (%s)\n", FormatStateMessage(state));
673  StartShutdown();
674  return;
675  }
676 
677  if (gArgs.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
678  LogPrintf("Stopping after block import\n");
679  StartShutdown();
680  return;
681  }
682  } // End scope of CImportingNow
683  if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
684  LoadMempool();
685  }
687 }
688 
693 static bool InitSanityCheck()
694 {
695  if(!ECC_InitSanityCheck()) {
696  InitError("Elliptic curve cryptography sanity check failure. Aborting.");
697  return false;
698  }
699 
701  return false;
702 
703  if (!Random_SanityCheck()) {
704  InitError("OS cryptographic RNG sanity check failure. Aborting.");
705  return false;
706  }
707 
708  return true;
709 }
710 
711 static bool AppInitServers()
712 {
713  RPCServer::OnStarted(&OnRPCStarted);
714  RPCServer::OnStopped(&OnRPCStopped);
715  if (!InitHTTPServer())
716  return false;
717  StartRPC();
718  if (!StartHTTPRPC())
719  return false;
720  if (gArgs.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) StartREST();
721  StartHTTPServer();
722  return true;
723 }
724 
725 // Parameter interaction based on rules
727 {
728  // when specifying an explicit binding address, you want to listen on it
729  // even when -connect or -proxy is specified
730  if (gArgs.IsArgSet("-bind")) {
731  if (gArgs.SoftSetBoolArg("-listen", true))
732  LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
733  }
734  if (gArgs.IsArgSet("-whitebind")) {
735  if (gArgs.SoftSetBoolArg("-listen", true))
736  LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
737  }
738 
739  if (gArgs.IsArgSet("-connect")) {
740  // when only connecting to trusted nodes, do not seed via DNS, or listen by default
741  if (gArgs.SoftSetBoolArg("-dnsseed", false))
742  LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
743  if (gArgs.SoftSetBoolArg("-listen", false))
744  LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
745  }
746 
747  if (gArgs.IsArgSet("-proxy")) {
748  // to protect privacy, do not listen by default if a default proxy server is specified
749  if (gArgs.SoftSetBoolArg("-listen", false))
750  LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
751  // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
752  // to listen locally, so don't rely on this happening through -listen below.
753  if (gArgs.SoftSetBoolArg("-upnp", false))
754  LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
755  // to protect privacy, do not discover addresses by default
756  if (gArgs.SoftSetBoolArg("-discover", false))
757  LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
758  }
759 
760  if (!gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
761  // do not map ports or try to retrieve public IP when not listening (pointless)
762  if (gArgs.SoftSetBoolArg("-upnp", false))
763  LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
764  if (gArgs.SoftSetBoolArg("-discover", false))
765  LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
766  if (gArgs.SoftSetBoolArg("-listenonion", false))
767  LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
768  }
769 
770  if (gArgs.IsArgSet("-externalip")) {
771  // if an explicit public IP is specified, do not try to find others
772  if (gArgs.SoftSetBoolArg("-discover", false))
773  LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
774  }
775 
776  // disable whitelistrelay in blocksonly mode
777  if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
778  if (gArgs.SoftSetBoolArg("-whitelistrelay", false))
779  LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
780  }
781 
782  // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
783  if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
784  if (gArgs.SoftSetBoolArg("-whitelistrelay", true))
785  LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
786  }
787 
788  // Warn if network-specific options (-addnode, -connect, etc) are
789  // specified in default section of config file, but not overridden
790  // on the command line or in this network's section of the config file.
792 }
793 
794 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
795 {
796  return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
797 }
798 
806 {
807  g_logger->m_print_to_file = !gArgs.IsArgNegated("-debuglogfile");
809 
810  // Add newlines to the logfile to distinguish this execution from the last
811  // one; called before console logging is set up, so this is only sent to
812  // debug.log.
813  LogPrintf("\n\n\n\n\n");
814 
815  g_logger->m_print_to_console = gArgs.GetBoolArg("-printtoconsole", !gArgs.GetBoolArg("-daemon", false));
816  g_logger->m_log_timestamps = gArgs.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
817  g_logger->m_log_time_micros = gArgs.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
818 
819  fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS);
820 
821  std::string version_string = FormatFullVersion();
822 #ifdef DEBUG
823  version_string += " (debug build)";
824 #else
825  version_string += " (release build)";
826 #endif
827  LogPrintf(PACKAGE_NAME " version %s\n", version_string);
828 }
829 
830 namespace { // Variables internal to initialization process only
831 
832 int nMaxConnections;
833 int nUserMaxConnections;
834 int nFD;
836 
837 } // namespace
838 
839 [[noreturn]] static void new_handler_terminate()
840 {
841  // Rather than throwing std::bad-alloc if allocation fails, terminate
842  // immediately to (try to) avoid chain corruption.
843  // Since LogPrintf may itself allocate memory, set the handler directly
844  // to terminate first.
845  std::set_new_handler(std::terminate);
846  LogPrintf("Error: Out of memory. Terminating.\n");
847 
848  // The log was successful, terminate now.
849  std::terminate();
850 };
851 
853 {
854  // ********************************************************* Step 1: setup
855 #ifdef _MSC_VER
856  // Turn off Microsoft heap dump noise
857  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
858  _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
859  // Disable confusing "helpful" text message on abort, Ctrl-C
860  _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
861 #endif
862 #ifdef WIN32
863  // Enable Data Execution Prevention (DEP)
864  // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
865  // A failure is non-critical and needs no further attention!
866 #ifndef PROCESS_DEP_ENABLE
867  // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
868  // which is not correct. Can be removed, when GCCs winbase.h is fixed!
869 #define PROCESS_DEP_ENABLE 0x00000001
870 #endif
871  typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
872  PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
873  if (setProcDEPPol != nullptr) setProcDEPPol(PROCESS_DEP_ENABLE);
874 #endif
875 
876  if (!SetupNetworking())
877  return InitError("Initializing networking failed");
878 
879 #ifndef WIN32
880  if (!gArgs.GetBoolArg("-sysperms", false)) {
881  umask(077);
882  }
883 
884  // Clean shutdown on SIGTERM
885  registerSignalHandler(SIGTERM, HandleSIGTERM);
886  registerSignalHandler(SIGINT, HandleSIGTERM);
887 
888  // Reopen debug.log on SIGHUP
889  registerSignalHandler(SIGHUP, HandleSIGHUP);
890 
891  // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
892  signal(SIGPIPE, SIG_IGN);
893 #else
894  SetConsoleCtrlHandler(consoleCtrlHandler, true);
895 #endif
896 
897  std::set_new_handler(new_handler_terminate);
898 
899  return true;
900 }
901 
903 {
904  const CChainParams& chainparams = Params();
905  // ********************************************************* Step 2: parameter interactions
906 
907  // also see: InitParameterInteraction()
908 
909  if (!fs::is_directory(GetBlocksDir(false))) {
910  return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist."), gArgs.GetArg("-blocksdir", "").c_str()));
911  }
912 
913  // if using block pruning, then disallow txindex
914  if (gArgs.GetArg("-prune", 0)) {
915  if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX))
916  return InitError(_("Prune mode is incompatible with -txindex."));
917  }
918 
919  // -bind and -whitebind can't be set when not listening
920  size_t nUserBind = gArgs.GetArgs("-bind").size() + gArgs.GetArgs("-whitebind").size();
921  if (nUserBind != 0 && !gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
922  return InitError("Cannot set -bind or -whitebind together with -listen=0");
923  }
924 
925  // Make sure enough file descriptors are available
926  int nBind = std::max(nUserBind, size_t(1));
927  nUserMaxConnections = gArgs.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
928  nMaxConnections = std::max(nUserMaxConnections, 0);
929 
930  // Trim requested connection counts, to fit into system limitations
931  // <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695
932  nMaxConnections = std::max(std::min<int>(nMaxConnections, FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS), 0);
933  nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
934  if (nFD < MIN_CORE_FILEDESCRIPTORS)
935  return InitError(_("Not enough file descriptors available."));
936  nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
937 
938  if (nMaxConnections < nUserMaxConnections)
939  InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
940 
941  // ********************************************************* Step 3: parameter-to-internal-flags
942  if (gArgs.IsArgSet("-debug")) {
943  // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
944  const std::vector<std::string> categories = gArgs.GetArgs("-debug");
945 
946  if (std::none_of(categories.begin(), categories.end(),
947  [](std::string cat){return cat == "0" || cat == "none";})) {
948  for (const auto& cat : categories) {
949  if (!g_logger->EnableCategory(cat)) {
950  InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
951  }
952  }
953  }
954  }
955 
956  // Now remove the logging categories which were explicitly excluded
957  for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
958  if (!g_logger->DisableCategory(cat)) {
959  InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
960  }
961  }
962 
963  // Checkmempool and checkblockindex default to true in regtest mode
964  int ratio = std::min<int>(std::max<int>(gArgs.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
965  if (ratio != 0) {
966  mempool.setSanityCheck(1.0 / ratio);
967  }
968  fCheckBlockIndex = gArgs.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
969  fCheckpointsEnabled = gArgs.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
970 
971  hashAssumeValid = uint256S(gArgs.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
972  if (!hashAssumeValid.IsNull())
973  LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
974  else
975  LogPrintf("Validating signatures for all blocks.\n");
976 
977  if (gArgs.IsArgSet("-minimumchainwork")) {
978  const std::string minChainWorkStr = gArgs.GetArg("-minimumchainwork", "");
979  if (!IsHexNumber(minChainWorkStr)) {
980  return InitError(strprintf("Invalid non-hex (%s) minimum chain work value specified", minChainWorkStr));
981  }
982  nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
983  } else {
985  }
986  LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
988  LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex());
989  }
990 
991  // mempool limits
992  int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
993  int64_t nMempoolSizeMin = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
994  if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
995  return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
996  // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
997  // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
998  if (gArgs.IsArgSet("-incrementalrelayfee"))
999  {
1000  CAmount n = 0;
1001  if (!ParseMoney(gArgs.GetArg("-incrementalrelayfee", ""), n))
1002  return InitError(AmountErrMsg("incrementalrelayfee", gArgs.GetArg("-incrementalrelayfee", "")));
1004  }
1005 
1006  // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
1007  nScriptCheckThreads = gArgs.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
1008  if (nScriptCheckThreads <= 0)
1010  if (nScriptCheckThreads <= 1)
1011  nScriptCheckThreads = 0;
1012  else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
1013  nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
1014 
1015  // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
1016  int64_t nPruneArg = gArgs.GetArg("-prune", 0);
1017  if (nPruneArg < 0) {
1018  return InitError(_("Prune cannot be configured with a negative value."));
1019  }
1020  nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
1021  if (nPruneArg == 1) { // manual pruning: -prune=1
1022  LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1023  nPruneTarget = std::numeric_limits<uint64_t>::max();
1024  fPruneMode = true;
1025  } else if (nPruneTarget) {
1026  if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
1027  return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1028  }
1029  LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1030  fPruneMode = true;
1031  }
1032 
1033  nConnectTimeout = gArgs.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1034  if (nConnectTimeout <= 0)
1035  nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1036 
1037  if (gArgs.IsArgSet("-minrelaytxfee")) {
1038  CAmount n = 0;
1039  if (!ParseMoney(gArgs.GetArg("-minrelaytxfee", ""), n)) {
1040  return InitError(AmountErrMsg("minrelaytxfee", gArgs.GetArg("-minrelaytxfee", "")));
1041  }
1042  // High fee check is done afterward in WalletParameterInteraction()
1044  } else if (incrementalRelayFee > ::minRelayTxFee) {
1045  // Allow only setting incrementalRelayFee to control both
1047  LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1048  }
1049 
1050  // Sanity check argument for min fee for including tx in block
1051  // TODO: Harmonize which arguments need sanity checking and where that happens
1052  if (gArgs.IsArgSet("-blockmintxfee"))
1053  {
1054  CAmount n = 0;
1055  if (!ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n))
1056  return InitError(AmountErrMsg("blockmintxfee", gArgs.GetArg("-blockmintxfee", "")));
1057  }
1058 
1059  // Feerate used to define dust. Shouldn't be changed lightly as old
1060  // implementations may inadvertently create non-standard transactions
1061  if (gArgs.IsArgSet("-dustrelayfee"))
1062  {
1063  CAmount n = 0;
1064  if (!ParseMoney(gArgs.GetArg("-dustrelayfee", ""), n))
1065  return InitError(AmountErrMsg("dustrelayfee", gArgs.GetArg("-dustrelayfee", "")));
1066  dustRelayFee = CFeeRate(n);
1067  }
1068 
1069  fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1070  if (chainparams.RequireStandard() && !fRequireStandard)
1071  return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1072  nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp);
1073 
1074  if (!g_wallet_init_interface.ParameterInteraction()) return false;
1075 
1076  fIsBareMultisigStd = gArgs.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1077  fAcceptDatacarrier = gArgs.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1078  nMaxDatacarrierBytes = gArgs.GetArg("-datacarriersize", nMaxDatacarrierBytes);
1079 
1080  // Option to startup with mocktime set (used for regression testing):
1081  SetMockTime(gArgs.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1082 
1083  if (gArgs.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1084  nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1085 
1086  if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1087  return InitError("rpcserialversion must be non-negative.");
1088 
1089  if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1090  return InitError("unknown rpcserialversion requested.");
1091 
1092  nMaxTipAge = gArgs.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1093 
1094  fEnableReplacement = gArgs.GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1095  if ((!fEnableReplacement) && gArgs.IsArgSet("-mempoolreplacement")) {
1096  // Minimal effort at forwards compatibility
1097  std::string strReplacementModeList = gArgs.GetArg("-mempoolreplacement", ""); // default is impossible
1098  std::vector<std::string> vstrReplacementModes;
1099  boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1100  fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1101  }
1102 
1103  return true;
1104 }
1105 
1106 static bool LockDataDirectory(bool probeOnly)
1107 {
1108  // Make sure only a single Bitcoin process is using the data directory.
1109  fs::path datadir = GetDataDir();
1110  if (!DirIsWritable(datadir)) {
1111  return InitError(strprintf(_("Cannot write to data directory '%s'; check permissions."), datadir.string()));
1112  }
1113  if (!LockDirectory(datadir, ".lock", probeOnly)) {
1114  return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), datadir.string(), _(PACKAGE_NAME)));
1115  }
1116  return true;
1117 }
1118 
1120 {
1121  // ********************************************************* Step 4: sanity checks
1122 
1123  // Initialize elliptic curve code
1124  std::string sha256_algo = SHA256AutoDetect();
1125  LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
1126  RandomInit();
1127  ECC_Start();
1128  globalVerifyHandle.reset(new ECCVerifyHandle());
1129 
1130  // Sanity check
1131  if (!InitSanityCheck())
1132  return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1133 
1134  // Probe the data directory lock to give an early error message, if possible
1135  // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened,
1136  // and a fork will cause weird behavior to it.
1137  return LockDataDirectory(true);
1138 }
1139 
1141 {
1142  // After daemonization get the data directory lock again and hold on to it until exit
1143  // This creates a slight window for a race condition to happen, however this condition is harmless: it
1144  // will at most make us exit without printing a message to console.
1145  if (!LockDataDirectory(false)) {
1146  // Detailed error printed inside LockDataDirectory
1147  return false;
1148  }
1149  return true;
1150 }
1151 
1153 {
1154  const CChainParams& chainparams = Params();
1155  // ********************************************************* Step 4a: application initialization
1156 #ifndef WIN32
1157  CreatePidFile(GetPidFile(), getpid());
1158 #endif
1159  if (g_logger->m_print_to_file) {
1160  if (gArgs.GetBoolArg("-shrinkdebugfile", g_logger->DefaultShrinkDebugFile())) {
1161  // Do this first since it both loads a bunch of debug.log into memory,
1162  // and because this needs to happen before any other debug.log printing
1164  }
1165  if (!g_logger->OpenDebugLog()) {
1166  return InitError(strprintf("Could not open debug log file %s",
1167  g_logger->m_file_path.string()));
1168  }
1169  }
1170 
1171  if (!g_logger->m_log_timestamps)
1172  LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
1173  LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1174  LogPrintf("Using data directory %s\n", GetDataDir().string());
1175 
1176  // Only log conf file usage message if conf file actually exists.
1177  fs::path config_file_path = GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME));
1178  if (fs::exists(config_file_path)) {
1179  LogPrintf("Config file: %s\n", config_file_path.string());
1180  } else if (gArgs.IsArgSet("-conf")) {
1181  // Warn if no conf file exists at path provided by user
1182  InitWarning(strprintf(_("The specified config file %s does not exist\n"), config_file_path.string()));
1183  } else {
1184  // Not categorizing as "Warning" because it's the default behavior
1185  LogPrintf("Config file: %s (not found, skipping)\n", config_file_path.string());
1186  }
1187 
1188  LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1189 
1190  // Warn about relative -datadir path.
1191  if (gArgs.IsArgSet("-datadir") && !fs::path(gArgs.GetArg("-datadir", "")).is_absolute()) {
1192  LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " /* Continued */
1193  "current working directory '%s'. This is fragile, because if bitcoin is started in the future "
1194  "from a different location, it will be unable to locate the current data files. There could "
1195  "also be data loss if bitcoin is started while in a temporary directory.\n",
1196  gArgs.GetArg("-datadir", ""), fs::current_path().string());
1197  }
1198 
1201 
1202  LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1203  if (nScriptCheckThreads) {
1204  for (int i=0; i<nScriptCheckThreads-1; i++)
1205  threadGroup.create_thread(&ThreadScriptCheck);
1206  }
1207 
1208  // Start the lightweight task scheduler thread
1209  CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1210  threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1211 
1214 
1215  /* Register RPC commands regardless of -server setting so they will be
1216  * available in the GUI RPC console even if external calls are disabled.
1217  */
1218  RegisterAllCoreRPCCommands(tableRPC);
1220 #if ENABLE_ZMQ
1222 #endif
1223 
1224  /* Start the RPC server already. It will be started in "warmup" mode
1225  * and not really process calls already (but it will signify connections
1226  * that the server is there and will be ready later). Warmup mode will
1227  * be disabled when initialisation is finished.
1228  */
1229  if (gArgs.GetBoolArg("-server", false))
1230  {
1231  uiInterface.InitMessage_connect(SetRPCWarmupStatus);
1232  if (!AppInitServers())
1233  return InitError(_("Unable to start HTTP server. See debug log for details."));
1234  }
1235 
1236  // ********************************************************* Step 5: verify wallet database integrity
1237  if (!g_wallet_init_interface.Verify()) return false;
1238 
1239  // ********************************************************* Step 6: network initialization
1240  // Note that we absolutely cannot open any actual connections
1241  // until the very end ("start node") as the UTXO/block state
1242  // is not yet setup and may end up being set up twice if we
1243  // need to reindex later.
1244 
1245  assert(!g_connman);
1246  g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1247  CConnman& connman = *g_connman;
1248 
1249  peerLogic.reset(new PeerLogicValidation(&connman, scheduler, gArgs.GetBoolArg("-enablebip61", DEFAULT_ENABLE_BIP61)));
1251 
1252  // sanitize comments per BIP-0014, format user agent and check total size
1253  std::vector<std::string> uacomments;
1254  for (const std::string& cmt : gArgs.GetArgs("-uacomment")) {
1255  if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1256  return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1257  uacomments.push_back(cmt);
1258  }
1259  strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1260  if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1261  return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1262  strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1263  }
1264 
1265  if (gArgs.IsArgSet("-onlynet")) {
1266  std::set<enum Network> nets;
1267  for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
1268  enum Network net = ParseNetwork(snet);
1269  if (net == NET_UNROUTABLE)
1270  return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1271  nets.insert(net);
1272  }
1273  for (int n = 0; n < NET_MAX; n++) {
1274  enum Network net = (enum Network)n;
1275  if (!nets.count(net))
1276  SetLimited(net);
1277  }
1278  }
1279 
1280  // Check for host lookup allowed before parsing any network related parameters
1281  fNameLookup = gArgs.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1282 
1283  bool proxyRandomize = gArgs.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1284  // -proxy sets a proxy for all outgoing network traffic
1285  // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1286  std::string proxyArg = gArgs.GetArg("-proxy", "");
1288  if (proxyArg != "" && proxyArg != "0") {
1289  CService proxyAddr;
1290  if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1291  return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1292  }
1293 
1294  proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1295  if (!addrProxy.IsValid())
1296  return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1297 
1298  SetProxy(NET_IPV4, addrProxy);
1299  SetProxy(NET_IPV6, addrProxy);
1300  SetProxy(NET_ONION, addrProxy);
1301  SetNameProxy(addrProxy);
1302  SetLimited(NET_ONION, false); // by default, -proxy sets onion as reachable, unless -noonion later
1303  }
1304 
1305  // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1306  // -noonion (or -onion=0) disables connecting to .onion entirely
1307  // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1308  std::string onionArg = gArgs.GetArg("-onion", "");
1309  if (onionArg != "") {
1310  if (onionArg == "0") { // Handle -noonion/-onion=0
1311  SetLimited(NET_ONION); // set onions as unreachable
1312  } else {
1313  CService onionProxy;
1314  if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1315  return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1316  }
1317  proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1318  if (!addrOnion.IsValid())
1319  return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1320  SetProxy(NET_ONION, addrOnion);
1321  SetLimited(NET_ONION, false);
1322  }
1323  }
1324 
1325  // see Step 2: parameter interactions for more information about these
1326  fListen = gArgs.GetBoolArg("-listen", DEFAULT_LISTEN);
1327  fDiscover = gArgs.GetBoolArg("-discover", true);
1328  fRelayTxes = !gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1329 
1330  for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
1331  CService addrLocal;
1332  if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1333  AddLocal(addrLocal, LOCAL_MANUAL);
1334  else
1335  return InitError(ResolveErrMsg("externalip", strAddr));
1336  }
1337 
1338 #if ENABLE_ZMQ
1340 
1343  }
1344 #endif
1345  uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1346  uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1347 
1348  if (gArgs.IsArgSet("-maxuploadtarget")) {
1349  nMaxOutboundLimit = gArgs.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1350  }
1351 
1352  // ********************************************************* Step 7: load block chain
1353 
1354  fReindex = gArgs.GetBoolArg("-reindex", false);
1355  bool fReindexChainState = gArgs.GetBoolArg("-reindex-chainstate", false);
1356 
1357  // cache size calculations
1358  int64_t nTotalCache = (gArgs.GetArg("-dbcache", nDefaultDbCache) << 20);
1359  nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1360  nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1361  int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20);
1362  nTotalCache -= nBlockTreeDBCache;
1363  int64_t nTxIndexCache = std::min(nTotalCache / 8, gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0);
1364  nTotalCache -= nTxIndexCache;
1365  int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1366  nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1367  nTotalCache -= nCoinDBCache;
1368  nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1369  int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1370  LogPrintf("Cache configuration:\n");
1371  LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1372  if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1373  LogPrintf("* Using %.1fMiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
1374  }
1375  LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1376  LogPrintf("* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
1377 
1378  bool fLoaded = false;
1379  while (!fLoaded && !ShutdownRequested()) {
1380  bool fReset = fReindex;
1381  std::string strLoadError;
1382 
1383  uiInterface.InitMessage(_("Loading block index..."));
1384 
1385  LOCK(cs_main);
1386 
1387  do {
1388  const int64_t load_block_index_start_time = GetTimeMillis();
1389  try {
1390  UnloadBlockIndex();
1391  pcoinsTip.reset();
1392  pcoinsdbview.reset();
1393  pcoinscatcher.reset();
1394  // new CBlockTreeDB tries to delete the existing file, which
1395  // fails if it's still open from the previous loop. Close it first:
1396  pblocktree.reset();
1397  pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
1398 
1399  if (fReset) {
1400  pblocktree->WriteReindexing(true);
1401  //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1402  if (fPruneMode)
1403  CleanupBlockRevFiles();
1404  }
1405 
1406  if (ShutdownRequested()) break;
1407 
1408  // LoadBlockIndex will load fHavePruned if we've ever removed a
1409  // block file from disk.
1410  // Note that it also sets fReindex based on the disk flag!
1411  // From here on out fReindex and fReset mean something different!
1412  if (!LoadBlockIndex(chainparams)) {
1413  strLoadError = _("Error loading block database");
1414  break;
1415  }
1416 
1417  // If the loaded chain has a wrong genesis, bail out immediately
1418  // (we're likely using a testnet datadir, or the other way around).
1419  if (!mapBlockIndex.empty() && !LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
1420  return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1421  }
1422 
1423  // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1424  // in the past, but is now trying to run unpruned.
1425  if (fHavePruned && !fPruneMode) {
1426  strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1427  break;
1428  }
1429 
1430  // At this point blocktree args are consistent with what's on disk.
1431  // If we're not mid-reindex (based on disk + args), add a genesis block on disk
1432  // (otherwise we use the one already on disk).
1433  // This is called again in ThreadImport after the reindex completes.
1434  if (!fReindex && !LoadGenesisBlock(chainparams)) {
1435  strLoadError = _("Error initializing block database");
1436  break;
1437  }
1438 
1439  // At this point we're either in reindex or we've loaded a useful
1440  // block tree into mapBlockIndex!
1441 
1442  pcoinsdbview.reset(new CCoinsViewDB(nCoinDBCache, false, fReset || fReindexChainState));
1443  pcoinscatcher.reset(new CCoinsViewErrorCatcher(pcoinsdbview.get()));
1444 
1445  // If necessary, upgrade from older database format.
1446  // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1447  if (!pcoinsdbview->Upgrade()) {
1448  strLoadError = _("Error upgrading chainstate database");
1449  break;
1450  }
1451 
1452  // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1453  if (!ReplayBlocks(chainparams, pcoinsdbview.get())) {
1454  strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1455  break;
1456  }
1457 
1458  // The on-disk coinsdb is now in a good state, create the cache
1459  pcoinsTip.reset(new CCoinsViewCache(pcoinscatcher.get()));
1460 
1461  bool is_coinsview_empty = fReset || fReindexChainState || pcoinsTip->GetBestBlock().IsNull();
1462  if (!is_coinsview_empty) {
1463  // LoadChainTip sets chainActive based on pcoinsTip's best block
1464  if (!LoadChainTip(chainparams)) {
1465  strLoadError = _("Error initializing block database");
1466  break;
1467  }
1468  assert(chainActive.Tip() != nullptr);
1469  }
1470 
1471  if (!fReset) {
1472  // Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate.
1473  // It both disconnects blocks based on chainActive, and drops block data in
1474  // mapBlockIndex based on lack of available witness data.
1475  uiInterface.InitMessage(_("Rewinding blocks..."));
1476  if (!RewindBlockIndex(chainparams)) {
1477  strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1478  break;
1479  }
1480  }
1481 
1482  if (!is_coinsview_empty) {
1483  uiInterface.InitMessage(_("Verifying blocks..."));
1484  if (fHavePruned && gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1485  LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
1486  MIN_BLOCKS_TO_KEEP);
1487  }
1488 
1489  CBlockIndex* tip = chainActive.Tip();
1490  RPCNotifyBlockChange(true, tip);
1491  if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1492  strLoadError = _("The block database contains a block which appears to be from the future. "
1493  "This may be due to your computer's date and time being set incorrectly. "
1494  "Only rebuild the block database if you are sure that your computer's date and time are correct");
1495  break;
1496  }
1497 
1498  if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview.get(), gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1499  gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1500  strLoadError = _("Corrupted block database detected");
1501  break;
1502  }
1503  }
1504  } catch (const std::exception& e) {
1505  LogPrintf("%s\n", e.what());
1506  strLoadError = _("Error opening block database");
1507  break;
1508  }
1509 
1510  fLoaded = true;
1511  LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time);
1512  } while(false);
1513 
1514  if (!fLoaded && !ShutdownRequested()) {
1515  // first suggest a reindex
1516  if (!fReset) {
1517  bool fRet = uiInterface.ThreadSafeQuestion(
1518  strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1519  strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1521  if (fRet) {
1522  fReindex = true;
1523  AbortShutdown();
1524  } else {
1525  LogPrintf("Aborted block database rebuild. Exiting.\n");
1526  return false;
1527  }
1528  } else {
1529  return InitError(strLoadError);
1530  }
1531  }
1532  }
1533 
1534  // As LoadBlockIndex can take several minutes, it's possible the user
1535  // requested to kill the GUI during the last operation. If so, exit.
1536  // As the program has not fully started yet, Shutdown() is possibly overkill.
1537  if (ShutdownRequested()) {
1538  LogPrintf("Shutdown requested. Exiting.\n");
1539  return false;
1540  }
1541 
1542  fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1543  CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
1544  // Allowed to fail as this file IS missing on first startup.
1545  if (!est_filein.IsNull())
1546  ::feeEstimator.Read(est_filein);
1547  fFeeEstimatesInitialized = true;
1548 
1549  // ********************************************************* Step 8: start indexers
1550  if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1551  g_txindex = MakeUnique<TxIndex>(nTxIndexCache, false, fReindex);
1552  g_txindex->Start();
1553  }
1554 
1555  // ********************************************************* Step 9: load wallet
1556  if (!g_wallet_init_interface.Open()) return false;
1557 
1558  // ********************************************************* Step 10: data directory maintenance
1559 
1560  // if pruning, unset the service bit and perform the initial blockstore prune
1561  // after any wallet rescanning has taken place.
1562  if (fPruneMode) {
1563  LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1564  nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1565  if (!fReindex) {
1566  uiInterface.InitMessage(_("Pruning blockstore..."));
1567  PruneAndFlush();
1568  }
1569  }
1570 
1571  if (chainparams.GetConsensus().nSegwitEnabled) {
1572  nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1573  }
1574 
1575  // ********************************************************* Step 11: import blocks
1576 
1577  if (!CheckDiskSpace() && !CheckDiskSpace(0, true))
1578  return false;
1579 
1580  // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1581  // No locking, as this happens before any background thread is started.
1582  if (chainActive.Tip() == nullptr) {
1583  uiInterface.NotifyBlockTip_connect(BlockNotifyGenesisWait);
1584  } else {
1585  fHaveGenesis = true;
1586  }
1587 
1588  if (gArgs.IsArgSet("-blocknotify"))
1589  uiInterface.NotifyBlockTip_connect(BlockNotifyCallback);
1590 
1591  std::vector<fs::path> vImportFiles;
1592  for (const std::string& strFile : gArgs.GetArgs("-loadblock")) {
1593  vImportFiles.push_back(strFile);
1594  }
1595 
1596  threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1597 
1598  // Wait for genesis block to be processed
1599  {
1600  WAIT_LOCK(g_genesis_wait_mutex, lock);
1601  // We previously could hang here if StartShutdown() is called prior to
1602  // ThreadImport getting started, so instead we just wait on a timer to
1603  // check ShutdownRequested() regularly.
1604  while (!fHaveGenesis && !ShutdownRequested()) {
1605  g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
1606  }
1607  uiInterface.NotifyBlockTip_disconnect(BlockNotifyGenesisWait);
1608  }
1609 
1610  if (ShutdownRequested()) {
1611  return false;
1612  }
1613 
1614  // ********************************************************* Step 12: start node
1615 
1616  int chain_active_height;
1617 
1619  {
1620  LOCK(cs_main);
1621  LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1622  chain_active_height = chainActive.Height();
1623  }
1624  LogPrintf("nBestHeight = %d\n", chain_active_height);
1625 
1626  if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1627  StartTorControl();
1628 
1629  Discover();
1630 
1631  // Map ports with UPnP
1632  if (gArgs.GetBoolArg("-upnp", DEFAULT_UPNP)) {
1633  StartMapPort();
1634  }
1635 
1636  CConnman::Options connOptions;
1637  connOptions.nLocalServices = nLocalServices;
1638  connOptions.nMaxConnections = nMaxConnections;
1639  connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1640  connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1641  connOptions.nMaxFeeler = 1;
1642  connOptions.nBestHeight = chain_active_height;
1643  connOptions.uiInterface = &uiInterface;
1644  connOptions.m_msgproc = peerLogic.get();
1645  connOptions.nSendBufferMaxSize = 1000*gArgs.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1646  connOptions.nReceiveFloodSize = 1000*gArgs.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1647  connOptions.m_added_nodes = gArgs.GetArgs("-addnode");
1648 
1649  connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1650  connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1651 
1652  for (const std::string& strBind : gArgs.GetArgs("-bind")) {
1653  CService addrBind;
1654  if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) {
1655  return InitError(ResolveErrMsg("bind", strBind));
1656  }
1657  connOptions.vBinds.push_back(addrBind);
1658  }
1659  for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
1660  CService addrBind;
1661  if (!Lookup(strBind.c_str(), addrBind, 0, false)) {
1662  return InitError(ResolveErrMsg("whitebind", strBind));
1663  }
1664  if (addrBind.GetPort() == 0) {
1665  return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1666  }
1667  connOptions.vWhiteBinds.push_back(addrBind);
1668  }
1669 
1670  for (const auto& net : gArgs.GetArgs("-whitelist")) {
1671  CSubNet subnet;
1672  LookupSubNet(net.c_str(), subnet);
1673  if (!subnet.IsValid())
1674  return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1675  connOptions.vWhitelistedRange.push_back(subnet);
1676  }
1677 
1678  connOptions.vSeedNodes = gArgs.GetArgs("-seednode");
1679 
1680  // Initiate outbound connections unless connect=0
1681  connOptions.m_use_addrman_outgoing = !gArgs.IsArgSet("-connect");
1682  if (!connOptions.m_use_addrman_outgoing) {
1683  const auto connect = gArgs.GetArgs("-connect");
1684  if (connect.size() != 1 || connect[0] != "0") {
1685  connOptions.m_specified_outgoing = connect;
1686  }
1687  }
1688  if (!connman.Start(scheduler, connOptions)) {
1689  return false;
1690  }
1691 
1692  // ********************************************************* Step 13: finished
1693 
1695  uiInterface.InitMessage(_("Done loading"));
1696 
1697  g_wallet_init_interface.Start(scheduler);
1698 
1699  return true;
1700 }
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: init.cpp:122
std::vector< CService > vBinds
Definition: net.h:142
std::unique_ptr< const CChainParams > CreateChainParams(const std::string &chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
void StartTorControl()
Definition: torcontrol.cpp:742
void EnableCategory(LogFlags flag)
Definition: logging.cpp:55
void RandomInit()
Initialize the RNG.
Definition: random.cpp:466
#define COPYRIGHT_YEAR
CTxMemPool mempool
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:74
bool(* handler)(HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:582
void ECC_Start()
Initialize the elliptic curve support.
Definition: key.cpp:343
unsigned short GetPort() const
Definition: netaddress.cpp:505
std::vector< CSubNet > vWhitelistedRange
Definition: net.h:141
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Creates and returns a std::unique_ptr<CBaseChainParams> of the chosen chain.
bool IsHexNumber(const std::string &str)
Return true if the string is a hex number, optionally prefixed with "0x".
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: util.cpp:502
bool ShutdownRequested()
Definition: shutdown.cpp:20
bool SetupNetworking()
Definition: util.cpp:1221
int nScriptCheckThreads
Definition: validation.cpp:224
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:228
std::condition_variable g_best_block_cv
Definition: validation.cpp:222
ServiceFlags
nServices flags
Definition: protocol.h:247
void UnloadBlockIndex()
Unload database information.
void InitLogging()
Initialize global loggers.
Definition: init.cpp:805
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:209
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:13
#define TRY_LOCK(cs, name)
Definition: sync.h:185
const char *const BITCOIN_CONF_FILENAME
Definition: util.cpp:85
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: util.cpp:558
static const std::string REGTEST
A UTXO entry.
Definition: coins.h:29
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:326
bool AppInitMain()
Bitcoin core main initialization.
Definition: init.cpp:1152
fs::path m_file_path
Definition: logging.h:85
const char *const BITCOIN_PID_FILENAME
Definition: util.cpp:86
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
#define strprintf
Definition: tinyformat.h:1066
virtual void RegisterRPC(CRPCTable &) const =0
Register wallet RPC.
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:227
~CImportingNow()
Definition: init.cpp:566
BlockMap & mapBlockIndex
Definition: validation.cpp:218
virtual void Start(CScheduler &scheduler) const =0
Start wallets.
std::string ListLogCategories()
Returns a string with the log categories.
Definition: logging.cpp:141
bool Write(CAutoFile &fileout) const
Write estimation data to a file.
Definition: fees.cpp:899
void FlushUnconfirmed()
Empty mempool transactions on shutdown to record failure to confirm for txs still in mempool...
Definition: fees.cpp:984
unsigned int nReceiveFloodSize
Definition: net.h:137
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: util.cpp:586
CClientUIInterface * uiInterface
Definition: net.h:134
bool LoadMempool()
Load the mempool from disk.
void WarnForSectionOnlyArgs()
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition: util.cpp:375
int Height() const
Return the maximal height in the chain.
Definition: chain.h:476
void SetMockTime(int64_t nMockTimeIn)
Definition: utiltime.cpp:30
bool StartHTTPRPC()
Start HTTP RPC subsystem.
Definition: httprpc.cpp:237
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
Definition: standard.cpp:17
void StopTorControl()
Definition: torcontrol.cpp:767
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:604
void OnStopped(std::function< void()> slot)
Definition: server.cpp:46
void SetLimited(enum Network net, bool fLimited)
Make a particular network entirely off-limits (no automatic connects to it)
Definition: net.cpp:248
std::atomic< bool > m_reopen_file
Definition: logging.h:86
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
void Interrupt()
Interrupt threads.
Definition: init.cpp:144
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:239
#define PACKAGE_NAME
void InterruptRPC()
Definition: server.cpp:306
bool m_print_to_console
Definition: logging.h:79
bool fDiscover
Definition: net.cpp:83
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
Definition: chainparams.h:67
void Discover()
Definition: net.cpp:2164
int nMaxConnections
Definition: net.h:129
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
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::function< void()> Function
Definition: scheduler.h:43
uint32_t nTime
Definition: chain.h:212
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:542
unsigned short GetListenPort()
Definition: net.cpp:99
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
Definition: sha256.cpp:573
void StartREST()
Start HTTP REST subsystem.
Definition: rest.cpp:594
std::vector< CService > vWhiteBinds
Definition: net.h:142
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:254
bool AppInitBasicSetup()
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:852
unsigned int nBytesPerSigOp
Definition: policy.cpp:244
std::string LicenseInfo()
Returns licensing information (for -version)
Definition: init.cpp:509
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:433
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: util.cpp:1255
uint64_t nPruneTarget
Number of MiB of block files that we&#39;re trying to stay below.
Definition: validation.cpp:234
bool SetNameProxy(const proxyType &addrProxy)
Definition: netbase.cpp:560
void RenameThread(const char *name)
Definition: util.cpp:1168
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: util.cpp:147
bool IsNull() const
Definition: uint256.h:32
bool fIsBareMultisigStd
Definition: validation.cpp:229
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Find the best known block, and make it the tip of the block chain.
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:666
arith_uint256 UintToArith256(const uint256 &a)
bool m_print_to_file
Definition: logging.h:80
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: init.cpp:121
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: util.cpp:1074
bool IsValid() const
Definition: netaddress.cpp:188
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:298
bool nSegwitEnabled
Definition: params.h:66
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
bool CheckDiskSpace(uint64_t nAdditionalBytes, bool blocks_dir)
Check whether enough disk space is available for an incoming block.
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:726
uint256 GetBlockHash() const
Definition: chain.h:292
void SetRPCWarmupFinished()
Definition: server.cpp:332
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:244
int ScheduleBatchPriority(void)
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: util.cpp:1273
void StopMapPort()
Definition: net.cpp:1607
bool glibc_sanity_test()
CRPCTable tableRPC
Definition: server.cpp:556
void setSanityCheck(double dFrequency=1.0)
Definition: txmempool.h:534
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:350
Users of this module must hold an ECCVerifyHandle.
Definition: pubkey.h:254
bool fCheckpointsEnabled
Definition: validation.cpp:232
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1119
bool ReplayBlocks(const CChainParams &params, CCoinsView *view)
Replay blocks that aren&#39;t fully applied to the database.
bool fRelayTxes
Definition: net.cpp:85
enum Network ParseNetwork(std::string net)
Definition: netbase.cpp:39
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: util.cpp:508
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
static CZMQNotificationInterface * Create()
CCriticalSection cs_main
Definition: validation.cpp:216
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:31
Access to the block database (blocks/index/)
Definition: txdb.h:86
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:448
Abstract view on the open txout dataset.
Definition: coins.h:145
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:241
bool m_log_time_micros
Definition: logging.h:83
#define LOCK(cs)
Definition: sync.h:181
fs::path GetPidFile()
Definition: util.cpp:983
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition: key.cpp:360
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:17
std::unique_ptr< CCoinsViewDB > pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
Definition: validation.cpp:297
NetEventsInterface * m_msgproc
Definition: net.h:135
CImportingNow()
Definition: init.cpp:561
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:142
virtual void Close() const =0
Close wallets.
std::vector< std::string > vSeedNodes
Definition: net.h:140
uint256 uint256S(const char *str)
Definition: uint256.h:142
std::vector< std::string > m_specified_outgoing
Definition: net.h:144
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:421
void RegisterWithMempoolSignals(CTxMemPool &pool)
Register with mempool to call TransactionRemovedFromMempool callbacks.
void InitSignatureCache()
Definition: sigcache.cpp:73
virtual bool Verify() const =0
Verify wallets.
void Shutdown()
Definition: init.cpp:159
int nMaxFeeler
Definition: net.h:132
CMainSignals & GetMainSignals()
void DisableCategory(LogFlags flag)
Definition: logging.cpp:68
Network
Definition: netaddress.h:20
void serviceQueue()
Definition: scheduler.cpp:33
void UnregisterWithMempoolSignals(CTxMemPool &pool)
Unregister with mempool.
bool ParseMoney(const std::string &str, CAmount &nRet)
Definition: net.h:115
#define WAIT_LOCK(cs, name)
Definition: sync.h:186
std::atomic_bool fImporting
void StartRPC()
Definition: server.cpp:299
BIP-0014 subset.
int nMaxOutbound
Definition: net.h:130
void ThreadScriptCheck()
Run an instance of the script checking thread.
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
bool fEnableReplacement
Definition: validation.cpp:236
const std::string CLIENT_NAME
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:89
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:349
bool RenameOver(fs::path src, fs::path dest)
Definition: util.cpp:999
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
int nConnectTimeout
Definition: netbase.cpp:32
bool DumpMempool()
Dump the mempool to disk.
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:235
std::string FormatFullVersion()
std::string CopyrightHolders(const std::string &strPrefix)
Definition: util.cpp:1238
virtual bool Open() const =0
Open wallets.
fs::path GetDefaultDataDir()
Definition: util.cpp:705
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:238
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:614
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:542
const fs::path & GetBlocksDir(bool fNetSpecific)
Definition: util.cpp:737
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
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:259
bool AppInitParameterInteraction()
Initialization: parameter interaction.
Definition: init.cpp:902
uint64_t nMaxOutboundTimeframe
Definition: net.h:138
std::atomic_bool fReindex
bool IsValid() const
Definition: netaddress.cpp:699
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once) ...
Capture information about block/transaction validation.
Definition: validation.h:26
bool glibcxx_sanity_test()
bool fCheckBlockIndex
Definition: validation.cpp:231
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
bool fFeeEstimatesInitialized
Definition: init.cpp:69
ArgsManager gArgs
Definition: util.cpp:88
void RegisterZMQRPCCommands(CRPCTable &t)
Definition: zmqrpc.cpp:56
uint256 nMinimumChainWork
Definition: params.h:63
std::atomic_bool g_is_mempool_loaded
Definition: validation.cpp:246
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
Definition: chainparams.h:69
const WalletInitInterface & g_wallet_init_interface
Definition: init.cpp:55
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:453
void SetupChainParamsBaseOptions()
Set the arguments for chainparams.
void SetupServerArgs()
Setup the arguments for gArgs.
Definition: init.cpp:315
void StopRPC()
Definition: server.cpp:313
int nMaxAddnode
Definition: net.h:131
bool InitError(const std::string &str)
Show error message.
bool IsValid() const
Definition: netbase.h:34
uint256 defaultAssumeValid
Definition: params.h:64
bool fRequireStandard
Definition: validation.cpp:230
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
const CChainParams & Params()
Return the currently selected parameters.
fs::path GetConfigFile(const std::string &confPath)
Definition: util.cpp:808
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: utiltime.cpp:79
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:44
int64_t GetTimeMillis()
Definition: utiltime.cpp:40
void InitScriptExecutionCache()
Initializes the script-execution cache.
void AddArg(const std::string &name, const std::string &help, const bool debug_only, const OptionsCategory &cat)
Add argument.
Definition: util.cpp:572
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:526
bool Read(CAutoFile &filein)
Read estimation data from a file.
Definition: fees.cpp:924
ServiceFlags nLocalServices
Definition: net.h:128
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:600
bool fLogIPs
Definition: logging.cpp:26
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
bool DirIsWritable(const fs::path &directory)
Definition: util.cpp:177
uint64_t nMaxOutboundLimit
Definition: net.h:139
void runCommand(const std::string &strCommand)
Definition: util.cpp:1156
std::vector< std::string > m_added_nodes
Definition: net.h:145
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:140
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:23
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:445
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:21
void AbortShutdown()
Definition: shutdown.cpp:16
bool fListen
Definition: net.cpp:84
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:74
virtual void Flush() const =0
Flush Wallets.
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:299
bool OpenDebugLog()
Definition: logging.cpp:33
std::unique_ptr< PeerLogicValidation > peerLogic
Definition: init.cpp:75
void StartShutdown()
Definition: shutdown.cpp:12
static const std::string TESTNET
unsigned int nSendBufferMaxSize
Definition: net.h:136
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:419
void RPCNotifyBlockChange(bool ibd, const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:198
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:766
void CreatePidFile(const fs::path &path, pid_t pid)
Definition: util.cpp:988
void InterruptTorControl()
Definition: torcontrol.cpp:759
bool m_log_timestamps
Definition: logging.h:82
void OnStarted(std::function< void()> slot)
Definition: server.cpp:41
std::string GetHex() const
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1140
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:20
std::string ToString() const
Definition: feerate.cpp:40
void InitWarning(const std::string &str)
Show warning message.
CClientUIInterface uiInterface
CCoinsView backed by another CCoinsView.
Definition: coins.h:182
int GetNumCores()
Return the number of cores available on the current system.
Definition: util.cpp:1233
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:336
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:60
virtual void Stop() const =0
Stop Wallets.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:201
void PruneAndFlush()
Prune block files and flush state to disk.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: util.cpp:483
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:219
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:83
std::string AmountErrMsg(const char *const optname, const std::string &strValue)
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:9
fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
Definition: init.cpp:118
bool m_use_addrman_outgoing
Definition: net.h:143
bool RewindBlockIndex(const CChainParams &params)
When there are blocks in the active chain with missing data, rewind the chainstate and remove them fr...
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:413
CFeeRate incrementalRelayFee
Definition: policy.cpp:242
unsigned nMaxDatacarrierBytes
Maximum size of TX_NULL_DATA scripts that this node considers standard.
Definition: standard.cpp:18
BCLog::Logger *const g_logger
NOTE: the logger instances is leaked on exit.
Definition: logging.cpp:24
bool fNameLookup
Definition: netbase.cpp:33
void StartMapPort()
Definition: net.cpp:1599
bool LoadChainTip(const CChainParams &chainparams)
Update the chain tip based on database information.
uint256 hashGenesisBlock
Definition: params.h:41
void InterruptMapPort()
Definition: net.cpp:1603
size_t nCoinCacheUsage
Definition: validation.cpp:233
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:621
std::string _(const char *psz)
Translation function.
Definition: util.h:50
int nBestHeight
Definition: net.h:133
int atoi(const std::string &str)
void ShrinkDebugFile()
Definition: logging.cpp:234
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:354
CZMQNotificationInterface * g_zmq_notification_interface
CFeeRate dustRelayFee
Definition: policy.cpp:243
CBlockIndex * LookupBlockIndex(const uint256 &hash)
Definition: validation.h:431
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:86
virtual void AddWalletOptions() const =0
Get wallet help string.