Merge #10502: scripted-diff: Remove BOOST_FOREACH, Q_FOREACH and PAIRTYPE
[bitcoinplatinum.git] / src / init.cpp
blobb6e4cd06f6627a428b11da01a84565844de29a48
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 /** Used to pass flags to the Bind() function */
92 enum BindFlags {
93 BF_NONE = 0,
94 BF_EXPLICIT = (1U << 0),
95 BF_REPORT_ERROR = (1U << 1),
96 BF_WHITELIST = (1U << 2),
99 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
101 //////////////////////////////////////////////////////////////////////////////
103 // Shutdown
107 // Thread management and startup/shutdown:
109 // The network-processing threads are all part of a thread group
110 // created by AppInit() or the Qt main() function.
112 // A clean exit happens when StartShutdown() or the SIGTERM
113 // signal handler sets fRequestShutdown, which triggers
114 // the DetectShutdownThread(), which interrupts the main thread group.
115 // DetectShutdownThread() then exits, which causes AppInit() to
116 // continue (it .joins the shutdown thread).
117 // Shutdown() is then
118 // called to clean up database connections, and stop other
119 // threads that should only be stopped after the main network-processing
120 // threads have exited.
122 // Shutdown for Qt is very similar, only it uses a QTimer to detect
123 // fRequestShutdown getting set, and then does the normal Qt
124 // shutdown thing.
127 std::atomic<bool> fRequestShutdown(false);
128 std::atomic<bool> fDumpMempoolLater(false);
130 void StartShutdown()
132 fRequestShutdown = true;
134 bool ShutdownRequested()
136 return fRequestShutdown;
140 * This is a minimally invasive approach to shutdown on LevelDB read errors from the
141 * chainstate, while keeping user interface out of the common library, which is shared
142 * between bitcoind, and bitcoin-qt and non-server tools.
144 class CCoinsViewErrorCatcher : public CCoinsViewBacked
146 public:
147 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
148 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override {
149 try {
150 return CCoinsViewBacked::GetCoin(outpoint, coin);
151 } catch(const std::runtime_error& e) {
152 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
153 LogPrintf("Error reading from database: %s\n", e.what());
154 // Starting the shutdown sequence and returning false to the caller would be
155 // interpreted as 'entry not found' (as opposed to unable to read data), and
156 // could lead to invalid interpretation. Just exit immediately, as we can't
157 // continue anyway, and all writes should be atomic.
158 abort();
161 // Writes do not need similar protection, as failure to write is handled by the caller.
164 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
165 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
167 void Interrupt(boost::thread_group& threadGroup)
169 InterruptHTTPServer();
170 InterruptHTTPRPC();
171 InterruptRPC();
172 InterruptREST();
173 InterruptTorControl();
174 if (g_connman)
175 g_connman->Interrupt();
176 threadGroup.interrupt_all();
179 void Shutdown()
181 LogPrintf("%s: In progress...\n", __func__);
182 static CCriticalSection cs_Shutdown;
183 TRY_LOCK(cs_Shutdown, lockShutdown);
184 if (!lockShutdown)
185 return;
187 /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
188 /// for example if the data directory was found to be locked.
189 /// Be sure that anything that writes files or flushes caches only does this if the respective
190 /// module was initialized.
191 RenameThread("bitcoin-shutoff");
192 mempool.AddTransactionsUpdated(1);
194 StopHTTPRPC();
195 StopREST();
196 StopRPC();
197 StopHTTPServer();
198 #ifdef ENABLE_WALLET
199 for (CWalletRef pwallet : vpwallets) {
200 pwallet->Flush(false);
202 #endif
203 MapPort(false);
204 UnregisterValidationInterface(peerLogic.get());
205 peerLogic.reset();
206 g_connman.reset();
208 StopTorControl();
209 UnregisterNodeSignals(GetNodeSignals());
210 if (fDumpMempoolLater && GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
211 DumpMempool();
214 if (fFeeEstimatesInitialized)
216 ::feeEstimator.FlushUnconfirmed(::mempool);
217 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
218 CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
219 if (!est_fileout.IsNull())
220 ::feeEstimator.Write(est_fileout);
221 else
222 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
223 fFeeEstimatesInitialized = false;
227 LOCK(cs_main);
228 if (pcoinsTip != NULL) {
229 FlushStateToDisk();
231 delete pcoinsTip;
232 pcoinsTip = NULL;
233 delete pcoinscatcher;
234 pcoinscatcher = NULL;
235 delete pcoinsdbview;
236 pcoinsdbview = NULL;
237 delete pblocktree;
238 pblocktree = NULL;
240 #ifdef ENABLE_WALLET
241 for (CWalletRef pwallet : vpwallets) {
242 pwallet->Flush(true);
244 #endif
246 #if ENABLE_ZMQ
247 if (pzmqNotificationInterface) {
248 UnregisterValidationInterface(pzmqNotificationInterface);
249 delete pzmqNotificationInterface;
250 pzmqNotificationInterface = NULL;
252 #endif
254 #ifndef WIN32
255 try {
256 fs::remove(GetPidFile());
257 } catch (const fs::filesystem_error& e) {
258 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
260 #endif
261 UnregisterAllValidationInterfaces();
262 #ifdef ENABLE_WALLET
263 for (CWalletRef pwallet : vpwallets) {
264 delete pwallet;
266 vpwallets.clear();
267 #endif
268 globalVerifyHandle.reset();
269 ECC_Stop();
270 LogPrintf("%s: done\n", __func__);
274 * Signal handlers are very limited in what they are allowed to do.
275 * The execution context the handler is invoked in is not guaranteed,
276 * so we restrict handler operations to just touching variables:
278 static void HandleSIGTERM(int)
280 fRequestShutdown = true;
283 static void HandleSIGHUP(int)
285 fReopenDebugLog = true;
288 #ifndef WIN32
289 static void registerSignalHandler(int signal, void(*handler)(int))
291 struct sigaction sa;
292 sa.sa_handler = handler;
293 sigemptyset(&sa.sa_mask);
294 sa.sa_flags = 0;
295 sigaction(signal, &sa, NULL);
297 #endif
299 bool static Bind(CConnman& connman, const CService &addr, unsigned int flags) {
300 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
301 return false;
302 std::string strError;
303 if (!connman.BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
304 if (flags & BF_REPORT_ERROR)
305 return InitError(strError);
306 return false;
308 return true;
310 void OnRPCStarted()
312 uiInterface.NotifyBlockTip.connect(&RPCNotifyBlockChange);
315 void OnRPCStopped()
317 uiInterface.NotifyBlockTip.disconnect(&RPCNotifyBlockChange);
318 RPCNotifyBlockChange(false, nullptr);
319 cvBlockChange.notify_all();
320 LogPrint(BCLog::RPC, "RPC stopped.\n");
323 void OnRPCPreCommand(const CRPCCommand& cmd)
325 // Observe safe mode
326 std::string strWarning = GetWarnings("rpc");
327 if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
328 !cmd.okSafeMode)
329 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
332 std::string HelpMessage(HelpMessageMode mode)
334 const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
335 const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
336 const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
337 const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET);
338 const bool showDebug = GetBoolArg("-help-debug", false);
340 // When adding new options to the categories, please keep and ensure alphabetical ordering.
341 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
342 std::string strUsage = HelpMessageGroup(_("Options:"));
343 strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
344 strUsage += HelpMessageOpt("-version", _("Print version and exit"));
345 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)"));
346 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
347 if (showDebug)
348 strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
349 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()));
350 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
351 if (mode == HMM_BITCOIND)
353 #if HAVE_DECL_DAEMON
354 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
355 #endif
357 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
358 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
359 if (showDebug)
360 strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
361 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
362 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
363 strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
364 strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
365 strUsage += HelpMessageOpt("-persistmempool", strprintf(_("Whether to save the mempool on shutdown and load on restart (default: %u)"), DEFAULT_PERSIST_MEMPOOL));
366 strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
367 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)"),
368 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
369 #ifndef WIN32
370 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
371 #endif
372 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. "
373 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
374 "(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));
375 strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
376 strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
377 #ifndef WIN32
378 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
379 #endif
380 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
382 strUsage += HelpMessageGroup(_("Connection options:"));
383 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
384 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
385 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
386 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
387 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -connect=0 disables automatic connections"));
388 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
389 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
390 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)"));
391 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
392 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
393 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
394 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
395 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
396 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
397 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
398 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));
399 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
400 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
401 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
402 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
403 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort()));
404 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
405 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
406 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
407 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
408 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
409 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
410 #ifdef USE_UPNP
411 #if USE_UPNP
412 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
413 #else
414 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
415 #endif
416 #endif
417 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
418 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.") +
419 " " + _("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"));
420 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));
422 #ifdef ENABLE_WALLET
423 strUsage += CWallet::GetWalletHelpString(showDebug);
424 #endif
426 #if ENABLE_ZMQ
427 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
428 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
429 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
430 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
431 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
432 #endif
434 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
435 strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
436 if (showDebug)
438 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
439 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
440 strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
441 strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
442 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
443 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
444 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
445 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
446 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
447 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
448 strUsage += HelpMessageOpt("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT));
450 strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
451 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));
452 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));
453 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));
454 strUsage += HelpMessageOpt("-vbparams=deployment:start:end", "Use given start/end times for specified version bits deployment (regtest-only)");
456 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
457 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + ListLogCategories() + ".");
458 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.")));
459 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
460 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
461 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
462 if (showDebug)
464 strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
465 strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
466 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
467 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
469 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)"),
470 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
471 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
472 if (showDebug)
474 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
476 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
478 AppendParamsHelpMessages(strUsage, showDebug);
480 strUsage += HelpMessageGroup(_("Node relay options:"));
481 if (showDebug) {
482 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", defaultChainParams->RequireStandard()));
483 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)));
484 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)));
486 strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
487 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
488 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
489 strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
490 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
491 CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
492 strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
493 strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
495 strUsage += HelpMessageGroup(_("Block creation options:"));
496 strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
497 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
498 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)));
499 if (showDebug)
500 strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
502 strUsage += HelpMessageGroup(_("RPC server options:"));
503 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
504 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
505 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)"));
506 strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
507 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
508 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
509 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"));
510 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
511 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"));
512 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));
513 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
514 if (showDebug) {
515 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
516 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
519 return strUsage;
522 std::string LicenseInfo()
524 const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
525 const std::string URL_WEBSITE = "<https://bitcoincore.org>";
527 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
528 "\n" +
529 strprintf(_("Please contribute if you find %s useful. "
530 "Visit %s for further information about the software."),
531 PACKAGE_NAME, URL_WEBSITE) +
532 "\n" +
533 strprintf(_("The source code is available from %s."),
534 URL_SOURCE_CODE) +
535 "\n" +
536 "\n" +
537 _("This is experimental software.") + "\n" +
538 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
539 "\n" +
540 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>") +
541 "\n";
544 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
546 if (initialSync || !pBlockIndex)
547 return;
549 std::string strCmd = GetArg("-blocknotify", "");
551 boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
552 boost::thread t(runCommand, strCmd); // thread runs free
555 static bool fHaveGenesis = false;
556 static boost::mutex cs_GenesisWait;
557 static CConditionVariable condvar_GenesisWait;
559 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
561 if (pBlockIndex != NULL) {
563 boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
564 fHaveGenesis = true;
566 condvar_GenesisWait.notify_all();
570 struct CImportingNow
572 CImportingNow() {
573 assert(fImporting == false);
574 fImporting = true;
577 ~CImportingNow() {
578 assert(fImporting == true);
579 fImporting = false;
584 // If we're using -prune with -reindex, then delete block files that will be ignored by the
585 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
586 // is missing, do the same here to delete any later block files after a gap. Also delete all
587 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
588 // is in sync with what's actually on disk by the time we start downloading, so that pruning
589 // works correctly.
590 void CleanupBlockRevFiles()
592 std::map<std::string, fs::path> mapBlockFiles;
594 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
595 // Remove the rev files immediately and insert the blk file paths into an
596 // ordered map keyed by block file index.
597 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
598 fs::path blocksdir = GetDataDir() / "blocks";
599 for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
600 if (is_regular_file(*it) &&
601 it->path().filename().string().length() == 12 &&
602 it->path().filename().string().substr(8,4) == ".dat")
604 if (it->path().filename().string().substr(0,3) == "blk")
605 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
606 else if (it->path().filename().string().substr(0,3) == "rev")
607 remove(it->path());
611 // Remove all block files that aren't part of a contiguous set starting at
612 // zero by walking the ordered map (keys are block file indices) by
613 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
614 // start removing block files.
615 int nContigCounter = 0;
616 for (const std::pair<std::string, fs::path>& item : mapBlockFiles) {
617 if (atoi(item.first) == nContigCounter) {
618 nContigCounter++;
619 continue;
621 remove(item.second);
625 void ThreadImport(std::vector<fs::path> vImportFiles)
627 const CChainParams& chainparams = Params();
628 RenameThread("bitcoin-loadblk");
631 CImportingNow imp;
633 // -reindex
634 if (fReindex) {
635 int nFile = 0;
636 while (true) {
637 CDiskBlockPos pos(nFile, 0);
638 if (!fs::exists(GetBlockPosFilename(pos, "blk")))
639 break; // No block files left to reindex
640 FILE *file = OpenBlockFile(pos, true);
641 if (!file)
642 break; // This error is logged in OpenBlockFile
643 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
644 LoadExternalBlockFile(chainparams, file, &pos);
645 nFile++;
647 pblocktree->WriteReindexing(false);
648 fReindex = false;
649 LogPrintf("Reindexing finished\n");
650 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
651 InitBlockIndex(chainparams);
654 // hardcoded $DATADIR/bootstrap.dat
655 fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
656 if (fs::exists(pathBootstrap)) {
657 FILE *file = fsbridge::fopen(pathBootstrap, "rb");
658 if (file) {
659 fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
660 LogPrintf("Importing bootstrap.dat...\n");
661 LoadExternalBlockFile(chainparams, file);
662 RenameOver(pathBootstrap, pathBootstrapOld);
663 } else {
664 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
668 // -loadblock=
669 for (const fs::path& path : vImportFiles) {
670 FILE *file = fsbridge::fopen(path, "rb");
671 if (file) {
672 LogPrintf("Importing blocks file %s...\n", path.string());
673 LoadExternalBlockFile(chainparams, file);
674 } else {
675 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
679 // scan for better chains in the block chain database, that are not yet connected in the active best chain
680 CValidationState state;
681 if (!ActivateBestChain(state, chainparams)) {
682 LogPrintf("Failed to connect best block");
683 StartShutdown();
686 if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
687 LogPrintf("Stopping after block import\n");
688 StartShutdown();
690 } // End scope of CImportingNow
691 if (GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
692 LoadMempool();
693 fDumpMempoolLater = !fRequestShutdown;
697 /** Sanity checks
698 * Ensure that Bitcoin is running in a usable environment with all
699 * necessary library support.
701 bool InitSanityCheck(void)
703 if(!ECC_InitSanityCheck()) {
704 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
705 return false;
708 if (!glibc_sanity_test() || !glibcxx_sanity_test())
709 return false;
711 if (!Random_SanityCheck()) {
712 InitError("OS cryptographic RNG sanity check failure. Aborting.");
713 return false;
716 return true;
719 bool AppInitServers(boost::thread_group& threadGroup)
721 RPCServer::OnStarted(&OnRPCStarted);
722 RPCServer::OnStopped(&OnRPCStopped);
723 RPCServer::OnPreCommand(&OnRPCPreCommand);
724 if (!InitHTTPServer())
725 return false;
726 if (!StartRPC())
727 return false;
728 if (!StartHTTPRPC())
729 return false;
730 if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
731 return false;
732 if (!StartHTTPServer())
733 return false;
734 return true;
737 // Parameter interaction based on rules
738 void InitParameterInteraction()
740 // when specifying an explicit binding address, you want to listen on it
741 // even when -connect or -proxy is specified
742 if (IsArgSet("-bind")) {
743 if (SoftSetBoolArg("-listen", true))
744 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
746 if (IsArgSet("-whitebind")) {
747 if (SoftSetBoolArg("-listen", true))
748 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
751 if (gArgs.IsArgSet("-connect")) {
752 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
753 if (SoftSetBoolArg("-dnsseed", false))
754 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
755 if (SoftSetBoolArg("-listen", false))
756 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
759 if (IsArgSet("-proxy")) {
760 // to protect privacy, do not listen by default if a default proxy server is specified
761 if (SoftSetBoolArg("-listen", false))
762 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
763 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
764 // to listen locally, so don't rely on this happening through -listen below.
765 if (SoftSetBoolArg("-upnp", false))
766 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
767 // to protect privacy, do not discover addresses by default
768 if (SoftSetBoolArg("-discover", false))
769 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
772 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
773 // do not map ports or try to retrieve public IP when not listening (pointless)
774 if (SoftSetBoolArg("-upnp", false))
775 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
776 if (SoftSetBoolArg("-discover", false))
777 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
778 if (SoftSetBoolArg("-listenonion", false))
779 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
782 if (IsArgSet("-externalip")) {
783 // if an explicit public IP is specified, do not try to find others
784 if (SoftSetBoolArg("-discover", false))
785 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
788 // disable whitelistrelay in blocksonly mode
789 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
790 if (SoftSetBoolArg("-whitelistrelay", false))
791 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
794 // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
795 if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
796 if (SoftSetBoolArg("-whitelistrelay", true))
797 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
801 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
803 return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
806 void InitLogging()
808 fPrintToConsole = GetBoolArg("-printtoconsole", false);
809 fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
810 fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
811 fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
813 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
814 LogPrintf("Bitcoin version %s\n", FormatFullVersion());
817 namespace { // Variables internal to initialization process only
819 ServiceFlags nRelevantServices = NODE_NETWORK;
820 int nMaxConnections;
821 int nUserMaxConnections;
822 int nFD;
823 ServiceFlags nLocalServices = NODE_NETWORK;
827 [[noreturn]] static void new_handler_terminate()
829 // Rather than throwing std::bad-alloc if allocation fails, terminate
830 // immediately to (try to) avoid chain corruption.
831 // Since LogPrintf may itself allocate memory, set the handler directly
832 // to terminate first.
833 std::set_new_handler(std::terminate);
834 LogPrintf("Error: Out of memory. Terminating.\n");
836 // The log was successful, terminate now.
837 std::terminate();
840 bool AppInitBasicSetup()
842 // ********************************************************* Step 1: setup
843 #ifdef _MSC_VER
844 // Turn off Microsoft heap dump noise
845 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
846 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
847 #endif
848 #if _MSC_VER >= 1400
849 // Disable confusing "helpful" text message on abort, Ctrl-C
850 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
851 #endif
852 #ifdef WIN32
853 // Enable Data Execution Prevention (DEP)
854 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
855 // A failure is non-critical and needs no further attention!
856 #ifndef PROCESS_DEP_ENABLE
857 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
858 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
859 #define PROCESS_DEP_ENABLE 0x00000001
860 #endif
861 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
862 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
863 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
864 #endif
866 if (!SetupNetworking())
867 return InitError("Initializing networking failed");
869 #ifndef WIN32
870 if (!GetBoolArg("-sysperms", false)) {
871 umask(077);
874 // Clean shutdown on SIGTERM
875 registerSignalHandler(SIGTERM, HandleSIGTERM);
876 registerSignalHandler(SIGINT, HandleSIGTERM);
878 // Reopen debug.log on SIGHUP
879 registerSignalHandler(SIGHUP, HandleSIGHUP);
881 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
882 signal(SIGPIPE, SIG_IGN);
883 #endif
885 std::set_new_handler(new_handler_terminate);
887 return true;
890 bool AppInitParameterInteraction()
892 const CChainParams& chainparams = Params();
893 // ********************************************************* Step 2: parameter interactions
895 // also see: InitParameterInteraction()
897 // if using block pruning, then disallow txindex
898 if (GetArg("-prune", 0)) {
899 if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
900 return InitError(_("Prune mode is incompatible with -txindex."));
903 // Make sure enough file descriptors are available
904 int nBind = std::max(
905 (gArgs.IsArgSet("-bind") ? gArgs.GetArgs("-bind").size() : 0) +
906 (gArgs.IsArgSet("-whitebind") ? gArgs.GetArgs("-whitebind").size() : 0), size_t(1));
907 nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
908 nMaxConnections = std::max(nUserMaxConnections, 0);
910 // Trim requested connection counts, to fit into system limitations
911 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
912 nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
913 if (nFD < MIN_CORE_FILEDESCRIPTORS)
914 return InitError(_("Not enough file descriptors available."));
915 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
917 if (nMaxConnections < nUserMaxConnections)
918 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
920 // ********************************************************* Step 3: parameter-to-internal-flags
921 if (gArgs.IsArgSet("-debug")) {
922 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
923 const std::vector<std::string> categories = gArgs.GetArgs("-debug");
925 if (find(categories.begin(), categories.end(), std::string("0")) == categories.end()) {
926 for (const auto& cat : categories) {
927 uint32_t flag = 0;
928 if (!GetLogCategory(&flag, &cat)) {
929 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
930 continue;
932 logCategories |= flag;
937 // Now remove the logging categories which were explicitly excluded
938 if (gArgs.IsArgSet("-debugexclude")) {
939 for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
940 uint32_t flag = 0;
941 if (!GetLogCategory(&flag, &cat)) {
942 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
943 continue;
945 logCategories &= ~flag;
949 // Check for -debugnet
950 if (GetBoolArg("-debugnet", false))
951 InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
952 // Check for -socks - as this is a privacy risk to continue, exit here
953 if (IsArgSet("-socks"))
954 return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
955 // Check for -tor - as this is a privacy risk to continue, exit here
956 if (GetBoolArg("-tor", false))
957 return InitError(_("Unsupported argument -tor found, use -onion."));
959 if (GetBoolArg("-benchmark", false))
960 InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
962 if (GetBoolArg("-whitelistalwaysrelay", false))
963 InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
965 if (IsArgSet("-blockminsize"))
966 InitWarning("Unsupported argument -blockminsize ignored.");
968 // Checkmempool and checkblockindex default to true in regtest mode
969 int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
970 if (ratio != 0) {
971 mempool.setSanityCheck(1.0 / ratio);
973 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
974 fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
976 hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
977 if (!hashAssumeValid.IsNull())
978 LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
979 else
980 LogPrintf("Validating signatures for all blocks.\n");
982 // mempool limits
983 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
984 int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
985 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
986 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
987 // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
988 // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
989 if (IsArgSet("-incrementalrelayfee"))
991 CAmount n = 0;
992 if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n))
993 return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", "")));
994 incrementalRelayFee = CFeeRate(n);
997 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
998 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
999 if (nScriptCheckThreads <= 0)
1000 nScriptCheckThreads += GetNumCores();
1001 if (nScriptCheckThreads <= 1)
1002 nScriptCheckThreads = 0;
1003 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
1004 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
1006 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
1007 int64_t nPruneArg = GetArg("-prune", 0);
1008 if (nPruneArg < 0) {
1009 return InitError(_("Prune cannot be configured with a negative value."));
1011 nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
1012 if (nPruneArg == 1) { // manual pruning: -prune=1
1013 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1014 nPruneTarget = std::numeric_limits<uint64_t>::max();
1015 fPruneMode = true;
1016 } else if (nPruneTarget) {
1017 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
1018 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1020 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1021 fPruneMode = true;
1024 RegisterAllCoreRPCCommands(tableRPC);
1025 #ifdef ENABLE_WALLET
1026 RegisterWalletRPCCommands(tableRPC);
1027 #endif
1029 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1030 if (nConnectTimeout <= 0)
1031 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1033 // Fee-per-kilobyte amount required for mempool acceptance and relay
1034 // If you are mining, be careful setting this:
1035 // if you set it to zero then
1036 // a transaction spammer can cheaply fill blocks using
1037 // 0-fee transactions. It should be set above the real
1038 // cost to you of processing a transaction.
1039 if (IsArgSet("-minrelaytxfee"))
1041 CAmount n = 0;
1042 if (!ParseMoney(GetArg("-minrelaytxfee", ""), n)) {
1043 return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
1045 // High fee check is done afterward in CWallet::ParameterInteraction()
1046 ::minRelayTxFee = CFeeRate(n);
1047 } else if (incrementalRelayFee > ::minRelayTxFee) {
1048 // Allow only setting incrementalRelayFee to control both
1049 ::minRelayTxFee = incrementalRelayFee;
1050 LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1053 // Sanity check argument for min fee for including tx in block
1054 // TODO: Harmonize which arguments need sanity checking and where that happens
1055 if (IsArgSet("-blockmintxfee"))
1057 CAmount n = 0;
1058 if (!ParseMoney(GetArg("-blockmintxfee", ""), n))
1059 return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", "")));
1062 // Feerate used to define dust. Shouldn't be changed lightly as old
1063 // implementations may inadvertently create non-standard transactions
1064 if (IsArgSet("-dustrelayfee"))
1066 CAmount n = 0;
1067 if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n)
1068 return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", "")));
1069 dustRelayFee = CFeeRate(n);
1072 fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1073 if (chainparams.RequireStandard() && !fRequireStandard)
1074 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1075 nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
1077 #ifdef ENABLE_WALLET
1078 if (!CWallet::ParameterInteraction())
1079 return false;
1080 #endif
1082 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1083 fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1084 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1086 // Option to startup with mocktime set (used for regression testing):
1087 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1089 if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1090 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1092 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1093 return InitError("rpcserialversion must be non-negative.");
1095 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1096 return InitError("unknown rpcserialversion requested.");
1098 nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1100 fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1101 if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
1102 // Minimal effort at forwards compatibility
1103 std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
1104 std::vector<std::string> vstrReplacementModes;
1105 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1106 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1109 if (gArgs.IsArgSet("-vbparams")) {
1110 // Allow overriding version bits parameters for testing
1111 if (!chainparams.MineBlocksOnDemand()) {
1112 return InitError("Version bits parameters may only be overridden on regtest.");
1114 for (const std::string& strDeployment : gArgs.GetArgs("-vbparams")) {
1115 std::vector<std::string> vDeploymentParams;
1116 boost::split(vDeploymentParams, strDeployment, boost::is_any_of(":"));
1117 if (vDeploymentParams.size() != 3) {
1118 return InitError("Version bits parameters malformed, expecting deployment:start:end");
1120 int64_t nStartTime, nTimeout;
1121 if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1122 return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1124 if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1125 return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1127 bool found = false;
1128 for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1130 if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1131 UpdateVersionBitsParameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1132 found = true;
1133 LogPrintf("Setting version bits activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1134 break;
1137 if (!found) {
1138 return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1142 return true;
1145 static bool LockDataDirectory(bool probeOnly)
1147 std::string strDataDir = GetDataDir().string();
1149 // Make sure only a single Bitcoin process is using the data directory.
1150 fs::path pathLockFile = GetDataDir() / ".lock";
1151 FILE* file = fsbridge::fopen(pathLockFile, "a"); // empty lock file; created if it doesn't exist.
1152 if (file) fclose(file);
1154 try {
1155 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1156 if (!lock.try_lock()) {
1157 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1159 if (probeOnly) {
1160 lock.unlock();
1162 } catch(const boost::interprocess::interprocess_exception& e) {
1163 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1165 return true;
1168 bool AppInitSanityChecks()
1170 // ********************************************************* Step 4: sanity checks
1172 // Initialize elliptic curve code
1173 ECC_Start();
1174 globalVerifyHandle.reset(new ECCVerifyHandle());
1176 // Sanity check
1177 if (!InitSanityCheck())
1178 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1180 // Probe the data directory lock to give an early error message, if possible
1181 return LockDataDirectory(true);
1184 bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
1186 const CChainParams& chainparams = Params();
1187 // ********************************************************* Step 4a: application initialization
1188 // After daemonization get the data directory lock again and hold on to it until exit
1189 // This creates a slight window for a race condition to happen, however this condition is harmless: it
1190 // will at most make us exit without printing a message to console.
1191 if (!LockDataDirectory(false)) {
1192 // Detailed error printed inside LockDataDirectory
1193 return false;
1196 #ifndef WIN32
1197 CreatePidFile(GetPidFile(), getpid());
1198 #endif
1199 if (GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
1200 // Do this first since it both loads a bunch of debug.log into memory,
1201 // and because this needs to happen before any other debug.log printing
1202 ShrinkDebugFile();
1205 if (fPrintToDebugLog)
1206 OpenDebugLog();
1208 if (!fLogTimestamps)
1209 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1210 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1211 LogPrintf("Using data directory %s\n", GetDataDir().string());
1212 LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1213 LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1215 InitSignatureCache();
1217 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1218 if (nScriptCheckThreads) {
1219 for (int i=0; i<nScriptCheckThreads-1; i++)
1220 threadGroup.create_thread(&ThreadScriptCheck);
1223 // Start the lightweight task scheduler thread
1224 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1225 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1227 /* Start the RPC server already. It will be started in "warmup" mode
1228 * and not really process calls already (but it will signify connections
1229 * that the server is there and will be ready later). Warmup mode will
1230 * be disabled when initialisation is finished.
1232 if (GetBoolArg("-server", false))
1234 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1235 if (!AppInitServers(threadGroup))
1236 return InitError(_("Unable to start HTTP server. See debug log for details."));
1239 int64_t nStart;
1241 // ********************************************************* Step 5: verify wallet database integrity
1242 #ifdef ENABLE_WALLET
1243 if (!CWallet::Verify())
1244 return false;
1245 #endif
1246 // ********************************************************* Step 6: network initialization
1247 // Note that we absolutely cannot open any actual connections
1248 // until the very end ("start node") as the UTXO/block state
1249 // is not yet setup and may end up being set up twice if we
1250 // need to reindex later.
1252 assert(!g_connman);
1253 g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1254 CConnman& connman = *g_connman;
1256 peerLogic.reset(new PeerLogicValidation(&connman));
1257 RegisterValidationInterface(peerLogic.get());
1258 RegisterNodeSignals(GetNodeSignals());
1260 // sanitize comments per BIP-0014, format user agent and check total size
1261 std::vector<std::string> uacomments;
1262 if (gArgs.IsArgSet("-uacomment")) {
1263 for (std::string cmt : gArgs.GetArgs("-uacomment"))
1265 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1266 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1267 uacomments.push_back(cmt);
1270 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1271 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1272 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1273 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1276 if (gArgs.IsArgSet("-onlynet")) {
1277 std::set<enum Network> nets;
1278 for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
1279 enum Network net = ParseNetwork(snet);
1280 if (net == NET_UNROUTABLE)
1281 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1282 nets.insert(net);
1284 for (int n = 0; n < NET_MAX; n++) {
1285 enum Network net = (enum Network)n;
1286 if (!nets.count(net))
1287 SetLimited(net);
1291 if (gArgs.IsArgSet("-whitelist")) {
1292 for (const std::string& net : gArgs.GetArgs("-whitelist")) {
1293 CSubNet subnet;
1294 LookupSubNet(net.c_str(), subnet);
1295 if (!subnet.IsValid())
1296 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1297 connman.AddWhitelistedRange(subnet);
1301 // Check for host lookup allowed before parsing any network related parameters
1302 fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1304 bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1305 // -proxy sets a proxy for all outgoing network traffic
1306 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1307 std::string proxyArg = GetArg("-proxy", "");
1308 SetLimited(NET_TOR);
1309 if (proxyArg != "" && proxyArg != "0") {
1310 CService proxyAddr;
1311 if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1312 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1315 proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1316 if (!addrProxy.IsValid())
1317 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1319 SetProxy(NET_IPV4, addrProxy);
1320 SetProxy(NET_IPV6, addrProxy);
1321 SetProxy(NET_TOR, addrProxy);
1322 SetNameProxy(addrProxy);
1323 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1326 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1327 // -noonion (or -onion=0) disables connecting to .onion entirely
1328 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1329 std::string onionArg = GetArg("-onion", "");
1330 if (onionArg != "") {
1331 if (onionArg == "0") { // Handle -noonion/-onion=0
1332 SetLimited(NET_TOR); // set onions as unreachable
1333 } else {
1334 CService onionProxy;
1335 if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1336 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1338 proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1339 if (!addrOnion.IsValid())
1340 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1341 SetProxy(NET_TOR, addrOnion);
1342 SetLimited(NET_TOR, false);
1346 // see Step 2: parameter interactions for more information about these
1347 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1348 fDiscover = GetBoolArg("-discover", true);
1349 fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1351 if (fListen) {
1352 bool fBound = false;
1353 if (gArgs.IsArgSet("-bind")) {
1354 for (const std::string& strBind : gArgs.GetArgs("-bind")) {
1355 CService addrBind;
1356 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1357 return InitError(ResolveErrMsg("bind", strBind));
1358 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1361 if (gArgs.IsArgSet("-whitebind")) {
1362 for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
1363 CService addrBind;
1364 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1365 return InitError(ResolveErrMsg("whitebind", strBind));
1366 if (addrBind.GetPort() == 0)
1367 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1368 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1371 if (!gArgs.IsArgSet("-bind") && !gArgs.IsArgSet("-whitebind")) {
1372 struct in_addr inaddr_any;
1373 inaddr_any.s_addr = INADDR_ANY;
1374 fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
1375 fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1377 if (!fBound)
1378 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1381 if (gArgs.IsArgSet("-externalip")) {
1382 for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
1383 CService addrLocal;
1384 if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1385 AddLocal(addrLocal, LOCAL_MANUAL);
1386 else
1387 return InitError(ResolveErrMsg("externalip", strAddr));
1391 #if ENABLE_ZMQ
1392 pzmqNotificationInterface = CZMQNotificationInterface::Create();
1394 if (pzmqNotificationInterface) {
1395 RegisterValidationInterface(pzmqNotificationInterface);
1397 #endif
1398 uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1399 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1401 if (IsArgSet("-maxuploadtarget")) {
1402 nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1405 // ********************************************************* Step 7: load block chain
1407 fReindex = GetBoolArg("-reindex", false);
1408 bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
1410 fs::create_directories(GetDataDir() / "blocks");
1412 // cache size calculations
1413 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1414 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1415 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1416 int64_t nBlockTreeDBCache = nTotalCache / 8;
1417 nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1418 nTotalCache -= nBlockTreeDBCache;
1419 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1420 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1421 nTotalCache -= nCoinDBCache;
1422 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1423 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1424 LogPrintf("Cache configuration:\n");
1425 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1426 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1427 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));
1429 bool fLoaded = false;
1430 while (!fLoaded) {
1431 bool fReset = fReindex;
1432 std::string strLoadError;
1434 uiInterface.InitMessage(_("Loading block index..."));
1436 nStart = GetTimeMillis();
1437 do {
1438 try {
1439 UnloadBlockIndex();
1440 delete pcoinsTip;
1441 delete pcoinsdbview;
1442 delete pcoinscatcher;
1443 delete pblocktree;
1445 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1446 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState);
1447 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1448 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1450 if (fReindex) {
1451 pblocktree->WriteReindexing(true);
1452 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1453 if (fPruneMode)
1454 CleanupBlockRevFiles();
1455 } else {
1456 // If necessary, upgrade from older database format.
1457 if (!pcoinsdbview->Upgrade()) {
1458 strLoadError = _("Error upgrading chainstate database");
1459 break;
1463 if (!LoadBlockIndex(chainparams)) {
1464 strLoadError = _("Error loading block database");
1465 break;
1468 // If the loaded chain has a wrong genesis, bail out immediately
1469 // (we're likely using a testnet datadir, or the other way around).
1470 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1471 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1473 // Initialize the block index (no-op if non-empty database was already loaded)
1474 if (!InitBlockIndex(chainparams)) {
1475 strLoadError = _("Error initializing block database");
1476 break;
1479 // Check for changed -txindex state
1480 if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1481 strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
1482 break;
1485 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1486 // in the past, but is now trying to run unpruned.
1487 if (fHavePruned && !fPruneMode) {
1488 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1489 break;
1492 if (!fReindex && chainActive.Tip() != NULL) {
1493 uiInterface.InitMessage(_("Rewinding blocks..."));
1494 if (!RewindBlockIndex(chainparams)) {
1495 strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1496 break;
1500 uiInterface.InitMessage(_("Verifying blocks..."));
1501 if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1502 LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
1503 MIN_BLOCKS_TO_KEEP);
1507 LOCK(cs_main);
1508 CBlockIndex* tip = chainActive.Tip();
1509 RPCNotifyBlockChange(true, tip);
1510 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1511 strLoadError = _("The block database contains a block which appears to be from the future. "
1512 "This may be due to your computer's date and time being set incorrectly. "
1513 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1514 break;
1518 if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1519 GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1520 strLoadError = _("Corrupted block database detected");
1521 break;
1523 } catch (const std::exception& e) {
1524 LogPrintf("%s\n", e.what());
1525 strLoadError = _("Error opening block database");
1526 break;
1529 fLoaded = true;
1530 } while(false);
1532 if (!fLoaded) {
1533 // first suggest a reindex
1534 if (!fReset) {
1535 bool fRet = uiInterface.ThreadSafeQuestion(
1536 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1537 strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1538 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1539 if (fRet) {
1540 fReindex = true;
1541 fRequestShutdown = false;
1542 } else {
1543 LogPrintf("Aborted block database rebuild. Exiting.\n");
1544 return false;
1546 } else {
1547 return InitError(strLoadError);
1552 // As LoadBlockIndex can take several minutes, it's possible the user
1553 // requested to kill the GUI during the last operation. If so, exit.
1554 // As the program has not fully started yet, Shutdown() is possibly overkill.
1555 if (fRequestShutdown)
1557 LogPrintf("Shutdown requested. Exiting.\n");
1558 return false;
1560 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1562 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1563 CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
1564 // Allowed to fail as this file IS missing on first startup.
1565 if (!est_filein.IsNull())
1566 ::feeEstimator.Read(est_filein);
1567 fFeeEstimatesInitialized = true;
1569 // ********************************************************* Step 8: load wallet
1570 #ifdef ENABLE_WALLET
1571 if (!CWallet::InitLoadWallet())
1572 return false;
1573 #else
1574 LogPrintf("No wallet support compiled in!\n");
1575 #endif
1577 // ********************************************************* Step 9: data directory maintenance
1579 // if pruning, unset the service bit and perform the initial blockstore prune
1580 // after any wallet rescanning has taken place.
1581 if (fPruneMode) {
1582 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1583 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1584 if (!fReindex) {
1585 uiInterface.InitMessage(_("Pruning blockstore..."));
1586 PruneAndFlush();
1590 if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
1591 // Only advertise witness capabilities if they have a reasonable start time.
1592 // This allows us to have the code merged without a defined softfork, by setting its
1593 // end time to 0.
1594 // Note that setting NODE_WITNESS is never required: the only downside from not
1595 // doing so is that after activation, no upgraded nodes will fetch from you.
1596 nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1597 // Only care about others providing witness capabilities if there is a softfork
1598 // defined.
1599 nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS);
1602 // ********************************************************* Step 10: import blocks
1604 if (!CheckDiskSpace())
1605 return false;
1607 // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1608 // No locking, as this happens before any background thread is started.
1609 if (chainActive.Tip() == NULL) {
1610 uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1611 } else {
1612 fHaveGenesis = true;
1615 if (IsArgSet("-blocknotify"))
1616 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1618 std::vector<fs::path> vImportFiles;
1619 if (gArgs.IsArgSet("-loadblock"))
1621 for (const std::string& strFile : gArgs.GetArgs("-loadblock"))
1622 vImportFiles.push_back(strFile);
1625 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1627 // Wait for genesis block to be processed
1629 boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
1630 while (!fHaveGenesis) {
1631 condvar_GenesisWait.wait(lock);
1633 uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1636 // ********************************************************* Step 11: start node
1638 //// debug print
1639 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1640 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1641 if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1642 StartTorControl(threadGroup, scheduler);
1644 Discover(threadGroup);
1646 // Map ports with UPnP
1647 MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
1649 std::string strNodeError;
1650 CConnman::Options connOptions;
1651 connOptions.nLocalServices = nLocalServices;
1652 connOptions.nRelevantServices = nRelevantServices;
1653 connOptions.nMaxConnections = nMaxConnections;
1654 connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1655 connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1656 connOptions.nMaxFeeler = 1;
1657 connOptions.nBestHeight = chainActive.Height();
1658 connOptions.uiInterface = &uiInterface;
1659 connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1660 connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1662 connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1663 connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1665 if (gArgs.IsArgSet("-seednode")) {
1666 connOptions.vSeedNodes = gArgs.GetArgs("-seednode");
1669 if (!connman.Start(scheduler, strNodeError, connOptions))
1670 return InitError(strNodeError);
1672 // ********************************************************* Step 12: finished
1674 SetRPCWarmupFinished();
1675 uiInterface.InitMessage(_("Done loading"));
1677 #ifdef ENABLE_WALLET
1678 for (CWalletRef pwallet : vpwallets) {
1679 pwallet->postInitProcess(scheduler);
1681 #endif
1683 return !fRequestShutdown;