Merge #11947: test: Fix rawtransactions test
[bitcoinplatinum.git] / src / init.cpp
blobe4cad01b703a6536ae6e18814466741df7480816
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
6 #if defined(HAVE_CONFIG_H)
7 #include <config/bitcoin-config.h>
8 #endif
10 #include <init.h>
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 <key.h>
23 #include <validation.h>
24 #include <miner.h>
25 #include <netbase.h>
26 #include <net.h>
27 #include <net_processing.h>
28 #include <policy/feerate.h>
29 #include <policy/fees.h>
30 #include <policy/policy.h>
31 #include <rpc/server.h>
32 #include <rpc/register.h>
33 #include <rpc/safemode.h>
34 #include <rpc/blockchain.h>
35 #include <script/standard.h>
36 #include <script/sigcache.h>
37 #include <scheduler.h>
38 #include <timedata.h>
39 #include <txdb.h>
40 #include <txmempool.h>
41 #include <torcontrol.h>
42 #include <ui_interface.h>
43 #include <util.h>
44 #include <utilmoneystr.h>
45 #include <validationinterface.h>
46 #ifdef ENABLE_WALLET
47 #include <wallet/init.h>
48 #endif
49 #include <warnings.h>
50 #include <stdint.h>
51 #include <stdio.h>
52 #include <memory>
54 #ifndef WIN32
55 #include <signal.h>
56 #endif
58 #include <boost/algorithm/string/classification.hpp>
59 #include <boost/algorithm/string/replace.hpp>
60 #include <boost/algorithm/string/split.hpp>
61 #include <boost/bind.hpp>
62 #include <boost/interprocess/sync/file_lock.hpp>
63 #include <boost/thread.hpp>
64 #include <openssl/crypto.h>
66 #if ENABLE_ZMQ
67 #include <zmq/zmqnotificationinterface.h>
68 #endif
70 bool fFeeEstimatesInitialized = false;
71 static const bool DEFAULT_PROXYRANDOMIZE = true;
72 static const bool DEFAULT_REST_ENABLE = false;
73 static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
75 std::unique_ptr<CConnman> g_connman;
76 std::unique_ptr<PeerLogicValidation> peerLogic;
78 #if ENABLE_ZMQ
79 static CZMQNotificationInterface* pzmqNotificationInterface = nullptr;
80 #endif
82 #ifdef WIN32
83 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
84 // accessing block files don't count towards the fd_set size limit
85 // anyway.
86 #define MIN_CORE_FILEDESCRIPTORS 0
87 #else
88 #define MIN_CORE_FILEDESCRIPTORS 150
89 #endif
91 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
93 //////////////////////////////////////////////////////////////////////////////
95 // Shutdown
99 // Thread management and startup/shutdown:
101 // The network-processing threads are all part of a thread group
102 // created by AppInit() or the Qt main() function.
104 // A clean exit happens when StartShutdown() or the SIGTERM
105 // signal handler sets fRequestShutdown, which makes main thread's
106 // WaitForShutdown() interrupts the thread group.
107 // And then, WaitForShutdown() makes all other on-going threads
108 // in the thread group join the main thread.
109 // Shutdown() is then called to clean up database connections, and stop other
110 // threads that should only be stopped after the main network-processing
111 // threads have exited.
113 // Shutdown for Qt is very similar, only it uses a QTimer to detect
114 // fRequestShutdown getting set, and then does the normal Qt
115 // shutdown thing.
118 std::atomic<bool> fRequestShutdown(false);
119 std::atomic<bool> fDumpMempoolLater(false);
121 void StartShutdown()
123 fRequestShutdown = true;
125 bool ShutdownRequested()
127 return fRequestShutdown;
131 * This is a minimally invasive approach to shutdown on LevelDB read errors from the
132 * chainstate, while keeping user interface out of the common library, which is shared
133 * between bitcoind, and bitcoin-qt and non-server tools.
135 class CCoinsViewErrorCatcher final : public CCoinsViewBacked
137 public:
138 explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
139 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override {
140 try {
141 return CCoinsViewBacked::GetCoin(outpoint, coin);
142 } catch(const std::runtime_error& e) {
143 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
144 LogPrintf("Error reading from database: %s\n", e.what());
145 // Starting the shutdown sequence and returning false to the caller would be
146 // interpreted as 'entry not found' (as opposed to unable to read data), and
147 // could lead to invalid interpretation. Just exit immediately, as we can't
148 // continue anyway, and all writes should be atomic.
149 abort();
152 // Writes do not need similar protection, as failure to write is handled by the caller.
155 static std::unique_ptr<CCoinsViewErrorCatcher> pcoinscatcher;
156 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
158 void Interrupt(boost::thread_group& threadGroup)
160 InterruptHTTPServer();
161 InterruptHTTPRPC();
162 InterruptRPC();
163 InterruptREST();
164 InterruptTorControl();
165 if (g_connman)
166 g_connman->Interrupt();
167 threadGroup.interrupt_all();
170 void Shutdown()
172 LogPrintf("%s: In progress...\n", __func__);
173 static CCriticalSection cs_Shutdown;
174 TRY_LOCK(cs_Shutdown, lockShutdown);
175 if (!lockShutdown)
176 return;
178 /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
179 /// for example if the data directory was found to be locked.
180 /// Be sure that anything that writes files or flushes caches only does this if the respective
181 /// module was initialized.
182 RenameThread("bitcoin-shutoff");
183 mempool.AddTransactionsUpdated(1);
185 StopHTTPRPC();
186 StopREST();
187 StopRPC();
188 StopHTTPServer();
189 #ifdef ENABLE_WALLET
190 FlushWallets();
191 #endif
192 MapPort(false);
194 // Because these depend on each-other, we make sure that neither can be
195 // using the other before destroying them.
196 if (peerLogic) UnregisterValidationInterface(peerLogic.get());
197 if (g_connman) g_connman->Stop();
198 peerLogic.reset();
199 g_connman.reset();
201 StopTorControl();
202 if (fDumpMempoolLater && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
203 DumpMempool();
206 if (fFeeEstimatesInitialized)
208 ::feeEstimator.FlushUnconfirmed(::mempool);
209 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
210 CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
211 if (!est_fileout.IsNull())
212 ::feeEstimator.Write(est_fileout);
213 else
214 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
215 fFeeEstimatesInitialized = false;
218 // FlushStateToDisk generates a SetBestChain callback, which we should avoid missing
219 if (pcoinsTip != nullptr) {
220 FlushStateToDisk();
223 // After there are no more peers/RPC left to give us new data which may generate
224 // CValidationInterface callbacks, flush them...
225 GetMainSignals().FlushBackgroundCallbacks();
227 // Any future callbacks will be dropped. This should absolutely be safe - if
228 // missing a callback results in an unrecoverable situation, unclean shutdown
229 // would too. The only reason to do the above flushes is to let the wallet catch
230 // up with our current chain to avoid any strange pruning edge cases and make
231 // next startup faster by avoiding rescan.
234 LOCK(cs_main);
235 if (pcoinsTip != nullptr) {
236 FlushStateToDisk();
238 pcoinsTip.reset();
239 pcoinscatcher.reset();
240 pcoinsdbview.reset();
241 pblocktree.reset();
243 #ifdef ENABLE_WALLET
244 StopWallets();
245 #endif
247 #if ENABLE_ZMQ
248 if (pzmqNotificationInterface) {
249 UnregisterValidationInterface(pzmqNotificationInterface);
250 delete pzmqNotificationInterface;
251 pzmqNotificationInterface = nullptr;
253 #endif
255 #ifndef WIN32
256 try {
257 fs::remove(GetPidFile());
258 } catch (const fs::filesystem_error& e) {
259 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
261 #endif
262 UnregisterAllValidationInterfaces();
263 GetMainSignals().UnregisterBackgroundSignalScheduler();
264 GetMainSignals().UnregisterWithMempoolSignals(mempool);
265 #ifdef ENABLE_WALLET
266 CloseWallets();
267 #endif
268 globalVerifyHandle.reset();
269 ECC_Stop();
270 LogPrintf("%s: done\n", __func__);
274 * Signal handlers are very limited in what they are allowed to do.
275 * The execution context the handler is invoked in is not guaranteed,
276 * so we restrict handler operations to just touching variables:
278 static void HandleSIGTERM(int)
280 fRequestShutdown = true;
283 static void HandleSIGHUP(int)
285 fReopenDebugLog = true;
288 #ifndef WIN32
289 static void registerSignalHandler(int signal, void(*handler)(int))
291 struct sigaction sa;
292 sa.sa_handler = handler;
293 sigemptyset(&sa.sa_mask);
294 sa.sa_flags = 0;
295 sigaction(signal, &sa, nullptr);
297 #endif
299 void OnRPCStarted()
301 uiInterface.NotifyBlockTip.connect(&RPCNotifyBlockChange);
304 void OnRPCStopped()
306 uiInterface.NotifyBlockTip.disconnect(&RPCNotifyBlockChange);
307 RPCNotifyBlockChange(false, nullptr);
308 cvBlockChange.notify_all();
309 LogPrint(BCLog::RPC, "RPC stopped.\n");
312 std::string HelpMessage(HelpMessageMode mode)
314 const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
315 const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
316 const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
317 const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET);
318 const bool showDebug = gArgs.GetBoolArg("-help-debug", false);
320 // When adding new options to the categories, please keep and ensure alphabetical ordering.
321 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
322 std::string strUsage = HelpMessageGroup(_("Options:"));
323 strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
324 strUsage += HelpMessageOpt("-version", _("Print version and exit"));
325 strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)"));
326 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
327 if (showDebug)
328 strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
329 strUsage +=HelpMessageOpt("-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()));
330 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
331 if (mode == HMM_BITCOIND)
333 #if HAVE_DECL_DAEMON
334 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
335 #endif
337 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
338 if (showDebug) {
339 strUsage += HelpMessageOpt("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize));
341 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
342 if (showDebug)
343 strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
344 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
345 strUsage += HelpMessageOpt("-debuglogfile=<file>", strprintf(_("Specify location of debug log file: this can be an absolute path or a path relative to the data directory (default: %s)"), DEFAULT_DEBUGLOGFILE));
346 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
347 strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
348 strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
349 if (showDebug) {
350 strUsage += HelpMessageOpt("-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()));
352 strUsage += HelpMessageOpt("-persistmempool", strprintf(_("Whether to save the mempool on shutdown and load on restart (default: %u)"), DEFAULT_PERSIST_MEMPOOL));
353 strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
354 strUsage += HelpMessageOpt("-par=<n>", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"),
355 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
356 #ifndef WIN32
357 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
358 #endif
359 strUsage += HelpMessageOpt("-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. "
360 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
361 "(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));
362 strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
363 strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
364 #ifndef WIN32
365 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
366 #endif
367 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
369 strUsage += HelpMessageGroup(_("Connection options:"));
370 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open (see the `addnode` RPC command help for more info)"));
371 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
372 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
373 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
374 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -connect=0 disables automatic connections (the rules for this peer are the same as for -addnode)"));
375 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
376 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
377 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)"));
378 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
379 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
380 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
381 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
382 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
383 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
384 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
385 strUsage += HelpMessageOpt("-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));
386 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
387 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
388 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
389 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
390 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort()));
391 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
392 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
393 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
394 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
395 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
396 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
397 #ifdef USE_UPNP
398 #if USE_UPNP
399 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
400 #else
401 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
402 #endif
403 #endif
404 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
405 strUsage += HelpMessageOpt("-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.") +
406 " " + _("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"));
407 strUsage += HelpMessageOpt("-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));
409 #ifdef ENABLE_WALLET
410 strUsage += GetWalletHelpString(showDebug);
411 #endif
413 #if ENABLE_ZMQ
414 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
415 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
416 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
417 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
418 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
419 #endif
421 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
422 strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
423 if (showDebug)
425 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
426 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
427 strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
428 strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
429 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
430 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
431 strUsage += HelpMessageOpt("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used");
432 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
433 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
434 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
435 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
436 strUsage += HelpMessageOpt("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT));
438 strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
439 strUsage += HelpMessageOpt("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT));
440 strUsage += HelpMessageOpt("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT));
441 strUsage += HelpMessageOpt("-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));
442 strUsage += HelpMessageOpt("-vbparams=deployment:start:end", "Use given start/end times for specified version bits deployment (regtest-only)");
444 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
445 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + ListLogCategories() + ".");
446 strUsage += HelpMessageOpt("-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.")));
447 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
448 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
449 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
450 if (showDebug)
452 strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
453 strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
454 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
455 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
457 strUsage += HelpMessageOpt("-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)"),
458 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
459 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
460 if (showDebug)
462 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
464 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
466 AppendParamsHelpMessages(strUsage, showDebug);
468 strUsage += HelpMessageGroup(_("Node relay options:"));
469 if (showDebug) {
470 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()));
471 strUsage += HelpMessageOpt("-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)));
472 strUsage += HelpMessageOpt("-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)));
474 strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
475 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
476 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
477 strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
478 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
479 CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
480 strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
481 strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
483 strUsage += HelpMessageGroup(_("Block creation options:"));
484 strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
485 strUsage += HelpMessageOpt("-blockmaxsize=<n>", _("Set maximum BIP141 block weight to this * 4. Deprecated, use blockmaxweight"));
486 strUsage += HelpMessageOpt("-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)));
487 if (showDebug)
488 strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
490 strUsage += HelpMessageGroup(_("RPC server options:"));
491 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
492 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
493 strUsage += HelpMessageOpt("-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)"));
494 strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
495 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
496 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
497 strUsage += HelpMessageOpt("-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/rpcuser. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times"));
498 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
499 strUsage += HelpMessageOpt("-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"));
500 strUsage += HelpMessageOpt("-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));
501 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
502 if (showDebug) {
503 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
504 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
507 return strUsage;
510 std::string LicenseInfo()
512 const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
513 const std::string URL_WEBSITE = "<https://bitcoincore.org>";
515 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
516 "\n" +
517 strprintf(_("Please contribute if you find %s useful. "
518 "Visit %s for further information about the software."),
519 PACKAGE_NAME, URL_WEBSITE) +
520 "\n" +
521 strprintf(_("The source code is available from %s."),
522 URL_SOURCE_CODE) +
523 "\n" +
524 "\n" +
525 _("This is experimental software.") + "\n" +
526 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
527 "\n" +
528 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>") +
529 "\n";
532 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
534 if (initialSync || !pBlockIndex)
535 return;
537 std::string strCmd = gArgs.GetArg("-blocknotify", "");
538 if (!strCmd.empty()) {
539 boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
540 boost::thread t(runCommand, strCmd); // thread runs free
544 static bool fHaveGenesis = false;
545 static CWaitableCriticalSection cs_GenesisWait;
546 static CConditionVariable condvar_GenesisWait;
548 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
550 if (pBlockIndex != nullptr) {
552 WaitableLock lock_GenesisWait(cs_GenesisWait);
553 fHaveGenesis = true;
555 condvar_GenesisWait.notify_all();
559 struct CImportingNow
561 CImportingNow() {
562 assert(fImporting == false);
563 fImporting = true;
566 ~CImportingNow() {
567 assert(fImporting == true);
568 fImporting = false;
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 void CleanupBlockRevFiles()
581 std::map<std::string, fs::path> mapBlockFiles;
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 = GetDataDir() / "blocks";
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")
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());
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<std::string, fs::path>& item : mapBlockFiles) {
606 if (atoi(item.first) == nContigCounter) {
607 nContigCounter++;
608 continue;
610 remove(item.second);
614 void ThreadImport(std::vector<fs::path> vImportFiles)
616 const CChainParams& chainparams = Params();
617 RenameThread("bitcoin-loadblk");
620 CImportingNow imp;
622 // -reindex
623 if (fReindex) {
624 int nFile = 0;
625 while (true) {
626 CDiskBlockPos pos(nFile, 0);
627 if (!fs::exists(GetBlockPosFilename(pos, "blk")))
628 break; // No block files left to reindex
629 FILE *file = OpenBlockFile(pos, true);
630 if (!file)
631 break; // This error is logged in OpenBlockFile
632 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
633 LoadExternalBlockFile(chainparams, file, &pos);
634 nFile++;
636 pblocktree->WriteReindexing(false);
637 fReindex = false;
638 LogPrintf("Reindexing finished\n");
639 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
640 LoadGenesisBlock(chainparams);
643 // hardcoded $DATADIR/bootstrap.dat
644 fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
645 if (fs::exists(pathBootstrap)) {
646 FILE *file = fsbridge::fopen(pathBootstrap, "rb");
647 if (file) {
648 fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
649 LogPrintf("Importing bootstrap.dat...\n");
650 LoadExternalBlockFile(chainparams, file);
651 RenameOver(pathBootstrap, pathBootstrapOld);
652 } else {
653 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
657 // -loadblock=
658 for (const fs::path& path : vImportFiles) {
659 FILE *file = fsbridge::fopen(path, "rb");
660 if (file) {
661 LogPrintf("Importing blocks file %s...\n", path.string());
662 LoadExternalBlockFile(chainparams, file);
663 } else {
664 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
668 // scan for better chains in the block chain database, that are not yet connected in the active best chain
669 CValidationState state;
670 if (!ActivateBestChain(state, chainparams)) {
671 LogPrintf("Failed to connect best block");
672 StartShutdown();
675 if (gArgs.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
676 LogPrintf("Stopping after block import\n");
677 StartShutdown();
679 } // End scope of CImportingNow
680 if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
681 LoadMempool();
682 fDumpMempoolLater = !fRequestShutdown;
686 /** Sanity checks
687 * Ensure that Bitcoin is running in a usable environment with all
688 * necessary library support.
690 bool InitSanityCheck(void)
692 if(!ECC_InitSanityCheck()) {
693 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
694 return false;
697 if (!glibc_sanity_test() || !glibcxx_sanity_test())
698 return false;
700 if (!Random_SanityCheck()) {
701 InitError("OS cryptographic RNG sanity check failure. Aborting.");
702 return false;
705 return true;
708 bool AppInitServers(boost::thread_group& threadGroup)
710 RPCServer::OnStarted(&OnRPCStarted);
711 RPCServer::OnStopped(&OnRPCStopped);
712 if (!InitHTTPServer())
713 return false;
714 if (!StartRPC())
715 return false;
716 if (!StartHTTPRPC())
717 return false;
718 if (gArgs.GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
719 return false;
720 if (!StartHTTPServer())
721 return false;
722 return true;
725 // Parameter interaction based on rules
726 void InitParameterInteraction()
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__);
734 if (gArgs.IsArgSet("-whitebind")) {
735 if (gArgs.SoftSetBoolArg("-listen", true))
736 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
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__);
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__);
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__);
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__);
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__);
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__);
788 if (gArgs.IsArgSet("-blockmaxsize")) {
789 unsigned int max_size = gArgs.GetArg("-blockmaxsize", 0);
790 if (gArgs.SoftSetArg("blockmaxweight", strprintf("%d", max_size * WITNESS_SCALE_FACTOR))) {
791 LogPrintf("%s: parameter interaction: -blockmaxsize=%d -> setting -blockmaxweight=%d (-blockmaxsize is deprecated!)\n", __func__, max_size, max_size * WITNESS_SCALE_FACTOR);
792 } else {
793 LogPrintf("%s: Ignoring blockmaxsize setting which is overridden by blockmaxweight", __func__);
798 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
800 return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
803 void InitLogging()
805 fPrintToConsole = gArgs.GetBoolArg("-printtoconsole", false);
806 fLogTimestamps = gArgs.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
807 fLogTimeMicros = gArgs.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
808 fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS);
810 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
811 LogPrintf("Bitcoin version %s\n", FormatFullVersion());
814 namespace { // Variables internal to initialization process only
816 int nMaxConnections;
817 int nUserMaxConnections;
818 int nFD;
819 ServiceFlags nLocalServices = ServiceFlags(NODE_NETWORK | NODE_NETWORK_LIMITED);
821 } // namespace
823 [[noreturn]] static void new_handler_terminate()
825 // Rather than throwing std::bad-alloc if allocation fails, terminate
826 // immediately to (try to) avoid chain corruption.
827 // Since LogPrintf may itself allocate memory, set the handler directly
828 // to terminate first.
829 std::set_new_handler(std::terminate);
830 LogPrintf("Error: Out of memory. Terminating.\n");
832 // The log was successful, terminate now.
833 std::terminate();
836 bool AppInitBasicSetup()
838 // ********************************************************* Step 1: setup
839 #ifdef _MSC_VER
840 // Turn off Microsoft heap dump noise
841 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
842 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
843 // Disable confusing "helpful" text message on abort, Ctrl-C
844 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
845 #endif
846 #ifdef WIN32
847 // Enable Data Execution Prevention (DEP)
848 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
849 // A failure is non-critical and needs no further attention!
850 #ifndef PROCESS_DEP_ENABLE
851 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
852 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
853 #define PROCESS_DEP_ENABLE 0x00000001
854 #endif
855 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
856 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
857 if (setProcDEPPol != nullptr) setProcDEPPol(PROCESS_DEP_ENABLE);
858 #endif
860 if (!SetupNetworking())
861 return InitError("Initializing networking failed");
863 #ifndef WIN32
864 if (!gArgs.GetBoolArg("-sysperms", false)) {
865 umask(077);
868 // Clean shutdown on SIGTERM
869 registerSignalHandler(SIGTERM, HandleSIGTERM);
870 registerSignalHandler(SIGINT, HandleSIGTERM);
872 // Reopen debug.log on SIGHUP
873 registerSignalHandler(SIGHUP, HandleSIGHUP);
875 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
876 signal(SIGPIPE, SIG_IGN);
877 #endif
879 std::set_new_handler(new_handler_terminate);
881 return true;
884 bool AppInitParameterInteraction()
886 const CChainParams& chainparams = Params();
887 // ********************************************************* Step 2: parameter interactions
889 // also see: InitParameterInteraction()
891 // if using block pruning, then disallow txindex
892 if (gArgs.GetArg("-prune", 0)) {
893 if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX))
894 return InitError(_("Prune mode is incompatible with -txindex."));
897 // -bind and -whitebind can't be set when not listening
898 size_t nUserBind = gArgs.GetArgs("-bind").size() + gArgs.GetArgs("-whitebind").size();
899 if (nUserBind != 0 && !gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
900 return InitError("Cannot set -bind or -whitebind together with -listen=0");
903 // Make sure enough file descriptors are available
904 int nBind = std::max(nUserBind, size_t(1));
905 nUserMaxConnections = gArgs.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
906 nMaxConnections = std::max(nUserMaxConnections, 0);
908 // Trim requested connection counts, to fit into system limitations
909 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
910 nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
911 if (nFD < MIN_CORE_FILEDESCRIPTORS)
912 return InitError(_("Not enough file descriptors available."));
913 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
915 if (nMaxConnections < nUserMaxConnections)
916 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
918 // ********************************************************* Step 3: parameter-to-internal-flags
919 if (gArgs.IsArgSet("-debug")) {
920 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
921 const std::vector<std::string> categories = gArgs.GetArgs("-debug");
923 if (std::none_of(categories.begin(), categories.end(),
924 [](std::string cat){return cat == "0" || cat == "none";})) {
925 for (const auto& cat : categories) {
926 uint32_t flag = 0;
927 if (!GetLogCategory(&flag, &cat)) {
928 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
929 continue;
931 logCategories |= flag;
936 // Now remove the logging categories which were explicitly excluded
937 for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
938 uint32_t flag = 0;
939 if (!GetLogCategory(&flag, &cat)) {
940 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
941 continue;
943 logCategories &= ~flag;
946 // Check for -debugnet
947 if (gArgs.GetBoolArg("-debugnet", false))
948 InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
949 // Check for -socks - as this is a privacy risk to continue, exit here
950 if (gArgs.IsArgSet("-socks"))
951 return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
952 // Check for -tor - as this is a privacy risk to continue, exit here
953 if (gArgs.GetBoolArg("-tor", false))
954 return InitError(_("Unsupported argument -tor found, use -onion."));
956 if (gArgs.GetBoolArg("-benchmark", false))
957 InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
959 if (gArgs.GetBoolArg("-whitelistalwaysrelay", false))
960 InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
962 if (gArgs.IsArgSet("-blockminsize"))
963 InitWarning("Unsupported argument -blockminsize ignored.");
965 // Checkmempool and checkblockindex default to true in regtest mode
966 int ratio = std::min<int>(std::max<int>(gArgs.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
967 if (ratio != 0) {
968 mempool.setSanityCheck(1.0 / ratio);
970 fCheckBlockIndex = gArgs.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
971 fCheckpointsEnabled = gArgs.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
973 hashAssumeValid = uint256S(gArgs.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
974 if (!hashAssumeValid.IsNull())
975 LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
976 else
977 LogPrintf("Validating signatures for all blocks.\n");
979 if (gArgs.IsArgSet("-minimumchainwork")) {
980 const std::string minChainWorkStr = gArgs.GetArg("-minimumchainwork", "");
981 if (!IsHexNumber(minChainWorkStr)) {
982 return InitError(strprintf("Invalid non-hex (%s) minimum chain work value specified", minChainWorkStr));
984 nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
985 } else {
986 nMinimumChainWork = UintToArith256(chainparams.GetConsensus().nMinimumChainWork);
988 LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
989 if (nMinimumChainWork < UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
990 LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex());
993 // mempool limits
994 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
995 int64_t nMempoolSizeMin = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
996 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
997 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
998 // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
999 // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
1000 if (gArgs.IsArgSet("-incrementalrelayfee"))
1002 CAmount n = 0;
1003 if (!ParseMoney(gArgs.GetArg("-incrementalrelayfee", ""), n))
1004 return InitError(AmountErrMsg("incrementalrelayfee", gArgs.GetArg("-incrementalrelayfee", "")));
1005 incrementalRelayFee = CFeeRate(n);
1008 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
1009 nScriptCheckThreads = gArgs.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
1010 if (nScriptCheckThreads <= 0)
1011 nScriptCheckThreads += GetNumCores();
1012 if (nScriptCheckThreads <= 1)
1013 nScriptCheckThreads = 0;
1014 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
1015 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
1017 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
1018 int64_t nPruneArg = gArgs.GetArg("-prune", 0);
1019 if (nPruneArg < 0) {
1020 return InitError(_("Prune cannot be configured with a negative value."));
1022 nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
1023 if (nPruneArg == 1) { // manual pruning: -prune=1
1024 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1025 nPruneTarget = std::numeric_limits<uint64_t>::max();
1026 fPruneMode = true;
1027 } else if (nPruneTarget) {
1028 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
1029 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1031 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1032 fPruneMode = true;
1035 nConnectTimeout = gArgs.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1036 if (nConnectTimeout <= 0)
1037 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1039 if (gArgs.IsArgSet("-minrelaytxfee")) {
1040 CAmount n = 0;
1041 if (!ParseMoney(gArgs.GetArg("-minrelaytxfee", ""), n)) {
1042 return InitError(AmountErrMsg("minrelaytxfee", gArgs.GetArg("-minrelaytxfee", "")));
1044 // High fee check is done afterward in WalletParameterInteraction()
1045 ::minRelayTxFee = CFeeRate(n);
1046 } else if (incrementalRelayFee > ::minRelayTxFee) {
1047 // Allow only setting incrementalRelayFee to control both
1048 ::minRelayTxFee = incrementalRelayFee;
1049 LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1052 // Sanity check argument for min fee for including tx in block
1053 // TODO: Harmonize which arguments need sanity checking and where that happens
1054 if (gArgs.IsArgSet("-blockmintxfee"))
1056 CAmount n = 0;
1057 if (!ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n))
1058 return InitError(AmountErrMsg("blockmintxfee", gArgs.GetArg("-blockmintxfee", "")));
1061 // Feerate used to define dust. Shouldn't be changed lightly as old
1062 // implementations may inadvertently create non-standard transactions
1063 if (gArgs.IsArgSet("-dustrelayfee"))
1065 CAmount n = 0;
1066 if (!ParseMoney(gArgs.GetArg("-dustrelayfee", ""), n) || 0 == n)
1067 return InitError(AmountErrMsg("dustrelayfee", gArgs.GetArg("-dustrelayfee", "")));
1068 dustRelayFee = CFeeRate(n);
1071 fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1072 if (chainparams.RequireStandard() && !fRequireStandard)
1073 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1074 nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp);
1076 #ifdef ENABLE_WALLET
1077 if (!WalletParameterInteraction())
1078 return false;
1079 #endif
1081 fIsBareMultisigStd = gArgs.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1082 fAcceptDatacarrier = gArgs.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1083 nMaxDatacarrierBytes = gArgs.GetArg("-datacarriersize", nMaxDatacarrierBytes);
1085 // Option to startup with mocktime set (used for regression testing):
1086 SetMockTime(gArgs.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1088 if (gArgs.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1089 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1091 if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1092 return InitError("rpcserialversion must be non-negative.");
1094 if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1095 return InitError("unknown rpcserialversion requested.");
1097 nMaxTipAge = gArgs.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1099 fEnableReplacement = gArgs.GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1100 if ((!fEnableReplacement) && gArgs.IsArgSet("-mempoolreplacement")) {
1101 // Minimal effort at forwards compatibility
1102 std::string strReplacementModeList = gArgs.GetArg("-mempoolreplacement", ""); // default is impossible
1103 std::vector<std::string> vstrReplacementModes;
1104 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1105 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1108 if (gArgs.IsArgSet("-vbparams")) {
1109 // Allow overriding version bits parameters for testing
1110 if (!chainparams.MineBlocksOnDemand()) {
1111 return InitError("Version bits parameters may only be overridden on regtest.");
1113 for (const std::string& strDeployment : gArgs.GetArgs("-vbparams")) {
1114 std::vector<std::string> vDeploymentParams;
1115 boost::split(vDeploymentParams, strDeployment, boost::is_any_of(":"));
1116 if (vDeploymentParams.size() != 3) {
1117 return InitError("Version bits parameters malformed, expecting deployment:start:end");
1119 int64_t nStartTime, nTimeout;
1120 if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1121 return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1123 if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1124 return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1126 bool found = false;
1127 for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1129 if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1130 UpdateVersionBitsParameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1131 found = true;
1132 LogPrintf("Setting version bits activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1133 break;
1136 if (!found) {
1137 return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1141 return true;
1144 static bool LockDataDirectory(bool probeOnly)
1146 std::string strDataDir = GetDataDir().string();
1148 // Make sure only a single Bitcoin process is using the data directory.
1149 fs::path pathLockFile = GetDataDir() / ".lock";
1150 FILE* file = fsbridge::fopen(pathLockFile, "a"); // empty lock file; created if it doesn't exist.
1151 if (file) fclose(file);
1153 try {
1154 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1155 if (!lock.try_lock()) {
1156 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1158 if (probeOnly) {
1159 lock.unlock();
1161 } catch(const boost::interprocess::interprocess_exception& e) {
1162 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1164 return true;
1167 bool AppInitSanityChecks()
1169 // ********************************************************* Step 4: sanity checks
1171 // Initialize elliptic curve code
1172 std::string sha256_algo = SHA256AutoDetect();
1173 LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
1174 RandomInit();
1175 ECC_Start();
1176 globalVerifyHandle.reset(new ECCVerifyHandle());
1178 // Sanity check
1179 if (!InitSanityCheck())
1180 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1182 // Probe the data directory lock to give an early error message, if possible
1183 // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened,
1184 // and a fork will cause weird behavior to it.
1185 return LockDataDirectory(true);
1188 bool AppInitLockDataDirectory()
1190 // After daemonization get the data directory lock again and hold on to it until exit
1191 // This creates a slight window for a race condition to happen, however this condition is harmless: it
1192 // will at most make us exit without printing a message to console.
1193 if (!LockDataDirectory(false)) {
1194 // Detailed error printed inside LockDataDirectory
1195 return false;
1197 return true;
1200 bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
1202 const CChainParams& chainparams = Params();
1203 // ********************************************************* Step 4a: application initialization
1204 #ifndef WIN32
1205 CreatePidFile(GetPidFile(), getpid());
1206 #endif
1207 if (gArgs.GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
1208 // Do this first since it both loads a bunch of debug.log into memory,
1209 // and because this needs to happen before any other debug.log printing
1210 ShrinkDebugFile();
1213 if (fPrintToDebugLog) {
1214 if (!OpenDebugLog()) {
1215 return InitError(strprintf("Could not open debug log file %s", GetDebugLogPath().string()));
1219 if (!fLogTimestamps)
1220 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1221 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1222 LogPrintf("Using data directory %s\n", GetDataDir().string());
1223 LogPrintf("Using config file %s\n", GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1224 LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1226 InitSignatureCache();
1227 InitScriptExecutionCache();
1229 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1230 if (nScriptCheckThreads) {
1231 for (int i=0; i<nScriptCheckThreads-1; i++)
1232 threadGroup.create_thread(&ThreadScriptCheck);
1235 // Start the lightweight task scheduler thread
1236 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1237 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1239 GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);
1240 GetMainSignals().RegisterWithMempoolSignals(mempool);
1242 /* Register RPC commands regardless of -server setting so they will be
1243 * available in the GUI RPC console even if external calls are disabled.
1245 RegisterAllCoreRPCCommands(tableRPC);
1246 #ifdef ENABLE_WALLET
1247 RegisterWalletRPC(tableRPC);
1248 #endif
1250 /* Start the RPC server already. It will be started in "warmup" mode
1251 * and not really process calls already (but it will signify connections
1252 * that the server is there and will be ready later). Warmup mode will
1253 * be disabled when initialisation is finished.
1255 if (gArgs.GetBoolArg("-server", false))
1257 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1258 if (!AppInitServers(threadGroup))
1259 return InitError(_("Unable to start HTTP server. See debug log for details."));
1262 int64_t nStart;
1264 // ********************************************************* Step 5: verify wallet database integrity
1265 #ifdef ENABLE_WALLET
1266 if (!VerifyWallets())
1267 return false;
1268 #endif
1269 // ********************************************************* Step 6: network initialization
1270 // Note that we absolutely cannot open any actual connections
1271 // until the very end ("start node") as the UTXO/block state
1272 // is not yet setup and may end up being set up twice if we
1273 // need to reindex later.
1275 assert(!g_connman);
1276 g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1277 CConnman& connman = *g_connman;
1279 peerLogic.reset(new PeerLogicValidation(&connman, scheduler));
1280 RegisterValidationInterface(peerLogic.get());
1282 // sanitize comments per BIP-0014, format user agent and check total size
1283 std::vector<std::string> uacomments;
1284 for (const std::string& cmt : gArgs.GetArgs("-uacomment")) {
1285 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1286 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1287 uacomments.push_back(cmt);
1289 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1290 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1291 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1292 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1295 if (gArgs.IsArgSet("-onlynet")) {
1296 std::set<enum Network> nets;
1297 for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
1298 enum Network net = ParseNetwork(snet);
1299 if (net == NET_UNROUTABLE)
1300 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1301 nets.insert(net);
1303 for (int n = 0; n < NET_MAX; n++) {
1304 enum Network net = (enum Network)n;
1305 if (!nets.count(net))
1306 SetLimited(net);
1310 // Check for host lookup allowed before parsing any network related parameters
1311 fNameLookup = gArgs.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1313 bool proxyRandomize = gArgs.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1314 // -proxy sets a proxy for all outgoing network traffic
1315 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1316 std::string proxyArg = gArgs.GetArg("-proxy", "");
1317 SetLimited(NET_TOR);
1318 if (proxyArg != "" && proxyArg != "0") {
1319 CService proxyAddr;
1320 if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1321 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1324 proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1325 if (!addrProxy.IsValid())
1326 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1328 SetProxy(NET_IPV4, addrProxy);
1329 SetProxy(NET_IPV6, addrProxy);
1330 SetProxy(NET_TOR, addrProxy);
1331 SetNameProxy(addrProxy);
1332 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1335 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1336 // -noonion (or -onion=0) disables connecting to .onion entirely
1337 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1338 std::string onionArg = gArgs.GetArg("-onion", "");
1339 if (onionArg != "") {
1340 if (onionArg == "0") { // Handle -noonion/-onion=0
1341 SetLimited(NET_TOR); // set onions as unreachable
1342 } else {
1343 CService onionProxy;
1344 if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1345 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1347 proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1348 if (!addrOnion.IsValid())
1349 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1350 SetProxy(NET_TOR, addrOnion);
1351 SetLimited(NET_TOR, false);
1355 // see Step 2: parameter interactions for more information about these
1356 fListen = gArgs.GetBoolArg("-listen", DEFAULT_LISTEN);
1357 fDiscover = gArgs.GetBoolArg("-discover", true);
1358 fRelayTxes = !gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1360 for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
1361 CService addrLocal;
1362 if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1363 AddLocal(addrLocal, LOCAL_MANUAL);
1364 else
1365 return InitError(ResolveErrMsg("externalip", strAddr));
1368 #if ENABLE_ZMQ
1369 pzmqNotificationInterface = CZMQNotificationInterface::Create();
1371 if (pzmqNotificationInterface) {
1372 RegisterValidationInterface(pzmqNotificationInterface);
1374 #endif
1375 uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1376 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1378 if (gArgs.IsArgSet("-maxuploadtarget")) {
1379 nMaxOutboundLimit = gArgs.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1382 // ********************************************************* Step 7: load block chain
1384 fReindex = gArgs.GetBoolArg("-reindex", false);
1385 bool fReindexChainState = gArgs.GetBoolArg("-reindex-chainstate", false);
1387 // cache size calculations
1388 int64_t nTotalCache = (gArgs.GetArg("-dbcache", nDefaultDbCache) << 20);
1389 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1390 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1391 int64_t nBlockTreeDBCache = nTotalCache / 8;
1392 nBlockTreeDBCache = std::min(nBlockTreeDBCache, (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1393 nTotalCache -= nBlockTreeDBCache;
1394 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1395 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1396 nTotalCache -= nCoinDBCache;
1397 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1398 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1399 LogPrintf("Cache configuration:\n");
1400 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1401 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1402 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));
1404 bool fLoaded = false;
1405 while (!fLoaded && !fRequestShutdown) {
1406 bool fReset = fReindex;
1407 std::string strLoadError;
1409 uiInterface.InitMessage(_("Loading block index..."));
1411 nStart = GetTimeMillis();
1412 do {
1413 try {
1414 UnloadBlockIndex();
1415 pcoinsTip.reset();
1416 pcoinsdbview.reset();
1417 pcoinscatcher.reset();
1418 pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
1420 if (fReset) {
1421 pblocktree->WriteReindexing(true);
1422 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1423 if (fPruneMode)
1424 CleanupBlockRevFiles();
1427 if (fRequestShutdown) break;
1429 // LoadBlockIndex will load fTxIndex from the db, or set it if
1430 // we're reindexing. It will also load fHavePruned if we've
1431 // ever removed a block file from disk.
1432 // Note that it also sets fReindex based on the disk flag!
1433 // From here on out fReindex and fReset mean something different!
1434 if (!LoadBlockIndex(chainparams)) {
1435 strLoadError = _("Error loading block database");
1436 break;
1439 // If the loaded chain has a wrong genesis, bail out immediately
1440 // (we're likely using a testnet datadir, or the other way around).
1441 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1442 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1444 // Check for changed -txindex state
1445 if (fTxIndex != gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1446 strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1447 break;
1450 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1451 // in the past, but is now trying to run unpruned.
1452 if (fHavePruned && !fPruneMode) {
1453 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1454 break;
1457 // At this point blocktree args are consistent with what's on disk.
1458 // If we're not mid-reindex (based on disk + args), add a genesis block on disk
1459 // (otherwise we use the one already on disk).
1460 // This is called again in ThreadImport after the reindex completes.
1461 if (!fReindex && !LoadGenesisBlock(chainparams)) {
1462 strLoadError = _("Error initializing block database");
1463 break;
1466 // At this point we're either in reindex or we've loaded a useful
1467 // block tree into mapBlockIndex!
1469 pcoinsdbview.reset(new CCoinsViewDB(nCoinDBCache, false, fReset || fReindexChainState));
1470 pcoinscatcher.reset(new CCoinsViewErrorCatcher(pcoinsdbview.get()));
1472 // If necessary, upgrade from older database format.
1473 // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1474 if (!pcoinsdbview->Upgrade()) {
1475 strLoadError = _("Error upgrading chainstate database");
1476 break;
1479 // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1480 if (!ReplayBlocks(chainparams, pcoinsdbview.get())) {
1481 strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1482 break;
1485 // The on-disk coinsdb is now in a good state, create the cache
1486 pcoinsTip.reset(new CCoinsViewCache(pcoinscatcher.get()));
1488 bool is_coinsview_empty = fReset || fReindexChainState || pcoinsTip->GetBestBlock().IsNull();
1489 if (!is_coinsview_empty) {
1490 // LoadChainTip sets chainActive based on pcoinsTip's best block
1491 if (!LoadChainTip(chainparams)) {
1492 strLoadError = _("Error initializing block database");
1493 break;
1495 assert(chainActive.Tip() != nullptr);
1498 if (!fReset) {
1499 // Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate.
1500 // It both disconnects blocks based on chainActive, and drops block data in
1501 // mapBlockIndex based on lack of available witness data.
1502 uiInterface.InitMessage(_("Rewinding blocks..."));
1503 if (!RewindBlockIndex(chainparams)) {
1504 strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1505 break;
1509 if (!is_coinsview_empty) {
1510 uiInterface.InitMessage(_("Verifying blocks..."));
1511 if (fHavePruned && gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1512 LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
1513 MIN_BLOCKS_TO_KEEP);
1517 LOCK(cs_main);
1518 CBlockIndex* tip = chainActive.Tip();
1519 RPCNotifyBlockChange(true, tip);
1520 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1521 strLoadError = _("The block database contains a block which appears to be from the future. "
1522 "This may be due to your computer's date and time being set incorrectly. "
1523 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1524 break;
1528 if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview.get(), gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1529 gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1530 strLoadError = _("Corrupted block database detected");
1531 break;
1534 } catch (const std::exception& e) {
1535 LogPrintf("%s\n", e.what());
1536 strLoadError = _("Error opening block database");
1537 break;
1540 fLoaded = true;
1541 } while(false);
1543 if (!fLoaded && !fRequestShutdown) {
1544 // first suggest a reindex
1545 if (!fReset) {
1546 bool fRet = uiInterface.ThreadSafeQuestion(
1547 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1548 strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1549 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1550 if (fRet) {
1551 fReindex = true;
1552 fRequestShutdown = false;
1553 } else {
1554 LogPrintf("Aborted block database rebuild. Exiting.\n");
1555 return false;
1557 } else {
1558 return InitError(strLoadError);
1563 // As LoadBlockIndex can take several minutes, it's possible the user
1564 // requested to kill the GUI during the last operation. If so, exit.
1565 // As the program has not fully started yet, Shutdown() is possibly overkill.
1566 if (fRequestShutdown)
1568 LogPrintf("Shutdown requested. Exiting.\n");
1569 return false;
1571 if (fLoaded) {
1572 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1575 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1576 CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
1577 // Allowed to fail as this file IS missing on first startup.
1578 if (!est_filein.IsNull())
1579 ::feeEstimator.Read(est_filein);
1580 fFeeEstimatesInitialized = true;
1582 // ********************************************************* Step 8: load wallet
1583 #ifdef ENABLE_WALLET
1584 if (!OpenWallets())
1585 return false;
1586 #else
1587 LogPrintf("No wallet support compiled in!\n");
1588 #endif
1590 // ********************************************************* Step 9: data directory maintenance
1592 // if pruning, unset the service bit and perform the initial blockstore prune
1593 // after any wallet rescanning has taken place.
1594 if (fPruneMode) {
1595 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1596 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1597 if (!fReindex) {
1598 uiInterface.InitMessage(_("Pruning blockstore..."));
1599 PruneAndFlush();
1603 if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
1604 // Only advertise witness capabilities if they have a reasonable start time.
1605 // This allows us to have the code merged without a defined softfork, by setting its
1606 // end time to 0.
1607 // Note that setting NODE_WITNESS is never required: the only downside from not
1608 // doing so is that after activation, no upgraded nodes will fetch from you.
1609 nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1612 // ********************************************************* Step 10: import blocks
1614 if (!CheckDiskSpace())
1615 return false;
1617 // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1618 // No locking, as this happens before any background thread is started.
1619 if (chainActive.Tip() == nullptr) {
1620 uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1621 } else {
1622 fHaveGenesis = true;
1625 if (gArgs.IsArgSet("-blocknotify"))
1626 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1628 std::vector<fs::path> vImportFiles;
1629 for (const std::string& strFile : gArgs.GetArgs("-loadblock")) {
1630 vImportFiles.push_back(strFile);
1633 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1635 // Wait for genesis block to be processed
1637 WaitableLock lock(cs_GenesisWait);
1638 while (!fHaveGenesis) {
1639 condvar_GenesisWait.wait(lock);
1641 uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1644 // ********************************************************* Step 11: start node
1646 int chain_active_height;
1648 //// debug print
1650 LOCK(cs_main);
1651 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1652 chain_active_height = chainActive.Height();
1654 LogPrintf("nBestHeight = %d\n", chain_active_height);
1656 if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1657 StartTorControl(threadGroup, scheduler);
1659 Discover(threadGroup);
1661 // Map ports with UPnP
1662 MapPort(gArgs.GetBoolArg("-upnp", DEFAULT_UPNP));
1664 CConnman::Options connOptions;
1665 connOptions.nLocalServices = nLocalServices;
1666 connOptions.nMaxConnections = nMaxConnections;
1667 connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1668 connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1669 connOptions.nMaxFeeler = 1;
1670 connOptions.nBestHeight = chain_active_height;
1671 connOptions.uiInterface = &uiInterface;
1672 connOptions.m_msgproc = peerLogic.get();
1673 connOptions.nSendBufferMaxSize = 1000*gArgs.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1674 connOptions.nReceiveFloodSize = 1000*gArgs.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1675 connOptions.m_added_nodes = gArgs.GetArgs("-addnode");
1677 connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1678 connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1680 for (const std::string& strBind : gArgs.GetArgs("-bind")) {
1681 CService addrBind;
1682 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) {
1683 return InitError(ResolveErrMsg("bind", strBind));
1685 connOptions.vBinds.push_back(addrBind);
1687 for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
1688 CService addrBind;
1689 if (!Lookup(strBind.c_str(), addrBind, 0, false)) {
1690 return InitError(ResolveErrMsg("whitebind", strBind));
1692 if (addrBind.GetPort() == 0) {
1693 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1695 connOptions.vWhiteBinds.push_back(addrBind);
1698 for (const auto& net : gArgs.GetArgs("-whitelist")) {
1699 CSubNet subnet;
1700 LookupSubNet(net.c_str(), subnet);
1701 if (!subnet.IsValid())
1702 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1703 connOptions.vWhitelistedRange.push_back(subnet);
1706 connOptions.vSeedNodes = gArgs.GetArgs("-seednode");
1708 // Initiate outbound connections unless connect=0
1709 connOptions.m_use_addrman_outgoing = !gArgs.IsArgSet("-connect");
1710 if (!connOptions.m_use_addrman_outgoing) {
1711 const auto connect = gArgs.GetArgs("-connect");
1712 if (connect.size() != 1 || connect[0] != "0") {
1713 connOptions.m_specified_outgoing = connect;
1716 if (!connman.Start(scheduler, connOptions)) {
1717 return false;
1720 // ********************************************************* Step 12: finished
1722 SetRPCWarmupFinished();
1723 uiInterface.InitMessage(_("Done loading"));
1725 #ifdef ENABLE_WALLET
1726 StartWallets(scheduler);
1727 #endif
1729 return true;