Merge #11155: Trivial: Documentation fixes for CVectorWriter ctors
[bitcoinplatinum.git] / src / init.cpp
blob7c99dc74efc5e068cc53cf1ebe47561d0c4d1ab3
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/init.h"
47 #include "wallet/wallet.h"
48 #endif
49 #include "warnings.h"
50 #include <stdint.h>
51 #include <stdio.h>
52 #include <memory>
54 #ifndef WIN32
55 #include <signal.h>
56 #endif
58 #include <boost/algorithm/string/classification.hpp>
59 #include <boost/algorithm/string/replace.hpp>
60 #include <boost/algorithm/string/split.hpp>
61 #include <boost/bind.hpp>
62 #include <boost/interprocess/sync/file_lock.hpp>
63 #include <boost/thread.hpp>
64 #include <openssl/crypto.h>
66 #if ENABLE_ZMQ
67 #include "zmq/zmqnotificationinterface.h"
68 #endif
70 bool fFeeEstimatesInitialized = false;
71 static const bool DEFAULT_PROXYRANDOMIZE = true;
72 static const bool DEFAULT_REST_ENABLE = false;
73 static const bool DEFAULT_DISABLE_SAFEMODE = true;
74 static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
76 std::unique_ptr<CConnman> g_connman;
77 std::unique_ptr<PeerLogicValidation> peerLogic;
79 #if ENABLE_ZMQ
80 static CZMQNotificationInterface* pzmqNotificationInterface = nullptr;
81 #endif
83 #ifdef WIN32
84 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
85 // accessing block files don't count towards the fd_set size limit
86 // anyway.
87 #define MIN_CORE_FILEDESCRIPTORS 0
88 #else
89 #define MIN_CORE_FILEDESCRIPTORS 150
90 #endif
92 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
94 //////////////////////////////////////////////////////////////////////////////
96 // Shutdown
100 // Thread management and startup/shutdown:
102 // The network-processing threads are all part of a thread group
103 // created by AppInit() or the Qt main() function.
105 // A clean exit happens when StartShutdown() or the SIGTERM
106 // signal handler sets fRequestShutdown, which triggers
107 // the DetectShutdownThread(), which interrupts the main thread group.
108 // DetectShutdownThread() then exits, which causes AppInit() to
109 // continue (it .joins the shutdown thread).
110 // Shutdown() is then
111 // called to clean up database connections, and stop other
112 // threads that should only be stopped after the main network-processing
113 // threads have exited.
115 // Shutdown for Qt is very similar, only it uses a QTimer to detect
116 // fRequestShutdown getting set, and then does the normal Qt
117 // shutdown thing.
120 std::atomic<bool> fRequestShutdown(false);
121 std::atomic<bool> fDumpMempoolLater(false);
123 void StartShutdown()
125 fRequestShutdown = true;
127 bool ShutdownRequested()
129 return fRequestShutdown;
133 * This is a minimally invasive approach to shutdown on LevelDB read errors from the
134 * chainstate, while keeping user interface out of the common library, which is shared
135 * between bitcoind, and bitcoin-qt and non-server tools.
137 class CCoinsViewErrorCatcher final : public CCoinsViewBacked
139 public:
140 explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
141 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override {
142 try {
143 return CCoinsViewBacked::GetCoin(outpoint, coin);
144 } catch(const std::runtime_error& e) {
145 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
146 LogPrintf("Error reading from database: %s\n", e.what());
147 // Starting the shutdown sequence and returning false to the caller would be
148 // interpreted as 'entry not found' (as opposed to unable to read data), and
149 // could lead to invalid interpretation. Just exit immediately, as we can't
150 // continue anyway, and all writes should be atomic.
151 abort();
154 // Writes do not need similar protection, as failure to write is handled by the caller.
157 static CCoinsViewErrorCatcher *pcoinscatcher = nullptr;
158 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
160 void Interrupt(boost::thread_group& threadGroup)
162 InterruptHTTPServer();
163 InterruptHTTPRPC();
164 InterruptRPC();
165 InterruptREST();
166 InterruptTorControl();
167 if (g_connman)
168 g_connman->Interrupt();
169 threadGroup.interrupt_all();
172 void Shutdown()
174 LogPrintf("%s: In progress...\n", __func__);
175 static CCriticalSection cs_Shutdown;
176 TRY_LOCK(cs_Shutdown, lockShutdown);
177 if (!lockShutdown)
178 return;
180 /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
181 /// for example if the data directory was found to be locked.
182 /// Be sure that anything that writes files or flushes caches only does this if the respective
183 /// module was initialized.
184 RenameThread("bitcoin-shutoff");
185 mempool.AddTransactionsUpdated(1);
187 StopHTTPRPC();
188 StopREST();
189 StopRPC();
190 StopHTTPServer();
191 #ifdef ENABLE_WALLET
192 for (CWalletRef pwallet : vpwallets) {
193 pwallet->Flush(false);
195 #endif
196 MapPort(false);
197 UnregisterValidationInterface(peerLogic.get());
198 peerLogic.reset();
199 g_connman.reset();
201 StopTorControl();
202 UnregisterNodeSignals(GetNodeSignals());
203 if (fDumpMempoolLater && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
204 DumpMempool();
207 if (fFeeEstimatesInitialized)
209 ::feeEstimator.FlushUnconfirmed(::mempool);
210 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
211 CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
212 if (!est_fileout.IsNull())
213 ::feeEstimator.Write(est_fileout);
214 else
215 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
216 fFeeEstimatesInitialized = false;
219 // FlushStateToDisk generates a SetBestChain callback, which we should avoid missing
220 if (pcoinsTip != nullptr) {
221 FlushStateToDisk();
224 // After there are no more peers/RPC left to give us new data which may generate
225 // CValidationInterface callbacks, flush them...
226 GetMainSignals().FlushBackgroundCallbacks();
228 // Any future callbacks will be dropped. This should absolutely be safe - if
229 // missing a callback results in an unrecoverable situation, unclean shutdown
230 // would too. The only reason to do the above flushes is to let the wallet catch
231 // up with our current chain to avoid any strange pruning edge cases and make
232 // next startup faster by avoiding rescan.
235 LOCK(cs_main);
236 if (pcoinsTip != nullptr) {
237 FlushStateToDisk();
239 delete pcoinsTip;
240 pcoinsTip = nullptr;
241 delete pcoinscatcher;
242 pcoinscatcher = nullptr;
243 delete pcoinsdbview;
244 pcoinsdbview = nullptr;
245 delete pblocktree;
246 pblocktree = nullptr;
248 #ifdef ENABLE_WALLET
249 for (CWalletRef pwallet : vpwallets) {
250 pwallet->Flush(true);
252 #endif
254 #if ENABLE_ZMQ
255 if (pzmqNotificationInterface) {
256 UnregisterValidationInterface(pzmqNotificationInterface);
257 delete pzmqNotificationInterface;
258 pzmqNotificationInterface = nullptr;
260 #endif
262 #ifndef WIN32
263 try {
264 fs::remove(GetPidFile());
265 } catch (const fs::filesystem_error& e) {
266 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
268 #endif
269 UnregisterAllValidationInterfaces();
270 GetMainSignals().UnregisterBackgroundSignalScheduler();
271 #ifdef ENABLE_WALLET
272 for (CWalletRef pwallet : vpwallets) {
273 delete pwallet;
275 vpwallets.clear();
276 #endif
277 globalVerifyHandle.reset();
278 ECC_Stop();
279 LogPrintf("%s: done\n", __func__);
283 * Signal handlers are very limited in what they are allowed to do.
284 * The execution context the handler is invoked in is not guaranteed,
285 * so we restrict handler operations to just touching variables:
287 static void HandleSIGTERM(int)
289 fRequestShutdown = true;
292 static void HandleSIGHUP(int)
294 fReopenDebugLog = true;
297 #ifndef WIN32
298 static void registerSignalHandler(int signal, void(*handler)(int))
300 struct sigaction sa;
301 sa.sa_handler = handler;
302 sigemptyset(&sa.sa_mask);
303 sa.sa_flags = 0;
304 sigaction(signal, &sa, nullptr);
306 #endif
308 void OnRPCStarted()
310 uiInterface.NotifyBlockTip.connect(&RPCNotifyBlockChange);
313 void OnRPCStopped()
315 uiInterface.NotifyBlockTip.disconnect(&RPCNotifyBlockChange);
316 RPCNotifyBlockChange(false, nullptr);
317 cvBlockChange.notify_all();
318 LogPrint(BCLog::RPC, "RPC stopped.\n");
321 void OnRPCPreCommand(const CRPCCommand& cmd)
323 // Observe safe mode
324 std::string strWarning = GetWarnings("rpc");
325 if (strWarning != "" && !gArgs.GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
326 !cmd.okSafeMode)
327 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
330 std::string HelpMessage(HelpMessageMode mode)
332 const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
333 const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
334 const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
335 const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET);
336 const bool showDebug = gArgs.GetBoolArg("-help-debug", false);
338 // When adding new options to the categories, please keep and ensure alphabetical ordering.
339 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
340 std::string strUsage = HelpMessageGroup(_("Options:"));
341 strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
342 strUsage += HelpMessageOpt("-version", _("Print version and exit"));
343 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)"));
344 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
345 if (showDebug)
346 strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
347 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()));
348 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
349 if (mode == HMM_BITCOIND)
351 #if HAVE_DECL_DAEMON
352 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
353 #endif
355 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
356 if (showDebug) {
357 strUsage += HelpMessageOpt("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize));
359 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
360 if (showDebug)
361 strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
362 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
363 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
364 strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
365 strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
366 strUsage += HelpMessageOpt("-persistmempool", strprintf(_("Whether to save the mempool on shutdown and load on restart (default: %u)"), DEFAULT_PERSIST_MEMPOOL));
367 strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
368 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)"),
369 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
370 #ifndef WIN32
371 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
372 #endif
373 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. "
374 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
375 "(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));
376 strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
377 strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
378 #ifndef WIN32
379 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
380 #endif
381 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
383 strUsage += HelpMessageGroup(_("Connection options:"));
384 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
385 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
386 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
387 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
388 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -connect=0 disables automatic connections"));
389 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
390 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
391 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)"));
392 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
393 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
394 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
395 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
396 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
397 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
398 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
399 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));
400 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
401 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
402 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
403 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
404 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort()));
405 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
406 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
407 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
408 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
409 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
410 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
411 #ifdef USE_UPNP
412 #if USE_UPNP
413 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
414 #else
415 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
416 #endif
417 #endif
418 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
419 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.") +
420 " " + _("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"));
421 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));
423 #ifdef ENABLE_WALLET
424 strUsage += GetWalletHelpString(showDebug);
425 #endif
427 #if ENABLE_ZMQ
428 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
429 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
430 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
431 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
432 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
433 #endif
435 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
436 strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
437 if (showDebug)
439 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
440 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
441 strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
442 strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
443 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
444 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
445 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
446 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
447 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
448 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
449 strUsage += HelpMessageOpt("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT));
451 strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
452 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));
453 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));
454 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));
455 strUsage += HelpMessageOpt("-vbparams=deployment:start:end", "Use given start/end times for specified version bits deployment (regtest-only)");
457 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
458 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + ListLogCategories() + ".");
459 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.")));
460 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
461 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
462 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
463 if (showDebug)
465 strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
466 strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
467 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
468 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
470 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)"),
471 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
472 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
473 if (showDebug)
475 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
477 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
479 AppendParamsHelpMessages(strUsage, showDebug);
481 strUsage += HelpMessageGroup(_("Node relay options:"));
482 if (showDebug) {
483 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()));
484 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)));
485 strUsage += HelpMessageOpt("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to defined dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)));
487 strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
488 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
489 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
490 strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
491 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
492 CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
493 strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
494 strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
496 strUsage += HelpMessageGroup(_("Block creation options:"));
497 strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
498 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
499 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)));
500 if (showDebug)
501 strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
503 strUsage += HelpMessageGroup(_("RPC server options:"));
504 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
505 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
506 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)"));
507 strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
508 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
509 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
510 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"));
511 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
512 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"));
513 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));
514 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
515 if (showDebug) {
516 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
517 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
520 return strUsage;
523 std::string LicenseInfo()
525 const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
526 const std::string URL_WEBSITE = "<https://bitcoincore.org>";
528 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
529 "\n" +
530 strprintf(_("Please contribute if you find %s useful. "
531 "Visit %s for further information about the software."),
532 PACKAGE_NAME, URL_WEBSITE) +
533 "\n" +
534 strprintf(_("The source code is available from %s."),
535 URL_SOURCE_CODE) +
536 "\n" +
537 "\n" +
538 _("This is experimental software.") + "\n" +
539 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
540 "\n" +
541 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>") +
542 "\n";
545 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
547 if (initialSync || !pBlockIndex)
548 return;
550 std::string strCmd = gArgs.GetArg("-blocknotify", "");
552 boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
553 boost::thread t(runCommand, strCmd); // thread runs free
556 static bool fHaveGenesis = false;
557 static boost::mutex cs_GenesisWait;
558 static CConditionVariable condvar_GenesisWait;
560 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
562 if (pBlockIndex != nullptr) {
564 boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
565 fHaveGenesis = true;
567 condvar_GenesisWait.notify_all();
571 struct CImportingNow
573 CImportingNow() {
574 assert(fImporting == false);
575 fImporting = true;
578 ~CImportingNow() {
579 assert(fImporting == true);
580 fImporting = false;
585 // If we're using -prune with -reindex, then delete block files that will be ignored by the
586 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
587 // is missing, do the same here to delete any later block files after a gap. Also delete all
588 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
589 // is in sync with what's actually on disk by the time we start downloading, so that pruning
590 // works correctly.
591 void CleanupBlockRevFiles()
593 std::map<std::string, fs::path> mapBlockFiles;
595 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
596 // Remove the rev files immediately and insert the blk file paths into an
597 // ordered map keyed by block file index.
598 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
599 fs::path blocksdir = GetDataDir() / "blocks";
600 for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
601 if (is_regular_file(*it) &&
602 it->path().filename().string().length() == 12 &&
603 it->path().filename().string().substr(8,4) == ".dat")
605 if (it->path().filename().string().substr(0,3) == "blk")
606 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
607 else if (it->path().filename().string().substr(0,3) == "rev")
608 remove(it->path());
612 // Remove all block files that aren't part of a contiguous set starting at
613 // zero by walking the ordered map (keys are block file indices) by
614 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
615 // start removing block files.
616 int nContigCounter = 0;
617 for (const std::pair<std::string, fs::path>& item : mapBlockFiles) {
618 if (atoi(item.first) == nContigCounter) {
619 nContigCounter++;
620 continue;
622 remove(item.second);
626 void ThreadImport(std::vector<fs::path> vImportFiles)
628 const CChainParams& chainparams = Params();
629 RenameThread("bitcoin-loadblk");
632 CImportingNow imp;
634 // -reindex
635 if (fReindex) {
636 int nFile = 0;
637 while (true) {
638 CDiskBlockPos pos(nFile, 0);
639 if (!fs::exists(GetBlockPosFilename(pos, "blk")))
640 break; // No block files left to reindex
641 FILE *file = OpenBlockFile(pos, true);
642 if (!file)
643 break; // This error is logged in OpenBlockFile
644 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
645 LoadExternalBlockFile(chainparams, file, &pos);
646 nFile++;
648 pblocktree->WriteReindexing(false);
649 fReindex = false;
650 LogPrintf("Reindexing finished\n");
651 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
652 LoadGenesisBlock(chainparams);
655 // hardcoded $DATADIR/bootstrap.dat
656 fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
657 if (fs::exists(pathBootstrap)) {
658 FILE *file = fsbridge::fopen(pathBootstrap, "rb");
659 if (file) {
660 fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
661 LogPrintf("Importing bootstrap.dat...\n");
662 LoadExternalBlockFile(chainparams, file);
663 RenameOver(pathBootstrap, pathBootstrapOld);
664 } else {
665 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
669 // -loadblock=
670 for (const fs::path& path : vImportFiles) {
671 FILE *file = fsbridge::fopen(path, "rb");
672 if (file) {
673 LogPrintf("Importing blocks file %s...\n", path.string());
674 LoadExternalBlockFile(chainparams, file);
675 } else {
676 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
680 // scan for better chains in the block chain database, that are not yet connected in the active best chain
681 CValidationState state;
682 if (!ActivateBestChain(state, chainparams)) {
683 LogPrintf("Failed to connect best block");
684 StartShutdown();
687 if (gArgs.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
688 LogPrintf("Stopping after block import\n");
689 StartShutdown();
691 } // End scope of CImportingNow
692 if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
693 LoadMempool();
694 fDumpMempoolLater = !fRequestShutdown;
698 /** Sanity checks
699 * Ensure that Bitcoin is running in a usable environment with all
700 * necessary library support.
702 bool InitSanityCheck(void)
704 if(!ECC_InitSanityCheck()) {
705 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
706 return false;
709 if (!glibc_sanity_test() || !glibcxx_sanity_test())
710 return false;
712 if (!Random_SanityCheck()) {
713 InitError("OS cryptographic RNG sanity check failure. Aborting.");
714 return false;
717 return true;
720 bool AppInitServers(boost::thread_group& threadGroup)
722 RPCServer::OnStarted(&OnRPCStarted);
723 RPCServer::OnStopped(&OnRPCStopped);
724 RPCServer::OnPreCommand(&OnRPCPreCommand);
725 if (!InitHTTPServer())
726 return false;
727 if (!StartRPC())
728 return false;
729 if (!StartHTTPRPC())
730 return false;
731 if (gArgs.GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
732 return false;
733 if (!StartHTTPServer())
734 return false;
735 return true;
738 // Parameter interaction based on rules
739 void InitParameterInteraction()
741 // when specifying an explicit binding address, you want to listen on it
742 // even when -connect or -proxy is specified
743 if (gArgs.IsArgSet("-bind")) {
744 if (gArgs.SoftSetBoolArg("-listen", true))
745 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
747 if (gArgs.IsArgSet("-whitebind")) {
748 if (gArgs.SoftSetBoolArg("-listen", true))
749 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
752 if (gArgs.IsArgSet("-connect")) {
753 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
754 if (gArgs.SoftSetBoolArg("-dnsseed", false))
755 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
756 if (gArgs.SoftSetBoolArg("-listen", false))
757 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
760 if (gArgs.IsArgSet("-proxy")) {
761 // to protect privacy, do not listen by default if a default proxy server is specified
762 if (gArgs.SoftSetBoolArg("-listen", false))
763 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
764 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
765 // to listen locally, so don't rely on this happening through -listen below.
766 if (gArgs.SoftSetBoolArg("-upnp", false))
767 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
768 // to protect privacy, do not discover addresses by default
769 if (gArgs.SoftSetBoolArg("-discover", false))
770 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
773 if (!gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
774 // do not map ports or try to retrieve public IP when not listening (pointless)
775 if (gArgs.SoftSetBoolArg("-upnp", false))
776 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
777 if (gArgs.SoftSetBoolArg("-discover", false))
778 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
779 if (gArgs.SoftSetBoolArg("-listenonion", false))
780 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
783 if (gArgs.IsArgSet("-externalip")) {
784 // if an explicit public IP is specified, do not try to find others
785 if (gArgs.SoftSetBoolArg("-discover", false))
786 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
789 // disable whitelistrelay in blocksonly mode
790 if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
791 if (gArgs.SoftSetBoolArg("-whitelistrelay", false))
792 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
795 // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
796 if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
797 if (gArgs.SoftSetBoolArg("-whitelistrelay", true))
798 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
802 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
804 return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
807 void InitLogging()
809 fPrintToConsole = gArgs.GetBoolArg("-printtoconsole", false);
810 fLogTimestamps = gArgs.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
811 fLogTimeMicros = gArgs.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
812 fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS);
814 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
815 LogPrintf("Bitcoin version %s\n", FormatFullVersion());
818 namespace { // Variables internal to initialization process only
820 ServiceFlags nRelevantServices = NODE_NETWORK;
821 int nMaxConnections;
822 int nUserMaxConnections;
823 int nFD;
824 ServiceFlags nLocalServices = NODE_NETWORK;
826 } // namespace
828 [[noreturn]] static void new_handler_terminate()
830 // Rather than throwing std::bad-alloc if allocation fails, terminate
831 // immediately to (try to) avoid chain corruption.
832 // Since LogPrintf may itself allocate memory, set the handler directly
833 // to terminate first.
834 std::set_new_handler(std::terminate);
835 LogPrintf("Error: Out of memory. Terminating.\n");
837 // The log was successful, terminate now.
838 std::terminate();
841 bool AppInitBasicSetup()
843 // ********************************************************* Step 1: setup
844 #ifdef _MSC_VER
845 // Turn off Microsoft heap dump noise
846 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
847 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
848 // Disable confusing "helpful" text message on abort, Ctrl-C
849 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
850 #endif
851 #ifdef WIN32
852 // Enable Data Execution Prevention (DEP)
853 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
854 // A failure is non-critical and needs no further attention!
855 #ifndef PROCESS_DEP_ENABLE
856 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
857 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
858 #define PROCESS_DEP_ENABLE 0x00000001
859 #endif
860 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
861 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
862 if (setProcDEPPol != nullptr) setProcDEPPol(PROCESS_DEP_ENABLE);
863 #endif
865 if (!SetupNetworking())
866 return InitError("Initializing networking failed");
868 #ifndef WIN32
869 if (!gArgs.GetBoolArg("-sysperms", false)) {
870 umask(077);
873 // Clean shutdown on SIGTERM
874 registerSignalHandler(SIGTERM, HandleSIGTERM);
875 registerSignalHandler(SIGINT, HandleSIGTERM);
877 // Reopen debug.log on SIGHUP
878 registerSignalHandler(SIGHUP, HandleSIGHUP);
880 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
881 signal(SIGPIPE, SIG_IGN);
882 #endif
884 std::set_new_handler(new_handler_terminate);
886 return true;
889 bool AppInitParameterInteraction()
891 const CChainParams& chainparams = Params();
892 // ********************************************************* Step 2: parameter interactions
894 // also see: InitParameterInteraction()
896 // if using block pruning, then disallow txindex
897 if (gArgs.GetArg("-prune", 0)) {
898 if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX))
899 return InitError(_("Prune mode is incompatible with -txindex."));
902 // -bind and -whitebind can't be set when not listening
903 size_t nUserBind = gArgs.GetArgs("-bind").size() + gArgs.GetArgs("-whitebind").size();
904 if (nUserBind != 0 && !gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
905 return InitError("Cannot set -bind or -whitebind together with -listen=0");
908 // Make sure enough file descriptors are available
909 int nBind = std::max(nUserBind, size_t(1));
910 nUserMaxConnections = gArgs.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
911 nMaxConnections = std::max(nUserMaxConnections, 0);
913 // Trim requested connection counts, to fit into system limitations
914 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
915 nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
916 if (nFD < MIN_CORE_FILEDESCRIPTORS)
917 return InitError(_("Not enough file descriptors available."));
918 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
920 if (nMaxConnections < nUserMaxConnections)
921 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
923 // ********************************************************* Step 3: parameter-to-internal-flags
924 if (gArgs.IsArgSet("-debug")) {
925 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
926 const std::vector<std::string> categories = gArgs.GetArgs("-debug");
928 if (find(categories.begin(), categories.end(), std::string("0")) == categories.end()) {
929 for (const auto& cat : categories) {
930 uint32_t flag = 0;
931 if (!GetLogCategory(&flag, &cat)) {
932 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
933 continue;
935 logCategories |= flag;
940 // Now remove the logging categories which were explicitly excluded
941 for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
942 uint32_t flag = 0;
943 if (!GetLogCategory(&flag, &cat)) {
944 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
945 continue;
947 logCategories &= ~flag;
950 // Check for -debugnet
951 if (gArgs.GetBoolArg("-debugnet", false))
952 InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
953 // Check for -socks - as this is a privacy risk to continue, exit here
954 if (gArgs.IsArgSet("-socks"))
955 return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
956 // Check for -tor - as this is a privacy risk to continue, exit here
957 if (gArgs.GetBoolArg("-tor", false))
958 return InitError(_("Unsupported argument -tor found, use -onion."));
960 if (gArgs.GetBoolArg("-benchmark", false))
961 InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
963 if (gArgs.GetBoolArg("-whitelistalwaysrelay", false))
964 InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
966 if (gArgs.IsArgSet("-blockminsize"))
967 InitWarning("Unsupported argument -blockminsize ignored.");
969 // Checkmempool and checkblockindex default to true in regtest mode
970 int ratio = std::min<int>(std::max<int>(gArgs.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
971 if (ratio != 0) {
972 mempool.setSanityCheck(1.0 / ratio);
974 fCheckBlockIndex = gArgs.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
975 fCheckpointsEnabled = gArgs.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
977 hashAssumeValid = uint256S(gArgs.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
978 if (!hashAssumeValid.IsNull())
979 LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
980 else
981 LogPrintf("Validating signatures for all blocks.\n");
983 // mempool limits
984 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
985 int64_t nMempoolSizeMin = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
986 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
987 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
988 // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
989 // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
990 if (gArgs.IsArgSet("-incrementalrelayfee"))
992 CAmount n = 0;
993 if (!ParseMoney(gArgs.GetArg("-incrementalrelayfee", ""), n))
994 return InitError(AmountErrMsg("incrementalrelayfee", gArgs.GetArg("-incrementalrelayfee", "")));
995 incrementalRelayFee = CFeeRate(n);
998 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
999 nScriptCheckThreads = gArgs.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
1000 if (nScriptCheckThreads <= 0)
1001 nScriptCheckThreads += GetNumCores();
1002 if (nScriptCheckThreads <= 1)
1003 nScriptCheckThreads = 0;
1004 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
1005 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
1007 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
1008 int64_t nPruneArg = gArgs.GetArg("-prune", 0);
1009 if (nPruneArg < 0) {
1010 return InitError(_("Prune cannot be configured with a negative value."));
1012 nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
1013 if (nPruneArg == 1) { // manual pruning: -prune=1
1014 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1015 nPruneTarget = std::numeric_limits<uint64_t>::max();
1016 fPruneMode = true;
1017 } else if (nPruneTarget) {
1018 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
1019 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1021 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1022 fPruneMode = true;
1025 RegisterAllCoreRPCCommands(tableRPC);
1026 #ifdef ENABLE_WALLET
1027 RegisterWalletRPCCommands(tableRPC);
1028 #endif
1030 nConnectTimeout = gArgs.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1031 if (nConnectTimeout <= 0)
1032 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1034 if (gArgs.IsArgSet("-minrelaytxfee")) {
1035 CAmount n = 0;
1036 if (!ParseMoney(gArgs.GetArg("-minrelaytxfee", ""), n)) {
1037 return InitError(AmountErrMsg("minrelaytxfee", gArgs.GetArg("-minrelaytxfee", "")));
1039 // High fee check is done afterward in WalletParameterInteraction()
1040 ::minRelayTxFee = CFeeRate(n);
1041 } else if (incrementalRelayFee > ::minRelayTxFee) {
1042 // Allow only setting incrementalRelayFee to control both
1043 ::minRelayTxFee = incrementalRelayFee;
1044 LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1047 // Sanity check argument for min fee for including tx in block
1048 // TODO: Harmonize which arguments need sanity checking and where that happens
1049 if (gArgs.IsArgSet("-blockmintxfee"))
1051 CAmount n = 0;
1052 if (!ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n))
1053 return InitError(AmountErrMsg("blockmintxfee", gArgs.GetArg("-blockmintxfee", "")));
1056 // Feerate used to define dust. Shouldn't be changed lightly as old
1057 // implementations may inadvertently create non-standard transactions
1058 if (gArgs.IsArgSet("-dustrelayfee"))
1060 CAmount n = 0;
1061 if (!ParseMoney(gArgs.GetArg("-dustrelayfee", ""), n) || 0 == n)
1062 return InitError(AmountErrMsg("dustrelayfee", gArgs.GetArg("-dustrelayfee", "")));
1063 dustRelayFee = CFeeRate(n);
1066 fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1067 if (chainparams.RequireStandard() && !fRequireStandard)
1068 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1069 nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp);
1071 #ifdef ENABLE_WALLET
1072 if (!WalletParameterInteraction())
1073 return false;
1074 #endif
1076 fIsBareMultisigStd = gArgs.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1077 fAcceptDatacarrier = gArgs.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1078 nMaxDatacarrierBytes = gArgs.GetArg("-datacarriersize", nMaxDatacarrierBytes);
1080 // Option to startup with mocktime set (used for regression testing):
1081 SetMockTime(gArgs.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1083 if (gArgs.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1084 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1086 if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1087 return InitError("rpcserialversion must be non-negative.");
1089 if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1090 return InitError("unknown rpcserialversion requested.");
1092 nMaxTipAge = gArgs.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1094 fEnableReplacement = gArgs.GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1095 if ((!fEnableReplacement) && gArgs.IsArgSet("-mempoolreplacement")) {
1096 // Minimal effort at forwards compatibility
1097 std::string strReplacementModeList = gArgs.GetArg("-mempoolreplacement", ""); // default is impossible
1098 std::vector<std::string> vstrReplacementModes;
1099 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1100 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1103 if (gArgs.IsArgSet("-vbparams")) {
1104 // Allow overriding version bits parameters for testing
1105 if (!chainparams.MineBlocksOnDemand()) {
1106 return InitError("Version bits parameters may only be overridden on regtest.");
1108 for (const std::string& strDeployment : gArgs.GetArgs("-vbparams")) {
1109 std::vector<std::string> vDeploymentParams;
1110 boost::split(vDeploymentParams, strDeployment, boost::is_any_of(":"));
1111 if (vDeploymentParams.size() != 3) {
1112 return InitError("Version bits parameters malformed, expecting deployment:start:end");
1114 int64_t nStartTime, nTimeout;
1115 if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1116 return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1118 if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1119 return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1121 bool found = false;
1122 for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1124 if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1125 UpdateVersionBitsParameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1126 found = true;
1127 LogPrintf("Setting version bits activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1128 break;
1131 if (!found) {
1132 return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1136 return true;
1139 static bool LockDataDirectory(bool probeOnly)
1141 std::string strDataDir = GetDataDir().string();
1143 // Make sure only a single Bitcoin process is using the data directory.
1144 fs::path pathLockFile = GetDataDir() / ".lock";
1145 FILE* file = fsbridge::fopen(pathLockFile, "a"); // empty lock file; created if it doesn't exist.
1146 if (file) fclose(file);
1148 try {
1149 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1150 if (!lock.try_lock()) {
1151 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1153 if (probeOnly) {
1154 lock.unlock();
1156 } catch(const boost::interprocess::interprocess_exception& e) {
1157 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1159 return true;
1162 bool AppInitSanityChecks()
1164 // ********************************************************* Step 4: sanity checks
1166 // Initialize elliptic curve code
1167 std::string sha256_algo = SHA256AutoDetect();
1168 LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
1169 RandomInit();
1170 ECC_Start();
1171 globalVerifyHandle.reset(new ECCVerifyHandle());
1173 // Sanity check
1174 if (!InitSanityCheck())
1175 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1177 // Probe the data directory lock to give an early error message, if possible
1178 // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened,
1179 // and a fork will cause weird behavior to it.
1180 return LockDataDirectory(true);
1183 bool AppInitLockDataDirectory()
1185 // After daemonization get the data directory lock again and hold on to it until exit
1186 // This creates a slight window for a race condition to happen, however this condition is harmless: it
1187 // will at most make us exit without printing a message to console.
1188 if (!LockDataDirectory(false)) {
1189 // Detailed error printed inside LockDataDirectory
1190 return false;
1192 return true;
1195 bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
1197 const CChainParams& chainparams = Params();
1198 // ********************************************************* Step 4a: application initialization
1199 #ifndef WIN32
1200 CreatePidFile(GetPidFile(), getpid());
1201 #endif
1202 if (gArgs.GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
1203 // Do this first since it both loads a bunch of debug.log into memory,
1204 // and because this needs to happen before any other debug.log printing
1205 ShrinkDebugFile();
1208 if (fPrintToDebugLog)
1209 OpenDebugLog();
1211 if (!fLogTimestamps)
1212 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1213 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1214 LogPrintf("Using data directory %s\n", GetDataDir().string());
1215 LogPrintf("Using config file %s\n", GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1216 LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1218 InitSignatureCache();
1219 InitScriptExecutionCache();
1221 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1222 if (nScriptCheckThreads) {
1223 for (int i=0; i<nScriptCheckThreads-1; i++)
1224 threadGroup.create_thread(&ThreadScriptCheck);
1227 // Start the lightweight task scheduler thread
1228 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1229 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1231 GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);
1233 /* Start the RPC server already. It will be started in "warmup" mode
1234 * and not really process calls already (but it will signify connections
1235 * that the server is there and will be ready later). Warmup mode will
1236 * be disabled when initialisation is finished.
1238 if (gArgs.GetBoolArg("-server", false))
1240 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1241 if (!AppInitServers(threadGroup))
1242 return InitError(_("Unable to start HTTP server. See debug log for details."));
1245 int64_t nStart;
1247 // ********************************************************* Step 5: verify wallet database integrity
1248 #ifdef ENABLE_WALLET
1249 if (!WalletVerify())
1250 return false;
1251 #endif
1252 // ********************************************************* Step 6: network initialization
1253 // Note that we absolutely cannot open any actual connections
1254 // until the very end ("start node") as the UTXO/block state
1255 // is not yet setup and may end up being set up twice if we
1256 // need to reindex later.
1258 assert(!g_connman);
1259 g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1260 CConnman& connman = *g_connman;
1262 peerLogic.reset(new PeerLogicValidation(&connman));
1263 RegisterValidationInterface(peerLogic.get());
1264 RegisterNodeSignals(GetNodeSignals());
1266 // sanitize comments per BIP-0014, format user agent and check total size
1267 std::vector<std::string> uacomments;
1268 for (const std::string& cmt : gArgs.GetArgs("-uacomment")) {
1269 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1270 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1271 uacomments.push_back(cmt);
1273 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1274 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1275 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1276 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1279 if (gArgs.IsArgSet("-onlynet")) {
1280 std::set<enum Network> nets;
1281 for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
1282 enum Network net = ParseNetwork(snet);
1283 if (net == NET_UNROUTABLE)
1284 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1285 nets.insert(net);
1287 for (int n = 0; n < NET_MAX; n++) {
1288 enum Network net = (enum Network)n;
1289 if (!nets.count(net))
1290 SetLimited(net);
1294 // Check for host lookup allowed before parsing any network related parameters
1295 fNameLookup = gArgs.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1297 bool proxyRandomize = gArgs.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1298 // -proxy sets a proxy for all outgoing network traffic
1299 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1300 std::string proxyArg = gArgs.GetArg("-proxy", "");
1301 SetLimited(NET_TOR);
1302 if (proxyArg != "" && proxyArg != "0") {
1303 CService proxyAddr;
1304 if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1305 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1308 proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1309 if (!addrProxy.IsValid())
1310 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1312 SetProxy(NET_IPV4, addrProxy);
1313 SetProxy(NET_IPV6, addrProxy);
1314 SetProxy(NET_TOR, addrProxy);
1315 SetNameProxy(addrProxy);
1316 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1319 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1320 // -noonion (or -onion=0) disables connecting to .onion entirely
1321 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1322 std::string onionArg = gArgs.GetArg("-onion", "");
1323 if (onionArg != "") {
1324 if (onionArg == "0") { // Handle -noonion/-onion=0
1325 SetLimited(NET_TOR); // set onions as unreachable
1326 } else {
1327 CService onionProxy;
1328 if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1329 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1331 proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1332 if (!addrOnion.IsValid())
1333 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1334 SetProxy(NET_TOR, addrOnion);
1335 SetLimited(NET_TOR, false);
1339 // see Step 2: parameter interactions for more information about these
1340 fListen = gArgs.GetBoolArg("-listen", DEFAULT_LISTEN);
1341 fDiscover = gArgs.GetBoolArg("-discover", true);
1342 fRelayTxes = !gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1344 for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
1345 CService addrLocal;
1346 if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1347 AddLocal(addrLocal, LOCAL_MANUAL);
1348 else
1349 return InitError(ResolveErrMsg("externalip", strAddr));
1352 #if ENABLE_ZMQ
1353 pzmqNotificationInterface = CZMQNotificationInterface::Create();
1355 if (pzmqNotificationInterface) {
1356 RegisterValidationInterface(pzmqNotificationInterface);
1358 #endif
1359 uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1360 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1362 if (gArgs.IsArgSet("-maxuploadtarget")) {
1363 nMaxOutboundLimit = gArgs.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1366 // ********************************************************* Step 7: load block chain
1368 fReindex = gArgs.GetBoolArg("-reindex", false);
1369 bool fReindexChainState = gArgs.GetBoolArg("-reindex-chainstate", false);
1371 // cache size calculations
1372 int64_t nTotalCache = (gArgs.GetArg("-dbcache", nDefaultDbCache) << 20);
1373 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1374 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1375 int64_t nBlockTreeDBCache = nTotalCache / 8;
1376 nBlockTreeDBCache = std::min(nBlockTreeDBCache, (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1377 nTotalCache -= nBlockTreeDBCache;
1378 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1379 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1380 nTotalCache -= nCoinDBCache;
1381 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1382 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1383 LogPrintf("Cache configuration:\n");
1384 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1385 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1386 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));
1388 bool fLoaded = false;
1389 while (!fLoaded && !fRequestShutdown) {
1390 bool fReset = fReindex;
1391 std::string strLoadError;
1393 uiInterface.InitMessage(_("Loading block index..."));
1395 nStart = GetTimeMillis();
1396 do {
1397 try {
1398 UnloadBlockIndex();
1399 delete pcoinsTip;
1400 delete pcoinsdbview;
1401 delete pcoinscatcher;
1402 delete pblocktree;
1404 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReset);
1406 if (fReset) {
1407 pblocktree->WriteReindexing(true);
1408 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1409 if (fPruneMode)
1410 CleanupBlockRevFiles();
1413 if (fRequestShutdown) break;
1415 // LoadBlockIndex will load fTxIndex from the db, or set it if
1416 // we're reindexing. It will also load fHavePruned if we've
1417 // ever removed a block file from disk.
1418 // Note that it also sets fReindex based on the disk flag!
1419 // From here on out fReindex and fReset mean something different!
1420 if (!LoadBlockIndex(chainparams)) {
1421 strLoadError = _("Error loading block database");
1422 break;
1425 // If the loaded chain has a wrong genesis, bail out immediately
1426 // (we're likely using a testnet datadir, or the other way around).
1427 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1428 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1430 // Check for changed -txindex state
1431 if (fTxIndex != gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1432 strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1433 break;
1436 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1437 // in the past, but is now trying to run unpruned.
1438 if (fHavePruned && !fPruneMode) {
1439 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1440 break;
1443 // At this point blocktree args are consistent with what's on disk.
1444 // If we're not mid-reindex (based on disk + args), add a genesis block on disk
1445 // (otherwise we use the one already on disk).
1446 // This is called again in ThreadImport after the reindex completes.
1447 if (!fReindex && !LoadGenesisBlock(chainparams)) {
1448 strLoadError = _("Error initializing block database");
1449 break;
1452 // At this point we're either in reindex or we've loaded a useful
1453 // block tree into mapBlockIndex!
1455 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReset || fReindexChainState);
1456 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1458 // If necessary, upgrade from older database format.
1459 // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1460 if (!pcoinsdbview->Upgrade()) {
1461 strLoadError = _("Error upgrading chainstate database");
1462 break;
1465 // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1466 if (!ReplayBlocks(chainparams, pcoinsdbview)) {
1467 strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1468 break;
1471 // The on-disk coinsdb is now in a good state, create the cache
1472 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1474 bool is_coinsview_empty = fReset || fReindexChainState || pcoinsTip->GetBestBlock().IsNull();
1475 if (!is_coinsview_empty) {
1476 // LoadChainTip sets chainActive based on pcoinsTip's best block
1477 if (!LoadChainTip(chainparams)) {
1478 strLoadError = _("Error initializing block database");
1479 break;
1481 assert(chainActive.Tip() != nullptr);
1484 if (!fReset) {
1485 // Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate.
1486 // It both disconnects blocks based on chainActive, and drops block data in
1487 // mapBlockIndex based on lack of available witness data.
1488 uiInterface.InitMessage(_("Rewinding blocks..."));
1489 if (!RewindBlockIndex(chainparams)) {
1490 strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1491 break;
1495 if (!is_coinsview_empty) {
1496 uiInterface.InitMessage(_("Verifying blocks..."));
1497 if (fHavePruned && gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1498 LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
1499 MIN_BLOCKS_TO_KEEP);
1503 LOCK(cs_main);
1504 CBlockIndex* tip = chainActive.Tip();
1505 RPCNotifyBlockChange(true, tip);
1506 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1507 strLoadError = _("The block database contains a block which appears to be from the future. "
1508 "This may be due to your computer's date and time being set incorrectly. "
1509 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1510 break;
1514 if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1515 gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1516 strLoadError = _("Corrupted block database detected");
1517 break;
1520 } catch (const std::exception& e) {
1521 LogPrintf("%s\n", e.what());
1522 strLoadError = _("Error opening block database");
1523 break;
1526 fLoaded = true;
1527 } while(false);
1529 if (!fLoaded && !fRequestShutdown) {
1530 // first suggest a reindex
1531 if (!fReset) {
1532 bool fRet = uiInterface.ThreadSafeQuestion(
1533 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1534 strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1535 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1536 if (fRet) {
1537 fReindex = true;
1538 fRequestShutdown = false;
1539 } else {
1540 LogPrintf("Aborted block database rebuild. Exiting.\n");
1541 return false;
1543 } else {
1544 return InitError(strLoadError);
1549 // As LoadBlockIndex can take several minutes, it's possible the user
1550 // requested to kill the GUI during the last operation. If so, exit.
1551 // As the program has not fully started yet, Shutdown() is possibly overkill.
1552 if (fRequestShutdown)
1554 LogPrintf("Shutdown requested. Exiting.\n");
1555 return false;
1557 if (fLoaded) {
1558 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1561 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1562 CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
1563 // Allowed to fail as this file IS missing on first startup.
1564 if (!est_filein.IsNull())
1565 ::feeEstimator.Read(est_filein);
1566 fFeeEstimatesInitialized = true;
1568 // ********************************************************* Step 8: load wallet
1569 #ifdef ENABLE_WALLET
1570 if (!InitLoadWallet())
1571 return false;
1572 #else
1573 LogPrintf("No wallet support compiled in!\n");
1574 #endif
1576 // ********************************************************* Step 9: data directory maintenance
1578 // if pruning, unset the service bit and perform the initial blockstore prune
1579 // after any wallet rescanning has taken place.
1580 if (fPruneMode) {
1581 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1582 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1583 if (!fReindex) {
1584 uiInterface.InitMessage(_("Pruning blockstore..."));
1585 PruneAndFlush();
1589 if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
1590 // Only advertise witness capabilities if they have a reasonable start time.
1591 // This allows us to have the code merged without a defined softfork, by setting its
1592 // end time to 0.
1593 // Note that setting NODE_WITNESS is never required: the only downside from not
1594 // doing so is that after activation, no upgraded nodes will fetch from you.
1595 nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1596 // Only care about others providing witness capabilities if there is a softfork
1597 // defined.
1598 nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS);
1601 // ********************************************************* Step 10: import blocks
1603 if (!CheckDiskSpace())
1604 return false;
1606 // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1607 // No locking, as this happens before any background thread is started.
1608 if (chainActive.Tip() == nullptr) {
1609 uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1610 } else {
1611 fHaveGenesis = true;
1614 if (gArgs.IsArgSet("-blocknotify"))
1615 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1617 std::vector<fs::path> vImportFiles;
1618 for (const std::string& strFile : gArgs.GetArgs("-loadblock")) {
1619 vImportFiles.push_back(strFile);
1622 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1624 // Wait for genesis block to be processed
1626 boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
1627 while (!fHaveGenesis) {
1628 condvar_GenesisWait.wait(lock);
1630 uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1633 // ********************************************************* Step 11: start node
1635 //// debug print
1636 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1637 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1638 if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1639 StartTorControl(threadGroup, scheduler);
1641 Discover(threadGroup);
1643 // Map ports with UPnP
1644 MapPort(gArgs.GetBoolArg("-upnp", DEFAULT_UPNP));
1646 CConnman::Options connOptions;
1647 connOptions.nLocalServices = nLocalServices;
1648 connOptions.nRelevantServices = nRelevantServices;
1649 connOptions.nMaxConnections = nMaxConnections;
1650 connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1651 connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1652 connOptions.nMaxFeeler = 1;
1653 connOptions.nBestHeight = chainActive.Height();
1654 connOptions.uiInterface = &uiInterface;
1655 connOptions.nSendBufferMaxSize = 1000*gArgs.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1656 connOptions.nReceiveFloodSize = 1000*gArgs.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1658 connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1659 connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1661 for (const std::string& strBind : gArgs.GetArgs("-bind")) {
1662 CService addrBind;
1663 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) {
1664 return InitError(ResolveErrMsg("bind", strBind));
1666 connOptions.vBinds.push_back(addrBind);
1668 for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
1669 CService addrBind;
1670 if (!Lookup(strBind.c_str(), addrBind, 0, false)) {
1671 return InitError(ResolveErrMsg("whitebind", strBind));
1673 if (addrBind.GetPort() == 0) {
1674 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1676 connOptions.vWhiteBinds.push_back(addrBind);
1679 for (const auto& net : gArgs.GetArgs("-whitelist")) {
1680 CSubNet subnet;
1681 LookupSubNet(net.c_str(), subnet);
1682 if (!subnet.IsValid())
1683 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1684 connOptions.vWhitelistedRange.push_back(subnet);
1687 if (gArgs.IsArgSet("-seednode")) {
1688 connOptions.vSeedNodes = gArgs.GetArgs("-seednode");
1691 if (!connman.Start(scheduler, connOptions)) {
1692 return false;
1695 // ********************************************************* Step 12: finished
1697 SetRPCWarmupFinished();
1698 uiInterface.InitMessage(_("Done loading"));
1700 #ifdef ENABLE_WALLET
1701 for (CWalletRef pwallet : vpwallets) {
1702 pwallet->postInitProcess(scheduler);
1704 #endif
1706 return !fRequestShutdown;