net: correctly ban before the handshake is complete
[bitcoinplatinum.git] / src / init.cpp
blob7c108ac4a63817510f8222807704f530441fd57f
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 // Note that if running -daemon the parent process returns from AppInit2
122 // before adding any threads to the threadGroup, so .join_all() returns
123 // immediately and the parent exits from main().
125 // Shutdown for Qt is very similar, only it uses a QTimer to detect
126 // fRequestShutdown getting set, and then does the normal Qt
127 // shutdown thing.
130 std::atomic<bool> fRequestShutdown(false);
131 std::atomic<bool> fDumpMempoolLater(false);
133 void StartShutdown()
135 fRequestShutdown = true;
137 bool ShutdownRequested()
139 return fRequestShutdown;
143 * This is a minimally invasive approach to shutdown on LevelDB read errors from the
144 * chainstate, while keeping user interface out of the common library, which is shared
145 * between bitcoind, and bitcoin-qt and non-server tools.
147 class CCoinsViewErrorCatcher : public CCoinsViewBacked
149 public:
150 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
151 bool GetCoins(const uint256 &txid, CCoins &coins) const {
152 try {
153 return CCoinsViewBacked::GetCoins(txid, coins);
154 } catch(const std::runtime_error& e) {
155 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
156 LogPrintf("Error reading from database: %s\n", e.what());
157 // Starting the shutdown sequence and returning false to the caller would be
158 // interpreted as 'entry not found' (as opposed to unable to read data), and
159 // could lead to invalid interpretation. Just exit immediately, as we can't
160 // continue anyway, and all writes should be atomic.
161 abort();
164 // Writes do not need similar protection, as failure to write is handled by the caller.
167 static CCoinsViewDB *pcoinsdbview = NULL;
168 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
169 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
171 void Interrupt(boost::thread_group& threadGroup)
173 InterruptHTTPServer();
174 InterruptHTTPRPC();
175 InterruptRPC();
176 InterruptREST();
177 InterruptTorControl();
178 if (g_connman)
179 g_connman->Interrupt();
180 threadGroup.interrupt_all();
183 void Shutdown()
185 LogPrintf("%s: In progress...\n", __func__);
186 static CCriticalSection cs_Shutdown;
187 TRY_LOCK(cs_Shutdown, lockShutdown);
188 if (!lockShutdown)
189 return;
191 /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
192 /// for example if the data directory was found to be locked.
193 /// Be sure that anything that writes files or flushes caches only does this if the respective
194 /// module was initialized.
195 RenameThread("bitcoin-shutoff");
196 mempool.AddTransactionsUpdated(1);
198 StopHTTPRPC();
199 StopREST();
200 StopRPC();
201 StopHTTPServer();
202 #ifdef ENABLE_WALLET
203 if (pwalletMain)
204 pwalletMain->Flush(false);
205 #endif
206 MapPort(false);
207 UnregisterValidationInterface(peerLogic.get());
208 peerLogic.reset();
209 g_connman.reset();
211 StopTorControl();
212 UnregisterNodeSignals(GetNodeSignals());
213 if (fDumpMempoolLater)
214 DumpMempool();
216 if (fFeeEstimatesInitialized)
218 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
219 CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
220 if (!est_fileout.IsNull())
221 mempool.WriteFeeEstimates(est_fileout);
222 else
223 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
224 fFeeEstimatesInitialized = false;
228 LOCK(cs_main);
229 if (pcoinsTip != NULL) {
230 FlushStateToDisk();
232 delete pcoinsTip;
233 pcoinsTip = NULL;
234 delete pcoinscatcher;
235 pcoinscatcher = NULL;
236 delete pcoinsdbview;
237 pcoinsdbview = NULL;
238 delete pblocktree;
239 pblocktree = NULL;
241 #ifdef ENABLE_WALLET
242 if (pwalletMain)
243 pwalletMain->Flush(true);
244 #endif
246 #if ENABLE_ZMQ
247 if (pzmqNotificationInterface) {
248 UnregisterValidationInterface(pzmqNotificationInterface);
249 delete pzmqNotificationInterface;
250 pzmqNotificationInterface = NULL;
252 #endif
254 #ifndef WIN32
255 try {
256 boost::filesystem::remove(GetPidFile());
257 } catch (const boost::filesystem::filesystem_error& e) {
258 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
260 #endif
261 UnregisterAllValidationInterfaces();
262 #ifdef ENABLE_WALLET
263 delete pwalletMain;
264 pwalletMain = NULL;
265 #endif
266 globalVerifyHandle.reset();
267 ECC_Stop();
268 LogPrintf("%s: done\n", __func__);
272 * Signal handlers are very limited in what they are allowed to do, so:
274 void HandleSIGTERM(int)
276 fRequestShutdown = true;
279 void HandleSIGHUP(int)
281 fReopenDebugLog = true;
284 bool static Bind(CConnman& connman, const CService &addr, unsigned int flags) {
285 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
286 return false;
287 std::string strError;
288 if (!connman.BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
289 if (flags & BF_REPORT_ERROR)
290 return InitError(strError);
291 return false;
293 return true;
295 void OnRPCStarted()
297 uiInterface.NotifyBlockTip.connect(&RPCNotifyBlockChange);
300 void OnRPCStopped()
302 uiInterface.NotifyBlockTip.disconnect(&RPCNotifyBlockChange);
303 RPCNotifyBlockChange(false, nullptr);
304 cvBlockChange.notify_all();
305 LogPrint("rpc", "RPC stopped.\n");
308 void OnRPCPreCommand(const CRPCCommand& cmd)
310 // Observe safe mode
311 std::string strWarning = GetWarnings("rpc");
312 if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
313 !cmd.okSafeMode)
314 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
317 std::string HelpMessage(HelpMessageMode mode)
319 const bool showDebug = GetBoolArg("-help-debug", false);
321 // When adding new options to the categories, please keep and ensure alphabetical ordering.
322 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
323 std::string strUsage = HelpMessageGroup(_("Options:"));
324 strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
325 strUsage += HelpMessageOpt("-version", _("Print version and exit"));
326 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)"));
327 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
328 if (showDebug)
329 strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
330 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()));
331 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
332 if (mode == HMM_BITCOIND)
334 #if HAVE_DECL_DAEMON
335 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
336 #endif
338 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
339 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
340 if (showDebug)
341 strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
342 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
343 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
344 strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
345 strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
346 strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
347 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)"),
348 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
349 #ifndef WIN32
350 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
351 #endif
352 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. "
353 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
354 "(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));
355 strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
356 strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
357 #ifndef WIN32
358 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
359 #endif
360 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
362 strUsage += HelpMessageGroup(_("Connection options:"));
363 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
364 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
365 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
366 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
367 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -noconnect or -connect=0 alone to disable automatic connections"));
368 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
369 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
370 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect/-noconnect)"));
371 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
372 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
373 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect/-noconnect)"));
374 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
375 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
376 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
377 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
378 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));
379 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
380 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
381 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
382 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
383 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), Params(CBaseChainParams::MAIN).GetDefaultPort(), Params(CBaseChainParams::TESTNET).GetDefaultPort()));
384 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
385 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
386 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));
387 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
388 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
389 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
390 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
391 #ifdef USE_UPNP
392 #if USE_UPNP
393 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
394 #else
395 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
396 #endif
397 #endif
398 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
399 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.") +
400 " " + _("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"));
401 strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
402 strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
403 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));
405 #ifdef ENABLE_WALLET
406 strUsage += CWallet::GetWalletHelpString(showDebug);
407 #endif
409 #if ENABLE_ZMQ
410 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
411 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
412 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
413 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
414 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
415 #endif
417 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
418 strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
419 if (showDebug)
421 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
422 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
423 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()));
424 strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
425 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
426 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
427 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
428 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
429 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
430 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
431 strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
432 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));
433 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));
434 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));
435 strUsage += HelpMessageOpt("-bip9params=deployment:start:end", "Use given start/end times for specified BIP9 deployment (regtest-only)");
437 std::string debugCategories = "addrman, alert, bench, cmpctblock, coindb, db, http, libevent, lock, mempool, mempoolrej, net, proxy, prune, rand, reindex, rpc, selectcoins, tor, zmq"; // Don't translate these and qt below
438 if (mode == HMM_BITCOIN_QT)
439 debugCategories += ", qt";
440 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
441 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
442 if (showDebug)
443 strUsage += HelpMessageOpt("-nodebug", "Turn off debugging messages, same as -debug=0");
444 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
445 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
446 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
447 if (showDebug)
449 strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
450 strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
451 strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", DEFAULT_LIMITFREERELAY));
452 strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", DEFAULT_RELAYPRIORITY));
453 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
454 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
456 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
457 CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
458 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)"),
459 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
460 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
461 if (showDebug)
463 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
465 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
467 AppendParamsHelpMessages(strUsage, showDebug);
469 strUsage += HelpMessageGroup(_("Node relay options:"));
470 if (showDebug) {
471 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
472 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)));
473 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)));
475 strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
476 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
477 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
478 strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
480 strUsage += HelpMessageGroup(_("Block creation options:"));
481 strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
482 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
483 strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
484 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)));
485 if (showDebug)
486 strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
488 strUsage += HelpMessageGroup(_("RPC server options:"));
489 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
490 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
491 strUsage += HelpMessageOpt("-rpcbind=<addr>", _("Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)"));
492 strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
493 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
494 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
495 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"));
496 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()));
497 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"));
498 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
499 if (showDebug) {
500 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
501 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
504 return strUsage;
507 std::string LicenseInfo()
509 const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
510 const std::string URL_WEBSITE = "<https://bitcoincore.org>";
512 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
513 "\n" +
514 strprintf(_("Please contribute if you find %s useful. "
515 "Visit %s for further information about the software."),
516 PACKAGE_NAME, URL_WEBSITE) +
517 "\n" +
518 strprintf(_("The source code is available from %s."),
519 URL_SOURCE_CODE) +
520 "\n" +
521 "\n" +
522 _("This is experimental software.") + "\n" +
523 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
524 "\n" +
525 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>") +
526 "\n";
529 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
531 if (initialSync || !pBlockIndex)
532 return;
534 std::string strCmd = GetArg("-blocknotify", "");
536 boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
537 boost::thread t(runCommand, strCmd); // thread runs free
540 static bool fHaveGenesis = false;
541 static boost::mutex cs_GenesisWait;
542 static CConditionVariable condvar_GenesisWait;
544 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
546 if (pBlockIndex != NULL) {
548 boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
549 fHaveGenesis = true;
551 condvar_GenesisWait.notify_all();
555 struct CImportingNow
557 CImportingNow() {
558 assert(fImporting == false);
559 fImporting = true;
562 ~CImportingNow() {
563 assert(fImporting == true);
564 fImporting = false;
569 // If we're using -prune with -reindex, then delete block files that will be ignored by the
570 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
571 // is missing, do the same here to delete any later block files after a gap. Also delete all
572 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
573 // is in sync with what's actually on disk by the time we start downloading, so that pruning
574 // works correctly.
575 void CleanupBlockRevFiles()
577 std::map<std::string, boost::filesystem::path> mapBlockFiles;
579 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
580 // Remove the rev files immediately and insert the blk file paths into an
581 // ordered map keyed by block file index.
582 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
583 boost::filesystem::path blocksdir = GetDataDir() / "blocks";
584 for (boost::filesystem::directory_iterator it(blocksdir); it != boost::filesystem::directory_iterator(); it++) {
585 if (is_regular_file(*it) &&
586 it->path().filename().string().length() == 12 &&
587 it->path().filename().string().substr(8,4) == ".dat")
589 if (it->path().filename().string().substr(0,3) == "blk")
590 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
591 else if (it->path().filename().string().substr(0,3) == "rev")
592 remove(it->path());
596 // Remove all block files that aren't part of a contiguous set starting at
597 // zero by walking the ordered map (keys are block file indices) by
598 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
599 // start removing block files.
600 int nContigCounter = 0;
601 BOOST_FOREACH(const PAIRTYPE(std::string, boost::filesystem::path)& item, mapBlockFiles) {
602 if (atoi(item.first) == nContigCounter) {
603 nContigCounter++;
604 continue;
606 remove(item.second);
610 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
612 const CChainParams& chainparams = Params();
613 RenameThread("bitcoin-loadblk");
616 CImportingNow imp;
618 // -reindex
619 if (fReindex) {
620 int nFile = 0;
621 while (true) {
622 CDiskBlockPos pos(nFile, 0);
623 if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
624 break; // No block files left to reindex
625 FILE *file = OpenBlockFile(pos, true);
626 if (!file)
627 break; // This error is logged in OpenBlockFile
628 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
629 LoadExternalBlockFile(chainparams, file, &pos);
630 nFile++;
632 pblocktree->WriteReindexing(false);
633 fReindex = false;
634 LogPrintf("Reindexing finished\n");
635 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
636 InitBlockIndex(chainparams);
639 // hardcoded $DATADIR/bootstrap.dat
640 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
641 if (boost::filesystem::exists(pathBootstrap)) {
642 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
643 if (file) {
644 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
645 LogPrintf("Importing bootstrap.dat...\n");
646 LoadExternalBlockFile(chainparams, file);
647 RenameOver(pathBootstrap, pathBootstrapOld);
648 } else {
649 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
653 // -loadblock=
654 BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
655 FILE *file = fopen(path.string().c_str(), "rb");
656 if (file) {
657 LogPrintf("Importing blocks file %s...\n", path.string());
658 LoadExternalBlockFile(chainparams, file);
659 } else {
660 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
664 // scan for better chains in the block chain database, that are not yet connected in the active best chain
665 CValidationState state;
666 if (!ActivateBestChain(state, chainparams)) {
667 LogPrintf("Failed to connect best block");
668 StartShutdown();
671 if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
672 LogPrintf("Stopping after block import\n");
673 StartShutdown();
675 } // End scope of CImportingNow
676 LoadMempool();
677 fDumpMempoolLater = !fRequestShutdown;
680 /** Sanity checks
681 * Ensure that Bitcoin is running in a usable environment with all
682 * necessary library support.
684 bool InitSanityCheck(void)
686 if(!ECC_InitSanityCheck()) {
687 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
688 return false;
690 if (!glibc_sanity_test() || !glibcxx_sanity_test())
691 return false;
693 return true;
696 bool AppInitServers(boost::thread_group& threadGroup)
698 RPCServer::OnStarted(&OnRPCStarted);
699 RPCServer::OnStopped(&OnRPCStopped);
700 RPCServer::OnPreCommand(&OnRPCPreCommand);
701 if (!InitHTTPServer())
702 return false;
703 if (!StartRPC())
704 return false;
705 if (!StartHTTPRPC())
706 return false;
707 if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
708 return false;
709 if (!StartHTTPServer())
710 return false;
711 return true;
714 // Parameter interaction based on rules
715 void InitParameterInteraction()
717 // when specifying an explicit binding address, you want to listen on it
718 // even when -connect or -proxy is specified
719 if (IsArgSet("-bind")) {
720 if (SoftSetBoolArg("-listen", true))
721 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
723 if (IsArgSet("-whitebind")) {
724 if (SoftSetBoolArg("-listen", true))
725 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
728 if (mapMultiArgs.count("-connect") && mapMultiArgs.at("-connect").size() > 0) {
729 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
730 if (SoftSetBoolArg("-dnsseed", false))
731 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
732 if (SoftSetBoolArg("-listen", false))
733 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
736 if (IsArgSet("-proxy")) {
737 // to protect privacy, do not listen by default if a default proxy server is specified
738 if (SoftSetBoolArg("-listen", false))
739 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
740 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
741 // to listen locally, so don't rely on this happening through -listen below.
742 if (SoftSetBoolArg("-upnp", false))
743 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
744 // to protect privacy, do not discover addresses by default
745 if (SoftSetBoolArg("-discover", false))
746 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
749 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
750 // do not map ports or try to retrieve public IP when not listening (pointless)
751 if (SoftSetBoolArg("-upnp", false))
752 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
753 if (SoftSetBoolArg("-discover", false))
754 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
755 if (SoftSetBoolArg("-listenonion", false))
756 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
759 if (IsArgSet("-externalip")) {
760 // if an explicit public IP is specified, do not try to find others
761 if (SoftSetBoolArg("-discover", false))
762 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
765 // disable whitelistrelay in blocksonly mode
766 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
767 if (SoftSetBoolArg("-whitelistrelay", false))
768 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
771 // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
772 if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
773 if (SoftSetBoolArg("-whitelistrelay", true))
774 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
778 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
780 return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
783 void InitLogging()
785 fPrintToConsole = GetBoolArg("-printtoconsole", false);
786 fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
787 fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
788 fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
790 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
791 LogPrintf("Bitcoin version %s\n", FormatFullVersion());
794 namespace { // Variables internal to initialization process only
796 ServiceFlags nRelevantServices = NODE_NETWORK;
797 int nMaxConnections;
798 int nUserMaxConnections;
799 int nFD;
800 ServiceFlags nLocalServices = NODE_NETWORK;
804 bool AppInitBasicSetup()
806 // ********************************************************* Step 1: setup
807 #ifdef _MSC_VER
808 // Turn off Microsoft heap dump noise
809 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
810 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
811 #endif
812 #if _MSC_VER >= 1400
813 // Disable confusing "helpful" text message on abort, Ctrl-C
814 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
815 #endif
816 #ifdef WIN32
817 // Enable Data Execution Prevention (DEP)
818 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
819 // A failure is non-critical and needs no further attention!
820 #ifndef PROCESS_DEP_ENABLE
821 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
822 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
823 #define PROCESS_DEP_ENABLE 0x00000001
824 #endif
825 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
826 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
827 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
828 #endif
830 if (!SetupNetworking())
831 return InitError("Initializing networking failed");
833 #ifndef WIN32
834 if (!GetBoolArg("-sysperms", false)) {
835 umask(077);
838 // Clean shutdown on SIGTERM
839 struct sigaction sa;
840 sa.sa_handler = HandleSIGTERM;
841 sigemptyset(&sa.sa_mask);
842 sa.sa_flags = 0;
843 sigaction(SIGTERM, &sa, NULL);
844 sigaction(SIGINT, &sa, NULL);
846 // Reopen debug.log on SIGHUP
847 struct sigaction sa_hup;
848 sa_hup.sa_handler = HandleSIGHUP;
849 sigemptyset(&sa_hup.sa_mask);
850 sa_hup.sa_flags = 0;
851 sigaction(SIGHUP, &sa_hup, NULL);
853 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
854 signal(SIGPIPE, SIG_IGN);
855 #endif
856 return true;
859 bool AppInitParameterInteraction()
861 const CChainParams& chainparams = Params();
862 // ********************************************************* Step 2: parameter interactions
864 // also see: InitParameterInteraction()
866 // if using block pruning, then disallow txindex
867 if (GetArg("-prune", 0)) {
868 if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
869 return InitError(_("Prune mode is incompatible with -txindex."));
872 // Make sure enough file descriptors are available
873 int nBind = std::max(
874 (mapMultiArgs.count("-bind") ? mapMultiArgs.at("-bind").size() : 0) +
875 (mapMultiArgs.count("-whitebind") ? mapMultiArgs.at("-whitebind").size() : 0), size_t(1));
876 nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
877 nMaxConnections = std::max(nUserMaxConnections, 0);
879 // Trim requested connection counts, to fit into system limitations
880 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
881 nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
882 if (nFD < MIN_CORE_FILEDESCRIPTORS)
883 return InitError(_("Not enough file descriptors available."));
884 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
886 if (nMaxConnections < nUserMaxConnections)
887 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
889 // ********************************************************* Step 3: parameter-to-internal-flags
891 fDebug = mapMultiArgs.count("-debug");
892 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
893 if (fDebug) {
894 const std::vector<std::string>& categories = mapMultiArgs.at("-debug");
895 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), std::string("0")) != categories.end())
896 fDebug = false;
899 // Check for -debugnet
900 if (GetBoolArg("-debugnet", false))
901 InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
902 // Check for -socks - as this is a privacy risk to continue, exit here
903 if (IsArgSet("-socks"))
904 return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
905 // Check for -tor - as this is a privacy risk to continue, exit here
906 if (GetBoolArg("-tor", false))
907 return InitError(_("Unsupported argument -tor found, use -onion."));
909 if (GetBoolArg("-benchmark", false))
910 InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
912 if (GetBoolArg("-whitelistalwaysrelay", false))
913 InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
915 if (IsArgSet("-blockminsize"))
916 InitWarning("Unsupported argument -blockminsize ignored.");
918 // Checkmempool and checkblockindex default to true in regtest mode
919 int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
920 if (ratio != 0) {
921 mempool.setSanityCheck(1.0 / ratio);
923 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
924 fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
926 hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
927 if (!hashAssumeValid.IsNull())
928 LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
929 else
930 LogPrintf("Validating signatures for all blocks.\n");
932 // mempool limits
933 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
934 int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
935 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
936 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
937 // incremental relay fee sets the minimimum feerate increase necessary for BIP 125 replacement in the mempool
938 // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
939 if (IsArgSet("-incrementalrelayfee"))
941 CAmount n = 0;
942 if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n))
943 return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", "")));
944 incrementalRelayFee = CFeeRate(n);
947 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
948 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
949 if (nScriptCheckThreads <= 0)
950 nScriptCheckThreads += GetNumCores();
951 if (nScriptCheckThreads <= 1)
952 nScriptCheckThreads = 0;
953 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
954 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
956 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
957 int64_t nPruneArg = GetArg("-prune", 0);
958 if (nPruneArg < 0) {
959 return InitError(_("Prune cannot be configured with a negative value."));
961 nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
962 if (nPruneArg == 1) { // manual pruning: -prune=1
963 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
964 nPruneTarget = std::numeric_limits<uint64_t>::max();
965 fPruneMode = true;
966 } else if (nPruneTarget) {
967 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
968 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
970 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
971 fPruneMode = true;
974 RegisterAllCoreRPCCommands(tableRPC);
975 #ifdef ENABLE_WALLET
976 RegisterWalletRPCCommands(tableRPC);
977 #endif
979 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
980 if (nConnectTimeout <= 0)
981 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
983 // Fee-per-kilobyte amount considered the same as "free"
984 // If you are mining, be careful setting this:
985 // if you set it to zero then
986 // a transaction spammer can cheaply fill blocks using
987 // 1-satoshi-fee transactions. It should be set above the real
988 // cost to you of processing a transaction.
989 if (IsArgSet("-minrelaytxfee"))
991 CAmount n = 0;
992 if (!ParseMoney(GetArg("-minrelaytxfee", ""), n) || 0 == n)
993 return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
994 // High fee check is done afterward in CWallet::ParameterInteraction()
995 ::minRelayTxFee = CFeeRate(n);
996 } else if (incrementalRelayFee > ::minRelayTxFee) {
997 // Allow only setting incrementalRelayFee to control both
998 ::minRelayTxFee = incrementalRelayFee;
999 LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1002 // Sanity check argument for min fee for including tx in block
1003 // TODO: Harmonize which arguments need sanity checking and where that happens
1004 if (IsArgSet("-blockmintxfee"))
1006 CAmount n = 0;
1007 if (!ParseMoney(GetArg("-blockmintxfee", ""), n))
1008 return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", "")));
1011 // Feerate used to define dust. Shouldn't be changed lightly as old
1012 // implementations may inadvertently create non-standard transactions
1013 if (IsArgSet("-dustrelayfee"))
1015 CAmount n = 0;
1016 if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n)
1017 return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", "")));
1018 dustRelayFee = CFeeRate(n);
1021 fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1022 if (chainparams.RequireStandard() && !fRequireStandard)
1023 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1024 nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
1026 #ifdef ENABLE_WALLET
1027 if (!CWallet::ParameterInteraction())
1028 return false;
1029 #endif
1031 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1032 fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1033 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1035 // Option to startup with mocktime set (used for regression testing):
1036 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1038 if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1039 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1041 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1042 return InitError("rpcserialversion must be non-negative.");
1044 if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1045 return InitError("unknown rpcserialversion requested.");
1047 nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1049 fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1050 if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
1051 // Minimal effort at forwards compatibility
1052 std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
1053 std::vector<std::string> vstrReplacementModes;
1054 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1055 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1058 if (mapMultiArgs.count("-bip9params")) {
1059 // Allow overriding BIP9 parameters for testing
1060 if (!chainparams.MineBlocksOnDemand()) {
1061 return InitError("BIP9 parameters may only be overridden on regtest.");
1063 const std::vector<std::string>& deployments = mapMultiArgs.at("-bip9params");
1064 for (auto i : deployments) {
1065 std::vector<std::string> vDeploymentParams;
1066 boost::split(vDeploymentParams, i, boost::is_any_of(":"));
1067 if (vDeploymentParams.size() != 3) {
1068 return InitError("BIP9 parameters malformed, expecting deployment:start:end");
1070 int64_t nStartTime, nTimeout;
1071 if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1072 return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1074 if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1075 return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1077 bool found = false;
1078 for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1080 if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1081 UpdateRegtestBIP9Parameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1082 found = true;
1083 LogPrintf("Setting BIP9 activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1084 break;
1087 if (!found) {
1088 return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1092 return true;
1095 static bool LockDataDirectory(bool probeOnly)
1097 std::string strDataDir = GetDataDir().string();
1099 // Make sure only a single Bitcoin process is using the data directory.
1100 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
1101 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
1102 if (file) fclose(file);
1104 try {
1105 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1106 if (!lock.try_lock()) {
1107 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1109 if (probeOnly) {
1110 lock.unlock();
1112 } catch(const boost::interprocess::interprocess_exception& e) {
1113 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1115 return true;
1118 bool AppInitSanityChecks()
1120 // ********************************************************* Step 4: sanity checks
1122 // Initialize elliptic curve code
1123 ECC_Start();
1124 globalVerifyHandle.reset(new ECCVerifyHandle());
1126 // Sanity check
1127 if (!InitSanityCheck())
1128 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1130 // Probe the data directory lock to give an early error message, if possible
1131 return LockDataDirectory(true);
1134 bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
1136 const CChainParams& chainparams = Params();
1137 // ********************************************************* Step 4a: application initialization
1138 // After daemonization get the data directory lock again and hold on to it until exit
1139 // This creates a slight window for a race condition to happen, however this condition is harmless: it
1140 // will at most make us exit without printing a message to console.
1141 if (!LockDataDirectory(false)) {
1142 // Detailed error printed inside LockDataDirectory
1143 return false;
1146 #ifndef WIN32
1147 CreatePidFile(GetPidFile(), getpid());
1148 #endif
1149 if (GetBoolArg("-shrinkdebugfile", !fDebug)) {
1150 // Do this first since it both loads a bunch of debug.log into memory,
1151 // and because this needs to happen before any other debug.log printing
1152 ShrinkDebugFile();
1155 if (fPrintToDebugLog)
1156 OpenDebugLog();
1158 if (!fLogTimestamps)
1159 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1160 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1161 LogPrintf("Using data directory %s\n", GetDataDir().string());
1162 LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1163 LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1165 InitSignatureCache();
1167 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1168 if (nScriptCheckThreads) {
1169 for (int i=0; i<nScriptCheckThreads-1; i++)
1170 threadGroup.create_thread(&ThreadScriptCheck);
1173 // Start the lightweight task scheduler thread
1174 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1175 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1177 /* Start the RPC server already. It will be started in "warmup" mode
1178 * and not really process calls already (but it will signify connections
1179 * that the server is there and will be ready later). Warmup mode will
1180 * be disabled when initialisation is finished.
1182 if (GetBoolArg("-server", false))
1184 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1185 if (!AppInitServers(threadGroup))
1186 return InitError(_("Unable to start HTTP server. See debug log for details."));
1189 int64_t nStart;
1191 // ********************************************************* Step 5: verify wallet database integrity
1192 #ifdef ENABLE_WALLET
1193 if (!CWallet::Verify())
1194 return false;
1195 #endif
1196 // ********************************************************* Step 6: network initialization
1197 // Note that we absolutely cannot open any actual connections
1198 // until the very end ("start node") as the UTXO/block state
1199 // is not yet setup and may end up being set up twice if we
1200 // need to reindex later.
1202 assert(!g_connman);
1203 g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1204 CConnman& connman = *g_connman;
1206 peerLogic.reset(new PeerLogicValidation(&connman));
1207 RegisterValidationInterface(peerLogic.get());
1208 RegisterNodeSignals(GetNodeSignals());
1210 // sanitize comments per BIP-0014, format user agent and check total size
1211 std::vector<std::string> uacomments;
1212 if (mapMultiArgs.count("-uacomment")) {
1213 BOOST_FOREACH(std::string cmt, mapMultiArgs.at("-uacomment"))
1215 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1216 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1217 uacomments.push_back(cmt);
1220 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1221 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1222 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1223 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1226 if (mapMultiArgs.count("-onlynet")) {
1227 std::set<enum Network> nets;
1228 BOOST_FOREACH(const std::string& snet, mapMultiArgs.at("-onlynet")) {
1229 enum Network net = ParseNetwork(snet);
1230 if (net == NET_UNROUTABLE)
1231 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1232 nets.insert(net);
1234 for (int n = 0; n < NET_MAX; n++) {
1235 enum Network net = (enum Network)n;
1236 if (!nets.count(net))
1237 SetLimited(net);
1241 if (mapMultiArgs.count("-whitelist")) {
1242 BOOST_FOREACH(const std::string& net, mapMultiArgs.at("-whitelist")) {
1243 CSubNet subnet;
1244 LookupSubNet(net.c_str(), subnet);
1245 if (!subnet.IsValid())
1246 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1247 connman.AddWhitelistedRange(subnet);
1251 bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1252 // -proxy sets a proxy for all outgoing network traffic
1253 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1254 std::string proxyArg = GetArg("-proxy", "");
1255 SetLimited(NET_TOR);
1256 if (proxyArg != "" && proxyArg != "0") {
1257 CService resolved(LookupNumeric(proxyArg.c_str(), 9050));
1258 proxyType addrProxy = proxyType(resolved, proxyRandomize);
1259 if (!addrProxy.IsValid())
1260 return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
1262 SetProxy(NET_IPV4, addrProxy);
1263 SetProxy(NET_IPV6, addrProxy);
1264 SetProxy(NET_TOR, addrProxy);
1265 SetNameProxy(addrProxy);
1266 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1269 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1270 // -noonion (or -onion=0) disables connecting to .onion entirely
1271 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1272 std::string onionArg = GetArg("-onion", "");
1273 if (onionArg != "") {
1274 if (onionArg == "0") { // Handle -noonion/-onion=0
1275 SetLimited(NET_TOR); // set onions as unreachable
1276 } else {
1277 CService resolved(LookupNumeric(onionArg.c_str(), 9050));
1278 proxyType addrOnion = proxyType(resolved, proxyRandomize);
1279 if (!addrOnion.IsValid())
1280 return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
1281 SetProxy(NET_TOR, addrOnion);
1282 SetLimited(NET_TOR, false);
1286 // see Step 2: parameter interactions for more information about these
1287 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1288 fDiscover = GetBoolArg("-discover", true);
1289 fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1290 fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1292 if (fListen) {
1293 bool fBound = false;
1294 if (mapMultiArgs.count("-bind")) {
1295 BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-bind")) {
1296 CService addrBind;
1297 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1298 return InitError(ResolveErrMsg("bind", strBind));
1299 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1302 if (mapMultiArgs.count("-whitebind")) {
1303 BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-whitebind")) {
1304 CService addrBind;
1305 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1306 return InitError(ResolveErrMsg("whitebind", strBind));
1307 if (addrBind.GetPort() == 0)
1308 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1309 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1312 if (!mapMultiArgs.count("-bind") && !mapMultiArgs.count("-whitebind")) {
1313 struct in_addr inaddr_any;
1314 inaddr_any.s_addr = INADDR_ANY;
1315 fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
1316 fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1318 if (!fBound)
1319 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1322 if (mapMultiArgs.count("-externalip")) {
1323 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-externalip")) {
1324 CService addrLocal;
1325 if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1326 AddLocal(addrLocal, LOCAL_MANUAL);
1327 else
1328 return InitError(ResolveErrMsg("externalip", strAddr));
1332 if (mapMultiArgs.count("-seednode")) {
1333 BOOST_FOREACH(const std::string& strDest, mapMultiArgs.at("-seednode"))
1334 connman.AddOneShot(strDest);
1337 #if ENABLE_ZMQ
1338 pzmqNotificationInterface = CZMQNotificationInterface::Create();
1340 if (pzmqNotificationInterface) {
1341 RegisterValidationInterface(pzmqNotificationInterface);
1343 #endif
1344 uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1345 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1347 if (IsArgSet("-maxuploadtarget")) {
1348 nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1351 // ********************************************************* Step 7: load block chain
1353 fReindex = GetBoolArg("-reindex", false);
1354 bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
1356 // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
1357 boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1358 if (!boost::filesystem::exists(blocksDir))
1360 boost::filesystem::create_directories(blocksDir);
1361 bool linked = false;
1362 for (unsigned int i = 1; i < 10000; i++) {
1363 boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1364 if (!boost::filesystem::exists(source)) break;
1365 boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
1366 try {
1367 boost::filesystem::create_hard_link(source, dest);
1368 LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
1369 linked = true;
1370 } catch (const boost::filesystem::filesystem_error& e) {
1371 // Note: hardlink creation failing is not a disaster, it just means
1372 // blocks will get re-downloaded from peers.
1373 LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
1374 break;
1377 if (linked)
1379 fReindex = true;
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(threadGroup);
1641 #endif
1643 return !fRequestShutdown;