Merge #9911: Wshadow: various gcc fixes
[bitcoinplatinum.git] / src / init.cpp
blob246d5f340a1a553bec2f475a6c84891680d0db9b
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 "httpserver.h"
20 #include "httprpc.h"
21 #include "key.h"
22 #include "validation.h"
23 #include "miner.h"
24 #include "netbase.h"
25 #include "net.h"
26 #include "net_processing.h"
27 #include "policy/policy.h"
28 #include "rpc/server.h"
29 #include "rpc/register.h"
30 #include "script/standard.h"
31 #include "script/sigcache.h"
32 #include "scheduler.h"
33 #include "timedata.h"
34 #include "txdb.h"
35 #include "txmempool.h"
36 #include "torcontrol.h"
37 #include "ui_interface.h"
38 #include "util.h"
39 #include "utilmoneystr.h"
40 #include "validationinterface.h"
41 #ifdef ENABLE_WALLET
42 #include "wallet/wallet.h"
43 #endif
44 #include "warnings.h"
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <memory>
49 #ifndef WIN32
50 #include <signal.h>
51 #endif
53 #include <boost/algorithm/string/classification.hpp>
54 #include <boost/algorithm/string/predicate.hpp>
55 #include <boost/algorithm/string/replace.hpp>
56 #include <boost/algorithm/string/split.hpp>
57 #include <boost/bind.hpp>
58 #include <boost/filesystem.hpp>
59 #include <boost/function.hpp>
60 #include <boost/interprocess/sync/file_lock.hpp>
61 #include <boost/thread.hpp>
62 #include <openssl/crypto.h>
64 #if ENABLE_ZMQ
65 #include "zmq/zmqnotificationinterface.h"
66 #endif
68 bool fFeeEstimatesInitialized = false;
69 static const bool DEFAULT_PROXYRANDOMIZE = true;
70 static const bool DEFAULT_REST_ENABLE = false;
71 static const bool DEFAULT_DISABLE_SAFEMODE = false;
72 static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
74 std::unique_ptr<CConnman> g_connman;
75 std::unique_ptr<PeerLogicValidation> peerLogic;
77 #if ENABLE_ZMQ
78 static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
79 #endif
81 #ifdef WIN32
82 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
83 // accessing block files don't count towards the fd_set size limit
84 // anyway.
85 #define MIN_CORE_FILEDESCRIPTORS 0
86 #else
87 #define MIN_CORE_FILEDESCRIPTORS 150
88 #endif
90 /** Used to pass flags to the Bind() function */
91 enum BindFlags {
92 BF_NONE = 0,
93 BF_EXPLICIT = (1U << 0),
94 BF_REPORT_ERROR = (1U << 1),
95 BF_WHITELIST = (1U << 2),
98 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
100 //////////////////////////////////////////////////////////////////////////////
102 // Shutdown
106 // Thread management and startup/shutdown:
108 // The network-processing threads are all part of a thread group
109 // created by AppInit() or the Qt main() function.
111 // A clean exit happens when StartShutdown() or the SIGTERM
112 // signal handler sets fRequestShutdown, which triggers
113 // the DetectShutdownThread(), which interrupts the main thread group.
114 // DetectShutdownThread() then exits, which causes AppInit() to
115 // continue (it .joins the shutdown thread).
116 // Shutdown() is then
117 // called to clean up database connections, and stop other
118 // threads that should only be stopped after the main network-processing
119 // threads have exited.
121 // Shutdown for Qt is very similar, only it uses a QTimer to detect
122 // fRequestShutdown getting set, and then does the normal Qt
123 // shutdown thing.
126 std::atomic<bool> fRequestShutdown(false);
127 std::atomic<bool> fDumpMempoolLater(false);
129 void StartShutdown()
131 fRequestShutdown = true;
133 bool ShutdownRequested()
135 return fRequestShutdown;
139 * This is a minimally invasive approach to shutdown on LevelDB read errors from the
140 * chainstate, while keeping user interface out of the common library, which is shared
141 * between bitcoind, and bitcoin-qt and non-server tools.
143 class CCoinsViewErrorCatcher : public CCoinsViewBacked
145 public:
146 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
147 bool GetCoins(const uint256 &txid, CCoins &coins) const {
148 try {
149 return CCoinsViewBacked::GetCoins(txid, coins);
150 } catch(const std::runtime_error& e) {
151 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
152 LogPrintf("Error reading from database: %s\n", e.what());
153 // Starting the shutdown sequence and returning false to the caller would be
154 // interpreted as 'entry not found' (as opposed to unable to read data), and
155 // could lead to invalid interpretation. Just exit immediately, as we can't
156 // continue anyway, and all writes should be atomic.
157 abort();
160 // Writes do not need similar protection, as failure to write is handled by the caller.
163 static CCoinsViewDB *pcoinsdbview = NULL;
164 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
165 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
167 void Interrupt(boost::thread_group& threadGroup)
169 InterruptHTTPServer();
170 InterruptHTTPRPC();
171 InterruptRPC();
172 InterruptREST();
173 InterruptTorControl();
174 if (g_connman)
175 g_connman->Interrupt();
176 threadGroup.interrupt_all();
179 void Shutdown()
181 LogPrintf("%s: In progress...\n", __func__);
182 static CCriticalSection cs_Shutdown;
183 TRY_LOCK(cs_Shutdown, lockShutdown);
184 if (!lockShutdown)
185 return;
187 /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
188 /// for example if the data directory was found to be locked.
189 /// Be sure that anything that writes files or flushes caches only does this if the respective
190 /// module was initialized.
191 RenameThread("bitcoin-shutoff");
192 mempool.AddTransactionsUpdated(1);
194 StopHTTPRPC();
195 StopREST();
196 StopRPC();
197 StopHTTPServer();
198 #ifdef ENABLE_WALLET
199 if (pwalletMain)
200 pwalletMain->Flush(false);
201 #endif
202 MapPort(false);
203 UnregisterValidationInterface(peerLogic.get());
204 peerLogic.reset();
205 g_connman.reset();
207 StopTorControl();
208 UnregisterNodeSignals(GetNodeSignals());
209 if (fDumpMempoolLater)
210 DumpMempool();
212 if (fFeeEstimatesInitialized)
214 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
215 CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
216 if (!est_fileout.IsNull())
217 mempool.WriteFeeEstimates(est_fileout);
218 else
219 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
220 fFeeEstimatesInitialized = false;
224 LOCK(cs_main);
225 if (pcoinsTip != NULL) {
226 FlushStateToDisk();
228 delete pcoinsTip;
229 pcoinsTip = NULL;
230 delete pcoinscatcher;
231 pcoinscatcher = NULL;
232 delete pcoinsdbview;
233 pcoinsdbview = NULL;
234 delete pblocktree;
235 pblocktree = NULL;
237 #ifdef ENABLE_WALLET
238 if (pwalletMain)
239 pwalletMain->Flush(true);
240 #endif
242 #if ENABLE_ZMQ
243 if (pzmqNotificationInterface) {
244 UnregisterValidationInterface(pzmqNotificationInterface);
245 delete pzmqNotificationInterface;
246 pzmqNotificationInterface = NULL;
248 #endif
250 #ifndef WIN32
251 try {
252 boost::filesystem::remove(GetPidFile());
253 } catch (const boost::filesystem::filesystem_error& e) {
254 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
256 #endif
257 UnregisterAllValidationInterfaces();
258 #ifdef ENABLE_WALLET
259 delete pwalletMain;
260 pwalletMain = NULL;
261 #endif
262 globalVerifyHandle.reset();
263 ECC_Stop();
264 LogPrintf("%s: done\n", __func__);
268 * Signal handlers are very limited in what they are allowed to do, so:
270 void HandleSIGTERM(int)
272 fRequestShutdown = true;
275 void HandleSIGHUP(int)
277 fReopenDebugLog = true;
280 bool static Bind(CConnman& connman, const CService &addr, unsigned int flags) {
281 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
282 return false;
283 std::string strError;
284 if (!connman.BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
285 if (flags & BF_REPORT_ERROR)
286 return InitError(strError);
287 return false;
289 return true;
291 void OnRPCStarted()
293 uiInterface.NotifyBlockTip.connect(&RPCNotifyBlockChange);
296 void OnRPCStopped()
298 uiInterface.NotifyBlockTip.disconnect(&RPCNotifyBlockChange);
299 RPCNotifyBlockChange(false, nullptr);
300 cvBlockChange.notify_all();
301 LogPrint("rpc", "RPC stopped.\n");
304 void OnRPCPreCommand(const CRPCCommand& cmd)
306 // Observe safe mode
307 std::string strWarning = GetWarnings("rpc");
308 if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
309 !cmd.okSafeMode)
310 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
313 std::string HelpMessage(HelpMessageMode mode)
315 const bool showDebug = GetBoolArg("-help-debug", false);
317 // When adding new options to the categories, please keep and ensure alphabetical ordering.
318 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
319 std::string strUsage = HelpMessageGroup(_("Options:"));
320 strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
321 strUsage += HelpMessageOpt("-version", _("Print version and exit"));
322 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)"));
323 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
324 if (showDebug)
325 strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
326 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()));
327 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
328 if (mode == HMM_BITCOIND)
330 #if HAVE_DECL_DAEMON
331 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
332 #endif
334 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
335 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
336 if (showDebug)
337 strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
338 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
339 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
340 strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
341 strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
342 strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
343 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)"),
344 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
345 #ifndef WIN32
346 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
347 #endif
348 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. "
349 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
350 "(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));
351 strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
352 strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
353 #ifndef WIN32
354 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
355 #endif
356 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
358 strUsage += HelpMessageGroup(_("Connection options:"));
359 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
360 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
361 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
362 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
363 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -noconnect or -connect=0 alone to disable automatic connections"));
364 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
365 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
366 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect/-noconnect)"));
367 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
368 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
369 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect/-noconnect)"));
370 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
371 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
372 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
373 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
374 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));
375 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
376 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
377 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
378 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
379 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), Params(CBaseChainParams::MAIN).GetDefaultPort(), Params(CBaseChainParams::TESTNET).GetDefaultPort()));
380 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
381 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
382 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));
383 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
384 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
385 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
386 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
387 #ifdef USE_UPNP
388 #if USE_UPNP
389 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
390 #else
391 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
392 #endif
393 #endif
394 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
395 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.") +
396 " " + _("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"));
397 strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
398 strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
399 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));
401 #ifdef ENABLE_WALLET
402 strUsage += CWallet::GetWalletHelpString(showDebug);
403 #endif
405 #if ENABLE_ZMQ
406 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
407 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
408 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
409 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
410 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
411 #endif
413 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
414 strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
415 if (showDebug)
417 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
418 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
419 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()));
420 strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
421 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
422 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
423 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
424 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
425 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
426 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
427 strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
428 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));
429 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));
430 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));
431 strUsage += HelpMessageOpt("-bip9params=deployment:start:end", "Use given start/end times for specified BIP9 deployment (regtest-only)");
433 std::string debugCategories = "addrman, alert, bench, cmpctblock, coindb, db, http, leveldb, libevent, lock, mempool, mempoolrej, net, proxy, prune, rand, reindex, rpc, selectcoins, tor, zmq"; // Don't translate these and qt below
434 if (mode == HMM_BITCOIN_QT)
435 debugCategories += ", qt";
436 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
437 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
438 if (showDebug)
439 strUsage += HelpMessageOpt("-nodebug", "Turn off debugging messages, same as -debug=0");
440 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
441 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
442 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
443 if (showDebug)
445 strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
446 strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
447 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
448 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
450 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
451 CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
452 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)"),
453 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
454 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
455 if (showDebug)
457 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
459 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
461 AppendParamsHelpMessages(strUsage, showDebug);
463 strUsage += HelpMessageGroup(_("Node relay options:"));
464 if (showDebug) {
465 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
466 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)));
467 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)));
469 strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
470 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
471 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
472 strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
474 strUsage += HelpMessageGroup(_("Block creation options:"));
475 strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
476 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
477 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)));
478 if (showDebug)
479 strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
481 strUsage += HelpMessageGroup(_("RPC server options:"));
482 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
483 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
484 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)"));
485 strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
486 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
487 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
488 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"));
489 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()));
490 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"));
491 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
492 if (showDebug) {
493 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
494 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
497 return strUsage;
500 std::string LicenseInfo()
502 const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
503 const std::string URL_WEBSITE = "<https://bitcoincore.org>";
505 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
506 "\n" +
507 strprintf(_("Please contribute if you find %s useful. "
508 "Visit %s for further information about the software."),
509 PACKAGE_NAME, URL_WEBSITE) +
510 "\n" +
511 strprintf(_("The source code is available from %s."),
512 URL_SOURCE_CODE) +
513 "\n" +
514 "\n" +
515 _("This is experimental software.") + "\n" +
516 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
517 "\n" +
518 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>") +
519 "\n";
522 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
524 if (initialSync || !pBlockIndex)
525 return;
527 std::string strCmd = GetArg("-blocknotify", "");
529 boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
530 boost::thread t(runCommand, strCmd); // thread runs free
533 static bool fHaveGenesis = false;
534 static boost::mutex cs_GenesisWait;
535 static CConditionVariable condvar_GenesisWait;
537 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
539 if (pBlockIndex != NULL) {
541 boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
542 fHaveGenesis = true;
544 condvar_GenesisWait.notify_all();
548 struct CImportingNow
550 CImportingNow() {
551 assert(fImporting == false);
552 fImporting = true;
555 ~CImportingNow() {
556 assert(fImporting == true);
557 fImporting = false;
562 // If we're using -prune with -reindex, then delete block files that will be ignored by the
563 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
564 // is missing, do the same here to delete any later block files after a gap. Also delete all
565 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
566 // is in sync with what's actually on disk by the time we start downloading, so that pruning
567 // works correctly.
568 void CleanupBlockRevFiles()
570 std::map<std::string, boost::filesystem::path> mapBlockFiles;
572 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
573 // Remove the rev files immediately and insert the blk file paths into an
574 // ordered map keyed by block file index.
575 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
576 boost::filesystem::path blocksdir = GetDataDir() / "blocks";
577 for (boost::filesystem::directory_iterator it(blocksdir); it != boost::filesystem::directory_iterator(); it++) {
578 if (is_regular_file(*it) &&
579 it->path().filename().string().length() == 12 &&
580 it->path().filename().string().substr(8,4) == ".dat")
582 if (it->path().filename().string().substr(0,3) == "blk")
583 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
584 else if (it->path().filename().string().substr(0,3) == "rev")
585 remove(it->path());
589 // Remove all block files that aren't part of a contiguous set starting at
590 // zero by walking the ordered map (keys are block file indices) by
591 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
592 // start removing block files.
593 int nContigCounter = 0;
594 BOOST_FOREACH(const PAIRTYPE(std::string, boost::filesystem::path)& item, mapBlockFiles) {
595 if (atoi(item.first) == nContigCounter) {
596 nContigCounter++;
597 continue;
599 remove(item.second);
603 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
605 const CChainParams& chainparams = Params();
606 RenameThread("bitcoin-loadblk");
609 CImportingNow imp;
611 // -reindex
612 if (fReindex) {
613 int nFile = 0;
614 while (true) {
615 CDiskBlockPos pos(nFile, 0);
616 if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
617 break; // No block files left to reindex
618 FILE *file = OpenBlockFile(pos, true);
619 if (!file)
620 break; // This error is logged in OpenBlockFile
621 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
622 LoadExternalBlockFile(chainparams, file, &pos);
623 nFile++;
625 pblocktree->WriteReindexing(false);
626 fReindex = false;
627 LogPrintf("Reindexing finished\n");
628 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
629 InitBlockIndex(chainparams);
632 // hardcoded $DATADIR/bootstrap.dat
633 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
634 if (boost::filesystem::exists(pathBootstrap)) {
635 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
636 if (file) {
637 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
638 LogPrintf("Importing bootstrap.dat...\n");
639 LoadExternalBlockFile(chainparams, file);
640 RenameOver(pathBootstrap, pathBootstrapOld);
641 } else {
642 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
646 // -loadblock=
647 BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
648 FILE *file = fopen(path.string().c_str(), "rb");
649 if (file) {
650 LogPrintf("Importing blocks file %s...\n", path.string());
651 LoadExternalBlockFile(chainparams, file);
652 } else {
653 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
657 // scan for better chains in the block chain database, that are not yet connected in the active best chain
658 CValidationState state;
659 if (!ActivateBestChain(state, chainparams)) {
660 LogPrintf("Failed to connect best block");
661 StartShutdown();
664 if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
665 LogPrintf("Stopping after block import\n");
666 StartShutdown();
668 } // End scope of CImportingNow
669 LoadMempool();
670 fDumpMempoolLater = !fRequestShutdown;
673 /** Sanity checks
674 * Ensure that Bitcoin is running in a usable environment with all
675 * necessary library support.
677 bool InitSanityCheck(void)
679 if(!ECC_InitSanityCheck()) {
680 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
681 return false;
684 if (!glibc_sanity_test() || !glibcxx_sanity_test())
685 return false;
687 if (!Random_SanityCheck()) {
688 InitError("OS cryptographic RNG sanity check failure. Aborting.");
689 return false;
692 return true;
695 bool AppInitServers(boost::thread_group& threadGroup)
697 RPCServer::OnStarted(&OnRPCStarted);
698 RPCServer::OnStopped(&OnRPCStopped);
699 RPCServer::OnPreCommand(&OnRPCPreCommand);
700 if (!InitHTTPServer())
701 return false;
702 if (!StartRPC())
703 return false;
704 if (!StartHTTPRPC())
705 return false;
706 if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
707 return false;
708 if (!StartHTTPServer())
709 return false;
710 return true;
713 // Parameter interaction based on rules
714 void InitParameterInteraction()
716 // when specifying an explicit binding address, you want to listen on it
717 // even when -connect or -proxy is specified
718 if (IsArgSet("-bind")) {
719 if (SoftSetBoolArg("-listen", true))
720 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
722 if (IsArgSet("-whitebind")) {
723 if (SoftSetBoolArg("-listen", true))
724 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
727 if (mapMultiArgs.count("-connect") && mapMultiArgs.at("-connect").size() > 0) {
728 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
729 if (SoftSetBoolArg("-dnsseed", false))
730 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
731 if (SoftSetBoolArg("-listen", false))
732 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
735 if (IsArgSet("-proxy")) {
736 // to protect privacy, do not listen by default if a default proxy server is specified
737 if (SoftSetBoolArg("-listen", false))
738 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
739 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
740 // to listen locally, so don't rely on this happening through -listen below.
741 if (SoftSetBoolArg("-upnp", false))
742 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
743 // to protect privacy, do not discover addresses by default
744 if (SoftSetBoolArg("-discover", false))
745 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
748 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
749 // do not map ports or try to retrieve public IP when not listening (pointless)
750 if (SoftSetBoolArg("-upnp", false))
751 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
752 if (SoftSetBoolArg("-discover", false))
753 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
754 if (SoftSetBoolArg("-listenonion", false))
755 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
758 if (IsArgSet("-externalip")) {
759 // if an explicit public IP is specified, do not try to find others
760 if (SoftSetBoolArg("-discover", false))
761 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
764 // disable whitelistrelay in blocksonly mode
765 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
766 if (SoftSetBoolArg("-whitelistrelay", false))
767 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
770 // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
771 if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
772 if (SoftSetBoolArg("-whitelistrelay", true))
773 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
777 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
779 return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
782 void InitLogging()
784 fPrintToConsole = GetBoolArg("-printtoconsole", false);
785 fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
786 fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
787 fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
789 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
790 LogPrintf("Bitcoin version %s\n", FormatFullVersion());
793 namespace { // Variables internal to initialization process only
795 ServiceFlags nRelevantServices = NODE_NETWORK;
796 int nMaxConnections;
797 int nUserMaxConnections;
798 int nFD;
799 ServiceFlags nLocalServices = NODE_NETWORK;
803 [[noreturn]] static void new_handler_terminate()
805 // Rather than throwing std::bad-alloc if allocation fails, terminate
806 // immediately to (try to) avoid chain corruption.
807 // Since LogPrintf may itself allocate memory, set the handler directly
808 // to terminate first.
809 std::set_new_handler(std::terminate);
810 LogPrintf("Error: Out of memory. Terminating.\n");
812 // The log was successful, terminate now.
813 std::terminate();
816 bool AppInitBasicSetup()
818 // ********************************************************* Step 1: setup
819 #ifdef _MSC_VER
820 // Turn off Microsoft heap dump noise
821 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
822 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
823 #endif
824 #if _MSC_VER >= 1400
825 // Disable confusing "helpful" text message on abort, Ctrl-C
826 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
827 #endif
828 #ifdef WIN32
829 // Enable Data Execution Prevention (DEP)
830 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
831 // A failure is non-critical and needs no further attention!
832 #ifndef PROCESS_DEP_ENABLE
833 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
834 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
835 #define PROCESS_DEP_ENABLE 0x00000001
836 #endif
837 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
838 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
839 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
840 #endif
842 if (!SetupNetworking())
843 return InitError("Initializing networking failed");
845 #ifndef WIN32
846 if (!GetBoolArg("-sysperms", false)) {
847 umask(077);
850 // Clean shutdown on SIGTERM
851 struct sigaction sa;
852 sa.sa_handler = HandleSIGTERM;
853 sigemptyset(&sa.sa_mask);
854 sa.sa_flags = 0;
855 sigaction(SIGTERM, &sa, NULL);
856 sigaction(SIGINT, &sa, NULL);
858 // Reopen debug.log on SIGHUP
859 struct sigaction sa_hup;
860 sa_hup.sa_handler = HandleSIGHUP;
861 sigemptyset(&sa_hup.sa_mask);
862 sa_hup.sa_flags = 0;
863 sigaction(SIGHUP, &sa_hup, NULL);
865 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
866 signal(SIGPIPE, SIG_IGN);
867 #endif
869 std::set_new_handler(new_handler_terminate);
871 return true;
874 bool AppInitParameterInteraction()
876 const CChainParams& chainparams = Params();
877 // ********************************************************* Step 2: parameter interactions
879 // also see: InitParameterInteraction()
881 // if using block pruning, then disallow txindex
882 if (GetArg("-prune", 0)) {
883 if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
884 return InitError(_("Prune mode is incompatible with -txindex."));
887 // Make sure enough file descriptors are available
888 int nBind = std::max(
889 (mapMultiArgs.count("-bind") ? mapMultiArgs.at("-bind").size() : 0) +
890 (mapMultiArgs.count("-whitebind") ? mapMultiArgs.at("-whitebind").size() : 0), size_t(1));
891 nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
892 nMaxConnections = std::max(nUserMaxConnections, 0);
894 // Trim requested connection counts, to fit into system limitations
895 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
896 nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
897 if (nFD < MIN_CORE_FILEDESCRIPTORS)
898 return InitError(_("Not enough file descriptors available."));
899 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
901 if (nMaxConnections < nUserMaxConnections)
902 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
904 // ********************************************************* Step 3: parameter-to-internal-flags
906 fDebug = mapMultiArgs.count("-debug");
907 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
908 if (fDebug) {
909 const std::vector<std::string>& categories = mapMultiArgs.at("-debug");
910 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), std::string("0")) != categories.end())
911 fDebug = false;
914 // Check for -debugnet
915 if (GetBoolArg("-debugnet", false))
916 InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
917 // Check for -socks - as this is a privacy risk to continue, exit here
918 if (IsArgSet("-socks"))
919 return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
920 // Check for -tor - as this is a privacy risk to continue, exit here
921 if (GetBoolArg("-tor", false))
922 return InitError(_("Unsupported argument -tor found, use -onion."));
924 if (GetBoolArg("-benchmark", false))
925 InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
927 if (GetBoolArg("-whitelistalwaysrelay", false))
928 InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
930 if (IsArgSet("-blockminsize"))
931 InitWarning("Unsupported argument -blockminsize ignored.");
933 // Checkmempool and checkblockindex default to true in regtest mode
934 int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
935 if (ratio != 0) {
936 mempool.setSanityCheck(1.0 / ratio);
938 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
939 fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
941 hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
942 if (!hashAssumeValid.IsNull())
943 LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
944 else
945 LogPrintf("Validating signatures for all blocks.\n");
947 // mempool limits
948 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
949 int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
950 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
951 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
952 // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
953 // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
954 if (IsArgSet("-incrementalrelayfee"))
956 CAmount n = 0;
957 if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n))
958 return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", "")));
959 incrementalRelayFee = CFeeRate(n);
962 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
963 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
964 if (nScriptCheckThreads <= 0)
965 nScriptCheckThreads += GetNumCores();
966 if (nScriptCheckThreads <= 1)
967 nScriptCheckThreads = 0;
968 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
969 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
971 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
972 int64_t nPruneArg = GetArg("-prune", 0);
973 if (nPruneArg < 0) {
974 return InitError(_("Prune cannot be configured with a negative value."));
976 nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
977 if (nPruneArg == 1) { // manual pruning: -prune=1
978 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
979 nPruneTarget = std::numeric_limits<uint64_t>::max();
980 fPruneMode = true;
981 } else if (nPruneTarget) {
982 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
983 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
985 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
986 fPruneMode = true;
989 RegisterAllCoreRPCCommands(tableRPC);
990 #ifdef ENABLE_WALLET
991 RegisterWalletRPCCommands(tableRPC);
992 #endif
994 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
995 if (nConnectTimeout <= 0)
996 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
998 // Fee-per-kilobyte amount required for mempool acceptance and relay
999 // If you are mining, be careful setting this:
1000 // if you set it to zero then
1001 // a transaction spammer can cheaply fill blocks using
1002 // 0-fee transactions. It should be set above the real
1003 // cost to you of processing a transaction.
1004 if (IsArgSet("-minrelaytxfee"))
1006 CAmount n = 0;
1007 if (!ParseMoney(GetArg("-minrelaytxfee", ""), n)) {
1008 return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
1010 // High fee check is done afterward in CWallet::ParameterInteraction()
1011 ::minRelayTxFee = CFeeRate(n);
1012 } else if (incrementalRelayFee > ::minRelayTxFee) {
1013 // Allow only setting incrementalRelayFee to control both
1014 ::minRelayTxFee = incrementalRelayFee;
1015 LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1018 // Sanity check argument for min fee for including tx in block
1019 // TODO: Harmonize which arguments need sanity checking and where that happens
1020 if (IsArgSet("-blockmintxfee"))
1022 CAmount n = 0;
1023 if (!ParseMoney(GetArg("-blockmintxfee", ""), n))
1024 return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", "")));
1027 // Feerate used to define dust. Shouldn't be changed lightly as old
1028 // implementations may inadvertently create non-standard transactions
1029 if (IsArgSet("-dustrelayfee"))
1031 CAmount n = 0;
1032 if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n)
1033 return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", "")));
1034 dustRelayFee = CFeeRate(n);
1037 fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1038 if (chainparams.RequireStandard() && !fRequireStandard)
1039 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1040 nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
1042 #ifdef ENABLE_WALLET
1043 if (!CWallet::ParameterInteraction())
1044 return false;
1045 #endif
1047 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1048 fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1049 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1051 // Option to startup with mocktime set (used for regression testing):
1052 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1054 if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1055 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1057 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1058 return InitError("rpcserialversion must be non-negative.");
1060 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1061 return InitError("unknown rpcserialversion requested.");
1063 nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1065 fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1066 if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
1067 // Minimal effort at forwards compatibility
1068 std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
1069 std::vector<std::string> vstrReplacementModes;
1070 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1071 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1074 if (mapMultiArgs.count("-bip9params")) {
1075 // Allow overriding BIP9 parameters for testing
1076 if (!chainparams.MineBlocksOnDemand()) {
1077 return InitError("BIP9 parameters may only be overridden on regtest.");
1079 const std::vector<std::string>& deployments = mapMultiArgs.at("-bip9params");
1080 for (auto i : deployments) {
1081 std::vector<std::string> vDeploymentParams;
1082 boost::split(vDeploymentParams, i, boost::is_any_of(":"));
1083 if (vDeploymentParams.size() != 3) {
1084 return InitError("BIP9 parameters malformed, expecting deployment:start:end");
1086 int64_t nStartTime, nTimeout;
1087 if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1088 return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1090 if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1091 return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1093 bool found = false;
1094 for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1096 if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1097 UpdateRegtestBIP9Parameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1098 found = true;
1099 LogPrintf("Setting BIP9 activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1100 break;
1103 if (!found) {
1104 return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1108 return true;
1111 static bool LockDataDirectory(bool probeOnly)
1113 std::string strDataDir = GetDataDir().string();
1115 // Make sure only a single Bitcoin process is using the data directory.
1116 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
1117 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
1118 if (file) fclose(file);
1120 try {
1121 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1122 if (!lock.try_lock()) {
1123 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1125 if (probeOnly) {
1126 lock.unlock();
1128 } catch(const boost::interprocess::interprocess_exception& e) {
1129 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1131 return true;
1134 bool AppInitSanityChecks()
1136 // ********************************************************* Step 4: sanity checks
1138 // Initialize elliptic curve code
1139 ECC_Start();
1140 globalVerifyHandle.reset(new ECCVerifyHandle());
1142 // Sanity check
1143 if (!InitSanityCheck())
1144 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1146 // Probe the data directory lock to give an early error message, if possible
1147 return LockDataDirectory(true);
1150 bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
1152 const CChainParams& chainparams = Params();
1153 // ********************************************************* Step 4a: application initialization
1154 // After daemonization get the data directory lock again and hold on to it until exit
1155 // This creates a slight window for a race condition to happen, however this condition is harmless: it
1156 // will at most make us exit without printing a message to console.
1157 if (!LockDataDirectory(false)) {
1158 // Detailed error printed inside LockDataDirectory
1159 return false;
1162 #ifndef WIN32
1163 CreatePidFile(GetPidFile(), getpid());
1164 #endif
1165 if (GetBoolArg("-shrinkdebugfile", !fDebug)) {
1166 // Do this first since it both loads a bunch of debug.log into memory,
1167 // and because this needs to happen before any other debug.log printing
1168 ShrinkDebugFile();
1171 if (fPrintToDebugLog)
1172 OpenDebugLog();
1174 if (!fLogTimestamps)
1175 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1176 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1177 LogPrintf("Using data directory %s\n", GetDataDir().string());
1178 LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1179 LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1181 InitSignatureCache();
1183 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1184 if (nScriptCheckThreads) {
1185 for (int i=0; i<nScriptCheckThreads-1; i++)
1186 threadGroup.create_thread(&ThreadScriptCheck);
1189 // Start the lightweight task scheduler thread
1190 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1191 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1193 /* Start the RPC server already. It will be started in "warmup" mode
1194 * and not really process calls already (but it will signify connections
1195 * that the server is there and will be ready later). Warmup mode will
1196 * be disabled when initialisation is finished.
1198 if (GetBoolArg("-server", false))
1200 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1201 if (!AppInitServers(threadGroup))
1202 return InitError(_("Unable to start HTTP server. See debug log for details."));
1205 int64_t nStart;
1207 // ********************************************************* Step 5: verify wallet database integrity
1208 #ifdef ENABLE_WALLET
1209 if (!CWallet::Verify())
1210 return false;
1211 #endif
1212 // ********************************************************* Step 6: network initialization
1213 // Note that we absolutely cannot open any actual connections
1214 // until the very end ("start node") as the UTXO/block state
1215 // is not yet setup and may end up being set up twice if we
1216 // need to reindex later.
1218 assert(!g_connman);
1219 g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1220 CConnman& connman = *g_connman;
1222 peerLogic.reset(new PeerLogicValidation(&connman));
1223 RegisterValidationInterface(peerLogic.get());
1224 RegisterNodeSignals(GetNodeSignals());
1226 // sanitize comments per BIP-0014, format user agent and check total size
1227 std::vector<std::string> uacomments;
1228 if (mapMultiArgs.count("-uacomment")) {
1229 BOOST_FOREACH(std::string cmt, mapMultiArgs.at("-uacomment"))
1231 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1232 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1233 uacomments.push_back(cmt);
1236 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1237 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1238 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1239 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1242 if (mapMultiArgs.count("-onlynet")) {
1243 std::set<enum Network> nets;
1244 BOOST_FOREACH(const std::string& snet, mapMultiArgs.at("-onlynet")) {
1245 enum Network net = ParseNetwork(snet);
1246 if (net == NET_UNROUTABLE)
1247 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1248 nets.insert(net);
1250 for (int n = 0; n < NET_MAX; n++) {
1251 enum Network net = (enum Network)n;
1252 if (!nets.count(net))
1253 SetLimited(net);
1257 if (mapMultiArgs.count("-whitelist")) {
1258 BOOST_FOREACH(const std::string& net, mapMultiArgs.at("-whitelist")) {
1259 CSubNet subnet;
1260 LookupSubNet(net.c_str(), subnet);
1261 if (!subnet.IsValid())
1262 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1263 connman.AddWhitelistedRange(subnet);
1267 // Check for host lookup allowed before parsing any network related parameters
1268 fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1270 bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1271 // -proxy sets a proxy for all outgoing network traffic
1272 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1273 std::string proxyArg = GetArg("-proxy", "");
1274 SetLimited(NET_TOR);
1275 if (proxyArg != "" && proxyArg != "0") {
1276 CService proxyAddr;
1277 if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1278 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1281 proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1282 if (!addrProxy.IsValid())
1283 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1285 SetProxy(NET_IPV4, addrProxy);
1286 SetProxy(NET_IPV6, addrProxy);
1287 SetProxy(NET_TOR, addrProxy);
1288 SetNameProxy(addrProxy);
1289 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1292 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1293 // -noonion (or -onion=0) disables connecting to .onion entirely
1294 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1295 std::string onionArg = GetArg("-onion", "");
1296 if (onionArg != "") {
1297 if (onionArg == "0") { // Handle -noonion/-onion=0
1298 SetLimited(NET_TOR); // set onions as unreachable
1299 } else {
1300 CService onionProxy;
1301 if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1302 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1304 proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1305 if (!addrOnion.IsValid())
1306 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1307 SetProxy(NET_TOR, addrOnion);
1308 SetLimited(NET_TOR, false);
1312 // see Step 2: parameter interactions for more information about these
1313 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1314 fDiscover = GetBoolArg("-discover", true);
1315 fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1317 if (fListen) {
1318 bool fBound = false;
1319 if (mapMultiArgs.count("-bind")) {
1320 BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-bind")) {
1321 CService addrBind;
1322 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1323 return InitError(ResolveErrMsg("bind", strBind));
1324 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1327 if (mapMultiArgs.count("-whitebind")) {
1328 BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-whitebind")) {
1329 CService addrBind;
1330 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1331 return InitError(ResolveErrMsg("whitebind", strBind));
1332 if (addrBind.GetPort() == 0)
1333 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1334 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1337 if (!mapMultiArgs.count("-bind") && !mapMultiArgs.count("-whitebind")) {
1338 struct in_addr inaddr_any;
1339 inaddr_any.s_addr = INADDR_ANY;
1340 fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
1341 fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1343 if (!fBound)
1344 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1347 if (mapMultiArgs.count("-externalip")) {
1348 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-externalip")) {
1349 CService addrLocal;
1350 if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1351 AddLocal(addrLocal, LOCAL_MANUAL);
1352 else
1353 return InitError(ResolveErrMsg("externalip", strAddr));
1357 if (mapMultiArgs.count("-seednode")) {
1358 BOOST_FOREACH(const std::string& strDest, mapMultiArgs.at("-seednode"))
1359 connman.AddOneShot(strDest);
1362 #if ENABLE_ZMQ
1363 pzmqNotificationInterface = CZMQNotificationInterface::Create();
1365 if (pzmqNotificationInterface) {
1366 RegisterValidationInterface(pzmqNotificationInterface);
1368 #endif
1369 uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1370 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1372 if (IsArgSet("-maxuploadtarget")) {
1373 nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1376 // ********************************************************* Step 7: load block chain
1378 fReindex = GetBoolArg("-reindex", false);
1379 bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
1381 boost::filesystem::create_directories(GetDataDir() / "blocks");
1383 // cache size calculations
1384 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1385 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1386 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1387 int64_t nBlockTreeDBCache = nTotalCache / 8;
1388 nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1389 nTotalCache -= nBlockTreeDBCache;
1390 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1391 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1392 nTotalCache -= nCoinDBCache;
1393 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1394 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1395 LogPrintf("Cache configuration:\n");
1396 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1397 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1398 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));
1400 bool fLoaded = false;
1401 while (!fLoaded) {
1402 bool fReset = fReindex;
1403 std::string strLoadError;
1405 uiInterface.InitMessage(_("Loading block index..."));
1407 nStart = GetTimeMillis();
1408 do {
1409 try {
1410 UnloadBlockIndex();
1411 delete pcoinsTip;
1412 delete pcoinsdbview;
1413 delete pcoinscatcher;
1414 delete pblocktree;
1416 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1417 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState);
1418 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1419 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1421 if (fReindex) {
1422 pblocktree->WriteReindexing(true);
1423 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1424 if (fPruneMode)
1425 CleanupBlockRevFiles();
1428 if (!LoadBlockIndex(chainparams)) {
1429 strLoadError = _("Error loading block database");
1430 break;
1433 // If the loaded chain has a wrong genesis, bail out immediately
1434 // (we're likely using a testnet datadir, or the other way around).
1435 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1436 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1438 // Initialize the block index (no-op if non-empty database was already loaded)
1439 if (!InitBlockIndex(chainparams)) {
1440 strLoadError = _("Error initializing block database");
1441 break;
1444 // Check for changed -txindex state
1445 if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1446 strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
1447 break;
1450 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1451 // in the past, but is now trying to run unpruned.
1452 if (fHavePruned && !fPruneMode) {
1453 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1454 break;
1457 if (!fReindex && chainActive.Tip() != NULL) {
1458 uiInterface.InitMessage(_("Rewinding blocks..."));
1459 if (!RewindBlockIndex(chainparams)) {
1460 strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1461 break;
1465 uiInterface.InitMessage(_("Verifying blocks..."));
1466 if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1467 LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
1468 MIN_BLOCKS_TO_KEEP);
1472 LOCK(cs_main);
1473 CBlockIndex* tip = chainActive.Tip();
1474 RPCNotifyBlockChange(true, tip);
1475 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1476 strLoadError = _("The block database contains a block which appears to be from the future. "
1477 "This may be due to your computer's date and time being set incorrectly. "
1478 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1479 break;
1483 if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1484 GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1485 strLoadError = _("Corrupted block database detected");
1486 break;
1488 } catch (const std::exception& e) {
1489 if (fDebug) LogPrintf("%s\n", e.what());
1490 strLoadError = _("Error opening block database");
1491 break;
1494 fLoaded = true;
1495 } while(false);
1497 if (!fLoaded) {
1498 // first suggest a reindex
1499 if (!fReset) {
1500 bool fRet = uiInterface.ThreadSafeQuestion(
1501 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1502 strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1503 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1504 if (fRet) {
1505 fReindex = true;
1506 fRequestShutdown = false;
1507 } else {
1508 LogPrintf("Aborted block database rebuild. Exiting.\n");
1509 return false;
1511 } else {
1512 return InitError(strLoadError);
1517 // As LoadBlockIndex can take several minutes, it's possible the user
1518 // requested to kill the GUI during the last operation. If so, exit.
1519 // As the program has not fully started yet, Shutdown() is possibly overkill.
1520 if (fRequestShutdown)
1522 LogPrintf("Shutdown requested. Exiting.\n");
1523 return false;
1525 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1527 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1528 CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
1529 // Allowed to fail as this file IS missing on first startup.
1530 if (!est_filein.IsNull())
1531 mempool.ReadFeeEstimates(est_filein);
1532 fFeeEstimatesInitialized = true;
1534 // ********************************************************* Step 8: load wallet
1535 #ifdef ENABLE_WALLET
1536 if (!CWallet::InitLoadWallet())
1537 return false;
1538 #else
1539 LogPrintf("No wallet support compiled in!\n");
1540 #endif
1542 // ********************************************************* Step 9: data directory maintenance
1544 // if pruning, unset the service bit and perform the initial blockstore prune
1545 // after any wallet rescanning has taken place.
1546 if (fPruneMode) {
1547 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1548 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1549 if (!fReindex) {
1550 uiInterface.InitMessage(_("Pruning blockstore..."));
1551 PruneAndFlush();
1555 if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
1556 // Only advertise witness capabilities if they have a reasonable start time.
1557 // This allows us to have the code merged without a defined softfork, by setting its
1558 // end time to 0.
1559 // Note that setting NODE_WITNESS is never required: the only downside from not
1560 // doing so is that after activation, no upgraded nodes will fetch from you.
1561 nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1562 // Only care about others providing witness capabilities if there is a softfork
1563 // defined.
1564 nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS);
1567 // ********************************************************* Step 10: import blocks
1569 if (!CheckDiskSpace())
1570 return false;
1572 // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1573 // No locking, as this happens before any background thread is started.
1574 if (chainActive.Tip() == NULL) {
1575 uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1576 } else {
1577 fHaveGenesis = true;
1580 if (IsArgSet("-blocknotify"))
1581 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1583 std::vector<boost::filesystem::path> vImportFiles;
1584 if (mapMultiArgs.count("-loadblock"))
1586 BOOST_FOREACH(const std::string& strFile, mapMultiArgs.at("-loadblock"))
1587 vImportFiles.push_back(strFile);
1590 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1592 // Wait for genesis block to be processed
1594 boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
1595 while (!fHaveGenesis) {
1596 condvar_GenesisWait.wait(lock);
1598 uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1601 // ********************************************************* Step 11: start node
1603 //// debug print
1604 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1605 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1606 if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1607 StartTorControl(threadGroup, scheduler);
1609 Discover(threadGroup);
1611 // Map ports with UPnP
1612 MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
1614 std::string strNodeError;
1615 CConnman::Options connOptions;
1616 connOptions.nLocalServices = nLocalServices;
1617 connOptions.nRelevantServices = nRelevantServices;
1618 connOptions.nMaxConnections = nMaxConnections;
1619 connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1620 connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1621 connOptions.nMaxFeeler = 1;
1622 connOptions.nBestHeight = chainActive.Height();
1623 connOptions.uiInterface = &uiInterface;
1624 connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1625 connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1627 connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1628 connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1630 if (!connman.Start(scheduler, strNodeError, connOptions))
1631 return InitError(strNodeError);
1633 // ********************************************************* Step 12: finished
1635 SetRPCWarmupFinished();
1636 uiInterface.InitMessage(_("Done loading"));
1638 #ifdef ENABLE_WALLET
1639 if (pwalletMain)
1640 pwalletMain->postInitProcess(scheduler);
1641 #endif
1643 return !fRequestShutdown;