Report [CANCELLED] instead of [DONE] when shut down during txdb upgrade
[bitcoinplatinum.git] / src / init.cpp
blobec1f18faef88db48c5271672bb82a915072f2853
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/blockchain.h"
34 #include "script/standard.h"
35 #include "script/sigcache.h"
36 #include "scheduler.h"
37 #include "timedata.h"
38 #include "txdb.h"
39 #include "txmempool.h"
40 #include "torcontrol.h"
41 #include "ui_interface.h"
42 #include "util.h"
43 #include "utilmoneystr.h"
44 #include "validationinterface.h"
45 #ifdef ENABLE_WALLET
46 #include "wallet/wallet.h"
47 #endif
48 #include "warnings.h"
49 #include <stdint.h>
50 #include <stdio.h>
51 #include <memory>
53 #ifndef WIN32
54 #include <signal.h>
55 #endif
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/interprocess/sync/file_lock.hpp>
62 #include <boost/thread.hpp>
63 #include <openssl/crypto.h>
65 #if ENABLE_ZMQ
66 #include "zmq/zmqnotificationinterface.h"
67 #endif
69 bool fFeeEstimatesInitialized = false;
70 static const bool DEFAULT_PROXYRANDOMIZE = true;
71 static const bool DEFAULT_REST_ENABLE = false;
72 static const bool DEFAULT_DISABLE_SAFEMODE = 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 = NULL;
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 triggers
106 // the DetectShutdownThread(), which interrupts the main thread group.
107 // DetectShutdownThread() then exits, which causes AppInit() to
108 // continue (it .joins the shutdown thread).
109 // Shutdown() is then
110 // called to clean up database connections, and stop other
111 // threads that should only be stopped after the main network-processing
112 // threads have exited.
114 // Shutdown for Qt is very similar, only it uses a QTimer to detect
115 // fRequestShutdown getting set, and then does the normal Qt
116 // shutdown thing.
119 std::atomic<bool> fRequestShutdown(false);
120 std::atomic<bool> fDumpMempoolLater(false);
122 void StartShutdown()
124 fRequestShutdown = true;
126 bool ShutdownRequested()
128 return fRequestShutdown;
132 * This is a minimally invasive approach to shutdown on LevelDB read errors from the
133 * chainstate, while keeping user interface out of the common library, which is shared
134 * between bitcoind, and bitcoin-qt and non-server tools.
136 class CCoinsViewErrorCatcher : public CCoinsViewBacked
138 public:
139 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
140 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override {
141 try {
142 return CCoinsViewBacked::GetCoin(outpoint, coin);
143 } catch(const std::runtime_error& e) {
144 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
145 LogPrintf("Error reading from database: %s\n", e.what());
146 // Starting the shutdown sequence and returning false to the caller would be
147 // interpreted as 'entry not found' (as opposed to unable to read data), and
148 // could lead to invalid interpretation. Just exit immediately, as we can't
149 // continue anyway, and all writes should be atomic.
150 abort();
153 // Writes do not need similar protection, as failure to write is handled by the caller.
156 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
157 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
159 void Interrupt(boost::thread_group& threadGroup)
161 InterruptHTTPServer();
162 InterruptHTTPRPC();
163 InterruptRPC();
164 InterruptREST();
165 InterruptTorControl();
166 if (g_connman)
167 g_connman->Interrupt();
168 threadGroup.interrupt_all();
171 void Shutdown()
173 LogPrintf("%s: In progress...\n", __func__);
174 static CCriticalSection cs_Shutdown;
175 TRY_LOCK(cs_Shutdown, lockShutdown);
176 if (!lockShutdown)
177 return;
179 /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
180 /// for example if the data directory was found to be locked.
181 /// Be sure that anything that writes files or flushes caches only does this if the respective
182 /// module was initialized.
183 RenameThread("bitcoin-shutoff");
184 mempool.AddTransactionsUpdated(1);
186 StopHTTPRPC();
187 StopREST();
188 StopRPC();
189 StopHTTPServer();
190 #ifdef ENABLE_WALLET
191 for (CWalletRef pwallet : vpwallets) {
192 pwallet->Flush(false);
194 #endif
195 MapPort(false);
196 UnregisterValidationInterface(peerLogic.get());
197 peerLogic.reset();
198 g_connman.reset();
200 StopTorControl();
201 UnregisterNodeSignals(GetNodeSignals());
202 if (fDumpMempoolLater && 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;
219 LOCK(cs_main);
220 if (pcoinsTip != NULL) {
221 FlushStateToDisk();
223 delete pcoinsTip;
224 pcoinsTip = NULL;
225 delete pcoinscatcher;
226 pcoinscatcher = NULL;
227 delete pcoinsdbview;
228 pcoinsdbview = NULL;
229 delete pblocktree;
230 pblocktree = NULL;
232 #ifdef ENABLE_WALLET
233 for (CWalletRef pwallet : vpwallets) {
234 pwallet->Flush(true);
236 #endif
238 #if ENABLE_ZMQ
239 if (pzmqNotificationInterface) {
240 UnregisterValidationInterface(pzmqNotificationInterface);
241 delete pzmqNotificationInterface;
242 pzmqNotificationInterface = NULL;
244 #endif
246 #ifndef WIN32
247 try {
248 fs::remove(GetPidFile());
249 } catch (const fs::filesystem_error& e) {
250 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
252 #endif
253 UnregisterAllValidationInterfaces();
254 #ifdef ENABLE_WALLET
255 for (CWalletRef pwallet : vpwallets) {
256 delete pwallet;
258 vpwallets.clear();
259 #endif
260 globalVerifyHandle.reset();
261 ECC_Stop();
262 LogPrintf("%s: done\n", __func__);
266 * Signal handlers are very limited in what they are allowed to do.
267 * The execution context the handler is invoked in is not guaranteed,
268 * so we restrict handler operations to just touching variables:
270 static void HandleSIGTERM(int)
272 fRequestShutdown = true;
275 static void HandleSIGHUP(int)
277 fReopenDebugLog = true;
280 #ifndef WIN32
281 static void registerSignalHandler(int signal, void(*handler)(int))
283 struct sigaction sa;
284 sa.sa_handler = handler;
285 sigemptyset(&sa.sa_mask);
286 sa.sa_flags = 0;
287 sigaction(signal, &sa, NULL);
289 #endif
291 void OnRPCStarted()
293 uiInterface.NotifyBlockTip.connect(&RPCNotifyBlockChange);
296 void OnRPCStopped()
298 uiInterface.NotifyBlockTip.disconnect(&RPCNotifyBlockChange);
299 RPCNotifyBlockChange(false, nullptr);
300 cvBlockChange.notify_all();
301 LogPrint(BCLog::RPC, "RPC stopped.\n");
304 void OnRPCPreCommand(const CRPCCommand& cmd)
306 // Observe safe mode
307 std::string strWarning = GetWarnings("rpc");
308 if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
309 !cmd.okSafeMode)
310 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
313 std::string HelpMessage(HelpMessageMode mode)
315 const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
316 const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
317 const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
318 const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET);
319 const bool showDebug = GetBoolArg("-help-debug", false);
321 // When adding new options to the categories, please keep and ensure alphabetical ordering.
322 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
323 std::string strUsage = HelpMessageGroup(_("Options:"));
324 strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
325 strUsage += HelpMessageOpt("-version", _("Print version and exit"));
326 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)"));
327 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
328 if (showDebug)
329 strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
330 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()));
331 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
332 if (mode == HMM_BITCOIND)
334 #if HAVE_DECL_DAEMON
335 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
336 #endif
338 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
339 if (showDebug) {
340 strUsage += HelpMessageOpt("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize));
342 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
343 if (showDebug)
344 strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
345 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
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 strUsage += HelpMessageOpt("-persistmempool", strprintf(_("Whether to save the mempool on shutdown and load on restart (default: %u)"), DEFAULT_PERSIST_MEMPOOL));
350 strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
351 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)"),
352 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
353 #ifndef WIN32
354 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
355 #endif
356 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. "
357 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
358 "(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));
359 strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
360 strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
361 #ifndef WIN32
362 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
363 #endif
364 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
366 strUsage += HelpMessageGroup(_("Connection options:"));
367 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
368 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
369 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
370 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
371 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -connect=0 disables automatic connections"));
372 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
373 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
374 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)"));
375 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
376 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
377 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
378 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
379 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
380 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
381 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
382 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));
383 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
384 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
385 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
386 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
387 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort()));
388 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
389 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
390 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
391 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
392 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
393 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
394 #ifdef USE_UPNP
395 #if USE_UPNP
396 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
397 #else
398 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
399 #endif
400 #endif
401 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
402 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.") +
403 " " + _("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"));
404 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));
406 #ifdef ENABLE_WALLET
407 strUsage += CWallet::GetWalletHelpString(showDebug);
408 #endif
410 #if ENABLE_ZMQ
411 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
412 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
413 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
414 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
415 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
416 #endif
418 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
419 strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
420 if (showDebug)
422 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
423 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
424 strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
425 strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
426 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
427 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
428 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
429 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
430 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
431 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
432 strUsage += HelpMessageOpt("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT));
434 strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
435 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));
436 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));
437 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));
438 strUsage += HelpMessageOpt("-vbparams=deployment:start:end", "Use given start/end times for specified version bits deployment (regtest-only)");
440 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
441 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + ListLogCategories() + ".");
442 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.")));
443 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
444 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
445 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
446 if (showDebug)
448 strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
449 strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
450 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
451 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
453 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)"),
454 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
455 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
456 if (showDebug)
458 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
460 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
462 AppendParamsHelpMessages(strUsage, showDebug);
464 strUsage += HelpMessageGroup(_("Node relay options:"));
465 if (showDebug) {
466 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", defaultChainParams->RequireStandard()));
467 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)));
468 strUsage += HelpMessageOpt("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to defined dust, the value of an output such that it will cost about 1/3 of its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)));
470 strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
471 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
472 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
473 strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
474 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
475 CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
476 strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
477 strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
479 strUsage += HelpMessageGroup(_("Block creation options:"));
480 strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
481 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
482 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)));
483 if (showDebug)
484 strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
486 strUsage += HelpMessageGroup(_("RPC server options:"));
487 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
488 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
489 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)"));
490 strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
491 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
492 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
493 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"));
494 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
495 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"));
496 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));
497 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
498 if (showDebug) {
499 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
500 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
503 return strUsage;
506 std::string LicenseInfo()
508 const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
509 const std::string URL_WEBSITE = "<https://bitcoincore.org>";
511 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
512 "\n" +
513 strprintf(_("Please contribute if you find %s useful. "
514 "Visit %s for further information about the software."),
515 PACKAGE_NAME, URL_WEBSITE) +
516 "\n" +
517 strprintf(_("The source code is available from %s."),
518 URL_SOURCE_CODE) +
519 "\n" +
520 "\n" +
521 _("This is experimental software.") + "\n" +
522 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
523 "\n" +
524 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>") +
525 "\n";
528 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
530 if (initialSync || !pBlockIndex)
531 return;
533 std::string strCmd = GetArg("-blocknotify", "");
535 boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
536 boost::thread t(runCommand, strCmd); // thread runs free
539 static bool fHaveGenesis = false;
540 static boost::mutex cs_GenesisWait;
541 static CConditionVariable condvar_GenesisWait;
543 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
545 if (pBlockIndex != NULL) {
547 boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
548 fHaveGenesis = true;
550 condvar_GenesisWait.notify_all();
554 struct CImportingNow
556 CImportingNow() {
557 assert(fImporting == false);
558 fImporting = true;
561 ~CImportingNow() {
562 assert(fImporting == true);
563 fImporting = false;
568 // If we're using -prune with -reindex, then delete block files that will be ignored by the
569 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
570 // is missing, do the same here to delete any later block files after a gap. Also delete all
571 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
572 // is in sync with what's actually on disk by the time we start downloading, so that pruning
573 // works correctly.
574 void CleanupBlockRevFiles()
576 std::map<std::string, fs::path> mapBlockFiles;
578 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
579 // Remove the rev files immediately and insert the blk file paths into an
580 // ordered map keyed by block file index.
581 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
582 fs::path blocksdir = GetDataDir() / "blocks";
583 for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
584 if (is_regular_file(*it) &&
585 it->path().filename().string().length() == 12 &&
586 it->path().filename().string().substr(8,4) == ".dat")
588 if (it->path().filename().string().substr(0,3) == "blk")
589 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
590 else if (it->path().filename().string().substr(0,3) == "rev")
591 remove(it->path());
595 // Remove all block files that aren't part of a contiguous set starting at
596 // zero by walking the ordered map (keys are block file indices) by
597 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
598 // start removing block files.
599 int nContigCounter = 0;
600 for (const std::pair<std::string, fs::path>& item : mapBlockFiles) {
601 if (atoi(item.first) == nContigCounter) {
602 nContigCounter++;
603 continue;
605 remove(item.second);
609 void ThreadImport(std::vector<fs::path> vImportFiles)
611 const CChainParams& chainparams = Params();
612 RenameThread("bitcoin-loadblk");
615 CImportingNow imp;
617 // -reindex
618 if (fReindex) {
619 int nFile = 0;
620 while (true) {
621 CDiskBlockPos pos(nFile, 0);
622 if (!fs::exists(GetBlockPosFilename(pos, "blk")))
623 break; // No block files left to reindex
624 FILE *file = OpenBlockFile(pos, true);
625 if (!file)
626 break; // This error is logged in OpenBlockFile
627 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
628 LoadExternalBlockFile(chainparams, file, &pos);
629 nFile++;
631 pblocktree->WriteReindexing(false);
632 fReindex = false;
633 LogPrintf("Reindexing finished\n");
634 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
635 InitBlockIndex(chainparams);
638 // hardcoded $DATADIR/bootstrap.dat
639 fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
640 if (fs::exists(pathBootstrap)) {
641 FILE *file = fsbridge::fopen(pathBootstrap, "rb");
642 if (file) {
643 fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
644 LogPrintf("Importing bootstrap.dat...\n");
645 LoadExternalBlockFile(chainparams, file);
646 RenameOver(pathBootstrap, pathBootstrapOld);
647 } else {
648 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
652 // -loadblock=
653 for (const fs::path& path : vImportFiles) {
654 FILE *file = fsbridge::fopen(path, "rb");
655 if (file) {
656 LogPrintf("Importing blocks file %s...\n", path.string());
657 LoadExternalBlockFile(chainparams, file);
658 } else {
659 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
663 // scan for better chains in the block chain database, that are not yet connected in the active best chain
664 CValidationState state;
665 if (!ActivateBestChain(state, chainparams)) {
666 LogPrintf("Failed to connect best block");
667 StartShutdown();
670 if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
671 LogPrintf("Stopping after block import\n");
672 StartShutdown();
674 } // End scope of CImportingNow
675 if (GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
676 LoadMempool();
677 fDumpMempoolLater = !fRequestShutdown;
681 /** Sanity checks
682 * Ensure that Bitcoin is running in a usable environment with all
683 * necessary library support.
685 bool InitSanityCheck(void)
687 if(!ECC_InitSanityCheck()) {
688 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
689 return false;
692 if (!glibc_sanity_test() || !glibcxx_sanity_test())
693 return false;
695 if (!Random_SanityCheck()) {
696 InitError("OS cryptographic RNG sanity check failure. Aborting.");
697 return false;
700 return true;
703 bool AppInitServers(boost::thread_group& threadGroup)
705 RPCServer::OnStarted(&OnRPCStarted);
706 RPCServer::OnStopped(&OnRPCStopped);
707 RPCServer::OnPreCommand(&OnRPCPreCommand);
708 if (!InitHTTPServer())
709 return false;
710 if (!StartRPC())
711 return false;
712 if (!StartHTTPRPC())
713 return false;
714 if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
715 return false;
716 if (!StartHTTPServer())
717 return false;
718 return true;
721 // Parameter interaction based on rules
722 void InitParameterInteraction()
724 // when specifying an explicit binding address, you want to listen on it
725 // even when -connect or -proxy is specified
726 if (IsArgSet("-bind")) {
727 if (SoftSetBoolArg("-listen", true))
728 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
730 if (IsArgSet("-whitebind")) {
731 if (SoftSetBoolArg("-listen", true))
732 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
735 if (gArgs.IsArgSet("-connect")) {
736 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
737 if (SoftSetBoolArg("-dnsseed", false))
738 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
739 if (SoftSetBoolArg("-listen", false))
740 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
743 if (IsArgSet("-proxy")) {
744 // to protect privacy, do not listen by default if a default proxy server is specified
745 if (SoftSetBoolArg("-listen", false))
746 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
747 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
748 // to listen locally, so don't rely on this happening through -listen below.
749 if (SoftSetBoolArg("-upnp", false))
750 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
751 // to protect privacy, do not discover addresses by default
752 if (SoftSetBoolArg("-discover", false))
753 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
756 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
757 // do not map ports or try to retrieve public IP when not listening (pointless)
758 if (SoftSetBoolArg("-upnp", false))
759 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
760 if (SoftSetBoolArg("-discover", false))
761 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
762 if (SoftSetBoolArg("-listenonion", false))
763 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
766 if (IsArgSet("-externalip")) {
767 // if an explicit public IP is specified, do not try to find others
768 if (SoftSetBoolArg("-discover", false))
769 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
772 // disable whitelistrelay in blocksonly mode
773 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
774 if (SoftSetBoolArg("-whitelistrelay", false))
775 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
778 // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
779 if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
780 if (SoftSetBoolArg("-whitelistrelay", true))
781 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
785 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
787 return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
790 void InitLogging()
792 fPrintToConsole = GetBoolArg("-printtoconsole", false);
793 fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
794 fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
795 fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
797 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
798 LogPrintf("Bitcoin version %s\n", FormatFullVersion());
801 namespace { // Variables internal to initialization process only
803 ServiceFlags nRelevantServices = NODE_NETWORK;
804 int nMaxConnections;
805 int nUserMaxConnections;
806 int nFD;
807 ServiceFlags nLocalServices = NODE_NETWORK;
809 } // namespace
811 [[noreturn]] static void new_handler_terminate()
813 // Rather than throwing std::bad-alloc if allocation fails, terminate
814 // immediately to (try to) avoid chain corruption.
815 // Since LogPrintf may itself allocate memory, set the handler directly
816 // to terminate first.
817 std::set_new_handler(std::terminate);
818 LogPrintf("Error: Out of memory. Terminating.\n");
820 // The log was successful, terminate now.
821 std::terminate();
824 bool AppInitBasicSetup()
826 // ********************************************************* Step 1: setup
827 #ifdef _MSC_VER
828 // Turn off Microsoft heap dump noise
829 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
830 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
831 // Disable confusing "helpful" text message on abort, Ctrl-C
832 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
833 #endif
834 #ifdef WIN32
835 // Enable Data Execution Prevention (DEP)
836 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
837 // A failure is non-critical and needs no further attention!
838 #ifndef PROCESS_DEP_ENABLE
839 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
840 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
841 #define PROCESS_DEP_ENABLE 0x00000001
842 #endif
843 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
844 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
845 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
846 #endif
848 if (!SetupNetworking())
849 return InitError("Initializing networking failed");
851 #ifndef WIN32
852 if (!GetBoolArg("-sysperms", false)) {
853 umask(077);
856 // Clean shutdown on SIGTERM
857 registerSignalHandler(SIGTERM, HandleSIGTERM);
858 registerSignalHandler(SIGINT, HandleSIGTERM);
860 // Reopen debug.log on SIGHUP
861 registerSignalHandler(SIGHUP, HandleSIGHUP);
863 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
864 signal(SIGPIPE, SIG_IGN);
865 #endif
867 std::set_new_handler(new_handler_terminate);
869 return true;
872 bool AppInitParameterInteraction()
874 const CChainParams& chainparams = Params();
875 // ********************************************************* Step 2: parameter interactions
877 // also see: InitParameterInteraction()
879 // if using block pruning, then disallow txindex
880 if (GetArg("-prune", 0)) {
881 if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
882 return InitError(_("Prune mode is incompatible with -txindex."));
885 // -bind and -whitebind can't be set when not listening
886 size_t nUserBind = gArgs.GetArgs("-bind").size() + gArgs.GetArgs("-whitebind").size();
887 if (nUserBind != 0 && !gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
888 return InitError("Cannot set -bind or -whitebind together with -listen=0");
891 // Make sure enough file descriptors are available
892 int nBind = std::max(nUserBind, size_t(1));
893 nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
894 nMaxConnections = std::max(nUserMaxConnections, 0);
896 // Trim requested connection counts, to fit into system limitations
897 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
898 nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
899 if (nFD < MIN_CORE_FILEDESCRIPTORS)
900 return InitError(_("Not enough file descriptors available."));
901 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
903 if (nMaxConnections < nUserMaxConnections)
904 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
906 // ********************************************************* Step 3: parameter-to-internal-flags
907 if (gArgs.IsArgSet("-debug")) {
908 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
909 const std::vector<std::string> categories = gArgs.GetArgs("-debug");
911 if (find(categories.begin(), categories.end(), std::string("0")) == categories.end()) {
912 for (const auto& cat : categories) {
913 uint32_t flag = 0;
914 if (!GetLogCategory(&flag, &cat)) {
915 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
916 continue;
918 logCategories |= flag;
923 // Now remove the logging categories which were explicitly excluded
924 for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
925 uint32_t flag = 0;
926 if (!GetLogCategory(&flag, &cat)) {
927 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
928 continue;
930 logCategories &= ~flag;
933 // Check for -debugnet
934 if (GetBoolArg("-debugnet", false))
935 InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
936 // Check for -socks - as this is a privacy risk to continue, exit here
937 if (IsArgSet("-socks"))
938 return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
939 // Check for -tor - as this is a privacy risk to continue, exit here
940 if (GetBoolArg("-tor", false))
941 return InitError(_("Unsupported argument -tor found, use -onion."));
943 if (GetBoolArg("-benchmark", false))
944 InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
946 if (GetBoolArg("-whitelistalwaysrelay", false))
947 InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
949 if (IsArgSet("-blockminsize"))
950 InitWarning("Unsupported argument -blockminsize ignored.");
952 // Checkmempool and checkblockindex default to true in regtest mode
953 int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
954 if (ratio != 0) {
955 mempool.setSanityCheck(1.0 / ratio);
957 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
958 fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
960 hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
961 if (!hashAssumeValid.IsNull())
962 LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
963 else
964 LogPrintf("Validating signatures for all blocks.\n");
966 // mempool limits
967 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
968 int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
969 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
970 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
971 // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
972 // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
973 if (IsArgSet("-incrementalrelayfee"))
975 CAmount n = 0;
976 if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n))
977 return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", "")));
978 incrementalRelayFee = CFeeRate(n);
981 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
982 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
983 if (nScriptCheckThreads <= 0)
984 nScriptCheckThreads += GetNumCores();
985 if (nScriptCheckThreads <= 1)
986 nScriptCheckThreads = 0;
987 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
988 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
990 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
991 int64_t nPruneArg = GetArg("-prune", 0);
992 if (nPruneArg < 0) {
993 return InitError(_("Prune cannot be configured with a negative value."));
995 nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
996 if (nPruneArg == 1) { // manual pruning: -prune=1
997 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
998 nPruneTarget = std::numeric_limits<uint64_t>::max();
999 fPruneMode = true;
1000 } else if (nPruneTarget) {
1001 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
1002 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1004 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1005 fPruneMode = true;
1008 RegisterAllCoreRPCCommands(tableRPC);
1009 #ifdef ENABLE_WALLET
1010 RegisterWalletRPCCommands(tableRPC);
1011 #endif
1013 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1014 if (nConnectTimeout <= 0)
1015 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1017 if (IsArgSet("-minrelaytxfee")) {
1018 CAmount n = 0;
1019 if (!ParseMoney(GetArg("-minrelaytxfee", ""), n)) {
1020 return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
1022 // High fee check is done afterward in CWallet::ParameterInteraction()
1023 ::minRelayTxFee = CFeeRate(n);
1024 } else if (incrementalRelayFee > ::minRelayTxFee) {
1025 // Allow only setting incrementalRelayFee to control both
1026 ::minRelayTxFee = incrementalRelayFee;
1027 LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1030 // Sanity check argument for min fee for including tx in block
1031 // TODO: Harmonize which arguments need sanity checking and where that happens
1032 if (IsArgSet("-blockmintxfee"))
1034 CAmount n = 0;
1035 if (!ParseMoney(GetArg("-blockmintxfee", ""), n))
1036 return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", "")));
1039 // Feerate used to define dust. Shouldn't be changed lightly as old
1040 // implementations may inadvertently create non-standard transactions
1041 if (IsArgSet("-dustrelayfee"))
1043 CAmount n = 0;
1044 if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n)
1045 return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", "")));
1046 dustRelayFee = CFeeRate(n);
1049 fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1050 if (chainparams.RequireStandard() && !fRequireStandard)
1051 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1052 nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
1054 #ifdef ENABLE_WALLET
1055 if (!CWallet::ParameterInteraction())
1056 return false;
1057 #endif
1059 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1060 fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1061 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1063 // Option to startup with mocktime set (used for regression testing):
1064 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1066 if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1067 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1069 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1070 return InitError("rpcserialversion must be non-negative.");
1072 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1073 return InitError("unknown rpcserialversion requested.");
1075 nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1077 fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1078 if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
1079 // Minimal effort at forwards compatibility
1080 std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
1081 std::vector<std::string> vstrReplacementModes;
1082 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1083 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1086 if (gArgs.IsArgSet("-vbparams")) {
1087 // Allow overriding version bits parameters for testing
1088 if (!chainparams.MineBlocksOnDemand()) {
1089 return InitError("Version bits parameters may only be overridden on regtest.");
1091 for (const std::string& strDeployment : gArgs.GetArgs("-vbparams")) {
1092 std::vector<std::string> vDeploymentParams;
1093 boost::split(vDeploymentParams, strDeployment, boost::is_any_of(":"));
1094 if (vDeploymentParams.size() != 3) {
1095 return InitError("Version bits parameters malformed, expecting deployment:start:end");
1097 int64_t nStartTime, nTimeout;
1098 if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1099 return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1101 if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1102 return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1104 bool found = false;
1105 for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1107 if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1108 UpdateVersionBitsParameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1109 found = true;
1110 LogPrintf("Setting version bits activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1111 break;
1114 if (!found) {
1115 return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1119 return true;
1122 static bool LockDataDirectory(bool probeOnly)
1124 std::string strDataDir = GetDataDir().string();
1126 // Make sure only a single Bitcoin process is using the data directory.
1127 fs::path pathLockFile = GetDataDir() / ".lock";
1128 FILE* file = fsbridge::fopen(pathLockFile, "a"); // empty lock file; created if it doesn't exist.
1129 if (file) fclose(file);
1131 try {
1132 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1133 if (!lock.try_lock()) {
1134 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1136 if (probeOnly) {
1137 lock.unlock();
1139 } catch(const boost::interprocess::interprocess_exception& e) {
1140 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1142 return true;
1145 bool AppInitSanityChecks()
1147 // ********************************************************* Step 4: sanity checks
1149 // Initialize elliptic curve code
1150 RandomInit();
1151 ECC_Start();
1152 globalVerifyHandle.reset(new ECCVerifyHandle());
1154 // Sanity check
1155 if (!InitSanityCheck())
1156 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1158 // Probe the data directory lock to give an early error message, if possible
1159 return LockDataDirectory(true);
1162 bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
1164 const CChainParams& chainparams = Params();
1165 // ********************************************************* Step 4a: application initialization
1166 // After daemonization get the data directory lock again and hold on to it until exit
1167 // This creates a slight window for a race condition to happen, however this condition is harmless: it
1168 // will at most make us exit without printing a message to console.
1169 if (!LockDataDirectory(false)) {
1170 // Detailed error printed inside LockDataDirectory
1171 return false;
1174 #ifndef WIN32
1175 CreatePidFile(GetPidFile(), getpid());
1176 #endif
1177 if (GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
1178 // Do this first since it both loads a bunch of debug.log into memory,
1179 // and because this needs to happen before any other debug.log printing
1180 ShrinkDebugFile();
1183 if (fPrintToDebugLog)
1184 OpenDebugLog();
1186 if (!fLogTimestamps)
1187 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1188 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1189 LogPrintf("Using data directory %s\n", GetDataDir().string());
1190 LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1191 LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1193 InitSignatureCache();
1195 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1196 if (nScriptCheckThreads) {
1197 for (int i=0; i<nScriptCheckThreads-1; i++)
1198 threadGroup.create_thread(&ThreadScriptCheck);
1201 // Start the lightweight task scheduler thread
1202 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1203 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1205 /* Start the RPC server already. It will be started in "warmup" mode
1206 * and not really process calls already (but it will signify connections
1207 * that the server is there and will be ready later). Warmup mode will
1208 * be disabled when initialisation is finished.
1210 if (GetBoolArg("-server", false))
1212 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1213 if (!AppInitServers(threadGroup))
1214 return InitError(_("Unable to start HTTP server. See debug log for details."));
1217 int64_t nStart;
1219 // ********************************************************* Step 5: verify wallet database integrity
1220 #ifdef ENABLE_WALLET
1221 if (!CWallet::Verify())
1222 return false;
1223 #endif
1224 // ********************************************************* Step 6: network initialization
1225 // Note that we absolutely cannot open any actual connections
1226 // until the very end ("start node") as the UTXO/block state
1227 // is not yet setup and may end up being set up twice if we
1228 // need to reindex later.
1230 assert(!g_connman);
1231 g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1232 CConnman& connman = *g_connman;
1234 peerLogic.reset(new PeerLogicValidation(&connman));
1235 RegisterValidationInterface(peerLogic.get());
1236 RegisterNodeSignals(GetNodeSignals());
1238 // sanitize comments per BIP-0014, format user agent and check total size
1239 std::vector<std::string> uacomments;
1240 for (const std::string& cmt : gArgs.GetArgs("-uacomment")) {
1241 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1242 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1243 uacomments.push_back(cmt);
1245 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1246 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1247 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1248 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1251 if (gArgs.IsArgSet("-onlynet")) {
1252 std::set<enum Network> nets;
1253 for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
1254 enum Network net = ParseNetwork(snet);
1255 if (net == NET_UNROUTABLE)
1256 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1257 nets.insert(net);
1259 for (int n = 0; n < NET_MAX; n++) {
1260 enum Network net = (enum Network)n;
1261 if (!nets.count(net))
1262 SetLimited(net);
1266 // Check for host lookup allowed before parsing any network related parameters
1267 fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1269 bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1270 // -proxy sets a proxy for all outgoing network traffic
1271 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1272 std::string proxyArg = GetArg("-proxy", "");
1273 SetLimited(NET_TOR);
1274 if (proxyArg != "" && proxyArg != "0") {
1275 CService proxyAddr;
1276 if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1277 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1280 proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1281 if (!addrProxy.IsValid())
1282 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1284 SetProxy(NET_IPV4, addrProxy);
1285 SetProxy(NET_IPV6, addrProxy);
1286 SetProxy(NET_TOR, addrProxy);
1287 SetNameProxy(addrProxy);
1288 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1291 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1292 // -noonion (or -onion=0) disables connecting to .onion entirely
1293 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1294 std::string onionArg = GetArg("-onion", "");
1295 if (onionArg != "") {
1296 if (onionArg == "0") { // Handle -noonion/-onion=0
1297 SetLimited(NET_TOR); // set onions as unreachable
1298 } else {
1299 CService onionProxy;
1300 if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1301 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1303 proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1304 if (!addrOnion.IsValid())
1305 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1306 SetProxy(NET_TOR, addrOnion);
1307 SetLimited(NET_TOR, false);
1311 // see Step 2: parameter interactions for more information about these
1312 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1313 fDiscover = GetBoolArg("-discover", true);
1314 fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1316 for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
1317 CService addrLocal;
1318 if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1319 AddLocal(addrLocal, LOCAL_MANUAL);
1320 else
1321 return InitError(ResolveErrMsg("externalip", strAddr));
1324 #if ENABLE_ZMQ
1325 pzmqNotificationInterface = CZMQNotificationInterface::Create();
1327 if (pzmqNotificationInterface) {
1328 RegisterValidationInterface(pzmqNotificationInterface);
1330 #endif
1331 uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1332 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1334 if (IsArgSet("-maxuploadtarget")) {
1335 nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1338 // ********************************************************* Step 7: load block chain
1340 fReindex = GetBoolArg("-reindex", false);
1341 bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
1343 // cache size calculations
1344 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1345 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1346 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1347 int64_t nBlockTreeDBCache = nTotalCache / 8;
1348 nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1349 nTotalCache -= nBlockTreeDBCache;
1350 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1351 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1352 nTotalCache -= nCoinDBCache;
1353 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1354 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1355 LogPrintf("Cache configuration:\n");
1356 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1357 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1358 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));
1360 bool fLoaded = false;
1361 while (!fLoaded && !fRequestShutdown) {
1362 bool fReset = fReindex;
1363 std::string strLoadError;
1365 uiInterface.InitMessage(_("Loading block index..."));
1367 nStart = GetTimeMillis();
1368 do {
1369 try {
1370 UnloadBlockIndex();
1371 delete pcoinsTip;
1372 delete pcoinsdbview;
1373 delete pcoinscatcher;
1374 delete pblocktree;
1376 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1377 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState);
1378 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1380 if (fReindex) {
1381 pblocktree->WriteReindexing(true);
1382 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1383 if (fPruneMode)
1384 CleanupBlockRevFiles();
1385 } else {
1386 // If necessary, upgrade from older database format.
1387 if (!pcoinsdbview->Upgrade()) {
1388 strLoadError = _("Error upgrading chainstate database");
1389 break;
1392 if (fRequestShutdown) break;
1394 if (!LoadBlockIndex(chainparams)) {
1395 strLoadError = _("Error loading block database");
1396 break;
1399 // If the loaded chain has a wrong genesis, bail out immediately
1400 // (we're likely using a testnet datadir, or the other way around).
1401 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1402 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1404 // Initialize the block index (no-op if non-empty database was already loaded)
1405 if (!InitBlockIndex(chainparams)) {
1406 strLoadError = _("Error initializing block database");
1407 break;
1410 // Check for changed -txindex state
1411 if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1412 strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
1413 break;
1416 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1417 // in the past, but is now trying to run unpruned.
1418 if (fHavePruned && !fPruneMode) {
1419 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1420 break;
1423 if (!ReplayBlocks(chainparams, pcoinsdbview)) {
1424 strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1425 break;
1427 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1428 LoadChainTip(chainparams);
1430 if (!fReindex && chainActive.Tip() != NULL) {
1431 uiInterface.InitMessage(_("Rewinding blocks..."));
1432 if (!RewindBlockIndex(chainparams)) {
1433 strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1434 break;
1438 uiInterface.InitMessage(_("Verifying blocks..."));
1439 if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1440 LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
1441 MIN_BLOCKS_TO_KEEP);
1445 LOCK(cs_main);
1446 CBlockIndex* tip = chainActive.Tip();
1447 RPCNotifyBlockChange(true, tip);
1448 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1449 strLoadError = _("The block database contains a block which appears to be from the future. "
1450 "This may be due to your computer's date and time being set incorrectly. "
1451 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1452 break;
1456 if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1457 GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1458 strLoadError = _("Corrupted block database detected");
1459 break;
1461 } catch (const std::exception& e) {
1462 LogPrintf("%s\n", e.what());
1463 strLoadError = _("Error opening block database");
1464 break;
1467 fLoaded = true;
1468 } while(false);
1470 if (!fLoaded && !fRequestShutdown) {
1471 // first suggest a reindex
1472 if (!fReset) {
1473 bool fRet = uiInterface.ThreadSafeQuestion(
1474 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1475 strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1476 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1477 if (fRet) {
1478 fReindex = true;
1479 fRequestShutdown = false;
1480 } else {
1481 LogPrintf("Aborted block database rebuild. Exiting.\n");
1482 return false;
1484 } else {
1485 return InitError(strLoadError);
1490 // As LoadBlockIndex can take several minutes, it's possible the user
1491 // requested to kill the GUI during the last operation. If so, exit.
1492 // As the program has not fully started yet, Shutdown() is possibly overkill.
1493 if (fRequestShutdown)
1495 LogPrintf("Shutdown requested. Exiting.\n");
1496 return false;
1498 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1500 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1501 CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
1502 // Allowed to fail as this file IS missing on first startup.
1503 if (!est_filein.IsNull())
1504 ::feeEstimator.Read(est_filein);
1505 fFeeEstimatesInitialized = true;
1507 // ********************************************************* Step 8: load wallet
1508 #ifdef ENABLE_WALLET
1509 if (!CWallet::InitLoadWallet())
1510 return false;
1511 #else
1512 LogPrintf("No wallet support compiled in!\n");
1513 #endif
1515 // ********************************************************* Step 9: data directory maintenance
1517 // if pruning, unset the service bit and perform the initial blockstore prune
1518 // after any wallet rescanning has taken place.
1519 if (fPruneMode) {
1520 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1521 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1522 if (!fReindex) {
1523 uiInterface.InitMessage(_("Pruning blockstore..."));
1524 PruneAndFlush();
1528 if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
1529 // Only advertise witness capabilities if they have a reasonable start time.
1530 // This allows us to have the code merged without a defined softfork, by setting its
1531 // end time to 0.
1532 // Note that setting NODE_WITNESS is never required: the only downside from not
1533 // doing so is that after activation, no upgraded nodes will fetch from you.
1534 nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1535 // Only care about others providing witness capabilities if there is a softfork
1536 // defined.
1537 nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS);
1540 // ********************************************************* Step 10: import blocks
1542 if (!CheckDiskSpace())
1543 return false;
1545 // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1546 // No locking, as this happens before any background thread is started.
1547 if (chainActive.Tip() == NULL) {
1548 uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1549 } else {
1550 fHaveGenesis = true;
1553 if (IsArgSet("-blocknotify"))
1554 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1556 std::vector<fs::path> vImportFiles;
1557 for (const std::string& strFile : gArgs.GetArgs("-loadblock")) {
1558 vImportFiles.push_back(strFile);
1561 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1563 // Wait for genesis block to be processed
1565 boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
1566 while (!fHaveGenesis) {
1567 condvar_GenesisWait.wait(lock);
1569 uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1572 // ********************************************************* Step 11: start node
1574 //// debug print
1575 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1576 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1577 if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1578 StartTorControl(threadGroup, scheduler);
1580 Discover(threadGroup);
1582 // Map ports with UPnP
1583 MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
1585 CConnman::Options connOptions;
1586 connOptions.nLocalServices = nLocalServices;
1587 connOptions.nRelevantServices = nRelevantServices;
1588 connOptions.nMaxConnections = nMaxConnections;
1589 connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1590 connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1591 connOptions.nMaxFeeler = 1;
1592 connOptions.nBestHeight = chainActive.Height();
1593 connOptions.uiInterface = &uiInterface;
1594 connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1595 connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1597 connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1598 connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1600 for (const std::string& strBind : gArgs.GetArgs("-bind")) {
1601 CService addrBind;
1602 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) {
1603 return InitError(ResolveErrMsg("bind", strBind));
1605 connOptions.vBinds.push_back(addrBind);
1607 for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
1608 CService addrBind;
1609 if (!Lookup(strBind.c_str(), addrBind, 0, false)) {
1610 return InitError(ResolveErrMsg("whitebind", strBind));
1612 if (addrBind.GetPort() == 0) {
1613 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1615 connOptions.vWhiteBinds.push_back(addrBind);
1618 for (const auto& net : gArgs.GetArgs("-whitelist")) {
1619 CSubNet subnet;
1620 LookupSubNet(net.c_str(), subnet);
1621 if (!subnet.IsValid())
1622 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1623 connOptions.vWhitelistedRange.push_back(subnet);
1626 if (gArgs.IsArgSet("-seednode")) {
1627 connOptions.vSeedNodes = gArgs.GetArgs("-seednode");
1630 if (!connman.Start(scheduler, connOptions)) {
1631 return false;
1634 // ********************************************************* Step 12: finished
1636 SetRPCWarmupFinished();
1637 uiInterface.InitMessage(_("Done loading"));
1639 #ifdef ENABLE_WALLET
1640 for (CWalletRef pwallet : vpwallets) {
1641 pwallet->postInitProcess(scheduler);
1643 #endif
1645 return !fRequestShutdown;