Add pblock to connectTrace at the end of ConnectTip, not start
[bitcoinplatinum.git] / src / init.cpp
blob1e7e388a52413c89d531c7998a571464d7b64992
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/policy.h"
29 #include "rpc/server.h"
30 #include "rpc/register.h"
31 #include "rpc/blockchain.h"
32 #include "script/standard.h"
33 #include "script/sigcache.h"
34 #include "scheduler.h"
35 #include "timedata.h"
36 #include "txdb.h"
37 #include "txmempool.h"
38 #include "torcontrol.h"
39 #include "ui_interface.h"
40 #include "util.h"
41 #include "utilmoneystr.h"
42 #include "validationinterface.h"
43 #ifdef ENABLE_WALLET
44 #include "wallet/wallet.h"
45 #endif
46 #include "warnings.h"
47 #include <stdint.h>
48 #include <stdio.h>
49 #include <memory>
51 #ifndef WIN32
52 #include <signal.h>
53 #endif
55 #include <boost/algorithm/string/classification.hpp>
56 #include <boost/algorithm/string/predicate.hpp>
57 #include <boost/algorithm/string/replace.hpp>
58 #include <boost/algorithm/string/split.hpp>
59 #include <boost/bind.hpp>
60 #include <boost/function.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 GetCoins(const uint256 &txid, CCoins &coins) const {
149 try {
150 return CCoinsViewBacked::GetCoins(txid, coins);
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 CCoinsViewDB *pcoinsdbview = NULL;
165 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
166 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
168 void Interrupt(boost::thread_group& threadGroup)
170 InterruptHTTPServer();
171 InterruptHTTPRPC();
172 InterruptRPC();
173 InterruptREST();
174 InterruptTorControl();
175 if (g_connman)
176 g_connman->Interrupt();
177 threadGroup.interrupt_all();
180 void Shutdown()
182 LogPrintf("%s: In progress...\n", __func__);
183 static CCriticalSection cs_Shutdown;
184 TRY_LOCK(cs_Shutdown, lockShutdown);
185 if (!lockShutdown)
186 return;
188 /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
189 /// for example if the data directory was found to be locked.
190 /// Be sure that anything that writes files or flushes caches only does this if the respective
191 /// module was initialized.
192 RenameThread("bitcoin-shutoff");
193 mempool.AddTransactionsUpdated(1);
195 StopHTTPRPC();
196 StopREST();
197 StopRPC();
198 StopHTTPServer();
199 #ifdef ENABLE_WALLET
200 if (pwalletMain)
201 pwalletMain->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)
211 DumpMempool();
213 if (fFeeEstimatesInitialized)
215 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
216 CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
217 if (!est_fileout.IsNull())
218 mempool.WriteFeeEstimates(est_fileout);
219 else
220 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
221 fFeeEstimatesInitialized = false;
225 LOCK(cs_main);
226 if (pcoinsTip != NULL) {
227 FlushStateToDisk();
229 delete pcoinsTip;
230 pcoinsTip = NULL;
231 delete pcoinscatcher;
232 pcoinscatcher = NULL;
233 delete pcoinsdbview;
234 pcoinsdbview = NULL;
235 delete pblocktree;
236 pblocktree = NULL;
238 #ifdef ENABLE_WALLET
239 if (pwalletMain)
240 pwalletMain->Flush(true);
241 #endif
243 #if ENABLE_ZMQ
244 if (pzmqNotificationInterface) {
245 UnregisterValidationInterface(pzmqNotificationInterface);
246 delete pzmqNotificationInterface;
247 pzmqNotificationInterface = NULL;
249 #endif
251 #ifndef WIN32
252 try {
253 fs::remove(GetPidFile());
254 } catch (const fs::filesystem_error& e) {
255 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
257 #endif
258 UnregisterAllValidationInterfaces();
259 #ifdef ENABLE_WALLET
260 delete pwalletMain;
261 pwalletMain = NULL;
262 #endif
263 globalVerifyHandle.reset();
264 ECC_Stop();
265 LogPrintf("%s: done\n", __func__);
269 * Signal handlers are very limited in what they are allowed to do.
270 * The execution context the handler is invoked in is not guaranteed,
271 * so we restrict handler operations to just touching variables:
273 static void HandleSIGTERM(int)
275 fRequestShutdown = true;
278 static void HandleSIGHUP(int)
280 fReopenDebugLog = true;
283 #ifndef WIN32
284 static void registerSignalHandler(int signal, void(*handler)(int))
286 struct sigaction sa;
287 sa.sa_handler = handler;
288 sigemptyset(&sa.sa_mask);
289 sa.sa_flags = 0;
290 sigaction(signal, &sa, NULL);
292 #endif
294 bool static Bind(CConnman& connman, const CService &addr, unsigned int flags) {
295 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
296 return false;
297 std::string strError;
298 if (!connman.BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
299 if (flags & BF_REPORT_ERROR)
300 return InitError(strError);
301 return false;
303 return true;
305 void OnRPCStarted()
307 uiInterface.NotifyBlockTip.connect(&RPCNotifyBlockChange);
310 void OnRPCStopped()
312 uiInterface.NotifyBlockTip.disconnect(&RPCNotifyBlockChange);
313 RPCNotifyBlockChange(false, nullptr);
314 cvBlockChange.notify_all();
315 LogPrint(BCLog::RPC, "RPC stopped.\n");
318 void OnRPCPreCommand(const CRPCCommand& cmd)
320 // Observe safe mode
321 std::string strWarning = GetWarnings("rpc");
322 if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
323 !cmd.okSafeMode)
324 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
327 std::string HelpMessage(HelpMessageMode mode)
329 const bool showDebug = GetBoolArg("-help-debug", false);
331 // When adding new options to the categories, please keep and ensure alphabetical ordering.
332 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
333 std::string strUsage = HelpMessageGroup(_("Options:"));
334 strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
335 strUsage += HelpMessageOpt("-version", _("Print version and exit"));
336 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)"));
337 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
338 if (showDebug)
339 strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
340 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)"), Params(CBaseChainParams::MAIN).GetConsensus().defaultAssumeValid.GetHex(), Params(CBaseChainParams::TESTNET).GetConsensus().defaultAssumeValid.GetHex()));
341 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
342 if (mode == HMM_BITCOIND)
344 #if HAVE_DECL_DAEMON
345 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
346 #endif
348 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
349 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
350 if (showDebug)
351 strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
352 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
353 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
354 strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
355 strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
356 strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
357 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)"),
358 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
359 #ifndef WIN32
360 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
361 #endif
362 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. "
363 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
364 "(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));
365 strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
366 strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
367 #ifndef WIN32
368 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
369 #endif
370 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
372 strUsage += HelpMessageGroup(_("Connection options:"));
373 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
374 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
375 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
376 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
377 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -connect=0 disables automatic connections"));
378 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
379 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
380 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)"));
381 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
382 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
383 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
384 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
385 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
386 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
387 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
388 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));
389 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
390 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
391 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
392 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
393 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), Params(CBaseChainParams::MAIN).GetDefaultPort(), Params(CBaseChainParams::TESTNET).GetDefaultPort()));
394 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
395 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
396 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
397 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
398 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
399 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
400 #ifdef USE_UPNP
401 #if USE_UPNP
402 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
403 #else
404 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
405 #endif
406 #endif
407 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
408 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.") +
409 " " + _("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"));
410 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));
412 #ifdef ENABLE_WALLET
413 strUsage += CWallet::GetWalletHelpString(showDebug);
414 #endif
416 #if ENABLE_ZMQ
417 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
418 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
419 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
420 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
421 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
422 #endif
424 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
425 strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
426 if (showDebug)
428 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
429 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
430 strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
431 strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
432 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
433 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
434 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
435 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
436 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
437 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
438 strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
439 strUsage += HelpMessageOpt("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT));
440 strUsage += HelpMessageOpt("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT));
441 strUsage += HelpMessageOpt("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT));
442 strUsage += HelpMessageOpt("-bip9params=deployment:start:end", "Use given start/end times for specified BIP9 deployment (regtest-only)");
444 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
445 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + ListLogCategories() + ".");
446 strUsage += HelpMessageOpt("-debugexclude=<category>", strprintf(_("Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except one or more specified categories.")));
447 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
448 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
449 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
450 if (showDebug)
452 strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
453 strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
454 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
455 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
457 strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)"),
458 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
459 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
460 if (showDebug)
462 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
464 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
466 AppendParamsHelpMessages(strUsage, showDebug);
468 strUsage += HelpMessageGroup(_("Node relay options:"));
469 if (showDebug) {
470 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
471 strUsage += HelpMessageOpt("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)));
472 strUsage += HelpMessageOpt("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to defined dust, the value of an output such that it will cost about 1/3 of its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)));
474 strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
475 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
476 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
477 strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
478 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
479 CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
480 strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
481 strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
483 strUsage += HelpMessageGroup(_("Block creation options:"));
484 strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
485 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
486 strUsage += HelpMessageOpt("-blockmintxfee=<amt>", strprintf(_("Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)"), CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)));
487 if (showDebug)
488 strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
490 strUsage += HelpMessageGroup(_("RPC server options:"));
491 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
492 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
493 strUsage += HelpMessageOpt("-rpcbind=<addr>[:port]", _("Bind to given address to listen for JSON-RPC connections. This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost, or if -rpcallowip has been specified, 0.0.0.0 and :: i.e., all addresses)"));
494 strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
495 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
496 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
497 strUsage += HelpMessageOpt("-rpcauth=<userpw>", _("Username and hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcuser. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times"));
498 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort()));
499 strUsage += HelpMessageOpt("-rpcallowip=<ip>", _("Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"));
500 strUsage += HelpMessageOpt("-rpcserialversion", strprintf(_("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)"), DEFAULT_RPC_SERIALIZE_VERSION));
501 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
502 if (showDebug) {
503 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
504 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
507 return strUsage;
510 std::string LicenseInfo()
512 const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
513 const std::string URL_WEBSITE = "<https://bitcoincore.org>";
515 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
516 "\n" +
517 strprintf(_("Please contribute if you find %s useful. "
518 "Visit %s for further information about the software."),
519 PACKAGE_NAME, URL_WEBSITE) +
520 "\n" +
521 strprintf(_("The source code is available from %s."),
522 URL_SOURCE_CODE) +
523 "\n" +
524 "\n" +
525 _("This is experimental software.") + "\n" +
526 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
527 "\n" +
528 strprintf(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard."), "<https://www.openssl.org>") +
529 "\n";
532 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
534 if (initialSync || !pBlockIndex)
535 return;
537 std::string strCmd = GetArg("-blocknotify", "");
539 boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
540 boost::thread t(runCommand, strCmd); // thread runs free
543 static bool fHaveGenesis = false;
544 static boost::mutex cs_GenesisWait;
545 static CConditionVariable condvar_GenesisWait;
547 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
549 if (pBlockIndex != NULL) {
551 boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
552 fHaveGenesis = true;
554 condvar_GenesisWait.notify_all();
558 struct CImportingNow
560 CImportingNow() {
561 assert(fImporting == false);
562 fImporting = true;
565 ~CImportingNow() {
566 assert(fImporting == true);
567 fImporting = false;
572 // If we're using -prune with -reindex, then delete block files that will be ignored by the
573 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
574 // is missing, do the same here to delete any later block files after a gap. Also delete all
575 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
576 // is in sync with what's actually on disk by the time we start downloading, so that pruning
577 // works correctly.
578 void CleanupBlockRevFiles()
580 std::map<std::string, fs::path> mapBlockFiles;
582 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
583 // Remove the rev files immediately and insert the blk file paths into an
584 // ordered map keyed by block file index.
585 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
586 fs::path blocksdir = GetDataDir() / "blocks";
587 for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
588 if (is_regular_file(*it) &&
589 it->path().filename().string().length() == 12 &&
590 it->path().filename().string().substr(8,4) == ".dat")
592 if (it->path().filename().string().substr(0,3) == "blk")
593 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
594 else if (it->path().filename().string().substr(0,3) == "rev")
595 remove(it->path());
599 // Remove all block files that aren't part of a contiguous set starting at
600 // zero by walking the ordered map (keys are block file indices) by
601 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
602 // start removing block files.
603 int nContigCounter = 0;
604 BOOST_FOREACH(const PAIRTYPE(std::string, fs::path)& item, mapBlockFiles) {
605 if (atoi(item.first) == nContigCounter) {
606 nContigCounter++;
607 continue;
609 remove(item.second);
613 void ThreadImport(std::vector<fs::path> vImportFiles)
615 const CChainParams& chainparams = Params();
616 RenameThread("bitcoin-loadblk");
619 CImportingNow imp;
621 // -reindex
622 if (fReindex) {
623 int nFile = 0;
624 while (true) {
625 CDiskBlockPos pos(nFile, 0);
626 if (!fs::exists(GetBlockPosFilename(pos, "blk")))
627 break; // No block files left to reindex
628 FILE *file = OpenBlockFile(pos, true);
629 if (!file)
630 break; // This error is logged in OpenBlockFile
631 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
632 LoadExternalBlockFile(chainparams, file, &pos);
633 nFile++;
635 pblocktree->WriteReindexing(false);
636 fReindex = false;
637 LogPrintf("Reindexing finished\n");
638 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
639 InitBlockIndex(chainparams);
642 // hardcoded $DATADIR/bootstrap.dat
643 fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
644 if (fs::exists(pathBootstrap)) {
645 FILE *file = fsbridge::fopen(pathBootstrap, "rb");
646 if (file) {
647 fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
648 LogPrintf("Importing bootstrap.dat...\n");
649 LoadExternalBlockFile(chainparams, file);
650 RenameOver(pathBootstrap, pathBootstrapOld);
651 } else {
652 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
656 // -loadblock=
657 BOOST_FOREACH(const fs::path& path, vImportFiles) {
658 FILE *file = fsbridge::fopen(path, "rb");
659 if (file) {
660 LogPrintf("Importing blocks file %s...\n", path.string());
661 LoadExternalBlockFile(chainparams, file);
662 } else {
663 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
667 // scan for better chains in the block chain database, that are not yet connected in the active best chain
668 CValidationState state;
669 if (!ActivateBestChain(state, chainparams)) {
670 LogPrintf("Failed to connect best block");
671 StartShutdown();
674 if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
675 LogPrintf("Stopping after block import\n");
676 StartShutdown();
678 } // End scope of CImportingNow
679 LoadMempool();
680 fDumpMempoolLater = !fRequestShutdown;
683 /** Sanity checks
684 * Ensure that Bitcoin is running in a usable environment with all
685 * necessary library support.
687 bool InitSanityCheck(void)
689 if(!ECC_InitSanityCheck()) {
690 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
691 return false;
694 if (!glibc_sanity_test() || !glibcxx_sanity_test())
695 return false;
697 if (!Random_SanityCheck()) {
698 InitError("OS cryptographic RNG sanity check failure. Aborting.");
699 return false;
702 return true;
705 bool AppInitServers(boost::thread_group& threadGroup)
707 RPCServer::OnStarted(&OnRPCStarted);
708 RPCServer::OnStopped(&OnRPCStopped);
709 RPCServer::OnPreCommand(&OnRPCPreCommand);
710 if (!InitHTTPServer())
711 return false;
712 if (!StartRPC())
713 return false;
714 if (!StartHTTPRPC())
715 return false;
716 if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
717 return false;
718 if (!StartHTTPServer())
719 return false;
720 return true;
723 // Parameter interaction based on rules
724 void InitParameterInteraction()
726 // when specifying an explicit binding address, you want to listen on it
727 // even when -connect or -proxy is specified
728 if (IsArgSet("-bind")) {
729 if (SoftSetBoolArg("-listen", true))
730 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
732 if (IsArgSet("-whitebind")) {
733 if (SoftSetBoolArg("-listen", true))
734 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
737 if (mapMultiArgs.count("-connect") && mapMultiArgs.at("-connect").size() > 0) {
738 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
739 if (SoftSetBoolArg("-dnsseed", false))
740 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
741 if (SoftSetBoolArg("-listen", false))
742 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
745 if (IsArgSet("-proxy")) {
746 // to protect privacy, do not listen by default if a default proxy server is specified
747 if (SoftSetBoolArg("-listen", false))
748 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
749 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
750 // to listen locally, so don't rely on this happening through -listen below.
751 if (SoftSetBoolArg("-upnp", false))
752 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
753 // to protect privacy, do not discover addresses by default
754 if (SoftSetBoolArg("-discover", false))
755 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
758 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
759 // do not map ports or try to retrieve public IP when not listening (pointless)
760 if (SoftSetBoolArg("-upnp", false))
761 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
762 if (SoftSetBoolArg("-discover", false))
763 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
764 if (SoftSetBoolArg("-listenonion", false))
765 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
768 if (IsArgSet("-externalip")) {
769 // if an explicit public IP is specified, do not try to find others
770 if (SoftSetBoolArg("-discover", false))
771 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
774 // disable whitelistrelay in blocksonly mode
775 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
776 if (SoftSetBoolArg("-whitelistrelay", false))
777 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
780 // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
781 if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
782 if (SoftSetBoolArg("-whitelistrelay", true))
783 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
787 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
789 return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
792 void InitLogging()
794 fPrintToConsole = GetBoolArg("-printtoconsole", false);
795 fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
796 fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
797 fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
799 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
800 LogPrintf("Bitcoin version %s\n", FormatFullVersion());
803 namespace { // Variables internal to initialization process only
805 ServiceFlags nRelevantServices = NODE_NETWORK;
806 int nMaxConnections;
807 int nUserMaxConnections;
808 int nFD;
809 ServiceFlags nLocalServices = NODE_NETWORK;
813 [[noreturn]] static void new_handler_terminate()
815 // Rather than throwing std::bad-alloc if allocation fails, terminate
816 // immediately to (try to) avoid chain corruption.
817 // Since LogPrintf may itself allocate memory, set the handler directly
818 // to terminate first.
819 std::set_new_handler(std::terminate);
820 LogPrintf("Error: Out of memory. Terminating.\n");
822 // The log was successful, terminate now.
823 std::terminate();
826 bool AppInitBasicSetup()
828 // ********************************************************* Step 1: setup
829 #ifdef _MSC_VER
830 // Turn off Microsoft heap dump noise
831 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
832 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
833 #endif
834 #if _MSC_VER >= 1400
835 // Disable confusing "helpful" text message on abort, Ctrl-C
836 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
837 #endif
838 #ifdef WIN32
839 // Enable Data Execution Prevention (DEP)
840 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
841 // A failure is non-critical and needs no further attention!
842 #ifndef PROCESS_DEP_ENABLE
843 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
844 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
845 #define PROCESS_DEP_ENABLE 0x00000001
846 #endif
847 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
848 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
849 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
850 #endif
852 if (!SetupNetworking())
853 return InitError("Initializing networking failed");
855 #ifndef WIN32
856 if (!GetBoolArg("-sysperms", false)) {
857 umask(077);
860 // Clean shutdown on SIGTERM
861 registerSignalHandler(SIGTERM, HandleSIGTERM);
862 registerSignalHandler(SIGINT, HandleSIGTERM);
864 // Reopen debug.log on SIGHUP
865 registerSignalHandler(SIGHUP, HandleSIGHUP);
867 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
868 signal(SIGPIPE, SIG_IGN);
869 #endif
871 std::set_new_handler(new_handler_terminate);
873 return true;
876 bool AppInitParameterInteraction()
878 const CChainParams& chainparams = Params();
879 // ********************************************************* Step 2: parameter interactions
881 // also see: InitParameterInteraction()
883 // if using block pruning, then disallow txindex
884 if (GetArg("-prune", 0)) {
885 if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
886 return InitError(_("Prune mode is incompatible with -txindex."));
889 // Make sure enough file descriptors are available
890 int nBind = std::max(
891 (mapMultiArgs.count("-bind") ? mapMultiArgs.at("-bind").size() : 0) +
892 (mapMultiArgs.count("-whitebind") ? mapMultiArgs.at("-whitebind").size() : 0), size_t(1));
893 nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
894 nMaxConnections = std::max(nUserMaxConnections, 0);
896 // Trim requested connection counts, to fit into system limitations
897 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
898 nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
899 if (nFD < MIN_CORE_FILEDESCRIPTORS)
900 return InitError(_("Not enough file descriptors available."));
901 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
903 if (nMaxConnections < nUserMaxConnections)
904 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
906 // ********************************************************* Step 3: parameter-to-internal-flags
907 if (mapMultiArgs.count("-debug") > 0) {
908 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
909 const std::vector<std::string>& categories = mapMultiArgs.at("-debug");
911 if (find(categories.begin(), categories.end(), std::string("0")) == categories.end()) {
912 for (const auto& cat : categories) {
913 uint32_t flag = 0;
914 if (!GetLogCategory(&flag, &cat)) {
915 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
916 continue;
918 logCategories |= flag;
923 // Now remove the logging categories which were explicitly excluded
924 if (mapMultiArgs.count("-debugexclude") > 0) {
925 const std::vector<std::string>& excludedCategories = mapMultiArgs.at("-debugexclude");
926 for (const auto& cat : excludedCategories) {
927 uint32_t flag = 0;
928 if (!GetLogCategory(&flag, &cat)) {
929 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
930 continue;
932 logCategories &= ~flag;
936 // Check for -debugnet
937 if (GetBoolArg("-debugnet", false))
938 InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
939 // Check for -socks - as this is a privacy risk to continue, exit here
940 if (IsArgSet("-socks"))
941 return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
942 // Check for -tor - as this is a privacy risk to continue, exit here
943 if (GetBoolArg("-tor", false))
944 return InitError(_("Unsupported argument -tor found, use -onion."));
946 if (GetBoolArg("-benchmark", false))
947 InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
949 if (GetBoolArg("-whitelistalwaysrelay", false))
950 InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
952 if (IsArgSet("-blockminsize"))
953 InitWarning("Unsupported argument -blockminsize ignored.");
955 // Checkmempool and checkblockindex default to true in regtest mode
956 int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
957 if (ratio != 0) {
958 mempool.setSanityCheck(1.0 / ratio);
960 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
961 fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
963 hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
964 if (!hashAssumeValid.IsNull())
965 LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
966 else
967 LogPrintf("Validating signatures for all blocks.\n");
969 // mempool limits
970 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
971 int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
972 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
973 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
974 // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
975 // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
976 if (IsArgSet("-incrementalrelayfee"))
978 CAmount n = 0;
979 if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n))
980 return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", "")));
981 incrementalRelayFee = CFeeRate(n);
984 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
985 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
986 if (nScriptCheckThreads <= 0)
987 nScriptCheckThreads += GetNumCores();
988 if (nScriptCheckThreads <= 1)
989 nScriptCheckThreads = 0;
990 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
991 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
993 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
994 int64_t nPruneArg = GetArg("-prune", 0);
995 if (nPruneArg < 0) {
996 return InitError(_("Prune cannot be configured with a negative value."));
998 nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
999 if (nPruneArg == 1) { // manual pruning: -prune=1
1000 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1001 nPruneTarget = std::numeric_limits<uint64_t>::max();
1002 fPruneMode = true;
1003 } else if (nPruneTarget) {
1004 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
1005 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1007 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1008 fPruneMode = true;
1011 RegisterAllCoreRPCCommands(tableRPC);
1012 #ifdef ENABLE_WALLET
1013 RegisterWalletRPCCommands(tableRPC);
1014 #endif
1016 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1017 if (nConnectTimeout <= 0)
1018 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1020 // Fee-per-kilobyte amount required for mempool acceptance and relay
1021 // If you are mining, be careful setting this:
1022 // if you set it to zero then
1023 // a transaction spammer can cheaply fill blocks using
1024 // 0-fee transactions. It should be set above the real
1025 // cost to you of processing a transaction.
1026 if (IsArgSet("-minrelaytxfee"))
1028 CAmount n = 0;
1029 if (!ParseMoney(GetArg("-minrelaytxfee", ""), n)) {
1030 return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
1032 // High fee check is done afterward in CWallet::ParameterInteraction()
1033 ::minRelayTxFee = CFeeRate(n);
1034 } else if (incrementalRelayFee > ::minRelayTxFee) {
1035 // Allow only setting incrementalRelayFee to control both
1036 ::minRelayTxFee = incrementalRelayFee;
1037 LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1040 // Sanity check argument for min fee for including tx in block
1041 // TODO: Harmonize which arguments need sanity checking and where that happens
1042 if (IsArgSet("-blockmintxfee"))
1044 CAmount n = 0;
1045 if (!ParseMoney(GetArg("-blockmintxfee", ""), n))
1046 return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", "")));
1049 // Feerate used to define dust. Shouldn't be changed lightly as old
1050 // implementations may inadvertently create non-standard transactions
1051 if (IsArgSet("-dustrelayfee"))
1053 CAmount n = 0;
1054 if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n)
1055 return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", "")));
1056 dustRelayFee = CFeeRate(n);
1059 fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1060 if (chainparams.RequireStandard() && !fRequireStandard)
1061 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1062 nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
1064 #ifdef ENABLE_WALLET
1065 if (!CWallet::ParameterInteraction())
1066 return false;
1067 #endif
1069 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1070 fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1071 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1073 // Option to startup with mocktime set (used for regression testing):
1074 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1076 if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1077 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1079 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1080 return InitError("rpcserialversion must be non-negative.");
1082 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1083 return InitError("unknown rpcserialversion requested.");
1085 nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1087 fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1088 if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
1089 // Minimal effort at forwards compatibility
1090 std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
1091 std::vector<std::string> vstrReplacementModes;
1092 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1093 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1096 if (mapMultiArgs.count("-bip9params")) {
1097 // Allow overriding BIP9 parameters for testing
1098 if (!chainparams.MineBlocksOnDemand()) {
1099 return InitError("BIP9 parameters may only be overridden on regtest.");
1101 const std::vector<std::string>& deployments = mapMultiArgs.at("-bip9params");
1102 for (auto i : deployments) {
1103 std::vector<std::string> vDeploymentParams;
1104 boost::split(vDeploymentParams, i, boost::is_any_of(":"));
1105 if (vDeploymentParams.size() != 3) {
1106 return InitError("BIP9 parameters malformed, expecting deployment:start:end");
1108 int64_t nStartTime, nTimeout;
1109 if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1110 return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1112 if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1113 return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1115 bool found = false;
1116 for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1118 if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1119 UpdateRegtestBIP9Parameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1120 found = true;
1121 LogPrintf("Setting BIP9 activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1122 break;
1125 if (!found) {
1126 return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1130 return true;
1133 static bool LockDataDirectory(bool probeOnly)
1135 std::string strDataDir = GetDataDir().string();
1137 // Make sure only a single Bitcoin process is using the data directory.
1138 fs::path pathLockFile = GetDataDir() / ".lock";
1139 FILE* file = fsbridge::fopen(pathLockFile, "a"); // empty lock file; created if it doesn't exist.
1140 if (file) fclose(file);
1142 try {
1143 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1144 if (!lock.try_lock()) {
1145 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1147 if (probeOnly) {
1148 lock.unlock();
1150 } catch(const boost::interprocess::interprocess_exception& e) {
1151 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1153 return true;
1156 bool AppInitSanityChecks()
1158 // ********************************************************* Step 4: sanity checks
1160 // Initialize elliptic curve code
1161 ECC_Start();
1162 globalVerifyHandle.reset(new ECCVerifyHandle());
1164 // Sanity check
1165 if (!InitSanityCheck())
1166 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1168 // Probe the data directory lock to give an early error message, if possible
1169 return LockDataDirectory(true);
1172 bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
1174 const CChainParams& chainparams = Params();
1175 // ********************************************************* Step 4a: application initialization
1176 // After daemonization get the data directory lock again and hold on to it until exit
1177 // This creates a slight window for a race condition to happen, however this condition is harmless: it
1178 // will at most make us exit without printing a message to console.
1179 if (!LockDataDirectory(false)) {
1180 // Detailed error printed inside LockDataDirectory
1181 return false;
1184 #ifndef WIN32
1185 CreatePidFile(GetPidFile(), getpid());
1186 #endif
1187 if (GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
1188 // Do this first since it both loads a bunch of debug.log into memory,
1189 // and because this needs to happen before any other debug.log printing
1190 ShrinkDebugFile();
1193 if (fPrintToDebugLog)
1194 OpenDebugLog();
1196 if (!fLogTimestamps)
1197 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1198 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1199 LogPrintf("Using data directory %s\n", GetDataDir().string());
1200 LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1201 LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1203 InitSignatureCache();
1205 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1206 if (nScriptCheckThreads) {
1207 for (int i=0; i<nScriptCheckThreads-1; i++)
1208 threadGroup.create_thread(&ThreadScriptCheck);
1211 // Start the lightweight task scheduler thread
1212 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1213 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1215 /* Start the RPC server already. It will be started in "warmup" mode
1216 * and not really process calls already (but it will signify connections
1217 * that the server is there and will be ready later). Warmup mode will
1218 * be disabled when initialisation is finished.
1220 if (GetBoolArg("-server", false))
1222 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1223 if (!AppInitServers(threadGroup))
1224 return InitError(_("Unable to start HTTP server. See debug log for details."));
1227 int64_t nStart;
1229 // ********************************************************* Step 5: verify wallet database integrity
1230 #ifdef ENABLE_WALLET
1231 if (!CWallet::Verify())
1232 return false;
1233 #endif
1234 // ********************************************************* Step 6: network initialization
1235 // Note that we absolutely cannot open any actual connections
1236 // until the very end ("start node") as the UTXO/block state
1237 // is not yet setup and may end up being set up twice if we
1238 // need to reindex later.
1240 assert(!g_connman);
1241 g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1242 CConnman& connman = *g_connman;
1244 peerLogic.reset(new PeerLogicValidation(&connman));
1245 RegisterValidationInterface(peerLogic.get());
1246 RegisterNodeSignals(GetNodeSignals());
1248 // sanitize comments per BIP-0014, format user agent and check total size
1249 std::vector<std::string> uacomments;
1250 if (mapMultiArgs.count("-uacomment")) {
1251 BOOST_FOREACH(std::string cmt, mapMultiArgs.at("-uacomment"))
1253 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1254 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1255 uacomments.push_back(cmt);
1258 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1259 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1260 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1261 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1264 if (mapMultiArgs.count("-onlynet")) {
1265 std::set<enum Network> nets;
1266 BOOST_FOREACH(const std::string& snet, mapMultiArgs.at("-onlynet")) {
1267 enum Network net = ParseNetwork(snet);
1268 if (net == NET_UNROUTABLE)
1269 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1270 nets.insert(net);
1272 for (int n = 0; n < NET_MAX; n++) {
1273 enum Network net = (enum Network)n;
1274 if (!nets.count(net))
1275 SetLimited(net);
1279 if (mapMultiArgs.count("-whitelist")) {
1280 BOOST_FOREACH(const std::string& net, mapMultiArgs.at("-whitelist")) {
1281 CSubNet subnet;
1282 LookupSubNet(net.c_str(), subnet);
1283 if (!subnet.IsValid())
1284 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1285 connman.AddWhitelistedRange(subnet);
1289 // Check for host lookup allowed before parsing any network related parameters
1290 fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1292 bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1293 // -proxy sets a proxy for all outgoing network traffic
1294 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1295 std::string proxyArg = GetArg("-proxy", "");
1296 SetLimited(NET_TOR);
1297 if (proxyArg != "" && proxyArg != "0") {
1298 CService proxyAddr;
1299 if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1300 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1303 proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1304 if (!addrProxy.IsValid())
1305 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1307 SetProxy(NET_IPV4, addrProxy);
1308 SetProxy(NET_IPV6, addrProxy);
1309 SetProxy(NET_TOR, addrProxy);
1310 SetNameProxy(addrProxy);
1311 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1314 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1315 // -noonion (or -onion=0) disables connecting to .onion entirely
1316 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1317 std::string onionArg = GetArg("-onion", "");
1318 if (onionArg != "") {
1319 if (onionArg == "0") { // Handle -noonion/-onion=0
1320 SetLimited(NET_TOR); // set onions as unreachable
1321 } else {
1322 CService onionProxy;
1323 if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1324 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1326 proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1327 if (!addrOnion.IsValid())
1328 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1329 SetProxy(NET_TOR, addrOnion);
1330 SetLimited(NET_TOR, false);
1334 // see Step 2: parameter interactions for more information about these
1335 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1336 fDiscover = GetBoolArg("-discover", true);
1337 fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1339 if (fListen) {
1340 bool fBound = false;
1341 if (mapMultiArgs.count("-bind")) {
1342 BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-bind")) {
1343 CService addrBind;
1344 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1345 return InitError(ResolveErrMsg("bind", strBind));
1346 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1349 if (mapMultiArgs.count("-whitebind")) {
1350 BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-whitebind")) {
1351 CService addrBind;
1352 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1353 return InitError(ResolveErrMsg("whitebind", strBind));
1354 if (addrBind.GetPort() == 0)
1355 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1356 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1359 if (!mapMultiArgs.count("-bind") && !mapMultiArgs.count("-whitebind")) {
1360 struct in_addr inaddr_any;
1361 inaddr_any.s_addr = INADDR_ANY;
1362 fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
1363 fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1365 if (!fBound)
1366 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1369 if (mapMultiArgs.count("-externalip")) {
1370 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-externalip")) {
1371 CService addrLocal;
1372 if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1373 AddLocal(addrLocal, LOCAL_MANUAL);
1374 else
1375 return InitError(ResolveErrMsg("externalip", strAddr));
1379 if (mapMultiArgs.count("-seednode")) {
1380 BOOST_FOREACH(const std::string& strDest, mapMultiArgs.at("-seednode"))
1381 connman.AddOneShot(strDest);
1384 #if ENABLE_ZMQ
1385 pzmqNotificationInterface = CZMQNotificationInterface::Create();
1387 if (pzmqNotificationInterface) {
1388 RegisterValidationInterface(pzmqNotificationInterface);
1390 #endif
1391 uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1392 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1394 if (IsArgSet("-maxuploadtarget")) {
1395 nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1398 // ********************************************************* Step 7: load block chain
1400 fReindex = GetBoolArg("-reindex", false);
1401 bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
1403 fs::create_directories(GetDataDir() / "blocks");
1405 // cache size calculations
1406 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1407 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1408 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1409 int64_t nBlockTreeDBCache = nTotalCache / 8;
1410 nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1411 nTotalCache -= nBlockTreeDBCache;
1412 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1413 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1414 nTotalCache -= nCoinDBCache;
1415 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1416 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1417 LogPrintf("Cache configuration:\n");
1418 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1419 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1420 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));
1422 bool fLoaded = false;
1423 while (!fLoaded) {
1424 bool fReset = fReindex;
1425 std::string strLoadError;
1427 uiInterface.InitMessage(_("Loading block index..."));
1429 nStart = GetTimeMillis();
1430 do {
1431 try {
1432 UnloadBlockIndex();
1433 delete pcoinsTip;
1434 delete pcoinsdbview;
1435 delete pcoinscatcher;
1436 delete pblocktree;
1438 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1439 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState);
1440 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1441 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1443 if (fReindex) {
1444 pblocktree->WriteReindexing(true);
1445 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1446 if (fPruneMode)
1447 CleanupBlockRevFiles();
1450 if (!LoadBlockIndex(chainparams)) {
1451 strLoadError = _("Error loading block database");
1452 break;
1455 // If the loaded chain has a wrong genesis, bail out immediately
1456 // (we're likely using a testnet datadir, or the other way around).
1457 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1458 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1460 // Initialize the block index (no-op if non-empty database was already loaded)
1461 if (!InitBlockIndex(chainparams)) {
1462 strLoadError = _("Error initializing block database");
1463 break;
1466 // Check for changed -txindex state
1467 if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1468 strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
1469 break;
1472 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1473 // in the past, but is now trying to run unpruned.
1474 if (fHavePruned && !fPruneMode) {
1475 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1476 break;
1479 if (!fReindex && chainActive.Tip() != NULL) {
1480 uiInterface.InitMessage(_("Rewinding blocks..."));
1481 if (!RewindBlockIndex(chainparams)) {
1482 strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1483 break;
1487 uiInterface.InitMessage(_("Verifying blocks..."));
1488 if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1489 LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
1490 MIN_BLOCKS_TO_KEEP);
1494 LOCK(cs_main);
1495 CBlockIndex* tip = chainActive.Tip();
1496 RPCNotifyBlockChange(true, tip);
1497 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1498 strLoadError = _("The block database contains a block which appears to be from the future. "
1499 "This may be due to your computer's date and time being set incorrectly. "
1500 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1501 break;
1505 if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1506 GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1507 strLoadError = _("Corrupted block database detected");
1508 break;
1510 } catch (const std::exception& e) {
1511 LogPrintf("%s\n", e.what());
1512 strLoadError = _("Error opening block database");
1513 break;
1516 fLoaded = true;
1517 } while(false);
1519 if (!fLoaded) {
1520 // first suggest a reindex
1521 if (!fReset) {
1522 bool fRet = uiInterface.ThreadSafeQuestion(
1523 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1524 strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1525 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1526 if (fRet) {
1527 fReindex = true;
1528 fRequestShutdown = false;
1529 } else {
1530 LogPrintf("Aborted block database rebuild. Exiting.\n");
1531 return false;
1533 } else {
1534 return InitError(strLoadError);
1539 // As LoadBlockIndex can take several minutes, it's possible the user
1540 // requested to kill the GUI during the last operation. If so, exit.
1541 // As the program has not fully started yet, Shutdown() is possibly overkill.
1542 if (fRequestShutdown)
1544 LogPrintf("Shutdown requested. Exiting.\n");
1545 return false;
1547 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1549 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1550 CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
1551 // Allowed to fail as this file IS missing on first startup.
1552 if (!est_filein.IsNull())
1553 mempool.ReadFeeEstimates(est_filein);
1554 fFeeEstimatesInitialized = true;
1556 // ********************************************************* Step 8: load wallet
1557 #ifdef ENABLE_WALLET
1558 if (!CWallet::InitLoadWallet())
1559 return false;
1560 #else
1561 LogPrintf("No wallet support compiled in!\n");
1562 #endif
1564 // ********************************************************* Step 9: data directory maintenance
1566 // if pruning, unset the service bit and perform the initial blockstore prune
1567 // after any wallet rescanning has taken place.
1568 if (fPruneMode) {
1569 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1570 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1571 if (!fReindex) {
1572 uiInterface.InitMessage(_("Pruning blockstore..."));
1573 PruneAndFlush();
1577 if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
1578 // Only advertise witness capabilities if they have a reasonable start time.
1579 // This allows us to have the code merged without a defined softfork, by setting its
1580 // end time to 0.
1581 // Note that setting NODE_WITNESS is never required: the only downside from not
1582 // doing so is that after activation, no upgraded nodes will fetch from you.
1583 nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1584 // Only care about others providing witness capabilities if there is a softfork
1585 // defined.
1586 nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS);
1589 // ********************************************************* Step 10: import blocks
1591 if (!CheckDiskSpace())
1592 return false;
1594 // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1595 // No locking, as this happens before any background thread is started.
1596 if (chainActive.Tip() == NULL) {
1597 uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1598 } else {
1599 fHaveGenesis = true;
1602 if (IsArgSet("-blocknotify"))
1603 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1605 std::vector<fs::path> vImportFiles;
1606 if (mapMultiArgs.count("-loadblock"))
1608 BOOST_FOREACH(const std::string& strFile, mapMultiArgs.at("-loadblock"))
1609 vImportFiles.push_back(strFile);
1612 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1614 // Wait for genesis block to be processed
1616 boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
1617 while (!fHaveGenesis) {
1618 condvar_GenesisWait.wait(lock);
1620 uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1623 // ********************************************************* Step 11: start node
1625 //// debug print
1626 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1627 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1628 if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1629 StartTorControl(threadGroup, scheduler);
1631 Discover(threadGroup);
1633 // Map ports with UPnP
1634 MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
1636 std::string strNodeError;
1637 CConnman::Options connOptions;
1638 connOptions.nLocalServices = nLocalServices;
1639 connOptions.nRelevantServices = nRelevantServices;
1640 connOptions.nMaxConnections = nMaxConnections;
1641 connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1642 connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1643 connOptions.nMaxFeeler = 1;
1644 connOptions.nBestHeight = chainActive.Height();
1645 connOptions.uiInterface = &uiInterface;
1646 connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1647 connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1649 connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1650 connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1652 if (!connman.Start(scheduler, strNodeError, connOptions))
1653 return InitError(strNodeError);
1655 // ********************************************************* Step 12: finished
1657 SetRPCWarmupFinished();
1658 uiInterface.InitMessage(_("Done loading"));
1660 #ifdef ENABLE_WALLET
1661 if (pwalletMain)
1662 pwalletMain->postInitProcess(scheduler);
1663 #endif
1665 return !fRequestShutdown;