Add DumpMempool and LoadMempool
[bitcoinplatinum.git] / src / init.cpp
blobefaf821f4feb5df164626186120d021aed673d41
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 "main.h"
23 #include "miner.h"
24 #include "netbase.h"
25 #include "net.h"
26 #include "policy/policy.h"
27 #include "rpc/server.h"
28 #include "rpc/register.h"
29 #include "script/standard.h"
30 #include "script/sigcache.h"
31 #include "scheduler.h"
32 #include "timedata.h"
33 #include "txdb.h"
34 #include "txmempool.h"
35 #include "torcontrol.h"
36 #include "ui_interface.h"
37 #include "util.h"
38 #include "utilmoneystr.h"
39 #include "validationinterface.h"
40 #ifdef ENABLE_WALLET
41 #include "wallet/wallet.h"
42 #endif
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <memory>
47 #ifndef WIN32
48 #include <signal.h>
49 #endif
51 #include <boost/algorithm/string/classification.hpp>
52 #include <boost/algorithm/string/predicate.hpp>
53 #include <boost/algorithm/string/replace.hpp>
54 #include <boost/algorithm/string/split.hpp>
55 #include <boost/bind.hpp>
56 #include <boost/filesystem.hpp>
57 #include <boost/function.hpp>
58 #include <boost/interprocess/sync/file_lock.hpp>
59 #include <boost/thread.hpp>
60 #include <openssl/crypto.h>
62 #if ENABLE_ZMQ
63 #include "zmq/zmqnotificationinterface.h"
64 #endif
66 using namespace std;
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);
132 void StartShutdown()
134 fRequestShutdown = true;
136 bool ShutdownRequested()
138 return fRequestShutdown;
142 * This is a minimally invasive approach to shutdown on LevelDB read errors from the
143 * chainstate, while keeping user interface out of the common library, which is shared
144 * between bitcoind, and bitcoin-qt and non-server tools.
146 class CCoinsViewErrorCatcher : public CCoinsViewBacked
148 public:
149 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
150 bool GetCoins(const uint256 &txid, CCoins &coins) const {
151 try {
152 return CCoinsViewBacked::GetCoins(txid, coins);
153 } catch(const std::runtime_error& e) {
154 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
155 LogPrintf("Error reading from database: %s\n", e.what());
156 // Starting the shutdown sequence and returning false to the caller would be
157 // interpreted as 'entry not found' (as opposed to unable to read data), and
158 // could lead to invalid interpretation. Just exit immediately, as we can't
159 // continue anyway, and all writes should be atomic.
160 abort();
163 // Writes do not need similar protection, as failure to write is handled by the caller.
166 static CCoinsViewDB *pcoinsdbview = NULL;
167 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
168 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
170 void Interrupt(boost::thread_group& threadGroup)
172 InterruptHTTPServer();
173 InterruptHTTPRPC();
174 InterruptRPC();
175 InterruptREST();
176 InterruptTorControl();
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 AppInit2() 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 DumpMempool();
212 if (fFeeEstimatesInitialized)
214 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
215 CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
216 if (!est_fileout.IsNull())
217 mempool.WriteFeeEstimates(est_fileout);
218 else
219 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
220 fFeeEstimatesInitialized = false;
224 LOCK(cs_main);
225 if (pcoinsTip != NULL) {
226 FlushStateToDisk();
228 delete pcoinsTip;
229 pcoinsTip = NULL;
230 delete pcoinscatcher;
231 pcoinscatcher = NULL;
232 delete pcoinsdbview;
233 pcoinsdbview = NULL;
234 delete pblocktree;
235 pblocktree = NULL;
237 #ifdef ENABLE_WALLET
238 if (pwalletMain)
239 pwalletMain->Flush(true);
240 #endif
242 #if ENABLE_ZMQ
243 if (pzmqNotificationInterface) {
244 UnregisterValidationInterface(pzmqNotificationInterface);
245 delete pzmqNotificationInterface;
246 pzmqNotificationInterface = NULL;
248 #endif
250 #ifndef WIN32
251 try {
252 boost::filesystem::remove(GetPidFile());
253 } catch (const boost::filesystem::filesystem_error& e) {
254 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
256 #endif
257 UnregisterAllValidationInterfaces();
258 #ifdef ENABLE_WALLET
259 delete pwalletMain;
260 pwalletMain = NULL;
261 #endif
262 globalVerifyHandle.reset();
263 ECC_Stop();
264 LogPrintf("%s: done\n", __func__);
268 * Signal handlers are very limited in what they are allowed to do, so:
270 void HandleSIGTERM(int)
272 fRequestShutdown = true;
275 void HandleSIGHUP(int)
277 fReopenDebugLog = true;
280 bool static Bind(CConnman& connman, const CService &addr, unsigned int flags) {
281 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
282 return false;
283 std::string strError;
284 if (!connman.BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
285 if (flags & BF_REPORT_ERROR)
286 return InitError(strError);
287 return false;
289 return true;
291 void OnRPCStarted()
293 uiInterface.NotifyBlockTip.connect(&RPCNotifyBlockChange);
296 void OnRPCStopped()
298 uiInterface.NotifyBlockTip.disconnect(&RPCNotifyBlockChange);
299 RPCNotifyBlockChange(false, nullptr);
300 cvBlockChange.notify_all();
301 LogPrint("rpc", "RPC stopped.\n");
304 void OnRPCPreCommand(const CRPCCommand& cmd)
306 // Observe safe mode
307 string strWarning = GetWarnings("rpc");
308 if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
309 !cmd.okSafeMode)
310 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
313 std::string HelpMessage(HelpMessageMode mode)
315 const bool showDebug = GetBoolArg("-help-debug", false);
317 // When adding new options to the categories, please keep and ensure alphabetical ordering.
318 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
319 string strUsage = HelpMessageGroup(_("Options:"));
320 strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
321 strUsage += HelpMessageOpt("-version", _("Print version and exit"));
322 strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)"));
323 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
324 if (showDebug)
325 strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
326 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
327 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
328 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
329 if (mode == HMM_BITCOIND)
331 #if HAVE_DECL_DAEMON
332 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
333 #endif
335 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
336 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
337 if (showDebug)
338 strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
339 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
340 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
341 strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
342 strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
343 strUsage += HelpMessageOpt("-par=<n>", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"),
344 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
345 #ifndef WIN32
346 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
347 #endif
348 strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. "
349 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
350 "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
351 strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
352 strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
353 #ifndef WIN32
354 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
355 #endif
356 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
358 strUsage += HelpMessageGroup(_("Connection options:"));
359 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
360 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
361 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
362 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
363 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -noconnect or -connect=0 alone to disable automatic connections"));
364 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
365 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
366 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect/-noconnect)"));
367 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
368 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
369 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect/-noconnect)"));
370 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
371 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
372 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
373 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
374 strUsage += HelpMessageOpt("-maxtimeadjustment", strprintf(_("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)"), DEFAULT_MAX_TIME_ADJUSTMENT));
375 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
376 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
377 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
378 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
379 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), Params(CBaseChainParams::MAIN).GetDefaultPort(), Params(CBaseChainParams::TESTNET).GetDefaultPort()));
380 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
381 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
382 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
383 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
384 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
385 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
386 #ifdef USE_UPNP
387 #if USE_UPNP
388 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
389 #else
390 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
391 #endif
392 #endif
393 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
394 strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
395 " " + _("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"));
396 strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
397 strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
398 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));
400 #ifdef ENABLE_WALLET
401 strUsage += CWallet::GetWalletHelpString(showDebug);
402 #endif
404 #if ENABLE_ZMQ
405 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
406 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
407 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
408 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
409 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
410 #endif
412 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
413 strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
414 if (showDebug)
416 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()));
417 strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
418 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
419 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
420 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
421 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
422 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
423 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
424 strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
425 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));
426 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));
427 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));
428 strUsage += HelpMessageOpt("-bip9params=deployment:start:end", "Use given start/end times for specified BIP9 deployment (regtest-only)");
430 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
431 if (mode == HMM_BITCOIN_QT)
432 debugCategories += ", qt";
433 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
434 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
435 if (showDebug)
436 strUsage += HelpMessageOpt("-nodebug", "Turn off debugging messages, same as -debug=0");
437 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
438 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
439 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
440 if (showDebug)
442 strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
443 strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
444 strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", DEFAULT_LIMITFREERELAY));
445 strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", DEFAULT_RELAYPRIORITY));
446 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
447 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
449 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
450 CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
451 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)"),
452 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
453 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
454 if (showDebug)
456 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
458 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
460 AppendParamsHelpMessages(strUsage, showDebug);
462 strUsage += HelpMessageGroup(_("Node relay options:"));
463 if (showDebug)
464 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
465 strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
466 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
467 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
468 strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
470 strUsage += HelpMessageGroup(_("Block creation options:"));
471 strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
472 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
473 strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
474 if (showDebug)
475 strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
477 strUsage += HelpMessageGroup(_("RPC server options:"));
478 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
479 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
480 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)"));
481 strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
482 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
483 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
484 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. This option can be specified multiple times"));
485 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()));
486 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"));
487 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
488 if (showDebug) {
489 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
490 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
493 return strUsage;
496 std::string LicenseInfo()
498 const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
499 const std::string URL_WEBSITE = "<https://bitcoincore.org>";
501 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
502 "\n" +
503 strprintf(_("Please contribute if you find %s useful. "
504 "Visit %s for further information about the software."),
505 PACKAGE_NAME, URL_WEBSITE) +
506 "\n" +
507 strprintf(_("The source code is available from %s."),
508 URL_SOURCE_CODE) +
509 "\n" +
510 "\n" +
511 _("This is experimental software.") + "\n" +
512 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
513 "\n" +
514 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>") +
515 "\n";
518 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
520 if (initialSync || !pBlockIndex)
521 return;
523 std::string strCmd = GetArg("-blocknotify", "");
525 boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
526 boost::thread t(runCommand, strCmd); // thread runs free
529 static bool fHaveGenesis = false;
530 static boost::mutex cs_GenesisWait;
531 static CConditionVariable condvar_GenesisWait;
533 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
535 if (pBlockIndex != NULL) {
537 boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
538 fHaveGenesis = true;
540 condvar_GenesisWait.notify_all();
544 struct CImportingNow
546 CImportingNow() {
547 assert(fImporting == false);
548 fImporting = true;
551 ~CImportingNow() {
552 assert(fImporting == true);
553 fImporting = false;
558 // If we're using -prune with -reindex, then delete block files that will be ignored by the
559 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
560 // is missing, do the same here to delete any later block files after a gap. Also delete all
561 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
562 // is in sync with what's actually on disk by the time we start downloading, so that pruning
563 // works correctly.
564 void CleanupBlockRevFiles()
566 using namespace boost::filesystem;
567 map<string, path> mapBlockFiles;
569 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
570 // Remove the rev files immediately and insert the blk file paths into an
571 // ordered map keyed by block file index.
572 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
573 path blocksdir = GetDataDir() / "blocks";
574 for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
575 if (is_regular_file(*it) &&
576 it->path().filename().string().length() == 12 &&
577 it->path().filename().string().substr(8,4) == ".dat")
579 if (it->path().filename().string().substr(0,3) == "blk")
580 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
581 else if (it->path().filename().string().substr(0,3) == "rev")
582 remove(it->path());
586 // Remove all block files that aren't part of a contiguous set starting at
587 // zero by walking the ordered map (keys are block file indices) by
588 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
589 // start removing block files.
590 int nContigCounter = 0;
591 BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) {
592 if (atoi(item.first) == nContigCounter) {
593 nContigCounter++;
594 continue;
596 remove(item.second);
600 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
602 const CChainParams& chainparams = Params();
603 RenameThread("bitcoin-loadblk");
604 CImportingNow imp;
606 // -reindex
607 if (fReindex) {
608 int nFile = 0;
609 while (true) {
610 CDiskBlockPos pos(nFile, 0);
611 if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
612 break; // No block files left to reindex
613 FILE *file = OpenBlockFile(pos, true);
614 if (!file)
615 break; // This error is logged in OpenBlockFile
616 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
617 LoadExternalBlockFile(chainparams, file, &pos);
618 nFile++;
620 pblocktree->WriteReindexing(false);
621 fReindex = false;
622 LogPrintf("Reindexing finished\n");
623 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
624 InitBlockIndex(chainparams);
627 // hardcoded $DATADIR/bootstrap.dat
628 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
629 if (boost::filesystem::exists(pathBootstrap)) {
630 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
631 if (file) {
632 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
633 LogPrintf("Importing bootstrap.dat...\n");
634 LoadExternalBlockFile(chainparams, file);
635 RenameOver(pathBootstrap, pathBootstrapOld);
636 } else {
637 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
641 // -loadblock=
642 BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
643 FILE *file = fopen(path.string().c_str(), "rb");
644 if (file) {
645 LogPrintf("Importing blocks file %s...\n", path.string());
646 LoadExternalBlockFile(chainparams, file);
647 } else {
648 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
652 // scan for better chains in the block chain database, that are not yet connected in the active best chain
653 CValidationState state;
654 if (!ActivateBestChain(state, chainparams)) {
655 LogPrintf("Failed to connect best block");
656 StartShutdown();
659 if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
660 LogPrintf("Stopping after block import\n");
661 StartShutdown();
664 LoadMempool();
667 /** Sanity checks
668 * Ensure that Bitcoin is running in a usable environment with all
669 * necessary library support.
671 bool InitSanityCheck(void)
673 if(!ECC_InitSanityCheck()) {
674 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
675 return false;
677 if (!glibc_sanity_test() || !glibcxx_sanity_test())
678 return false;
680 return true;
683 bool AppInitServers(boost::thread_group& threadGroup)
685 RPCServer::OnStarted(&OnRPCStarted);
686 RPCServer::OnStopped(&OnRPCStopped);
687 RPCServer::OnPreCommand(&OnRPCPreCommand);
688 if (!InitHTTPServer())
689 return false;
690 if (!StartRPC())
691 return false;
692 if (!StartHTTPRPC())
693 return false;
694 if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
695 return false;
696 if (!StartHTTPServer())
697 return false;
698 return true;
701 // Parameter interaction based on rules
702 void InitParameterInteraction()
704 // when specifying an explicit binding address, you want to listen on it
705 // even when -connect or -proxy is specified
706 if (mapArgs.count("-bind")) {
707 if (SoftSetBoolArg("-listen", true))
708 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
710 if (mapArgs.count("-whitebind")) {
711 if (SoftSetBoolArg("-listen", true))
712 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
715 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
716 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
717 if (SoftSetBoolArg("-dnsseed", false))
718 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
719 if (SoftSetBoolArg("-listen", false))
720 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
723 if (mapArgs.count("-proxy")) {
724 // to protect privacy, do not listen by default if a default proxy server is specified
725 if (SoftSetBoolArg("-listen", false))
726 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
727 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
728 // to listen locally, so don't rely on this happening through -listen below.
729 if (SoftSetBoolArg("-upnp", false))
730 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
731 // to protect privacy, do not discover addresses by default
732 if (SoftSetBoolArg("-discover", false))
733 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
736 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
737 // do not map ports or try to retrieve public IP when not listening (pointless)
738 if (SoftSetBoolArg("-upnp", false))
739 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
740 if (SoftSetBoolArg("-discover", false))
741 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
742 if (SoftSetBoolArg("-listenonion", false))
743 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
746 if (mapArgs.count("-externalip")) {
747 // if an explicit public IP is specified, do not try to find others
748 if (SoftSetBoolArg("-discover", false))
749 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
752 if (GetBoolArg("-salvagewallet", false)) {
753 // Rewrite just private keys: rescan to find transactions
754 if (SoftSetBoolArg("-rescan", true))
755 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
758 // -zapwallettx implies a rescan
759 if (GetBoolArg("-zapwallettxes", false)) {
760 if (SoftSetBoolArg("-rescan", true))
761 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
764 // disable walletbroadcast and whitelistrelay in blocksonly mode
765 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
766 if (SoftSetBoolArg("-whitelistrelay", false))
767 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
768 // walletbroadcast is disabled in CWallet::ParameterInteraction()
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 /** Initialize bitcoin.
795 * @pre Parameters should be parsed and config file should be read.
797 bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
799 // ********************************************************* Step 1: setup
800 #ifdef _MSC_VER
801 // Turn off Microsoft heap dump noise
802 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
803 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
804 #endif
805 #if _MSC_VER >= 1400
806 // Disable confusing "helpful" text message on abort, Ctrl-C
807 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
808 #endif
809 #ifdef WIN32
810 // Enable Data Execution Prevention (DEP)
811 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
812 // A failure is non-critical and needs no further attention!
813 #ifndef PROCESS_DEP_ENABLE
814 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
815 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
816 #define PROCESS_DEP_ENABLE 0x00000001
817 #endif
818 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
819 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
820 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
821 #endif
823 if (!SetupNetworking())
824 return InitError("Initializing networking failed");
826 #ifndef WIN32
827 if (!GetBoolArg("-sysperms", false)) {
828 umask(077);
831 // Clean shutdown on SIGTERM
832 struct sigaction sa;
833 sa.sa_handler = HandleSIGTERM;
834 sigemptyset(&sa.sa_mask);
835 sa.sa_flags = 0;
836 sigaction(SIGTERM, &sa, NULL);
837 sigaction(SIGINT, &sa, NULL);
839 // Reopen debug.log on SIGHUP
840 struct sigaction sa_hup;
841 sa_hup.sa_handler = HandleSIGHUP;
842 sigemptyset(&sa_hup.sa_mask);
843 sa_hup.sa_flags = 0;
844 sigaction(SIGHUP, &sa_hup, NULL);
846 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
847 signal(SIGPIPE, SIG_IGN);
848 #endif
850 // ********************************************************* Step 2: parameter interactions
851 const CChainParams& chainparams = Params();
853 // also see: InitParameterInteraction()
855 // if using block pruning, then disallow txindex
856 if (GetArg("-prune", 0)) {
857 if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
858 return InitError(_("Prune mode is incompatible with -txindex."));
861 // Make sure enough file descriptors are available
862 int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
863 int nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
864 int nMaxConnections = std::max(nUserMaxConnections, 0);
866 // Trim requested connection counts, to fit into system limitations
867 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
868 int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
869 if (nFD < MIN_CORE_FILEDESCRIPTORS)
870 return InitError(_("Not enough file descriptors available."));
871 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS, nMaxConnections);
873 if (nMaxConnections < nUserMaxConnections)
874 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
876 // ********************************************************* Step 3: parameter-to-internal-flags
878 fDebug = !mapMultiArgs["-debug"].empty();
879 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
880 const vector<string>& categories = mapMultiArgs["-debug"];
881 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
882 fDebug = false;
884 // Check for -debugnet
885 if (GetBoolArg("-debugnet", false))
886 InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
887 // Check for -socks - as this is a privacy risk to continue, exit here
888 if (mapArgs.count("-socks"))
889 return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
890 // Check for -tor - as this is a privacy risk to continue, exit here
891 if (GetBoolArg("-tor", false))
892 return InitError(_("Unsupported argument -tor found, use -onion."));
894 if (GetBoolArg("-benchmark", false))
895 InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
897 if (GetBoolArg("-whitelistalwaysrelay", false))
898 InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
900 if (mapArgs.count("-blockminsize"))
901 InitWarning("Unsupported argument -blockminsize ignored.");
903 // Checkmempool and checkblockindex default to true in regtest mode
904 int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
905 if (ratio != 0) {
906 mempool.setSanityCheck(1.0 / ratio);
908 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
909 fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
911 // mempool limits
912 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
913 int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
914 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
915 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
917 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
918 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
919 if (nScriptCheckThreads <= 0)
920 nScriptCheckThreads += GetNumCores();
921 if (nScriptCheckThreads <= 1)
922 nScriptCheckThreads = 0;
923 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
924 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
926 fServer = GetBoolArg("-server", false);
928 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
929 int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
930 if (nSignedPruneTarget < 0) {
931 return InitError(_("Prune cannot be configured with a negative value."));
933 nPruneTarget = (uint64_t) nSignedPruneTarget;
934 if (nPruneTarget) {
935 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
936 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
938 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
939 fPruneMode = true;
942 RegisterAllCoreRPCCommands(tableRPC);
943 #ifdef ENABLE_WALLET
944 RegisterWalletRPCCommands(tableRPC);
945 #endif
947 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
948 if (nConnectTimeout <= 0)
949 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
951 // Fee-per-kilobyte amount considered the same as "free"
952 // If you are mining, be careful setting this:
953 // if you set it to zero then
954 // a transaction spammer can cheaply fill blocks using
955 // 1-satoshi-fee transactions. It should be set above the real
956 // cost to you of processing a transaction.
957 if (mapArgs.count("-minrelaytxfee"))
959 CAmount n = 0;
960 if (!ParseMoney(mapArgs["-minrelaytxfee"], n) || 0 == n)
961 return InitError(AmountErrMsg("minrelaytxfee", mapArgs["-minrelaytxfee"]));
962 // High fee check is done afterward in CWallet::ParameterInteraction()
963 ::minRelayTxFee = CFeeRate(n);
966 fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
967 if (chainparams.RequireStandard() && !fRequireStandard)
968 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
969 nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
971 #ifdef ENABLE_WALLET
972 if (!CWallet::ParameterInteraction())
973 return false;
974 #endif
976 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
977 fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
978 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
980 // Option to startup with mocktime set (used for regression testing):
981 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
983 ServiceFlags nLocalServices = NODE_NETWORK;
984 ServiceFlags nRelevantServices = NODE_NETWORK;
986 if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
987 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
989 nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
991 fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
992 if ((!fEnableReplacement) && mapArgs.count("-mempoolreplacement")) {
993 // Minimal effort at forwards compatibility
994 std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
995 std::vector<std::string> vstrReplacementModes;
996 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
997 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1000 if (!mapMultiArgs["-bip9params"].empty()) {
1001 // Allow overriding BIP9 parameters for testing
1002 if (!chainparams.MineBlocksOnDemand()) {
1003 return InitError("BIP9 parameters may only be overridden on regtest.");
1005 const vector<string>& deployments = mapMultiArgs["-bip9params"];
1006 for (auto i : deployments) {
1007 std::vector<std::string> vDeploymentParams;
1008 boost::split(vDeploymentParams, i, boost::is_any_of(":"));
1009 if (vDeploymentParams.size() != 3) {
1010 return InitError("BIP9 parameters malformed, expecting deployment:start:end");
1012 int64_t nStartTime, nTimeout;
1013 if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1014 return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1016 if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1017 return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1019 bool found = false;
1020 for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1022 if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1023 UpdateRegtestBIP9Parameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1024 found = true;
1025 LogPrintf("Setting BIP9 activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1026 break;
1029 if (!found) {
1030 return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1035 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
1037 // Initialize elliptic curve code
1038 ECC_Start();
1039 globalVerifyHandle.reset(new ECCVerifyHandle());
1041 // Sanity check
1042 if (!InitSanityCheck())
1043 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1045 std::string strDataDir = GetDataDir().string();
1047 // Make sure only a single Bitcoin process is using the data directory.
1048 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
1049 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
1050 if (file) fclose(file);
1052 try {
1053 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1054 if (!lock.try_lock())
1055 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1056 } catch(const boost::interprocess::interprocess_exception& e) {
1057 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1060 #ifndef WIN32
1061 CreatePidFile(GetPidFile(), getpid());
1062 #endif
1063 if (GetBoolArg("-shrinkdebugfile", !fDebug))
1064 ShrinkDebugFile();
1066 if (fPrintToDebugLog)
1067 OpenDebugLog();
1069 if (!fLogTimestamps)
1070 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1071 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1072 LogPrintf("Using data directory %s\n", strDataDir);
1073 LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1074 LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
1076 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1077 if (nScriptCheckThreads) {
1078 for (int i=0; i<nScriptCheckThreads-1; i++)
1079 threadGroup.create_thread(&ThreadScriptCheck);
1082 // Start the lightweight task scheduler thread
1083 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1084 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1086 /* Start the RPC server already. It will be started in "warmup" mode
1087 * and not really process calls already (but it will signify connections
1088 * that the server is there and will be ready later). Warmup mode will
1089 * be disabled when initialisation is finished.
1091 if (fServer)
1093 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1094 if (!AppInitServers(threadGroup))
1095 return InitError(_("Unable to start HTTP server. See debug log for details."));
1098 int64_t nStart;
1100 // ********************************************************* Step 5: verify wallet database integrity
1101 #ifdef ENABLE_WALLET
1102 if (!CWallet::Verify())
1103 return false;
1104 #endif
1105 // ********************************************************* Step 6: network initialization
1107 assert(!g_connman);
1108 g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1109 CConnman& connman = *g_connman;
1111 peerLogic.reset(new PeerLogicValidation(&connman));
1112 RegisterValidationInterface(peerLogic.get());
1113 RegisterNodeSignals(GetNodeSignals());
1115 // sanitize comments per BIP-0014, format user agent and check total size
1116 std::vector<string> uacomments;
1117 BOOST_FOREACH(string cmt, mapMultiArgs["-uacomment"])
1119 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1120 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1121 uacomments.push_back(SanitizeString(cmt, SAFE_CHARS_UA_COMMENT));
1123 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1124 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1125 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1126 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1129 if (mapArgs.count("-onlynet")) {
1130 std::set<enum Network> nets;
1131 BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) {
1132 enum Network net = ParseNetwork(snet);
1133 if (net == NET_UNROUTABLE)
1134 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1135 nets.insert(net);
1137 for (int n = 0; n < NET_MAX; n++) {
1138 enum Network net = (enum Network)n;
1139 if (!nets.count(net))
1140 SetLimited(net);
1144 if (mapArgs.count("-whitelist")) {
1145 BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
1146 CSubNet subnet;
1147 LookupSubNet(net.c_str(), subnet);
1148 if (!subnet.IsValid())
1149 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1150 connman.AddWhitelistedRange(subnet);
1154 bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1155 // -proxy sets a proxy for all outgoing network traffic
1156 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1157 std::string proxyArg = GetArg("-proxy", "");
1158 SetLimited(NET_TOR);
1159 if (proxyArg != "" && proxyArg != "0") {
1160 CService resolved(LookupNumeric(proxyArg.c_str(), 9050));
1161 proxyType addrProxy = proxyType(resolved, proxyRandomize);
1162 if (!addrProxy.IsValid())
1163 return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
1165 SetProxy(NET_IPV4, addrProxy);
1166 SetProxy(NET_IPV6, addrProxy);
1167 SetProxy(NET_TOR, addrProxy);
1168 SetNameProxy(addrProxy);
1169 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1172 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1173 // -noonion (or -onion=0) disables connecting to .onion entirely
1174 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1175 std::string onionArg = GetArg("-onion", "");
1176 if (onionArg != "") {
1177 if (onionArg == "0") { // Handle -noonion/-onion=0
1178 SetLimited(NET_TOR); // set onions as unreachable
1179 } else {
1180 CService resolved(LookupNumeric(onionArg.c_str(), 9050));
1181 proxyType addrOnion = proxyType(resolved, proxyRandomize);
1182 if (!addrOnion.IsValid())
1183 return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
1184 SetProxy(NET_TOR, addrOnion);
1185 SetLimited(NET_TOR, false);
1189 // see Step 2: parameter interactions for more information about these
1190 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1191 fDiscover = GetBoolArg("-discover", true);
1192 fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1193 fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1195 if (fListen) {
1196 bool fBound = false;
1197 if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
1198 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
1199 CService addrBind;
1200 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1201 return InitError(ResolveErrMsg("bind", strBind));
1202 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1204 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
1205 CService addrBind;
1206 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1207 return InitError(ResolveErrMsg("whitebind", strBind));
1208 if (addrBind.GetPort() == 0)
1209 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1210 fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1213 else {
1214 struct in_addr inaddr_any;
1215 inaddr_any.s_addr = INADDR_ANY;
1216 fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
1217 fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1219 if (!fBound)
1220 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1223 if (mapArgs.count("-externalip")) {
1224 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
1225 CService addrLocal;
1226 if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1227 AddLocal(addrLocal, LOCAL_MANUAL);
1228 else
1229 return InitError(ResolveErrMsg("externalip", strAddr));
1233 BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
1234 connman.AddOneShot(strDest);
1236 #if ENABLE_ZMQ
1237 pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
1239 if (pzmqNotificationInterface) {
1240 RegisterValidationInterface(pzmqNotificationInterface);
1242 #endif
1243 uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1244 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1246 if (mapArgs.count("-maxuploadtarget")) {
1247 nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1250 // ********************************************************* Step 7: load block chain
1252 fReindex = GetBoolArg("-reindex", false);
1253 bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
1255 // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
1256 boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1257 if (!boost::filesystem::exists(blocksDir))
1259 boost::filesystem::create_directories(blocksDir);
1260 bool linked = false;
1261 for (unsigned int i = 1; i < 10000; i++) {
1262 boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1263 if (!boost::filesystem::exists(source)) break;
1264 boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
1265 try {
1266 boost::filesystem::create_hard_link(source, dest);
1267 LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
1268 linked = true;
1269 } catch (const boost::filesystem::filesystem_error& e) {
1270 // Note: hardlink creation failing is not a disaster, it just means
1271 // blocks will get re-downloaded from peers.
1272 LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
1273 break;
1276 if (linked)
1278 fReindex = true;
1282 // cache size calculations
1283 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1284 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1285 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1286 int64_t nBlockTreeDBCache = nTotalCache / 8;
1287 nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1288 nTotalCache -= nBlockTreeDBCache;
1289 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1290 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1291 nTotalCache -= nCoinDBCache;
1292 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1293 LogPrintf("Cache configuration:\n");
1294 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1295 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1296 LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
1298 bool fLoaded = false;
1299 while (!fLoaded) {
1300 bool fReset = fReindex;
1301 std::string strLoadError;
1303 uiInterface.InitMessage(_("Loading block index..."));
1305 nStart = GetTimeMillis();
1306 do {
1307 try {
1308 UnloadBlockIndex();
1309 delete pcoinsTip;
1310 delete pcoinsdbview;
1311 delete pcoinscatcher;
1312 delete pblocktree;
1314 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1315 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState);
1316 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1317 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1319 if (fReindex) {
1320 pblocktree->WriteReindexing(true);
1321 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1322 if (fPruneMode)
1323 CleanupBlockRevFiles();
1326 if (!LoadBlockIndex()) {
1327 strLoadError = _("Error loading block database");
1328 break;
1331 // If the loaded chain has a wrong genesis, bail out immediately
1332 // (we're likely using a testnet datadir, or the other way around).
1333 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1334 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1336 // Initialize the block index (no-op if non-empty database was already loaded)
1337 if (!InitBlockIndex(chainparams)) {
1338 strLoadError = _("Error initializing block database");
1339 break;
1342 // Check for changed -txindex state
1343 if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1344 strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
1345 break;
1348 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1349 // in the past, but is now trying to run unpruned.
1350 if (fHavePruned && !fPruneMode) {
1351 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1352 break;
1355 if (!fReindex && chainActive.Tip() != NULL) {
1356 uiInterface.InitMessage(_("Rewinding blocks..."));
1357 if (!RewindBlockIndex(chainparams)) {
1358 strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1359 break;
1363 uiInterface.InitMessage(_("Verifying blocks..."));
1364 if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1365 LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
1366 MIN_BLOCKS_TO_KEEP);
1370 LOCK(cs_main);
1371 CBlockIndex* tip = chainActive.Tip();
1372 RPCNotifyBlockChange(true, tip);
1373 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1374 strLoadError = _("The block database contains a block which appears to be from the future. "
1375 "This may be due to your computer's date and time being set incorrectly. "
1376 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1377 break;
1381 if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1382 GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1383 strLoadError = _("Corrupted block database detected");
1384 break;
1386 } catch (const std::exception& e) {
1387 if (fDebug) LogPrintf("%s\n", e.what());
1388 strLoadError = _("Error opening block database");
1389 break;
1392 fLoaded = true;
1393 } while(false);
1395 if (!fLoaded) {
1396 // first suggest a reindex
1397 if (!fReset) {
1398 bool fRet = uiInterface.ThreadSafeQuestion(
1399 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1400 strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1401 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1402 if (fRet) {
1403 fReindex = true;
1404 fRequestShutdown = false;
1405 } else {
1406 LogPrintf("Aborted block database rebuild. Exiting.\n");
1407 return false;
1409 } else {
1410 return InitError(strLoadError);
1415 // As LoadBlockIndex can take several minutes, it's possible the user
1416 // requested to kill the GUI during the last operation. If so, exit.
1417 // As the program has not fully started yet, Shutdown() is possibly overkill.
1418 if (fRequestShutdown)
1420 LogPrintf("Shutdown requested. Exiting.\n");
1421 return false;
1423 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1425 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1426 CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
1427 // Allowed to fail as this file IS missing on first startup.
1428 if (!est_filein.IsNull())
1429 mempool.ReadFeeEstimates(est_filein);
1430 fFeeEstimatesInitialized = true;
1432 // ********************************************************* Step 8: load wallet
1433 #ifdef ENABLE_WALLET
1434 if (!CWallet::InitLoadWallet())
1435 return false;
1436 #else
1437 LogPrintf("No wallet support compiled in!\n");
1438 #endif
1440 // ********************************************************* Step 9: data directory maintenance
1442 // if pruning, unset the service bit and perform the initial blockstore prune
1443 // after any wallet rescanning has taken place.
1444 if (fPruneMode) {
1445 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1446 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1447 if (!fReindex) {
1448 uiInterface.InitMessage(_("Pruning blockstore..."));
1449 PruneAndFlush();
1453 if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
1454 // Only advertize witness capabilities if they have a reasonable start time.
1455 // This allows us to have the code merged without a defined softfork, by setting its
1456 // end time to 0.
1457 // Note that setting NODE_WITNESS is never required: the only downside from not
1458 // doing so is that after activation, no upgraded nodes will fetch from you.
1459 nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1460 // Only care about others providing witness capabilities if there is a softfork
1461 // defined.
1462 nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS);
1465 // ********************************************************* Step 10: import blocks
1467 if (!CheckDiskSpace())
1468 return false;
1470 // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1471 // No locking, as this happens before any background thread is started.
1472 if (chainActive.Tip() == NULL) {
1473 uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1474 } else {
1475 fHaveGenesis = true;
1478 if (mapArgs.count("-blocknotify"))
1479 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1481 std::vector<boost::filesystem::path> vImportFiles;
1482 if (mapArgs.count("-loadblock"))
1484 BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
1485 vImportFiles.push_back(strFile);
1488 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1490 // Wait for genesis block to be processed
1492 boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
1493 while (!fHaveGenesis) {
1494 condvar_GenesisWait.wait(lock);
1496 uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1499 #ifdef ENABLE_WALLET
1500 // Add wallet transactions that aren't already in a block to mempool
1501 // Do this here as mempool requires genesis block to be loaded
1502 if (pwalletMain)
1503 pwalletMain->ReacceptWalletTransactions();
1504 #endif
1506 // ********************************************************* Step 11: start node
1508 //// debug print
1509 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1510 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1511 if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1512 StartTorControl(threadGroup, scheduler);
1514 Discover(threadGroup);
1516 // Map ports with UPnP
1517 MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
1519 std::string strNodeError;
1520 CConnman::Options connOptions;
1521 connOptions.nLocalServices = nLocalServices;
1522 connOptions.nRelevantServices = nRelevantServices;
1523 connOptions.nMaxConnections = nMaxConnections;
1524 connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1525 connOptions.nMaxFeeler = 1;
1526 connOptions.nBestHeight = chainActive.Height();
1527 connOptions.uiInterface = &uiInterface;
1528 connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1529 connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1531 connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1532 connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1534 if(!connman.Start(threadGroup, scheduler, strNodeError, connOptions))
1535 return InitError(strNodeError);
1537 // ********************************************************* Step 12: finished
1539 SetRPCWarmupFinished();
1540 uiInterface.InitMessage(_("Done loading"));
1542 #ifdef ENABLE_WALLET
1543 if (pwalletMain) {
1544 // Run a thread to flush wallet periodically
1545 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1547 #endif
1549 return !fRequestShutdown;