Merge #10690: [qa] Bugfix: allow overriding extra_args in ComparisonTestFramework
[bitcoinplatinum.git] / src / init.cpp
blob57232c7df328ca5496ca2cb861dc4b3238855122
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 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
340 if (showDebug)
341 strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
342 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
343 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
344 strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
345 strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
346 strUsage += HelpMessageOpt("-persistmempool", strprintf(_("Whether to save the mempool on shutdown and load on restart (default: %u)"), DEFAULT_PERSIST_MEMPOOL));
347 strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
348 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)"),
349 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
350 #ifndef WIN32
351 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
352 #endif
353 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. "
354 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
355 "(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));
356 strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
357 strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
358 #ifndef WIN32
359 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
360 #endif
361 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
363 strUsage += HelpMessageGroup(_("Connection options:"));
364 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
365 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
366 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
367 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
368 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -connect=0 disables automatic connections"));
369 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
370 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
371 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)"));
372 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
373 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
374 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
375 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
376 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
377 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
378 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
379 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));
380 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
381 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
382 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
383 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
384 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort()));
385 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
386 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
387 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
388 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
389 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
390 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
391 #ifdef USE_UPNP
392 #if USE_UPNP
393 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
394 #else
395 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
396 #endif
397 #endif
398 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
399 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.") +
400 " " + _("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"));
401 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));
403 #ifdef ENABLE_WALLET
404 strUsage += CWallet::GetWalletHelpString(showDebug);
405 #endif
407 #if ENABLE_ZMQ
408 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
409 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
410 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
411 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
412 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
413 #endif
415 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
416 strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
417 if (showDebug)
419 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
420 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
421 strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
422 strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
423 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
424 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
425 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
426 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
427 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
428 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
429 strUsage += HelpMessageOpt("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT));
431 strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
432 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));
433 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));
434 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));
435 strUsage += HelpMessageOpt("-vbparams=deployment:start:end", "Use given start/end times for specified version bits deployment (regtest-only)");
437 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
438 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + ListLogCategories() + ".");
439 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.")));
440 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
441 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
442 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
443 if (showDebug)
445 strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
446 strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
447 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
448 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
450 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)"),
451 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
452 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
453 if (showDebug)
455 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
457 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
459 AppendParamsHelpMessages(strUsage, showDebug);
461 strUsage += HelpMessageGroup(_("Node relay options:"));
462 if (showDebug) {
463 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", defaultChainParams->RequireStandard()));
464 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)));
465 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)));
467 strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
468 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
469 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
470 strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
471 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
472 CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
473 strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
474 strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
476 strUsage += HelpMessageGroup(_("Block creation options:"));
477 strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
478 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
479 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)));
480 if (showDebug)
481 strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
483 strUsage += HelpMessageGroup(_("RPC server options:"));
484 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
485 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
486 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)"));
487 strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
488 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
489 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
490 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"));
491 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
492 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"));
493 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));
494 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
495 if (showDebug) {
496 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
497 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
500 return strUsage;
503 std::string LicenseInfo()
505 const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
506 const std::string URL_WEBSITE = "<https://bitcoincore.org>";
508 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
509 "\n" +
510 strprintf(_("Please contribute if you find %s useful. "
511 "Visit %s for further information about the software."),
512 PACKAGE_NAME, URL_WEBSITE) +
513 "\n" +
514 strprintf(_("The source code is available from %s."),
515 URL_SOURCE_CODE) +
516 "\n" +
517 "\n" +
518 _("This is experimental software.") + "\n" +
519 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
520 "\n" +
521 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>") +
522 "\n";
525 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
527 if (initialSync || !pBlockIndex)
528 return;
530 std::string strCmd = GetArg("-blocknotify", "");
532 boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
533 boost::thread t(runCommand, strCmd); // thread runs free
536 static bool fHaveGenesis = false;
537 static boost::mutex cs_GenesisWait;
538 static CConditionVariable condvar_GenesisWait;
540 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
542 if (pBlockIndex != NULL) {
544 boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
545 fHaveGenesis = true;
547 condvar_GenesisWait.notify_all();
551 struct CImportingNow
553 CImportingNow() {
554 assert(fImporting == false);
555 fImporting = true;
558 ~CImportingNow() {
559 assert(fImporting == true);
560 fImporting = false;
565 // If we're using -prune with -reindex, then delete block files that will be ignored by the
566 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
567 // is missing, do the same here to delete any later block files after a gap. Also delete all
568 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
569 // is in sync with what's actually on disk by the time we start downloading, so that pruning
570 // works correctly.
571 void CleanupBlockRevFiles()
573 std::map<std::string, fs::path> mapBlockFiles;
575 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
576 // Remove the rev files immediately and insert the blk file paths into an
577 // ordered map keyed by block file index.
578 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
579 fs::path blocksdir = GetDataDir() / "blocks";
580 for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
581 if (is_regular_file(*it) &&
582 it->path().filename().string().length() == 12 &&
583 it->path().filename().string().substr(8,4) == ".dat")
585 if (it->path().filename().string().substr(0,3) == "blk")
586 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
587 else if (it->path().filename().string().substr(0,3) == "rev")
588 remove(it->path());
592 // Remove all block files that aren't part of a contiguous set starting at
593 // zero by walking the ordered map (keys are block file indices) by
594 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
595 // start removing block files.
596 int nContigCounter = 0;
597 for (const std::pair<std::string, fs::path>& item : mapBlockFiles) {
598 if (atoi(item.first) == nContigCounter) {
599 nContigCounter++;
600 continue;
602 remove(item.second);
606 void ThreadImport(std::vector<fs::path> vImportFiles)
608 const CChainParams& chainparams = Params();
609 RenameThread("bitcoin-loadblk");
612 CImportingNow imp;
614 // -reindex
615 if (fReindex) {
616 int nFile = 0;
617 while (true) {
618 CDiskBlockPos pos(nFile, 0);
619 if (!fs::exists(GetBlockPosFilename(pos, "blk")))
620 break; // No block files left to reindex
621 FILE *file = OpenBlockFile(pos, true);
622 if (!file)
623 break; // This error is logged in OpenBlockFile
624 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
625 LoadExternalBlockFile(chainparams, file, &pos);
626 nFile++;
628 pblocktree->WriteReindexing(false);
629 fReindex = false;
630 LogPrintf("Reindexing finished\n");
631 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
632 InitBlockIndex(chainparams);
635 // hardcoded $DATADIR/bootstrap.dat
636 fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
637 if (fs::exists(pathBootstrap)) {
638 FILE *file = fsbridge::fopen(pathBootstrap, "rb");
639 if (file) {
640 fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
641 LogPrintf("Importing bootstrap.dat...\n");
642 LoadExternalBlockFile(chainparams, file);
643 RenameOver(pathBootstrap, pathBootstrapOld);
644 } else {
645 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
649 // -loadblock=
650 for (const fs::path& path : vImportFiles) {
651 FILE *file = fsbridge::fopen(path, "rb");
652 if (file) {
653 LogPrintf("Importing blocks file %s...\n", path.string());
654 LoadExternalBlockFile(chainparams, file);
655 } else {
656 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
660 // scan for better chains in the block chain database, that are not yet connected in the active best chain
661 CValidationState state;
662 if (!ActivateBestChain(state, chainparams)) {
663 LogPrintf("Failed to connect best block");
664 StartShutdown();
667 if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
668 LogPrintf("Stopping after block import\n");
669 StartShutdown();
671 } // End scope of CImportingNow
672 if (GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
673 LoadMempool();
674 fDumpMempoolLater = !fRequestShutdown;
678 /** Sanity checks
679 * Ensure that Bitcoin is running in a usable environment with all
680 * necessary library support.
682 bool InitSanityCheck(void)
684 if(!ECC_InitSanityCheck()) {
685 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
686 return false;
689 if (!glibc_sanity_test() || !glibcxx_sanity_test())
690 return false;
692 if (!Random_SanityCheck()) {
693 InitError("OS cryptographic RNG sanity check failure. Aborting.");
694 return false;
697 return true;
700 bool AppInitServers(boost::thread_group& threadGroup)
702 RPCServer::OnStarted(&OnRPCStarted);
703 RPCServer::OnStopped(&OnRPCStopped);
704 RPCServer::OnPreCommand(&OnRPCPreCommand);
705 if (!InitHTTPServer())
706 return false;
707 if (!StartRPC())
708 return false;
709 if (!StartHTTPRPC())
710 return false;
711 if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
712 return false;
713 if (!StartHTTPServer())
714 return false;
715 return true;
718 // Parameter interaction based on rules
719 void InitParameterInteraction()
721 // when specifying an explicit binding address, you want to listen on it
722 // even when -connect or -proxy is specified
723 if (IsArgSet("-bind")) {
724 if (SoftSetBoolArg("-listen", true))
725 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
727 if (IsArgSet("-whitebind")) {
728 if (SoftSetBoolArg("-listen", true))
729 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
732 if (gArgs.IsArgSet("-connect")) {
733 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
734 if (SoftSetBoolArg("-dnsseed", false))
735 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
736 if (SoftSetBoolArg("-listen", false))
737 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
740 if (IsArgSet("-proxy")) {
741 // to protect privacy, do not listen by default if a default proxy server is specified
742 if (SoftSetBoolArg("-listen", false))
743 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
744 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
745 // to listen locally, so don't rely on this happening through -listen below.
746 if (SoftSetBoolArg("-upnp", false))
747 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
748 // to protect privacy, do not discover addresses by default
749 if (SoftSetBoolArg("-discover", false))
750 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
753 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
754 // do not map ports or try to retrieve public IP when not listening (pointless)
755 if (SoftSetBoolArg("-upnp", false))
756 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
757 if (SoftSetBoolArg("-discover", false))
758 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
759 if (SoftSetBoolArg("-listenonion", false))
760 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
763 if (IsArgSet("-externalip")) {
764 // if an explicit public IP is specified, do not try to find others
765 if (SoftSetBoolArg("-discover", false))
766 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
769 // disable whitelistrelay in blocksonly mode
770 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
771 if (SoftSetBoolArg("-whitelistrelay", false))
772 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
775 // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
776 if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
777 if (SoftSetBoolArg("-whitelistrelay", true))
778 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
782 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
784 return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
787 void InitLogging()
789 fPrintToConsole = GetBoolArg("-printtoconsole", false);
790 fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
791 fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
792 fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
794 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
795 LogPrintf("Bitcoin version %s\n", FormatFullVersion());
798 namespace { // Variables internal to initialization process only
800 ServiceFlags nRelevantServices = NODE_NETWORK;
801 int nMaxConnections;
802 int nUserMaxConnections;
803 int nFD;
804 ServiceFlags nLocalServices = NODE_NETWORK;
806 } // namespace
808 [[noreturn]] static void new_handler_terminate()
810 // Rather than throwing std::bad-alloc if allocation fails, terminate
811 // immediately to (try to) avoid chain corruption.
812 // Since LogPrintf may itself allocate memory, set the handler directly
813 // to terminate first.
814 std::set_new_handler(std::terminate);
815 LogPrintf("Error: Out of memory. Terminating.\n");
817 // The log was successful, terminate now.
818 std::terminate();
821 bool AppInitBasicSetup()
823 // ********************************************************* Step 1: setup
824 #ifdef _MSC_VER
825 // Turn off Microsoft heap dump noise
826 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
827 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
828 // Disable confusing "helpful" text message on abort, Ctrl-C
829 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
830 #endif
831 #ifdef WIN32
832 // Enable Data Execution Prevention (DEP)
833 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
834 // A failure is non-critical and needs no further attention!
835 #ifndef PROCESS_DEP_ENABLE
836 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
837 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
838 #define PROCESS_DEP_ENABLE 0x00000001
839 #endif
840 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
841 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
842 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
843 #endif
845 if (!SetupNetworking())
846 return InitError("Initializing networking failed");
848 #ifndef WIN32
849 if (!GetBoolArg("-sysperms", false)) {
850 umask(077);
853 // Clean shutdown on SIGTERM
854 registerSignalHandler(SIGTERM, HandleSIGTERM);
855 registerSignalHandler(SIGINT, HandleSIGTERM);
857 // Reopen debug.log on SIGHUP
858 registerSignalHandler(SIGHUP, HandleSIGHUP);
860 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
861 signal(SIGPIPE, SIG_IGN);
862 #endif
864 std::set_new_handler(new_handler_terminate);
866 return true;
869 bool AppInitParameterInteraction()
871 const CChainParams& chainparams = Params();
872 // ********************************************************* Step 2: parameter interactions
874 // also see: InitParameterInteraction()
876 // if using block pruning, then disallow txindex
877 if (GetArg("-prune", 0)) {
878 if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
879 return InitError(_("Prune mode is incompatible with -txindex."));
882 // -bind and -whitebind can't be set when not listening
883 size_t nUserBind = gArgs.GetArgs("-bind").size() + gArgs.GetArgs("-whitebind").size();
884 if (nUserBind != 0 && !gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
885 return InitError("Cannot set -bind or -whitebind together with -listen=0");
888 // Make sure enough file descriptors are available
889 int nBind = std::max(nUserBind, size_t(1));
890 nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
891 nMaxConnections = std::max(nUserMaxConnections, 0);
893 // Trim requested connection counts, to fit into system limitations
894 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
895 nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
896 if (nFD < MIN_CORE_FILEDESCRIPTORS)
897 return InitError(_("Not enough file descriptors available."));
898 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
900 if (nMaxConnections < nUserMaxConnections)
901 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
903 // ********************************************************* Step 3: parameter-to-internal-flags
904 if (gArgs.IsArgSet("-debug")) {
905 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
906 const std::vector<std::string> categories = gArgs.GetArgs("-debug");
908 if (find(categories.begin(), categories.end(), std::string("0")) == categories.end()) {
909 for (const auto& cat : categories) {
910 uint32_t flag = 0;
911 if (!GetLogCategory(&flag, &cat)) {
912 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
913 continue;
915 logCategories |= flag;
920 // Now remove the logging categories which were explicitly excluded
921 for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
922 uint32_t flag = 0;
923 if (!GetLogCategory(&flag, &cat)) {
924 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
925 continue;
927 logCategories &= ~flag;
930 // Check for -debugnet
931 if (GetBoolArg("-debugnet", false))
932 InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
933 // Check for -socks - as this is a privacy risk to continue, exit here
934 if (IsArgSet("-socks"))
935 return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
936 // Check for -tor - as this is a privacy risk to continue, exit here
937 if (GetBoolArg("-tor", false))
938 return InitError(_("Unsupported argument -tor found, use -onion."));
940 if (GetBoolArg("-benchmark", false))
941 InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
943 if (GetBoolArg("-whitelistalwaysrelay", false))
944 InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
946 if (IsArgSet("-blockminsize"))
947 InitWarning("Unsupported argument -blockminsize ignored.");
949 // Checkmempool and checkblockindex default to true in regtest mode
950 int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
951 if (ratio != 0) {
952 mempool.setSanityCheck(1.0 / ratio);
954 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
955 fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
957 hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
958 if (!hashAssumeValid.IsNull())
959 LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
960 else
961 LogPrintf("Validating signatures for all blocks.\n");
963 // mempool limits
964 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
965 int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
966 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
967 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
968 // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
969 // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
970 if (IsArgSet("-incrementalrelayfee"))
972 CAmount n = 0;
973 if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n))
974 return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", "")));
975 incrementalRelayFee = CFeeRate(n);
978 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
979 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
980 if (nScriptCheckThreads <= 0)
981 nScriptCheckThreads += GetNumCores();
982 if (nScriptCheckThreads <= 1)
983 nScriptCheckThreads = 0;
984 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
985 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
987 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
988 int64_t nPruneArg = GetArg("-prune", 0);
989 if (nPruneArg < 0) {
990 return InitError(_("Prune cannot be configured with a negative value."));
992 nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
993 if (nPruneArg == 1) { // manual pruning: -prune=1
994 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
995 nPruneTarget = std::numeric_limits<uint64_t>::max();
996 fPruneMode = true;
997 } else if (nPruneTarget) {
998 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
999 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1001 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1002 fPruneMode = true;
1005 RegisterAllCoreRPCCommands(tableRPC);
1006 #ifdef ENABLE_WALLET
1007 RegisterWalletRPCCommands(tableRPC);
1008 #endif
1010 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1011 if (nConnectTimeout <= 0)
1012 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1014 if (IsArgSet("-minrelaytxfee")) {
1015 CAmount n = 0;
1016 if (!ParseMoney(GetArg("-minrelaytxfee", ""), n)) {
1017 return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
1019 // High fee check is done afterward in CWallet::ParameterInteraction()
1020 ::minRelayTxFee = CFeeRate(n);
1021 } else if (incrementalRelayFee > ::minRelayTxFee) {
1022 // Allow only setting incrementalRelayFee to control both
1023 ::minRelayTxFee = incrementalRelayFee;
1024 LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1027 // Sanity check argument for min fee for including tx in block
1028 // TODO: Harmonize which arguments need sanity checking and where that happens
1029 if (IsArgSet("-blockmintxfee"))
1031 CAmount n = 0;
1032 if (!ParseMoney(GetArg("-blockmintxfee", ""), n))
1033 return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", "")));
1036 // Feerate used to define dust. Shouldn't be changed lightly as old
1037 // implementations may inadvertently create non-standard transactions
1038 if (IsArgSet("-dustrelayfee"))
1040 CAmount n = 0;
1041 if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n)
1042 return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", "")));
1043 dustRelayFee = CFeeRate(n);
1046 fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1047 if (chainparams.RequireStandard() && !fRequireStandard)
1048 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1049 nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
1051 #ifdef ENABLE_WALLET
1052 if (!CWallet::ParameterInteraction())
1053 return false;
1054 #endif
1056 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1057 fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1058 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1060 // Option to startup with mocktime set (used for regression testing):
1061 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1063 if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1064 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1066 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1067 return InitError("rpcserialversion must be non-negative.");
1069 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1070 return InitError("unknown rpcserialversion requested.");
1072 nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1074 fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1075 if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
1076 // Minimal effort at forwards compatibility
1077 std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
1078 std::vector<std::string> vstrReplacementModes;
1079 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1080 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1083 if (gArgs.IsArgSet("-vbparams")) {
1084 // Allow overriding version bits parameters for testing
1085 if (!chainparams.MineBlocksOnDemand()) {
1086 return InitError("Version bits parameters may only be overridden on regtest.");
1088 for (const std::string& strDeployment : gArgs.GetArgs("-vbparams")) {
1089 std::vector<std::string> vDeploymentParams;
1090 boost::split(vDeploymentParams, strDeployment, boost::is_any_of(":"));
1091 if (vDeploymentParams.size() != 3) {
1092 return InitError("Version bits parameters malformed, expecting deployment:start:end");
1094 int64_t nStartTime, nTimeout;
1095 if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1096 return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1098 if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1099 return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1101 bool found = false;
1102 for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1104 if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1105 UpdateVersionBitsParameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1106 found = true;
1107 LogPrintf("Setting version bits activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1108 break;
1111 if (!found) {
1112 return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1116 return true;
1119 static bool LockDataDirectory(bool probeOnly)
1121 std::string strDataDir = GetDataDir().string();
1123 // Make sure only a single Bitcoin process is using the data directory.
1124 fs::path pathLockFile = GetDataDir() / ".lock";
1125 FILE* file = fsbridge::fopen(pathLockFile, "a"); // empty lock file; created if it doesn't exist.
1126 if (file) fclose(file);
1128 try {
1129 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1130 if (!lock.try_lock()) {
1131 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1133 if (probeOnly) {
1134 lock.unlock();
1136 } catch(const boost::interprocess::interprocess_exception& e) {
1137 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1139 return true;
1142 bool AppInitSanityChecks()
1144 // ********************************************************* Step 4: sanity checks
1146 // Initialize elliptic curve code
1147 RandomInit();
1148 ECC_Start();
1149 globalVerifyHandle.reset(new ECCVerifyHandle());
1151 // Sanity check
1152 if (!InitSanityCheck())
1153 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1155 // Probe the data directory lock to give an early error message, if possible
1156 return LockDataDirectory(true);
1159 bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
1161 const CChainParams& chainparams = Params();
1162 // ********************************************************* Step 4a: application initialization
1163 // After daemonization get the data directory lock again and hold on to it until exit
1164 // This creates a slight window for a race condition to happen, however this condition is harmless: it
1165 // will at most make us exit without printing a message to console.
1166 if (!LockDataDirectory(false)) {
1167 // Detailed error printed inside LockDataDirectory
1168 return false;
1171 #ifndef WIN32
1172 CreatePidFile(GetPidFile(), getpid());
1173 #endif
1174 if (GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
1175 // Do this first since it both loads a bunch of debug.log into memory,
1176 // and because this needs to happen before any other debug.log printing
1177 ShrinkDebugFile();
1180 if (fPrintToDebugLog)
1181 OpenDebugLog();
1183 if (!fLogTimestamps)
1184 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1185 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1186 LogPrintf("Using data directory %s\n", GetDataDir().string());
1187 LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1188 LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1190 InitSignatureCache();
1192 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1193 if (nScriptCheckThreads) {
1194 for (int i=0; i<nScriptCheckThreads-1; i++)
1195 threadGroup.create_thread(&ThreadScriptCheck);
1198 // Start the lightweight task scheduler thread
1199 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1200 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1202 /* Start the RPC server already. It will be started in "warmup" mode
1203 * and not really process calls already (but it will signify connections
1204 * that the server is there and will be ready later). Warmup mode will
1205 * be disabled when initialisation is finished.
1207 if (GetBoolArg("-server", false))
1209 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1210 if (!AppInitServers(threadGroup))
1211 return InitError(_("Unable to start HTTP server. See debug log for details."));
1214 int64_t nStart;
1216 // ********************************************************* Step 5: verify wallet database integrity
1217 #ifdef ENABLE_WALLET
1218 if (!CWallet::Verify())
1219 return false;
1220 #endif
1221 // ********************************************************* Step 6: network initialization
1222 // Note that we absolutely cannot open any actual connections
1223 // until the very end ("start node") as the UTXO/block state
1224 // is not yet setup and may end up being set up twice if we
1225 // need to reindex later.
1227 assert(!g_connman);
1228 g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1229 CConnman& connman = *g_connman;
1231 peerLogic.reset(new PeerLogicValidation(&connman));
1232 RegisterValidationInterface(peerLogic.get());
1233 RegisterNodeSignals(GetNodeSignals());
1235 // sanitize comments per BIP-0014, format user agent and check total size
1236 std::vector<std::string> uacomments;
1237 for (const std::string& cmt : gArgs.GetArgs("-uacomment")) {
1238 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1239 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1240 uacomments.push_back(cmt);
1242 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1243 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1244 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1245 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1248 if (gArgs.IsArgSet("-onlynet")) {
1249 std::set<enum Network> nets;
1250 for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
1251 enum Network net = ParseNetwork(snet);
1252 if (net == NET_UNROUTABLE)
1253 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1254 nets.insert(net);
1256 for (int n = 0; n < NET_MAX; n++) {
1257 enum Network net = (enum Network)n;
1258 if (!nets.count(net))
1259 SetLimited(net);
1263 // Check for host lookup allowed before parsing any network related parameters
1264 fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1266 bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1267 // -proxy sets a proxy for all outgoing network traffic
1268 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1269 std::string proxyArg = GetArg("-proxy", "");
1270 SetLimited(NET_TOR);
1271 if (proxyArg != "" && proxyArg != "0") {
1272 CService proxyAddr;
1273 if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1274 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1277 proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1278 if (!addrProxy.IsValid())
1279 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1281 SetProxy(NET_IPV4, addrProxy);
1282 SetProxy(NET_IPV6, addrProxy);
1283 SetProxy(NET_TOR, addrProxy);
1284 SetNameProxy(addrProxy);
1285 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1288 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1289 // -noonion (or -onion=0) disables connecting to .onion entirely
1290 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1291 std::string onionArg = GetArg("-onion", "");
1292 if (onionArg != "") {
1293 if (onionArg == "0") { // Handle -noonion/-onion=0
1294 SetLimited(NET_TOR); // set onions as unreachable
1295 } else {
1296 CService onionProxy;
1297 if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1298 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1300 proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1301 if (!addrOnion.IsValid())
1302 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1303 SetProxy(NET_TOR, addrOnion);
1304 SetLimited(NET_TOR, false);
1308 // see Step 2: parameter interactions for more information about these
1309 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1310 fDiscover = GetBoolArg("-discover", true);
1311 fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1313 for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
1314 CService addrLocal;
1315 if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1316 AddLocal(addrLocal, LOCAL_MANUAL);
1317 else
1318 return InitError(ResolveErrMsg("externalip", strAddr));
1321 #if ENABLE_ZMQ
1322 pzmqNotificationInterface = CZMQNotificationInterface::Create();
1324 if (pzmqNotificationInterface) {
1325 RegisterValidationInterface(pzmqNotificationInterface);
1327 #endif
1328 uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1329 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1331 if (IsArgSet("-maxuploadtarget")) {
1332 nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1335 // ********************************************************* Step 7: load block chain
1337 fReindex = GetBoolArg("-reindex", false);
1338 bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
1340 // cache size calculations
1341 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1342 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1343 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1344 int64_t nBlockTreeDBCache = nTotalCache / 8;
1345 nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1346 nTotalCache -= nBlockTreeDBCache;
1347 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1348 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1349 nTotalCache -= nCoinDBCache;
1350 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1351 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1352 LogPrintf("Cache configuration:\n");
1353 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1354 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1355 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));
1357 bool fLoaded = false;
1358 while (!fLoaded) {
1359 bool fReset = fReindex;
1360 std::string strLoadError;
1362 uiInterface.InitMessage(_("Loading block index..."));
1364 nStart = GetTimeMillis();
1365 do {
1366 try {
1367 UnloadBlockIndex();
1368 delete pcoinsTip;
1369 delete pcoinsdbview;
1370 delete pcoinscatcher;
1371 delete pblocktree;
1373 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1374 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState);
1375 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1376 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1378 if (fReindex) {
1379 pblocktree->WriteReindexing(true);
1380 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1381 if (fPruneMode)
1382 CleanupBlockRevFiles();
1383 } else {
1384 // If necessary, upgrade from older database format.
1385 if (!pcoinsdbview->Upgrade()) {
1386 strLoadError = _("Error upgrading chainstate database");
1387 break;
1391 if (!LoadBlockIndex(chainparams)) {
1392 strLoadError = _("Error loading block database");
1393 break;
1396 // If the loaded chain has a wrong genesis, bail out immediately
1397 // (we're likely using a testnet datadir, or the other way around).
1398 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1399 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1401 // Initialize the block index (no-op if non-empty database was already loaded)
1402 if (!InitBlockIndex(chainparams)) {
1403 strLoadError = _("Error initializing block database");
1404 break;
1407 // Check for changed -txindex state
1408 if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1409 strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
1410 break;
1413 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1414 // in the past, but is now trying to run unpruned.
1415 if (fHavePruned && !fPruneMode) {
1416 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1417 break;
1420 if (!fReindex && chainActive.Tip() != NULL) {
1421 uiInterface.InitMessage(_("Rewinding blocks..."));
1422 if (!RewindBlockIndex(chainparams)) {
1423 strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1424 break;
1428 uiInterface.InitMessage(_("Verifying blocks..."));
1429 if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1430 LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
1431 MIN_BLOCKS_TO_KEEP);
1435 LOCK(cs_main);
1436 CBlockIndex* tip = chainActive.Tip();
1437 RPCNotifyBlockChange(true, tip);
1438 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1439 strLoadError = _("The block database contains a block which appears to be from the future. "
1440 "This may be due to your computer's date and time being set incorrectly. "
1441 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1442 break;
1446 if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1447 GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1448 strLoadError = _("Corrupted block database detected");
1449 break;
1451 } catch (const std::exception& e) {
1452 LogPrintf("%s\n", e.what());
1453 strLoadError = _("Error opening block database");
1454 break;
1457 fLoaded = true;
1458 } while(false);
1460 if (!fLoaded) {
1461 // first suggest a reindex
1462 if (!fReset) {
1463 bool fRet = uiInterface.ThreadSafeQuestion(
1464 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1465 strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1466 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1467 if (fRet) {
1468 fReindex = true;
1469 fRequestShutdown = false;
1470 } else {
1471 LogPrintf("Aborted block database rebuild. Exiting.\n");
1472 return false;
1474 } else {
1475 return InitError(strLoadError);
1480 // As LoadBlockIndex can take several minutes, it's possible the user
1481 // requested to kill the GUI during the last operation. If so, exit.
1482 // As the program has not fully started yet, Shutdown() is possibly overkill.
1483 if (fRequestShutdown)
1485 LogPrintf("Shutdown requested. Exiting.\n");
1486 return false;
1488 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1490 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1491 CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
1492 // Allowed to fail as this file IS missing on first startup.
1493 if (!est_filein.IsNull())
1494 ::feeEstimator.Read(est_filein);
1495 fFeeEstimatesInitialized = true;
1497 // ********************************************************* Step 8: load wallet
1498 #ifdef ENABLE_WALLET
1499 if (!CWallet::InitLoadWallet())
1500 return false;
1501 #else
1502 LogPrintf("No wallet support compiled in!\n");
1503 #endif
1505 // ********************************************************* Step 9: data directory maintenance
1507 // if pruning, unset the service bit and perform the initial blockstore prune
1508 // after any wallet rescanning has taken place.
1509 if (fPruneMode) {
1510 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1511 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1512 if (!fReindex) {
1513 uiInterface.InitMessage(_("Pruning blockstore..."));
1514 PruneAndFlush();
1518 if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
1519 // Only advertise witness capabilities if they have a reasonable start time.
1520 // This allows us to have the code merged without a defined softfork, by setting its
1521 // end time to 0.
1522 // Note that setting NODE_WITNESS is never required: the only downside from not
1523 // doing so is that after activation, no upgraded nodes will fetch from you.
1524 nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1525 // Only care about others providing witness capabilities if there is a softfork
1526 // defined.
1527 nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS);
1530 // ********************************************************* Step 10: import blocks
1532 if (!CheckDiskSpace())
1533 return false;
1535 // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1536 // No locking, as this happens before any background thread is started.
1537 if (chainActive.Tip() == NULL) {
1538 uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1539 } else {
1540 fHaveGenesis = true;
1543 if (IsArgSet("-blocknotify"))
1544 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1546 std::vector<fs::path> vImportFiles;
1547 for (const std::string& strFile : gArgs.GetArgs("-loadblock")) {
1548 vImportFiles.push_back(strFile);
1551 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1553 // Wait for genesis block to be processed
1555 boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
1556 while (!fHaveGenesis) {
1557 condvar_GenesisWait.wait(lock);
1559 uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1562 // ********************************************************* Step 11: start node
1564 //// debug print
1565 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1566 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1567 if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1568 StartTorControl(threadGroup, scheduler);
1570 Discover(threadGroup);
1572 // Map ports with UPnP
1573 MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
1575 CConnman::Options connOptions;
1576 connOptions.nLocalServices = nLocalServices;
1577 connOptions.nRelevantServices = nRelevantServices;
1578 connOptions.nMaxConnections = nMaxConnections;
1579 connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1580 connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1581 connOptions.nMaxFeeler = 1;
1582 connOptions.nBestHeight = chainActive.Height();
1583 connOptions.uiInterface = &uiInterface;
1584 connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1585 connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1587 connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1588 connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1590 for (const std::string& strBind : gArgs.GetArgs("-bind")) {
1591 CService addrBind;
1592 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) {
1593 return InitError(ResolveErrMsg("bind", strBind));
1595 connOptions.vBinds.push_back(addrBind);
1597 for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
1598 CService addrBind;
1599 if (!Lookup(strBind.c_str(), addrBind, 0, false)) {
1600 return InitError(ResolveErrMsg("whitebind", strBind));
1602 if (addrBind.GetPort() == 0) {
1603 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1605 connOptions.vWhiteBinds.push_back(addrBind);
1608 for (const auto& net : gArgs.GetArgs("-whitelist")) {
1609 CSubNet subnet;
1610 LookupSubNet(net.c_str(), subnet);
1611 if (!subnet.IsValid())
1612 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1613 connOptions.vWhitelistedRange.push_back(subnet);
1616 if (gArgs.IsArgSet("-seednode")) {
1617 connOptions.vSeedNodes = gArgs.GetArgs("-seednode");
1620 if (!connman.Start(scheduler, connOptions)) {
1621 return false;
1624 // ********************************************************* Step 12: finished
1626 SetRPCWarmupFinished();
1627 uiInterface.InitMessage(_("Done loading"));
1629 #ifdef ENABLE_WALLET
1630 for (CWalletRef pwallet : vpwallets) {
1631 pwallet->postInitProcess(scheduler);
1633 #endif
1635 return !fRequestShutdown;