logging: Fix off-by-one for shrinkdebugfile
[bitcoinplatinum.git] / src / init.cpp
blob5fee8de752b4639a8aecf500c35e69ee898b739d
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 "rpc/blockchain.h"
31 #include "script/standard.h"
32 #include "script/sigcache.h"
33 #include "scheduler.h"
34 #include "timedata.h"
35 #include "txdb.h"
36 #include "txmempool.h"
37 #include "torcontrol.h"
38 #include "ui_interface.h"
39 #include "util.h"
40 #include "utilmoneystr.h"
41 #include "validationinterface.h"
42 #ifdef ENABLE_WALLET
43 #include "wallet/wallet.h"
44 #endif
45 #include "warnings.h"
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <memory>
50 #ifndef WIN32
51 #include <signal.h>
52 #endif
54 #include <boost/algorithm/string/classification.hpp>
55 #include <boost/algorithm/string/predicate.hpp>
56 #include <boost/algorithm/string/replace.hpp>
57 #include <boost/algorithm/string/split.hpp>
58 #include <boost/bind.hpp>
59 #include <boost/filesystem.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 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
216 CAutoFile est_fileout(fopen(est_path.string().c_str(), "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 boost::filesystem::remove(GetPidFile());
254 } catch (const boost::filesystem::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 if (showDebug)
448 strUsage += HelpMessageOpt("-nodebug", "Turn off debugging messages, same as -debug=0");
449 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
450 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
451 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
452 if (showDebug)
454 strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
455 strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
456 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
457 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
459 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)"),
460 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
461 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
462 if (showDebug)
464 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
466 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
468 AppendParamsHelpMessages(strUsage, showDebug);
470 strUsage += HelpMessageGroup(_("Node relay options:"));
471 if (showDebug) {
472 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
473 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)));
474 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)));
476 strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
477 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
478 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
479 strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
480 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
481 CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
482 strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
483 strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
485 strUsage += HelpMessageGroup(_("Block creation options:"));
486 strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
487 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
488 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)));
489 if (showDebug)
490 strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
492 strUsage += HelpMessageGroup(_("RPC server options:"));
493 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
494 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
495 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)"));
496 strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
497 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
498 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
499 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"));
500 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()));
501 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"));
502 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));
503 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
504 if (showDebug) {
505 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
506 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
509 return strUsage;
512 std::string LicenseInfo()
514 const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
515 const std::string URL_WEBSITE = "<https://bitcoincore.org>";
517 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
518 "\n" +
519 strprintf(_("Please contribute if you find %s useful. "
520 "Visit %s for further information about the software."),
521 PACKAGE_NAME, URL_WEBSITE) +
522 "\n" +
523 strprintf(_("The source code is available from %s."),
524 URL_SOURCE_CODE) +
525 "\n" +
526 "\n" +
527 _("This is experimental software.") + "\n" +
528 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
529 "\n" +
530 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>") +
531 "\n";
534 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
536 if (initialSync || !pBlockIndex)
537 return;
539 std::string strCmd = GetArg("-blocknotify", "");
541 boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
542 boost::thread t(runCommand, strCmd); // thread runs free
545 static bool fHaveGenesis = false;
546 static boost::mutex cs_GenesisWait;
547 static CConditionVariable condvar_GenesisWait;
549 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
551 if (pBlockIndex != NULL) {
553 boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
554 fHaveGenesis = true;
556 condvar_GenesisWait.notify_all();
560 struct CImportingNow
562 CImportingNow() {
563 assert(fImporting == false);
564 fImporting = true;
567 ~CImportingNow() {
568 assert(fImporting == true);
569 fImporting = false;
574 // If we're using -prune with -reindex, then delete block files that will be ignored by the
575 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
576 // is missing, do the same here to delete any later block files after a gap. Also delete all
577 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
578 // is in sync with what's actually on disk by the time we start downloading, so that pruning
579 // works correctly.
580 void CleanupBlockRevFiles()
582 std::map<std::string, boost::filesystem::path> mapBlockFiles;
584 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
585 // Remove the rev files immediately and insert the blk file paths into an
586 // ordered map keyed by block file index.
587 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
588 boost::filesystem::path blocksdir = GetDataDir() / "blocks";
589 for (boost::filesystem::directory_iterator it(blocksdir); it != boost::filesystem::directory_iterator(); it++) {
590 if (is_regular_file(*it) &&
591 it->path().filename().string().length() == 12 &&
592 it->path().filename().string().substr(8,4) == ".dat")
594 if (it->path().filename().string().substr(0,3) == "blk")
595 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
596 else if (it->path().filename().string().substr(0,3) == "rev")
597 remove(it->path());
601 // Remove all block files that aren't part of a contiguous set starting at
602 // zero by walking the ordered map (keys are block file indices) by
603 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
604 // start removing block files.
605 int nContigCounter = 0;
606 BOOST_FOREACH(const PAIRTYPE(std::string, boost::filesystem::path)& item, mapBlockFiles) {
607 if (atoi(item.first) == nContigCounter) {
608 nContigCounter++;
609 continue;
611 remove(item.second);
615 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
617 const CChainParams& chainparams = Params();
618 RenameThread("bitcoin-loadblk");
621 CImportingNow imp;
623 // -reindex
624 if (fReindex) {
625 int nFile = 0;
626 while (true) {
627 CDiskBlockPos pos(nFile, 0);
628 if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
629 break; // No block files left to reindex
630 FILE *file = OpenBlockFile(pos, true);
631 if (!file)
632 break; // This error is logged in OpenBlockFile
633 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
634 LoadExternalBlockFile(chainparams, file, &pos);
635 nFile++;
637 pblocktree->WriteReindexing(false);
638 fReindex = false;
639 LogPrintf("Reindexing finished\n");
640 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
641 InitBlockIndex(chainparams);
644 // hardcoded $DATADIR/bootstrap.dat
645 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
646 if (boost::filesystem::exists(pathBootstrap)) {
647 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
648 if (file) {
649 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
650 LogPrintf("Importing bootstrap.dat...\n");
651 LoadExternalBlockFile(chainparams, file);
652 RenameOver(pathBootstrap, pathBootstrapOld);
653 } else {
654 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
658 // -loadblock=
659 BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
660 FILE *file = fopen(path.string().c_str(), "rb");
661 if (file) {
662 LogPrintf("Importing blocks file %s...\n", path.string());
663 LoadExternalBlockFile(chainparams, file);
664 } else {
665 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
669 // scan for better chains in the block chain database, that are not yet connected in the active best chain
670 CValidationState state;
671 if (!ActivateBestChain(state, chainparams)) {
672 LogPrintf("Failed to connect best block");
673 StartShutdown();
676 if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
677 LogPrintf("Stopping after block import\n");
678 StartShutdown();
680 } // End scope of CImportingNow
681 LoadMempool();
682 fDumpMempoolLater = !fRequestShutdown;
685 /** Sanity checks
686 * Ensure that Bitcoin is running in a usable environment with all
687 * necessary library support.
689 bool InitSanityCheck(void)
691 if(!ECC_InitSanityCheck()) {
692 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
693 return false;
696 if (!glibc_sanity_test() || !glibcxx_sanity_test())
697 return false;
699 if (!Random_SanityCheck()) {
700 InitError("OS cryptographic RNG sanity check failure. Aborting.");
701 return false;
704 return true;
707 bool AppInitServers(boost::thread_group& threadGroup)
709 RPCServer::OnStarted(&OnRPCStarted);
710 RPCServer::OnStopped(&OnRPCStopped);
711 RPCServer::OnPreCommand(&OnRPCPreCommand);
712 if (!InitHTTPServer())
713 return false;
714 if (!StartRPC())
715 return false;
716 if (!StartHTTPRPC())
717 return false;
718 if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
719 return false;
720 if (!StartHTTPServer())
721 return false;
722 return true;
725 // Parameter interaction based on rules
726 void InitParameterInteraction()
728 // when specifying an explicit binding address, you want to listen on it
729 // even when -connect or -proxy is specified
730 if (IsArgSet("-bind")) {
731 if (SoftSetBoolArg("-listen", true))
732 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
734 if (IsArgSet("-whitebind")) {
735 if (SoftSetBoolArg("-listen", true))
736 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
739 if (mapMultiArgs.count("-connect") && mapMultiArgs.at("-connect").size() > 0) {
740 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
741 if (SoftSetBoolArg("-dnsseed", false))
742 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
743 if (SoftSetBoolArg("-listen", false))
744 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
747 if (IsArgSet("-proxy")) {
748 // to protect privacy, do not listen by default if a default proxy server is specified
749 if (SoftSetBoolArg("-listen", false))
750 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
751 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
752 // to listen locally, so don't rely on this happening through -listen below.
753 if (SoftSetBoolArg("-upnp", false))
754 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
755 // to protect privacy, do not discover addresses by default
756 if (SoftSetBoolArg("-discover", false))
757 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
760 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
761 // do not map ports or try to retrieve public IP when not listening (pointless)
762 if (SoftSetBoolArg("-upnp", false))
763 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
764 if (SoftSetBoolArg("-discover", false))
765 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
766 if (SoftSetBoolArg("-listenonion", false))
767 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
770 if (IsArgSet("-externalip")) {
771 // if an explicit public IP is specified, do not try to find others
772 if (SoftSetBoolArg("-discover", false))
773 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
776 // disable whitelistrelay in blocksonly mode
777 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
778 if (SoftSetBoolArg("-whitelistrelay", false))
779 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
782 // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
783 if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
784 if (SoftSetBoolArg("-whitelistrelay", true))
785 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
789 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
791 return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
794 void InitLogging()
796 fPrintToConsole = GetBoolArg("-printtoconsole", false);
797 fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
798 fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
799 fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
801 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
802 LogPrintf("Bitcoin version %s\n", FormatFullVersion());
805 namespace { // Variables internal to initialization process only
807 ServiceFlags nRelevantServices = NODE_NETWORK;
808 int nMaxConnections;
809 int nUserMaxConnections;
810 int nFD;
811 ServiceFlags nLocalServices = NODE_NETWORK;
815 [[noreturn]] static void new_handler_terminate()
817 // Rather than throwing std::bad-alloc if allocation fails, terminate
818 // immediately to (try to) avoid chain corruption.
819 // Since LogPrintf may itself allocate memory, set the handler directly
820 // to terminate first.
821 std::set_new_handler(std::terminate);
822 LogPrintf("Error: Out of memory. Terminating.\n");
824 // The log was successful, terminate now.
825 std::terminate();
828 bool AppInitBasicSetup()
830 // ********************************************************* Step 1: setup
831 #ifdef _MSC_VER
832 // Turn off Microsoft heap dump noise
833 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
834 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
835 #endif
836 #if _MSC_VER >= 1400
837 // Disable confusing "helpful" text message on abort, Ctrl-C
838 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
839 #endif
840 #ifdef WIN32
841 // Enable Data Execution Prevention (DEP)
842 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
843 // A failure is non-critical and needs no further attention!
844 #ifndef PROCESS_DEP_ENABLE
845 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
846 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
847 #define PROCESS_DEP_ENABLE 0x00000001
848 #endif
849 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
850 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
851 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
852 #endif
854 if (!SetupNetworking())
855 return InitError("Initializing networking failed");
857 #ifndef WIN32
858 if (!GetBoolArg("-sysperms", false)) {
859 umask(077);
862 // Clean shutdown on SIGTERM
863 registerSignalHandler(SIGTERM, HandleSIGTERM);
864 registerSignalHandler(SIGINT, HandleSIGTERM);
866 // Reopen debug.log on SIGHUP
867 registerSignalHandler(SIGHUP, HandleSIGHUP);
869 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
870 signal(SIGPIPE, SIG_IGN);
871 #endif
873 std::set_new_handler(new_handler_terminate);
875 return true;
878 bool AppInitParameterInteraction()
880 const CChainParams& chainparams = Params();
881 // ********************************************************* Step 2: parameter interactions
883 // also see: InitParameterInteraction()
885 // if using block pruning, then disallow txindex
886 if (GetArg("-prune", 0)) {
887 if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
888 return InitError(_("Prune mode is incompatible with -txindex."));
891 // Make sure enough file descriptors are available
892 int nBind = std::max(
893 (mapMultiArgs.count("-bind") ? mapMultiArgs.at("-bind").size() : 0) +
894 (mapMultiArgs.count("-whitebind") ? mapMultiArgs.at("-whitebind").size() : 0), size_t(1));
895 nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
896 nMaxConnections = std::max(nUserMaxConnections, 0);
898 // Trim requested connection counts, to fit into system limitations
899 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
900 nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
901 if (nFD < MIN_CORE_FILEDESCRIPTORS)
902 return InitError(_("Not enough file descriptors available."));
903 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
905 if (nMaxConnections < nUserMaxConnections)
906 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
908 // ********************************************************* Step 3: parameter-to-internal-flags
910 if (mapMultiArgs.count("-debug") > 0) {
911 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
912 const std::vector<std::string>& categories = mapMultiArgs.at("-debug");
914 if (!(GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), std::string("0")) != categories.end())) {
915 for (const auto& cat : categories) {
916 uint32_t flag;
917 if (!GetLogCategory(&flag, &cat)) {
918 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
920 logCategories |= flag;
925 // Now remove the logging categories which were explicitly excluded
926 if (mapMultiArgs.count("-debugexclude") > 0) {
927 const std::vector<std::string>& excludedCategories = mapMultiArgs.at("-debugexclude");
928 for (const auto& cat : excludedCategories) {
929 uint32_t flag;
930 if (!GetLogCategory(&flag, &cat)) {
931 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
933 logCategories &= ~flag;
937 // Check for -debugnet
938 if (GetBoolArg("-debugnet", false))
939 InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
940 // Check for -socks - as this is a privacy risk to continue, exit here
941 if (IsArgSet("-socks"))
942 return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
943 // Check for -tor - as this is a privacy risk to continue, exit here
944 if (GetBoolArg("-tor", false))
945 return InitError(_("Unsupported argument -tor found, use -onion."));
947 if (GetBoolArg("-benchmark", false))
948 InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
950 if (GetBoolArg("-whitelistalwaysrelay", false))
951 InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
953 if (IsArgSet("-blockminsize"))
954 InitWarning("Unsupported argument -blockminsize ignored.");
956 // Checkmempool and checkblockindex default to true in regtest mode
957 int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
958 if (ratio != 0) {
959 mempool.setSanityCheck(1.0 / ratio);
961 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
962 fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
964 hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
965 if (!hashAssumeValid.IsNull())
966 LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
967 else
968 LogPrintf("Validating signatures for all blocks.\n");
970 // mempool limits
971 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
972 int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
973 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
974 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
975 // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
976 // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
977 if (IsArgSet("-incrementalrelayfee"))
979 CAmount n = 0;
980 if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n))
981 return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", "")));
982 incrementalRelayFee = CFeeRate(n);
985 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
986 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
987 if (nScriptCheckThreads <= 0)
988 nScriptCheckThreads += GetNumCores();
989 if (nScriptCheckThreads <= 1)
990 nScriptCheckThreads = 0;
991 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
992 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
994 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
995 int64_t nPruneArg = GetArg("-prune", 0);
996 if (nPruneArg < 0) {
997 return InitError(_("Prune cannot be configured with a negative value."));
999 nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
1000 if (nPruneArg == 1) { // manual pruning: -prune=1
1001 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1002 nPruneTarget = std::numeric_limits<uint64_t>::max();
1003 fPruneMode = true;
1004 } else if (nPruneTarget) {
1005 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
1006 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1008 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1009 fPruneMode = true;
1012 RegisterAllCoreRPCCommands(tableRPC);
1013 #ifdef ENABLE_WALLET
1014 RegisterWalletRPCCommands(tableRPC);
1015 #endif
1017 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1018 if (nConnectTimeout <= 0)
1019 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1021 // Fee-per-kilobyte amount required for mempool acceptance and relay
1022 // If you are mining, be careful setting this:
1023 // if you set it to zero then
1024 // a transaction spammer can cheaply fill blocks using
1025 // 0-fee transactions. It should be set above the real
1026 // cost to you of processing a transaction.
1027 if (IsArgSet("-minrelaytxfee"))
1029 CAmount n = 0;
1030 if (!ParseMoney(GetArg("-minrelaytxfee", ""), n)) {
1031 return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
1033 // High fee check is done afterward in CWallet::ParameterInteraction()
1034 ::minRelayTxFee = CFeeRate(n);
1035 } else if (incrementalRelayFee > ::minRelayTxFee) {
1036 // Allow only setting incrementalRelayFee to control both
1037 ::minRelayTxFee = incrementalRelayFee;
1038 LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1041 // Sanity check argument for min fee for including tx in block
1042 // TODO: Harmonize which arguments need sanity checking and where that happens
1043 if (IsArgSet("-blockmintxfee"))
1045 CAmount n = 0;
1046 if (!ParseMoney(GetArg("-blockmintxfee", ""), n))
1047 return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", "")));
1050 // Feerate used to define dust. Shouldn't be changed lightly as old
1051 // implementations may inadvertently create non-standard transactions
1052 if (IsArgSet("-dustrelayfee"))
1054 CAmount n = 0;
1055 if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n)
1056 return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", "")));
1057 dustRelayFee = CFeeRate(n);
1060 fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1061 if (chainparams.RequireStandard() && !fRequireStandard)
1062 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1063 nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
1065 #ifdef ENABLE_WALLET
1066 if (!CWallet::ParameterInteraction())
1067 return false;
1068 #endif
1070 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1071 fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1072 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1074 // Option to startup with mocktime set (used for regression testing):
1075 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1077 if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1078 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1080 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1081 return InitError("rpcserialversion must be non-negative.");
1083 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1084 return InitError("unknown rpcserialversion requested.");
1086 nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1088 fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1089 if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
1090 // Minimal effort at forwards compatibility
1091 std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
1092 std::vector<std::string> vstrReplacementModes;
1093 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1094 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1097 if (mapMultiArgs.count("-bip9params")) {
1098 // Allow overriding BIP9 parameters for testing
1099 if (!chainparams.MineBlocksOnDemand()) {
1100 return InitError("BIP9 parameters may only be overridden on regtest.");
1102 const std::vector<std::string>& deployments = mapMultiArgs.at("-bip9params");
1103 for (auto i : deployments) {
1104 std::vector<std::string> vDeploymentParams;
1105 boost::split(vDeploymentParams, i, boost::is_any_of(":"));
1106 if (vDeploymentParams.size() != 3) {
1107 return InitError("BIP9 parameters malformed, expecting deployment:start:end");
1109 int64_t nStartTime, nTimeout;
1110 if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1111 return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1113 if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1114 return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1116 bool found = false;
1117 for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1119 if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1120 UpdateRegtestBIP9Parameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1121 found = true;
1122 LogPrintf("Setting BIP9 activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1123 break;
1126 if (!found) {
1127 return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1131 return true;
1134 static bool LockDataDirectory(bool probeOnly)
1136 std::string strDataDir = GetDataDir().string();
1138 // Make sure only a single Bitcoin process is using the data directory.
1139 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
1140 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
1141 if (file) fclose(file);
1143 try {
1144 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1145 if (!lock.try_lock()) {
1146 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1148 if (probeOnly) {
1149 lock.unlock();
1151 } catch(const boost::interprocess::interprocess_exception& e) {
1152 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1154 return true;
1157 bool AppInitSanityChecks()
1159 // ********************************************************* Step 4: sanity checks
1161 // Initialize elliptic curve code
1162 ECC_Start();
1163 globalVerifyHandle.reset(new ECCVerifyHandle());
1165 // Sanity check
1166 if (!InitSanityCheck())
1167 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1169 // Probe the data directory lock to give an early error message, if possible
1170 return LockDataDirectory(true);
1173 bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
1175 const CChainParams& chainparams = Params();
1176 // ********************************************************* Step 4a: application initialization
1177 // After daemonization get the data directory lock again and hold on to it until exit
1178 // This creates a slight window for a race condition to happen, however this condition is harmless: it
1179 // will at most make us exit without printing a message to console.
1180 if (!LockDataDirectory(false)) {
1181 // Detailed error printed inside LockDataDirectory
1182 return false;
1185 #ifndef WIN32
1186 CreatePidFile(GetPidFile(), getpid());
1187 #endif
1188 if (GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
1189 // Do this first since it both loads a bunch of debug.log into memory,
1190 // and because this needs to happen before any other debug.log printing
1191 ShrinkDebugFile();
1194 if (fPrintToDebugLog)
1195 OpenDebugLog();
1197 if (!fLogTimestamps)
1198 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1199 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1200 LogPrintf("Using data directory %s\n", GetDataDir().string());
1201 LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1202 LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1204 InitSignatureCache();
1206 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1207 if (nScriptCheckThreads) {
1208 for (int i=0; i<nScriptCheckThreads-1; i++)
1209 threadGroup.create_thread(&ThreadScriptCheck);
1212 // Start the lightweight task scheduler thread
1213 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1214 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1216 /* Start the RPC server already. It will be started in "warmup" mode
1217 * and not really process calls already (but it will signify connections
1218 * that the server is there and will be ready later). Warmup mode will
1219 * be disabled when initialisation is finished.
1221 if (GetBoolArg("-server", false))
1223 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1224 if (!AppInitServers(threadGroup))
1225 return InitError(_("Unable to start HTTP server. See debug log for details."));
1228 int64_t nStart;
1230 // ********************************************************* Step 5: verify wallet database integrity
1231 #ifdef ENABLE_WALLET
1232 if (!CWallet::Verify())
1233 return false;
1234 #endif
1235 // ********************************************************* Step 6: network initialization
1236 // Note that we absolutely cannot open any actual connections
1237 // until the very end ("start node") as the UTXO/block state
1238 // is not yet setup and may end up being set up twice if we
1239 // need to reindex later.
1241 assert(!g_connman);
1242 g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1243 CConnman& connman = *g_connman;
1245 peerLogic.reset(new PeerLogicValidation(&connman));
1246 RegisterValidationInterface(peerLogic.get());
1247 RegisterNodeSignals(GetNodeSignals());
1249 // sanitize comments per BIP-0014, format user agent and check total size
1250 std::vector<std::string> uacomments;
1251 if (mapMultiArgs.count("-uacomment")) {
1252 BOOST_FOREACH(std::string cmt, mapMultiArgs.at("-uacomment"))
1254 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1255 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1256 uacomments.push_back(cmt);
1259 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1260 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1261 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1262 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1265 if (mapMultiArgs.count("-onlynet")) {
1266 std::set<enum Network> nets;
1267 BOOST_FOREACH(const std::string& snet, mapMultiArgs.at("-onlynet")) {
1268 enum Network net = ParseNetwork(snet);
1269 if (net == NET_UNROUTABLE)
1270 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1271 nets.insert(net);
1273 for (int n = 0; n < NET_MAX; n++) {
1274 enum Network net = (enum Network)n;
1275 if (!nets.count(net))
1276 SetLimited(net);
1280 if (mapMultiArgs.count("-whitelist")) {
1281 BOOST_FOREACH(const std::string& net, mapMultiArgs.at("-whitelist")) {
1282 CSubNet subnet;
1283 LookupSubNet(net.c_str(), subnet);
1284 if (!subnet.IsValid())
1285 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1286 connman.AddWhitelistedRange(subnet);
1290 // Check for host lookup allowed before parsing any network related parameters
1291 fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1293 bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1294 // -proxy sets a proxy for all outgoing network traffic
1295 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1296 std::string proxyArg = GetArg("-proxy", "");
1297 SetLimited(NET_TOR);
1298 if (proxyArg != "" && proxyArg != "0") {
1299 CService proxyAddr;
1300 if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1301 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1304 proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1305 if (!addrProxy.IsValid())
1306 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1308 SetProxy(NET_IPV4, addrProxy);
1309 SetProxy(NET_IPV6, addrProxy);
1310 SetProxy(NET_TOR, addrProxy);
1311 SetNameProxy(addrProxy);
1312 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1315 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1316 // -noonion (or -onion=0) disables connecting to .onion entirely
1317 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1318 std::string onionArg = GetArg("-onion", "");
1319 if (onionArg != "") {
1320 if (onionArg == "0") { // Handle -noonion/-onion=0
1321 SetLimited(NET_TOR); // set onions as unreachable
1322 } else {
1323 CService onionProxy;
1324 if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1325 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1327 proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1328 if (!addrOnion.IsValid())
1329 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1330 SetProxy(NET_TOR, addrOnion);
1331 SetLimited(NET_TOR, false);
1335 // see Step 2: parameter interactions for more information about these
1336 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1337 fDiscover = GetBoolArg("-discover", true);
1338 fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1340 if (fListen) {
1341 bool fBound = false;
1342 if (mapMultiArgs.count("-bind")) {
1343 BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-bind")) {
1344 CService addrBind;
1345 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1346 return InitError(ResolveErrMsg("bind", strBind));
1347 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1350 if (mapMultiArgs.count("-whitebind")) {
1351 BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-whitebind")) {
1352 CService addrBind;
1353 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1354 return InitError(ResolveErrMsg("whitebind", strBind));
1355 if (addrBind.GetPort() == 0)
1356 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1357 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1360 if (!mapMultiArgs.count("-bind") && !mapMultiArgs.count("-whitebind")) {
1361 struct in_addr inaddr_any;
1362 inaddr_any.s_addr = INADDR_ANY;
1363 fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
1364 fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1366 if (!fBound)
1367 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1370 if (mapMultiArgs.count("-externalip")) {
1371 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-externalip")) {
1372 CService addrLocal;
1373 if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1374 AddLocal(addrLocal, LOCAL_MANUAL);
1375 else
1376 return InitError(ResolveErrMsg("externalip", strAddr));
1380 if (mapMultiArgs.count("-seednode")) {
1381 BOOST_FOREACH(const std::string& strDest, mapMultiArgs.at("-seednode"))
1382 connman.AddOneShot(strDest);
1385 #if ENABLE_ZMQ
1386 pzmqNotificationInterface = CZMQNotificationInterface::Create();
1388 if (pzmqNotificationInterface) {
1389 RegisterValidationInterface(pzmqNotificationInterface);
1391 #endif
1392 uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1393 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1395 if (IsArgSet("-maxuploadtarget")) {
1396 nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1399 // ********************************************************* Step 7: load block chain
1401 fReindex = GetBoolArg("-reindex", false);
1402 bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
1404 boost::filesystem::create_directories(GetDataDir() / "blocks");
1406 // cache size calculations
1407 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1408 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1409 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1410 int64_t nBlockTreeDBCache = nTotalCache / 8;
1411 nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1412 nTotalCache -= nBlockTreeDBCache;
1413 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1414 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1415 nTotalCache -= nCoinDBCache;
1416 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1417 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1418 LogPrintf("Cache configuration:\n");
1419 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1420 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1421 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));
1423 bool fLoaded = false;
1424 while (!fLoaded) {
1425 bool fReset = fReindex;
1426 std::string strLoadError;
1428 uiInterface.InitMessage(_("Loading block index..."));
1430 nStart = GetTimeMillis();
1431 do {
1432 try {
1433 UnloadBlockIndex();
1434 delete pcoinsTip;
1435 delete pcoinsdbview;
1436 delete pcoinscatcher;
1437 delete pblocktree;
1439 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1440 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState);
1441 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1442 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1444 if (fReindex) {
1445 pblocktree->WriteReindexing(true);
1446 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1447 if (fPruneMode)
1448 CleanupBlockRevFiles();
1451 if (!LoadBlockIndex(chainparams)) {
1452 strLoadError = _("Error loading block database");
1453 break;
1456 // If the loaded chain has a wrong genesis, bail out immediately
1457 // (we're likely using a testnet datadir, or the other way around).
1458 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1459 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1461 // Initialize the block index (no-op if non-empty database was already loaded)
1462 if (!InitBlockIndex(chainparams)) {
1463 strLoadError = _("Error initializing block database");
1464 break;
1467 // Check for changed -txindex state
1468 if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1469 strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
1470 break;
1473 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1474 // in the past, but is now trying to run unpruned.
1475 if (fHavePruned && !fPruneMode) {
1476 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1477 break;
1480 if (!fReindex && chainActive.Tip() != NULL) {
1481 uiInterface.InitMessage(_("Rewinding blocks..."));
1482 if (!RewindBlockIndex(chainparams)) {
1483 strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1484 break;
1488 uiInterface.InitMessage(_("Verifying blocks..."));
1489 if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1490 LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
1491 MIN_BLOCKS_TO_KEEP);
1495 LOCK(cs_main);
1496 CBlockIndex* tip = chainActive.Tip();
1497 RPCNotifyBlockChange(true, tip);
1498 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1499 strLoadError = _("The block database contains a block which appears to be from the future. "
1500 "This may be due to your computer's date and time being set incorrectly. "
1501 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1502 break;
1506 if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1507 GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1508 strLoadError = _("Corrupted block database detected");
1509 break;
1511 } catch (const std::exception& e) {
1512 LogPrintf("%s\n", e.what());
1513 strLoadError = _("Error opening block database");
1514 break;
1517 fLoaded = true;
1518 } while(false);
1520 if (!fLoaded) {
1521 // first suggest a reindex
1522 if (!fReset) {
1523 bool fRet = uiInterface.ThreadSafeQuestion(
1524 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1525 strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1526 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1527 if (fRet) {
1528 fReindex = true;
1529 fRequestShutdown = false;
1530 } else {
1531 LogPrintf("Aborted block database rebuild. Exiting.\n");
1532 return false;
1534 } else {
1535 return InitError(strLoadError);
1540 // As LoadBlockIndex can take several minutes, it's possible the user
1541 // requested to kill the GUI during the last operation. If so, exit.
1542 // As the program has not fully started yet, Shutdown() is possibly overkill.
1543 if (fRequestShutdown)
1545 LogPrintf("Shutdown requested. Exiting.\n");
1546 return false;
1548 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1550 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1551 CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
1552 // Allowed to fail as this file IS missing on first startup.
1553 if (!est_filein.IsNull())
1554 mempool.ReadFeeEstimates(est_filein);
1555 fFeeEstimatesInitialized = true;
1557 // ********************************************************* Step 8: load wallet
1558 #ifdef ENABLE_WALLET
1559 if (!CWallet::InitLoadWallet())
1560 return false;
1561 #else
1562 LogPrintf("No wallet support compiled in!\n");
1563 #endif
1565 // ********************************************************* Step 9: data directory maintenance
1567 // if pruning, unset the service bit and perform the initial blockstore prune
1568 // after any wallet rescanning has taken place.
1569 if (fPruneMode) {
1570 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1571 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1572 if (!fReindex) {
1573 uiInterface.InitMessage(_("Pruning blockstore..."));
1574 PruneAndFlush();
1578 if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
1579 // Only advertise witness capabilities if they have a reasonable start time.
1580 // This allows us to have the code merged without a defined softfork, by setting its
1581 // end time to 0.
1582 // Note that setting NODE_WITNESS is never required: the only downside from not
1583 // doing so is that after activation, no upgraded nodes will fetch from you.
1584 nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1585 // Only care about others providing witness capabilities if there is a softfork
1586 // defined.
1587 nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS);
1590 // ********************************************************* Step 10: import blocks
1592 if (!CheckDiskSpace())
1593 return false;
1595 // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1596 // No locking, as this happens before any background thread is started.
1597 if (chainActive.Tip() == NULL) {
1598 uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1599 } else {
1600 fHaveGenesis = true;
1603 if (IsArgSet("-blocknotify"))
1604 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1606 std::vector<boost::filesystem::path> vImportFiles;
1607 if (mapMultiArgs.count("-loadblock"))
1609 BOOST_FOREACH(const std::string& strFile, mapMultiArgs.at("-loadblock"))
1610 vImportFiles.push_back(strFile);
1613 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1615 // Wait for genesis block to be processed
1617 boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
1618 while (!fHaveGenesis) {
1619 condvar_GenesisWait.wait(lock);
1621 uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1624 // ********************************************************* Step 11: start node
1626 //// debug print
1627 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1628 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1629 if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1630 StartTorControl(threadGroup, scheduler);
1632 Discover(threadGroup);
1634 // Map ports with UPnP
1635 MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
1637 std::string strNodeError;
1638 CConnman::Options connOptions;
1639 connOptions.nLocalServices = nLocalServices;
1640 connOptions.nRelevantServices = nRelevantServices;
1641 connOptions.nMaxConnections = nMaxConnections;
1642 connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1643 connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1644 connOptions.nMaxFeeler = 1;
1645 connOptions.nBestHeight = chainActive.Height();
1646 connOptions.uiInterface = &uiInterface;
1647 connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1648 connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1650 connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1651 connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1653 if (!connman.Start(scheduler, strNodeError, connOptions))
1654 return InitError(strNodeError);
1656 // ********************************************************* Step 12: finished
1658 SetRPCWarmupFinished();
1659 uiInterface.InitMessage(_("Done loading"));
1661 #ifdef ENABLE_WALLET
1662 if (pwalletMain)
1663 pwalletMain->postInitProcess(scheduler);
1664 #endif
1666 return !fRequestShutdown;