Add UpdatedBlockTip signal to CMainSignals and CValidationInterface
[bitcoinplatinum.git] / src / init.cpp
bloba12e38ff5348bc70c1f972aa8e6900da03082543
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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 "net.h"
25 #include "policy/policy.h"
26 #include "rpcserver.h"
27 #include "script/standard.h"
28 #include "scheduler.h"
29 #include "txdb.h"
30 #include "txmempool.h"
31 #include "ui_interface.h"
32 #include "util.h"
33 #include "utilmoneystr.h"
34 #include "utilstrencodings.h"
35 #include "validationinterface.h"
36 #ifdef ENABLE_WALLET
37 #include "wallet/db.h"
38 #include "wallet/wallet.h"
39 #include "wallet/walletdb.h"
40 #endif
42 #include <stdint.h>
43 #include <stdio.h>
45 #ifndef WIN32
46 #include <signal.h>
47 #endif
49 #include <boost/algorithm/string/predicate.hpp>
50 #include <boost/algorithm/string/replace.hpp>
51 #include <boost/bind.hpp>
52 #include <boost/filesystem.hpp>
53 #include <boost/function.hpp>
54 #include <boost/interprocess/sync/file_lock.hpp>
55 #include <boost/thread.hpp>
56 #include <openssl/crypto.h>
58 using namespace std;
60 #ifdef ENABLE_WALLET
61 CWallet* pwalletMain = NULL;
62 #endif
63 bool fFeeEstimatesInitialized = false;
65 #ifdef WIN32
66 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
67 // accessing block files don't count towards the fd_set size limit
68 // anyway.
69 #define MIN_CORE_FILEDESCRIPTORS 0
70 #else
71 #define MIN_CORE_FILEDESCRIPTORS 150
72 #endif
74 /** Used to pass flags to the Bind() function */
75 enum BindFlags {
76 BF_NONE = 0,
77 BF_EXPLICIT = (1U << 0),
78 BF_REPORT_ERROR = (1U << 1),
79 BF_WHITELIST = (1U << 2),
82 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
83 CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h
85 //////////////////////////////////////////////////////////////////////////////
87 // Shutdown
91 // Thread management and startup/shutdown:
93 // The network-processing threads are all part of a thread group
94 // created by AppInit() or the Qt main() function.
96 // A clean exit happens when StartShutdown() or the SIGTERM
97 // signal handler sets fRequestShutdown, which triggers
98 // the DetectShutdownThread(), which interrupts the main thread group.
99 // DetectShutdownThread() then exits, which causes AppInit() to
100 // continue (it .joins the shutdown thread).
101 // Shutdown() is then
102 // called to clean up database connections, and stop other
103 // threads that should only be stopped after the main network-processing
104 // threads have exited.
106 // Note that if running -daemon the parent process returns from AppInit2
107 // before adding any threads to the threadGroup, so .join_all() returns
108 // immediately and the parent exits from main().
110 // Shutdown for Qt is very similar, only it uses a QTimer to detect
111 // fRequestShutdown getting set, and then does the normal Qt
112 // shutdown thing.
115 volatile bool fRequestShutdown = false;
117 void StartShutdown()
119 fRequestShutdown = true;
121 bool ShutdownRequested()
123 return fRequestShutdown;
126 class CCoinsViewErrorCatcher : public CCoinsViewBacked
128 public:
129 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
130 bool GetCoins(const uint256 &txid, CCoins &coins) const {
131 try {
132 return CCoinsViewBacked::GetCoins(txid, coins);
133 } catch(const std::runtime_error& e) {
134 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
135 LogPrintf("Error reading from database: %s\n", e.what());
136 // Starting the shutdown sequence and returning false to the caller would be
137 // interpreted as 'entry not found' (as opposed to unable to read data), and
138 // could lead to invalid interpretation. Just exit immediately, as we can't
139 // continue anyway, and all writes should be atomic.
140 abort();
143 // Writes do not need similar protection, as failure to write is handled by the caller.
146 static CCoinsViewDB *pcoinsdbview = NULL;
147 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
149 void Interrupt(boost::thread_group& threadGroup)
151 InterruptHTTPServer();
152 InterruptHTTPRPC();
153 InterruptRPC();
154 InterruptREST();
155 threadGroup.interrupt_all();
158 void Shutdown()
160 LogPrintf("%s: In progress...\n", __func__);
161 static CCriticalSection cs_Shutdown;
162 TRY_LOCK(cs_Shutdown, lockShutdown);
163 if (!lockShutdown)
164 return;
166 /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
167 /// for example if the data directory was found to be locked.
168 /// Be sure that anything that writes files or flushes caches only does this if the respective
169 /// module was initialized.
170 RenameThread("bitcoin-shutoff");
171 mempool.AddTransactionsUpdated(1);
173 StopHTTPRPC();
174 StopREST();
175 StopRPC();
176 StopHTTPServer();
177 #ifdef ENABLE_WALLET
178 if (pwalletMain)
179 pwalletMain->Flush(false);
180 #endif
181 GenerateBitcoins(false, 0, Params());
182 StopNode();
183 UnregisterNodeSignals(GetNodeSignals());
185 if (fFeeEstimatesInitialized)
187 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
188 CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
189 if (!est_fileout.IsNull())
190 mempool.WriteFeeEstimates(est_fileout);
191 else
192 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
193 fFeeEstimatesInitialized = false;
197 LOCK(cs_main);
198 if (pcoinsTip != NULL) {
199 FlushStateToDisk();
201 delete pcoinsTip;
202 pcoinsTip = NULL;
203 delete pcoinscatcher;
204 pcoinscatcher = NULL;
205 delete pcoinsdbview;
206 pcoinsdbview = NULL;
207 delete pblocktree;
208 pblocktree = NULL;
210 #ifdef ENABLE_WALLET
211 if (pwalletMain)
212 pwalletMain->Flush(true);
213 #endif
214 #ifndef WIN32
215 try {
216 boost::filesystem::remove(GetPidFile());
217 } catch (const boost::filesystem::filesystem_error& e) {
218 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
220 #endif
221 UnregisterAllValidationInterfaces();
222 #ifdef ENABLE_WALLET
223 delete pwalletMain;
224 pwalletMain = NULL;
225 #endif
226 ECC_Stop();
227 LogPrintf("%s: done\n", __func__);
231 * Signal handlers are very limited in what they are allowed to do, so:
233 void HandleSIGTERM(int)
235 fRequestShutdown = true;
238 void HandleSIGHUP(int)
240 fReopenDebugLog = true;
243 bool static InitError(const std::string &str)
245 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
246 return false;
249 bool static InitWarning(const std::string &str)
251 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
252 return true;
255 bool static Bind(const CService &addr, unsigned int flags) {
256 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
257 return false;
258 std::string strError;
259 if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
260 if (flags & BF_REPORT_ERROR)
261 return InitError(strError);
262 return false;
264 return true;
267 void OnRPCStopped()
269 cvBlockChange.notify_all();
270 LogPrint("rpc", "RPC stopped.\n");
273 void OnRPCPreCommand(const CRPCCommand& cmd)
275 // Observe safe mode
276 string strWarning = GetWarnings("rpc");
277 if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
278 !cmd.okSafeMode)
279 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
282 std::string HelpMessage(HelpMessageMode mode)
284 const bool showDebug = GetBoolArg("-help-debug", false);
286 // When adding new options to the categories, please keep and ensure alphabetical ordering.
287 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
288 string strUsage = HelpMessageGroup(_("Options:"));
289 strUsage += HelpMessageOpt("-?", _("This help message"));
290 strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
291 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)"));
292 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
293 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 288));
294 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), 3));
295 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "bitcoin.conf"));
296 if (mode == HMM_BITCOIND)
298 #if !defined(WIN32)
299 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
300 #endif
302 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
303 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
304 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup"));
305 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
306 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)"),
307 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
308 #ifndef WIN32
309 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "bitcoind.pid"));
310 #endif
311 strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. "
312 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
313 "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
314 strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files on startup"));
315 #if !defined(WIN32)
316 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
317 #endif
318 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
320 strUsage += HelpMessageGroup(_("Connection options:"));
321 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
322 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100));
323 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400));
324 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
325 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)"));
326 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
327 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)"));
328 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)"));
329 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
330 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0));
331 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
332 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
333 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000));
334 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000));
335 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
336 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
337 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1));
338 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 8333, 18333));
339 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
340 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1));
341 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
342 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
343 #ifdef USE_UPNP
344 #if USE_UPNP
345 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
346 #else
347 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
348 #endif
349 #endif
350 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
351 strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
352 " " + _("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"));
354 #ifdef ENABLE_WALLET
355 strUsage += HelpMessageGroup(_("Wallet options:"));
356 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
357 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100));
358 if (showDebug)
359 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)",
360 CURRENCY_UNIT, FormatMoney(CWallet::minTxFee.GetFeePerK())));
361 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
362 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
363 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
364 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
365 strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
366 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1));
367 strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET));
368 strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees (in %s) to use in a single wallet transaction; setting this too low may abort large transactions (default: %s)"),
369 CURRENCY_UNIT, FormatMoney(maxTxFee)));
370 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup"));
371 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
372 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), true));
373 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
374 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
375 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
376 #endif
378 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
379 if (showDebug)
381 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", 1));
382 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)", 100));
383 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", 0));
384 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", 0));
385 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
386 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
387 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", 1));
388 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", 0));
390 string debugCategories = "addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, mempool, mempoolrej, net, proxy, prune, http"; // Don't translate these and qt below
391 if (mode == HMM_BITCOIN_QT)
392 debugCategories += ", qt";
393 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
394 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
395 strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0));
396 strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
397 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
398 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
399 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
400 if (showDebug)
402 strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
403 strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 1));
404 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> entries (default: %u)", 50000));
406 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying (default: %s)"),
407 CURRENCY_UNIT, FormatMoney(::minRelayTxFee.GetFeePerK())));
408 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
409 if (showDebug)
411 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", 0));
412 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", 1));
413 strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
414 "This is intended for regression testing tools and app development.");
416 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
417 strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
419 strUsage += HelpMessageGroup(_("Node relay options:"));
420 if (showDebug)
421 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
422 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1));
423 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
425 strUsage += HelpMessageGroup(_("Block creation options:"));
426 strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), 0));
427 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
428 strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
429 if (showDebug)
430 strUsage += HelpMessageOpt("-blockversion=<n>", strprintf("Override block version to test forking scenarios (default: %d)", (int)CBlock::CURRENT_VERSION));
432 strUsage += HelpMessageGroup(_("RPC server options:"));
433 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
434 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0));
435 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)"));
436 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
437 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
438 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 8332, 18332));
439 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"));
440 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
441 if (showDebug) {
442 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
443 strUsage += HelpMessageOpt("-rpctimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_TIMEOUT));
446 if (mode == HMM_BITCOIN_QT)
448 strUsage += HelpMessageGroup(_("UI Options:"));
449 if (showDebug) {
450 strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", "Allow self signed root certificates (default: 0)");
452 strUsage += HelpMessageOpt("-choosedatadir", _("Choose data directory on startup (default: 0)"));
453 strUsage += HelpMessageOpt("-lang=<lang>", _("Set language, for example \"de_DE\" (default: system locale)"));
454 strUsage += HelpMessageOpt("-min", _("Start minimized"));
455 strUsage += HelpMessageOpt("-rootcertificates=<file>", _("Set SSL root certificates for payment request (default: -system-)"));
456 strUsage += HelpMessageOpt("-splash", _("Show splash screen on startup (default: 1)"));
457 if (showDebug) {
458 strUsage += HelpMessageOpt("-uiplatform", "Select platform to customize UI for (one of windows, macosx, other; default: platform compiled on)");
462 return strUsage;
465 std::string LicenseInfo()
467 return FormatParagraph(strprintf(_("Copyright (C) 2009-%i The Bitcoin Core Developers"), COPYRIGHT_YEAR)) + "\n" +
468 "\n" +
469 FormatParagraph(_("This is experimental software.")) + "\n" +
470 "\n" +
471 FormatParagraph(_("Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.")) + "\n" +
472 "\n" +
473 FormatParagraph(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.")) +
474 "\n";
477 static void BlockNotifyCallback(const uint256& hashNewTip)
479 std::string strCmd = GetArg("-blocknotify", "");
481 boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
482 boost::thread t(runCommand, strCmd); // thread runs free
485 struct CImportingNow
487 CImportingNow() {
488 assert(fImporting == false);
489 fImporting = true;
492 ~CImportingNow() {
493 assert(fImporting == true);
494 fImporting = false;
499 // If we're using -prune with -reindex, then delete block files that will be ignored by the
500 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
501 // is missing, do the same here to delete any later block files after a gap. Also delete all
502 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
503 // is in sync with what's actually on disk by the time we start downloading, so that pruning
504 // works correctly.
505 void CleanupBlockRevFiles()
507 using namespace boost::filesystem;
508 map<string, path> mapBlockFiles;
510 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
511 // Remove the rev files immediately and insert the blk file paths into an
512 // ordered map keyed by block file index.
513 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
514 path blocksdir = GetDataDir() / "blocks";
515 for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
516 if (is_regular_file(*it) &&
517 it->path().filename().string().length() == 12 &&
518 it->path().filename().string().substr(8,4) == ".dat")
520 if (it->path().filename().string().substr(0,3) == "blk")
521 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
522 else if (it->path().filename().string().substr(0,3) == "rev")
523 remove(it->path());
527 // Remove all block files that aren't part of a contiguous set starting at
528 // zero by walking the ordered map (keys are block file indices) by
529 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
530 // start removing block files.
531 int nContigCounter = 0;
532 BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) {
533 if (atoi(item.first) == nContigCounter) {
534 nContigCounter++;
535 continue;
537 remove(item.second);
541 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
543 RenameThread("bitcoin-loadblk");
544 // -reindex
545 if (fReindex) {
546 CImportingNow imp;
547 int nFile = 0;
548 while (true) {
549 CDiskBlockPos pos(nFile, 0);
550 if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
551 break; // No block files left to reindex
552 FILE *file = OpenBlockFile(pos, true);
553 if (!file)
554 break; // This error is logged in OpenBlockFile
555 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
556 LoadExternalBlockFile(file, &pos);
557 nFile++;
559 pblocktree->WriteReindexing(false);
560 fReindex = false;
561 LogPrintf("Reindexing finished\n");
562 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
563 InitBlockIndex();
566 // hardcoded $DATADIR/bootstrap.dat
567 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
568 if (boost::filesystem::exists(pathBootstrap)) {
569 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
570 if (file) {
571 CImportingNow imp;
572 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
573 LogPrintf("Importing bootstrap.dat...\n");
574 LoadExternalBlockFile(file);
575 RenameOver(pathBootstrap, pathBootstrapOld);
576 } else {
577 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
581 // -loadblock=
582 BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
583 FILE *file = fopen(path.string().c_str(), "rb");
584 if (file) {
585 CImportingNow imp;
586 LogPrintf("Importing blocks file %s...\n", path.string());
587 LoadExternalBlockFile(file);
588 } else {
589 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
593 if (GetBoolArg("-stopafterblockimport", false)) {
594 LogPrintf("Stopping after block import\n");
595 StartShutdown();
599 /** Sanity checks
600 * Ensure that Bitcoin is running in a usable environment with all
601 * necessary library support.
603 bool InitSanityCheck(void)
605 if(!ECC_InitSanityCheck()) {
606 InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more "
607 "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries");
608 return false;
610 if (!glibc_sanity_test() || !glibcxx_sanity_test())
611 return false;
613 return true;
616 bool AppInitServers(boost::thread_group& threadGroup)
618 RPCServer::OnStopped(&OnRPCStopped);
619 RPCServer::OnPreCommand(&OnRPCPreCommand);
620 if (!InitHTTPServer())
621 return false;
622 if (!StartRPC())
623 return false;
624 if (!StartHTTPRPC())
625 return false;
626 if (GetBoolArg("-rest", false) && !StartREST())
627 return false;
628 if (!StartHTTPServer(threadGroup))
629 return false;
630 return true;
633 /** Initialize bitcoin.
634 * @pre Parameters should be parsed and config file should be read.
636 bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
638 // ********************************************************* Step 1: setup
639 #ifdef _MSC_VER
640 // Turn off Microsoft heap dump noise
641 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
642 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
643 #endif
644 #if _MSC_VER >= 1400
645 // Disable confusing "helpful" text message on abort, Ctrl-C
646 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
647 #endif
648 #ifdef WIN32
649 // Enable Data Execution Prevention (DEP)
650 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
651 // A failure is non-critical and needs no further attention!
652 #ifndef PROCESS_DEP_ENABLE
653 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
654 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
655 #define PROCESS_DEP_ENABLE 0x00000001
656 #endif
657 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
658 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
659 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
660 #endif
662 if (!SetupNetworking())
663 return InitError("Error: Initializing networking failed");
665 #ifndef WIN32
666 if (GetBoolArg("-sysperms", false)) {
667 #ifdef ENABLE_WALLET
668 if (!GetBoolArg("-disablewallet", false))
669 return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
670 #endif
671 } else {
672 umask(077);
675 // Clean shutdown on SIGTERM
676 struct sigaction sa;
677 sa.sa_handler = HandleSIGTERM;
678 sigemptyset(&sa.sa_mask);
679 sa.sa_flags = 0;
680 sigaction(SIGTERM, &sa, NULL);
681 sigaction(SIGINT, &sa, NULL);
683 // Reopen debug.log on SIGHUP
684 struct sigaction sa_hup;
685 sa_hup.sa_handler = HandleSIGHUP;
686 sigemptyset(&sa_hup.sa_mask);
687 sa_hup.sa_flags = 0;
688 sigaction(SIGHUP, &sa_hup, NULL);
690 #if defined (__SVR4) && defined (__sun)
691 // ignore SIGPIPE on Solaris
692 signal(SIGPIPE, SIG_IGN);
693 #endif
694 #endif
696 // ********************************************************* Step 2: parameter interactions
697 const CChainParams& chainparams = Params();
699 // Set this early so that parameter interactions go to console
700 fPrintToConsole = GetBoolArg("-printtoconsole", false);
701 fLogTimestamps = GetBoolArg("-logtimestamps", true);
702 fLogIPs = GetBoolArg("-logips", false);
704 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
705 LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
707 // when specifying an explicit binding address, you want to listen on it
708 // even when -connect or -proxy is specified
709 if (mapArgs.count("-bind")) {
710 if (SoftSetBoolArg("-listen", true))
711 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
713 if (mapArgs.count("-whitebind")) {
714 if (SoftSetBoolArg("-listen", true))
715 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
718 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
719 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
720 if (SoftSetBoolArg("-dnsseed", false))
721 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
722 if (SoftSetBoolArg("-listen", false))
723 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
726 if (mapArgs.count("-proxy")) {
727 // to protect privacy, do not listen by default if a default proxy server is specified
728 if (SoftSetBoolArg("-listen", false))
729 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
730 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
731 // to listen locally, so don't rely on this happening through -listen below.
732 if (SoftSetBoolArg("-upnp", false))
733 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
734 // to protect privacy, do not discover addresses by default
735 if (SoftSetBoolArg("-discover", false))
736 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
739 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
740 // do not map ports or try to retrieve public IP when not listening (pointless)
741 if (SoftSetBoolArg("-upnp", false))
742 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
743 if (SoftSetBoolArg("-discover", false))
744 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
747 if (mapArgs.count("-externalip")) {
748 // if an explicit public IP is specified, do not try to find others
749 if (SoftSetBoolArg("-discover", false))
750 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
753 if (GetBoolArg("-salvagewallet", false)) {
754 // Rewrite just private keys: rescan to find transactions
755 if (SoftSetBoolArg("-rescan", true))
756 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
759 // -zapwallettx implies a rescan
760 if (GetBoolArg("-zapwallettxes", false)) {
761 if (SoftSetBoolArg("-rescan", true))
762 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
765 // if using block pruning, then disable txindex
766 if (GetArg("-prune", 0)) {
767 if (GetBoolArg("-txindex", false))
768 return InitError(_("Prune mode is incompatible with -txindex."));
769 #ifdef ENABLE_WALLET
770 if (GetBoolArg("-rescan", false)) {
771 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
773 #endif
776 // Make sure enough file descriptors are available
777 int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
778 int nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
779 nMaxConnections = std::max(nUserMaxConnections, 0);
781 // Trim requested connection counts, to fit into system limitations
782 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
783 int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
784 if (nFD < MIN_CORE_FILEDESCRIPTORS)
785 return InitError(_("Not enough file descriptors available."));
786 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS, nMaxConnections);
788 if (nMaxConnections < nUserMaxConnections)
789 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
791 // ********************************************************* Step 3: parameter-to-internal-flags
793 fDebug = !mapMultiArgs["-debug"].empty();
794 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
795 const vector<string>& categories = mapMultiArgs["-debug"];
796 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
797 fDebug = false;
799 // Check for -debugnet
800 if (GetBoolArg("-debugnet", false))
801 InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
802 // Check for -socks - as this is a privacy risk to continue, exit here
803 if (mapArgs.count("-socks"))
804 return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
805 // Check for -tor - as this is a privacy risk to continue, exit here
806 if (GetBoolArg("-tor", false))
807 return InitError(_("Error: Unsupported argument -tor found, use -onion."));
809 if (GetBoolArg("-benchmark", false))
810 InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
812 // Checkmempool and checkblockindex default to true in regtest mode
813 mempool.setSanityCheck(GetBoolArg("-checkmempool", chainparams.DefaultConsistencyChecks()));
814 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
815 fCheckpointsEnabled = GetBoolArg("-checkpoints", true);
817 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
818 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
819 if (nScriptCheckThreads <= 0)
820 nScriptCheckThreads += GetNumCores();
821 if (nScriptCheckThreads <= 1)
822 nScriptCheckThreads = 0;
823 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
824 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
826 fServer = GetBoolArg("-server", false);
828 // block pruning; get the amount of disk space (in MB) to allot for block & undo files
829 int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
830 if (nSignedPruneTarget < 0) {
831 return InitError(_("Prune cannot be configured with a negative value."));
833 nPruneTarget = (uint64_t) nSignedPruneTarget;
834 if (nPruneTarget) {
835 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
836 return InitError(strprintf(_("Prune configured below the minimum of %d MB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
838 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
839 fPruneMode = true;
842 #ifdef ENABLE_WALLET
843 bool fDisableWallet = GetBoolArg("-disablewallet", false);
844 #endif
846 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
847 if (nConnectTimeout <= 0)
848 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
850 // Fee-per-kilobyte amount considered the same as "free"
851 // If you are mining, be careful setting this:
852 // if you set it to zero then
853 // a transaction spammer can cheaply fill blocks using
854 // 1-satoshi-fee transactions. It should be set above the real
855 // cost to you of processing a transaction.
856 if (mapArgs.count("-minrelaytxfee"))
858 CAmount n = 0;
859 if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
860 ::minRelayTxFee = CFeeRate(n);
861 else
862 return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
865 fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !Params().RequireStandard());
866 if (Params().RequireStandard() && !fRequireStandard)
867 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
869 #ifdef ENABLE_WALLET
870 if (mapArgs.count("-mintxfee"))
872 CAmount n = 0;
873 if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
874 CWallet::minTxFee = CFeeRate(n);
875 else
876 return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
878 if (mapArgs.count("-paytxfee"))
880 CAmount nFeePerK = 0;
881 if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
882 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
883 if (nFeePerK > nHighTransactionFeeWarning)
884 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
885 payTxFee = CFeeRate(nFeePerK, 1000);
886 if (payTxFee < ::minRelayTxFee)
888 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
889 mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
892 if (mapArgs.count("-maxtxfee"))
894 CAmount nMaxFee = 0;
895 if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
896 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maptxfee"]));
897 if (nMaxFee > nHighTransactionMaxFeeWarning)
898 InitWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction."));
899 maxTxFee = nMaxFee;
900 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
902 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
903 mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
906 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
907 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", true);
908 fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false);
910 std::string strWalletFile = GetArg("-wallet", "wallet.dat");
911 #endif // ENABLE_WALLET
913 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true);
914 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
916 fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
918 // Option to startup with mocktime set (used for regression testing):
919 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
921 if (GetBoolArg("-peerbloomfilters", true))
922 nLocalServices |= NODE_BLOOM;
924 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
926 // Initialize elliptic curve code
927 ECC_Start();
929 // Sanity check
930 if (!InitSanityCheck())
931 return InitError(_("Initialization sanity check failed. Bitcoin Core is shutting down."));
933 std::string strDataDir = GetDataDir().string();
934 #ifdef ENABLE_WALLET
935 // Wallet file must be a plain filename without a directory
936 if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
937 return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
938 #endif
939 // Make sure only a single Bitcoin process is using the data directory.
940 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
941 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
942 if (file) fclose(file);
944 try {
945 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
946 if (!lock.try_lock())
947 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running."), strDataDir));
948 } catch(const boost::interprocess::interprocess_exception& e) {
949 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running.") + " %s.", strDataDir, e.what()));
952 #ifndef WIN32
953 CreatePidFile(GetPidFile(), getpid());
954 #endif
955 if (GetBoolArg("-shrinkdebugfile", !fDebug))
956 ShrinkDebugFile();
958 if (fPrintToDebugLog)
959 OpenDebugLog();
961 LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
962 #ifdef ENABLE_WALLET
963 LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
964 #endif
965 if (!fLogTimestamps)
966 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
967 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
968 LogPrintf("Using data directory %s\n", strDataDir);
969 LogPrintf("Using config file %s\n", GetConfigFile().string());
970 LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
971 std::ostringstream strErrors;
973 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
974 if (nScriptCheckThreads) {
975 for (int i=0; i<nScriptCheckThreads-1; i++)
976 threadGroup.create_thread(&ThreadScriptCheck);
979 // Start the lightweight task scheduler thread
980 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
981 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
983 /* Start the RPC server already. It will be started in "warmup" mode
984 * and not really process calls already (but it will signify connections
985 * that the server is there and will be ready later). Warmup mode will
986 * be disabled when initialisation is finished.
988 if (fServer)
990 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
991 if (!AppInitServers(threadGroup))
992 return InitError(_("Unable to start HTTP server. See debug log for details."));
995 int64_t nStart;
997 // ********************************************************* Step 5: verify wallet database integrity
998 #ifdef ENABLE_WALLET
999 if (!fDisableWallet) {
1000 LogPrintf("Using wallet %s\n", strWalletFile);
1001 uiInterface.InitMessage(_("Verifying wallet..."));
1003 std::string warningString;
1004 std::string errorString;
1006 if (!CWallet::Verify(strWalletFile, warningString, errorString))
1007 return false;
1009 if (!warningString.empty())
1010 InitWarning(warningString);
1011 if (!errorString.empty())
1012 return InitError(warningString);
1014 } // (!fDisableWallet)
1015 #endif // ENABLE_WALLET
1016 // ********************************************************* Step 6: network initialization
1018 RegisterNodeSignals(GetNodeSignals());
1020 // format user agent, check total size
1021 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, mapMultiArgs.count("-uacomment") ? mapMultiArgs["-uacomment"] : std::vector<string>());
1022 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1023 return InitError(strprintf("Total length of network version string %i exceeds maximum of %i characters. Reduce the number and/or size of uacomments.",
1024 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1027 if (mapArgs.count("-onlynet")) {
1028 std::set<enum Network> nets;
1029 BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) {
1030 enum Network net = ParseNetwork(snet);
1031 if (net == NET_UNROUTABLE)
1032 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1033 nets.insert(net);
1035 for (int n = 0; n < NET_MAX; n++) {
1036 enum Network net = (enum Network)n;
1037 if (!nets.count(net))
1038 SetLimited(net);
1042 if (mapArgs.count("-whitelist")) {
1043 BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
1044 CSubNet subnet(net);
1045 if (!subnet.IsValid())
1046 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1047 CNode::AddWhitelistedRange(subnet);
1051 bool proxyRandomize = GetBoolArg("-proxyrandomize", true);
1052 // -proxy sets a proxy for all outgoing network traffic
1053 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1054 std::string proxyArg = GetArg("-proxy", "");
1055 if (proxyArg != "" && proxyArg != "0") {
1056 proxyType addrProxy = proxyType(CService(proxyArg, 9050), proxyRandomize);
1057 if (!addrProxy.IsValid())
1058 return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
1060 SetProxy(NET_IPV4, addrProxy);
1061 SetProxy(NET_IPV6, addrProxy);
1062 SetProxy(NET_TOR, addrProxy);
1063 SetNameProxy(addrProxy);
1064 SetReachable(NET_TOR); // by default, -proxy sets onion as reachable, unless -noonion later
1067 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1068 // -noonion (or -onion=0) disables connecting to .onion entirely
1069 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1070 std::string onionArg = GetArg("-onion", "");
1071 if (onionArg != "") {
1072 if (onionArg == "0") { // Handle -noonion/-onion=0
1073 SetReachable(NET_TOR, false); // set onions as unreachable
1074 } else {
1075 proxyType addrOnion = proxyType(CService(onionArg, 9050), proxyRandomize);
1076 if (!addrOnion.IsValid())
1077 return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
1078 SetProxy(NET_TOR, addrOnion);
1079 SetReachable(NET_TOR);
1083 // see Step 2: parameter interactions for more information about these
1084 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1085 fDiscover = GetBoolArg("-discover", true);
1086 fNameLookup = GetBoolArg("-dns", true);
1088 bool fBound = false;
1089 if (fListen) {
1090 if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
1091 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
1092 CService addrBind;
1093 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1094 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
1095 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1097 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
1098 CService addrBind;
1099 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1100 return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
1101 if (addrBind.GetPort() == 0)
1102 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1103 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1106 else {
1107 struct in_addr inaddr_any;
1108 inaddr_any.s_addr = INADDR_ANY;
1109 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
1110 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1112 if (!fBound)
1113 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1116 if (mapArgs.count("-externalip")) {
1117 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
1118 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
1119 if (!addrLocal.IsValid())
1120 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
1121 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
1125 BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
1126 AddOneShot(strDest);
1128 // ********************************************************* Step 7: load block chain
1130 fReindex = GetBoolArg("-reindex", false);
1132 // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
1133 boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1134 if (!boost::filesystem::exists(blocksDir))
1136 boost::filesystem::create_directories(blocksDir);
1137 bool linked = false;
1138 for (unsigned int i = 1; i < 10000; i++) {
1139 boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1140 if (!boost::filesystem::exists(source)) break;
1141 boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
1142 try {
1143 boost::filesystem::create_hard_link(source, dest);
1144 LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
1145 linked = true;
1146 } catch (const boost::filesystem::filesystem_error& e) {
1147 // Note: hardlink creation failing is not a disaster, it just means
1148 // blocks will get re-downloaded from peers.
1149 LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
1150 break;
1153 if (linked)
1155 fReindex = true;
1159 // cache size calculations
1160 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1161 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1162 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache
1163 int64_t nBlockTreeDBCache = nTotalCache / 8;
1164 if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
1165 nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
1166 nTotalCache -= nBlockTreeDBCache;
1167 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1168 nTotalCache -= nCoinDBCache;
1169 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1170 LogPrintf("Cache configuration:\n");
1171 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1172 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1173 LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
1175 bool fLoaded = false;
1176 while (!fLoaded) {
1177 bool fReset = fReindex;
1178 std::string strLoadError;
1180 uiInterface.InitMessage(_("Loading block index..."));
1182 nStart = GetTimeMillis();
1183 do {
1184 try {
1185 UnloadBlockIndex();
1186 delete pcoinsTip;
1187 delete pcoinsdbview;
1188 delete pcoinscatcher;
1189 delete pblocktree;
1191 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1192 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
1193 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1194 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1196 if (fReindex) {
1197 pblocktree->WriteReindexing(true);
1198 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1199 if (fPruneMode)
1200 CleanupBlockRevFiles();
1203 if (!LoadBlockIndex()) {
1204 strLoadError = _("Error loading block database");
1205 break;
1208 // If the loaded chain has a wrong genesis, bail out immediately
1209 // (we're likely using a testnet datadir, or the other way around).
1210 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1211 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1213 // Initialize the block index (no-op if non-empty database was already loaded)
1214 if (!InitBlockIndex()) {
1215 strLoadError = _("Error initializing block database");
1216 break;
1219 // Check for changed -txindex state
1220 if (fTxIndex != GetBoolArg("-txindex", false)) {
1221 strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1222 break;
1225 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1226 // in the past, but is now trying to run unpruned.
1227 if (fHavePruned && !fPruneMode) {
1228 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1229 break;
1232 uiInterface.InitMessage(_("Verifying blocks..."));
1233 if (fHavePruned && GetArg("-checkblocks", 288) > MIN_BLOCKS_TO_KEEP) {
1234 LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
1235 MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", 288));
1239 LOCK(cs_main);
1240 CBlockIndex* tip = chainActive.Tip();
1241 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1242 strLoadError = _("The block database contains a block which appears to be from the future. "
1243 "This may be due to your computer's date and time being set incorrectly. "
1244 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1245 break;
1249 if (!CVerifyDB().VerifyDB(pcoinsdbview, GetArg("-checklevel", 3),
1250 GetArg("-checkblocks", 288))) {
1251 strLoadError = _("Corrupted block database detected");
1252 break;
1254 } catch (const std::exception& e) {
1255 if (fDebug) LogPrintf("%s\n", e.what());
1256 strLoadError = _("Error opening block database");
1257 break;
1260 fLoaded = true;
1261 } while(false);
1263 if (!fLoaded) {
1264 // first suggest a reindex
1265 if (!fReset) {
1266 bool fRet = uiInterface.ThreadSafeMessageBox(
1267 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1268 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1269 if (fRet) {
1270 fReindex = true;
1271 fRequestShutdown = false;
1272 } else {
1273 LogPrintf("Aborted block database rebuild. Exiting.\n");
1274 return false;
1276 } else {
1277 return InitError(strLoadError);
1282 // As LoadBlockIndex can take several minutes, it's possible the user
1283 // requested to kill the GUI during the last operation. If so, exit.
1284 // As the program has not fully started yet, Shutdown() is possibly overkill.
1285 if (fRequestShutdown)
1287 LogPrintf("Shutdown requested. Exiting.\n");
1288 return false;
1290 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1292 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1293 CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
1294 // Allowed to fail as this file IS missing on first startup.
1295 if (!est_filein.IsNull())
1296 mempool.ReadFeeEstimates(est_filein);
1297 fFeeEstimatesInitialized = true;
1299 // ********************************************************* Step 8: load wallet
1300 #ifdef ENABLE_WALLET
1301 if (fDisableWallet) {
1302 pwalletMain = NULL;
1303 LogPrintf("Wallet disabled!\n");
1304 } else {
1306 // needed to restore wallet transaction meta data after -zapwallettxes
1307 std::vector<CWalletTx> vWtx;
1309 if (GetBoolArg("-zapwallettxes", false)) {
1310 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
1312 pwalletMain = new CWallet(strWalletFile);
1313 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
1314 if (nZapWalletRet != DB_LOAD_OK) {
1315 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
1316 return false;
1319 delete pwalletMain;
1320 pwalletMain = NULL;
1323 uiInterface.InitMessage(_("Loading wallet..."));
1325 nStart = GetTimeMillis();
1326 bool fFirstRun = true;
1327 pwalletMain = new CWallet(strWalletFile);
1328 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
1329 if (nLoadWalletRet != DB_LOAD_OK)
1331 if (nLoadWalletRet == DB_CORRUPT)
1332 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
1333 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
1335 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
1336 " or address book entries might be missing or incorrect."));
1337 InitWarning(msg);
1339 else if (nLoadWalletRet == DB_TOO_NEW)
1340 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin Core") << "\n";
1341 else if (nLoadWalletRet == DB_NEED_REWRITE)
1343 strErrors << _("Wallet needed to be rewritten: restart Bitcoin Core to complete") << "\n";
1344 LogPrintf("%s", strErrors.str());
1345 return InitError(strErrors.str());
1347 else
1348 strErrors << _("Error loading wallet.dat") << "\n";
1351 if (GetBoolArg("-upgradewallet", fFirstRun))
1353 int nMaxVersion = GetArg("-upgradewallet", 0);
1354 if (nMaxVersion == 0) // the -upgradewallet without argument case
1356 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
1357 nMaxVersion = CLIENT_VERSION;
1358 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
1360 else
1361 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
1362 if (nMaxVersion < pwalletMain->GetVersion())
1363 strErrors << _("Cannot downgrade wallet") << "\n";
1364 pwalletMain->SetMaxVersion(nMaxVersion);
1367 if (fFirstRun)
1369 // Create new keyUser and set as default key
1370 RandAddSeedPerfmon();
1372 CPubKey newDefaultKey;
1373 if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
1374 pwalletMain->SetDefaultKey(newDefaultKey);
1375 if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
1376 strErrors << _("Cannot write default address") << "\n";
1379 pwalletMain->SetBestChain(chainActive.GetLocator());
1382 LogPrintf("%s", strErrors.str());
1383 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
1385 RegisterValidationInterface(pwalletMain);
1387 CBlockIndex *pindexRescan = chainActive.Tip();
1388 if (GetBoolArg("-rescan", false))
1389 pindexRescan = chainActive.Genesis();
1390 else
1392 CWalletDB walletdb(strWalletFile);
1393 CBlockLocator locator;
1394 if (walletdb.ReadBestBlock(locator))
1395 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
1396 else
1397 pindexRescan = chainActive.Genesis();
1399 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
1401 //We can't rescan beyond non-pruned blocks, stop and throw an error
1402 //this might happen if a user uses a old wallet within a pruned node
1403 // or if he ran -disablewallet for a longer time, then decided to re-enable
1404 if (fPruneMode)
1406 CBlockIndex *block = chainActive.Tip();
1407 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
1408 block = block->pprev;
1410 if (pindexRescan != block)
1411 return InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
1414 uiInterface.InitMessage(_("Rescanning..."));
1415 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
1416 nStart = GetTimeMillis();
1417 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
1418 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
1419 pwalletMain->SetBestChain(chainActive.GetLocator());
1420 nWalletDBUpdated++;
1422 // Restore wallet transaction metadata after -zapwallettxes=1
1423 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
1425 CWalletDB walletdb(strWalletFile);
1427 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
1429 uint256 hash = wtxOld.GetHash();
1430 std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
1431 if (mi != pwalletMain->mapWallet.end())
1433 const CWalletTx* copyFrom = &wtxOld;
1434 CWalletTx* copyTo = &mi->second;
1435 copyTo->mapValue = copyFrom->mapValue;
1436 copyTo->vOrderForm = copyFrom->vOrderForm;
1437 copyTo->nTimeReceived = copyFrom->nTimeReceived;
1438 copyTo->nTimeSmart = copyFrom->nTimeSmart;
1439 copyTo->fFromMe = copyFrom->fFromMe;
1440 copyTo->strFromAccount = copyFrom->strFromAccount;
1441 copyTo->nOrderPos = copyFrom->nOrderPos;
1442 copyTo->WriteToDisk(&walletdb);
1447 pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true));
1448 } // (!fDisableWallet)
1449 #else // ENABLE_WALLET
1450 LogPrintf("No wallet support compiled in!\n");
1451 #endif // !ENABLE_WALLET
1453 // ********************************************************* Step 9: data directory maintenance
1455 // if pruning, unset the service bit and perform the initial blockstore prune
1456 // after any wallet rescanning has taken place.
1457 if (fPruneMode) {
1458 uiInterface.InitMessage(_("Pruning blockstore..."));
1459 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1460 nLocalServices &= ~NODE_NETWORK;
1461 if (!fReindex) {
1462 PruneAndFlush();
1466 // ********************************************************* Step 10: import blocks
1468 if (mapArgs.count("-blocknotify"))
1469 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1471 uiInterface.InitMessage(_("Activating best chain..."));
1472 // scan for better chains in the block chain database, that are not yet connected in the active best chain
1473 CValidationState state;
1474 if (!ActivateBestChain(state))
1475 strErrors << "Failed to connect best block";
1477 std::vector<boost::filesystem::path> vImportFiles;
1478 if (mapArgs.count("-loadblock"))
1480 BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
1481 vImportFiles.push_back(strFile);
1483 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1484 if (chainActive.Tip() == NULL) {
1485 LogPrintf("Waiting for genesis block to be imported...\n");
1486 while (!fRequestShutdown && chainActive.Tip() == NULL)
1487 MilliSleep(10);
1490 // ********************************************************* Step 11: start node
1492 if (!CheckDiskSpace())
1493 return false;
1495 if (!strErrors.str().empty())
1496 return InitError(strErrors.str());
1498 RandAddSeedPerfmon();
1500 //// debug print
1501 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1502 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1503 #ifdef ENABLE_WALLET
1504 LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
1505 LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
1506 LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
1507 #endif
1509 StartNode(threadGroup, scheduler);
1511 // Monitor the chain, and alert if we get blocks much quicker or slower than expected
1512 int64_t nPowTargetSpacing = Params().GetConsensus().nPowTargetSpacing;
1513 CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload,
1514 boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing);
1515 scheduler.scheduleEvery(f, nPowTargetSpacing);
1517 // Generate coins in the background
1518 GenerateBitcoins(GetBoolArg("-gen", false), GetArg("-genproclimit", 1), Params());
1520 // ********************************************************* Step 11: finished
1522 SetRPCWarmupFinished();
1523 uiInterface.InitMessage(_("Done loading"));
1525 #ifdef ENABLE_WALLET
1526 if (pwalletMain) {
1527 // Add wallet transactions that aren't already in a block to mapTransactions
1528 pwalletMain->ReacceptWalletTransactions();
1530 // Run a thread to flush wallet periodically
1531 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1533 #endif
1535 return !fRequestShutdown;