Add ZeroMQ support. Notify blocks and transactions via ZeroMQ
[bitcoinplatinum.git] / src / init.cpp
blobf03388120cdc6bc3f74bfdeb34e0f5d2c9f1082a
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
41 #include <stdint.h>
42 #include <stdio.h>
44 #ifndef WIN32
45 #include <signal.h>
46 #endif
48 #include <boost/algorithm/string/predicate.hpp>
49 #include <boost/algorithm/string/replace.hpp>
50 #include <boost/bind.hpp>
51 #include <boost/filesystem.hpp>
52 #include <boost/function.hpp>
53 #include <boost/interprocess/sync/file_lock.hpp>
54 #include <boost/thread.hpp>
55 #include <openssl/crypto.h>
57 #if ENABLE_ZMQ
58 #include "zmq/zmqnotificationinterface.h"
59 #endif
61 using namespace std;
63 #ifdef ENABLE_WALLET
64 CWallet* pwalletMain = NULL;
65 #endif
66 bool fFeeEstimatesInitialized = false;
68 #if ENABLE_ZMQ
69 static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
70 #endif
72 #ifdef WIN32
73 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
74 // accessing block files don't count towards the fd_set size limit
75 // anyway.
76 #define MIN_CORE_FILEDESCRIPTORS 0
77 #else
78 #define MIN_CORE_FILEDESCRIPTORS 150
79 #endif
81 /** Used to pass flags to the Bind() function */
82 enum BindFlags {
83 BF_NONE = 0,
84 BF_EXPLICIT = (1U << 0),
85 BF_REPORT_ERROR = (1U << 1),
86 BF_WHITELIST = (1U << 2),
89 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
90 CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h
92 //////////////////////////////////////////////////////////////////////////////
94 // Shutdown
98 // Thread management and startup/shutdown:
100 // The network-processing threads are all part of a thread group
101 // created by AppInit() or the Qt main() function.
103 // A clean exit happens when StartShutdown() or the SIGTERM
104 // signal handler sets fRequestShutdown, which triggers
105 // the DetectShutdownThread(), which interrupts the main thread group.
106 // DetectShutdownThread() then exits, which causes AppInit() to
107 // continue (it .joins the shutdown thread).
108 // Shutdown() is then
109 // called to clean up database connections, and stop other
110 // threads that should only be stopped after the main network-processing
111 // threads have exited.
113 // Note that if running -daemon the parent process returns from AppInit2
114 // before adding any threads to the threadGroup, so .join_all() returns
115 // immediately and the parent exits from main().
117 // Shutdown for Qt is very similar, only it uses a QTimer to detect
118 // fRequestShutdown getting set, and then does the normal Qt
119 // shutdown thing.
122 volatile bool fRequestShutdown = false;
124 void StartShutdown()
126 fRequestShutdown = true;
128 bool ShutdownRequested()
130 return fRequestShutdown;
133 class CCoinsViewErrorCatcher : public CCoinsViewBacked
135 public:
136 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
137 bool GetCoins(const uint256 &txid, CCoins &coins) const {
138 try {
139 return CCoinsViewBacked::GetCoins(txid, coins);
140 } catch(const std::runtime_error& e) {
141 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
142 LogPrintf("Error reading from database: %s\n", e.what());
143 // Starting the shutdown sequence and returning false to the caller would be
144 // interpreted as 'entry not found' (as opposed to unable to read data), and
145 // could lead to invalid interpretation. Just exit immediately, as we can't
146 // continue anyway, and all writes should be atomic.
147 abort();
150 // Writes do not need similar protection, as failure to write is handled by the caller.
153 static CCoinsViewDB *pcoinsdbview = NULL;
154 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
156 void Interrupt(boost::thread_group& threadGroup)
158 InterruptHTTPServer();
159 InterruptHTTPRPC();
160 InterruptRPC();
161 InterruptREST();
162 threadGroup.interrupt_all();
165 void Shutdown()
167 LogPrintf("%s: In progress...\n", __func__);
168 static CCriticalSection cs_Shutdown;
169 TRY_LOCK(cs_Shutdown, lockShutdown);
170 if (!lockShutdown)
171 return;
173 /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
174 /// for example if the data directory was found to be locked.
175 /// Be sure that anything that writes files or flushes caches only does this if the respective
176 /// module was initialized.
177 RenameThread("bitcoin-shutoff");
178 mempool.AddTransactionsUpdated(1);
180 StopHTTPRPC();
181 StopREST();
182 StopRPC();
183 StopHTTPServer();
184 #ifdef ENABLE_WALLET
185 if (pwalletMain)
186 pwalletMain->Flush(false);
187 #endif
188 GenerateBitcoins(false, 0, Params());
189 StopNode();
190 UnregisterNodeSignals(GetNodeSignals());
192 if (fFeeEstimatesInitialized)
194 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
195 CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
196 if (!est_fileout.IsNull())
197 mempool.WriteFeeEstimates(est_fileout);
198 else
199 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
200 fFeeEstimatesInitialized = false;
204 LOCK(cs_main);
205 if (pcoinsTip != NULL) {
206 FlushStateToDisk();
208 delete pcoinsTip;
209 pcoinsTip = NULL;
210 delete pcoinscatcher;
211 pcoinscatcher = NULL;
212 delete pcoinsdbview;
213 pcoinsdbview = NULL;
214 delete pblocktree;
215 pblocktree = NULL;
217 #ifdef ENABLE_WALLET
218 if (pwalletMain)
219 pwalletMain->Flush(true);
220 #endif
222 #if ENABLE_ZMQ
223 if (pzmqNotificationInterface) {
224 UnregisterValidationInterface(pzmqNotificationInterface);
225 pzmqNotificationInterface->Shutdown();
226 delete pzmqNotificationInterface;
227 pzmqNotificationInterface = NULL;
229 #endif
231 #ifndef WIN32
232 try {
233 boost::filesystem::remove(GetPidFile());
234 } catch (const boost::filesystem::filesystem_error& e) {
235 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
237 #endif
238 UnregisterAllValidationInterfaces();
239 #ifdef ENABLE_WALLET
240 delete pwalletMain;
241 pwalletMain = NULL;
242 #endif
243 ECC_Stop();
244 LogPrintf("%s: done\n", __func__);
248 * Signal handlers are very limited in what they are allowed to do, so:
250 void HandleSIGTERM(int)
252 fRequestShutdown = true;
255 void HandleSIGHUP(int)
257 fReopenDebugLog = true;
260 bool static InitError(const std::string &str)
262 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
263 return false;
266 bool static InitWarning(const std::string &str)
268 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
269 return true;
272 bool static Bind(const CService &addr, unsigned int flags) {
273 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
274 return false;
275 std::string strError;
276 if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
277 if (flags & BF_REPORT_ERROR)
278 return InitError(strError);
279 return false;
281 return true;
284 void OnRPCStopped()
286 cvBlockChange.notify_all();
287 LogPrint("rpc", "RPC stopped.\n");
290 void OnRPCPreCommand(const CRPCCommand& cmd)
292 // Observe safe mode
293 string strWarning = GetWarnings("rpc");
294 if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
295 !cmd.okSafeMode)
296 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
299 std::string HelpMessage(HelpMessageMode mode)
301 const bool showDebug = GetBoolArg("-help-debug", false);
303 // When adding new options to the categories, please keep and ensure alphabetical ordering.
304 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
305 string strUsage = HelpMessageGroup(_("Options:"));
306 strUsage += HelpMessageOpt("-?", _("This help message"));
307 strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
308 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)"));
309 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
310 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 288));
311 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), 3));
312 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "bitcoin.conf"));
313 if (mode == HMM_BITCOIND)
315 #if !defined(WIN32)
316 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
317 #endif
319 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
320 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
321 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup"));
322 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
323 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)"),
324 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
325 #ifndef WIN32
326 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "bitcoind.pid"));
327 #endif
328 strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. "
329 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
330 "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
331 strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files on startup"));
332 #if !defined(WIN32)
333 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
334 #endif
335 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
337 strUsage += HelpMessageGroup(_("Connection options:"));
338 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
339 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100));
340 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400));
341 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
342 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)"));
343 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
344 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)"));
345 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)"));
346 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
347 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0));
348 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
349 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
350 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000));
351 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000));
352 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
353 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
354 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1));
355 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 8333, 18333));
356 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
357 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1));
358 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
359 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
360 #ifdef USE_UPNP
361 #if USE_UPNP
362 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
363 #else
364 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
365 #endif
366 #endif
367 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
368 strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
369 " " + _("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"));
371 #ifdef ENABLE_WALLET
372 strUsage += HelpMessageGroup(_("Wallet options:"));
373 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
374 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100));
375 if (showDebug)
376 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)",
377 CURRENCY_UNIT, FormatMoney(CWallet::minTxFee.GetFeePerK())));
378 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
379 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
380 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
381 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
382 strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
383 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1));
384 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));
385 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)"),
386 CURRENCY_UNIT, FormatMoney(maxTxFee)));
387 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup"));
388 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
389 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), true));
390 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
391 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
392 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
393 #endif
395 #if ENABLE_ZMQ
396 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
397 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
398 strUsage += HelpMessageOpt("-zmqpubhashtransaction=<address>", _("Enable publish hash transaction in <address>"));
399 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
400 strUsage += HelpMessageOpt("-zmqpubrawtransaction=<address>", _("Enable publish raw transaction in <address>"));
401 #endif
403 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
404 if (showDebug)
406 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", 1));
407 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)", 100));
408 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", 0));
409 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", 0));
410 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
411 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
412 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", 1));
413 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", 0));
415 string debugCategories = "addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, mempool, mempoolrej, net, proxy, prune, http"; // Don't translate these and qt below
416 if (mode == HMM_BITCOIN_QT)
417 debugCategories += ", qt";
418 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
419 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
420 strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0));
421 strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
422 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
423 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
424 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
425 if (showDebug)
427 strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
428 strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 1));
429 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> entries (default: %u)", 50000));
431 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying (default: %s)"),
432 CURRENCY_UNIT, FormatMoney(::minRelayTxFee.GetFeePerK())));
433 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
434 if (showDebug)
436 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", 0));
437 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", 1));
438 strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
439 "This is intended for regression testing tools and app development.");
441 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
442 strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
444 strUsage += HelpMessageGroup(_("Node relay options:"));
445 if (showDebug)
446 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
447 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1));
448 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
450 strUsage += HelpMessageGroup(_("Block creation options:"));
451 strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), 0));
452 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
453 strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
454 if (showDebug)
455 strUsage += HelpMessageOpt("-blockversion=<n>", strprintf("Override block version to test forking scenarios (default: %d)", (int)CBlock::CURRENT_VERSION));
457 strUsage += HelpMessageGroup(_("RPC server options:"));
458 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
459 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0));
460 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)"));
461 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
462 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
463 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 8332, 18332));
464 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"));
465 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
466 if (showDebug) {
467 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
468 strUsage += HelpMessageOpt("-rpctimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_TIMEOUT));
471 if (mode == HMM_BITCOIN_QT)
473 strUsage += HelpMessageGroup(_("UI Options:"));
474 if (showDebug) {
475 strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", "Allow self signed root certificates (default: 0)");
477 strUsage += HelpMessageOpt("-choosedatadir", _("Choose data directory on startup (default: 0)"));
478 strUsage += HelpMessageOpt("-lang=<lang>", _("Set language, for example \"de_DE\" (default: system locale)"));
479 strUsage += HelpMessageOpt("-min", _("Start minimized"));
480 strUsage += HelpMessageOpt("-rootcertificates=<file>", _("Set SSL root certificates for payment request (default: -system-)"));
481 strUsage += HelpMessageOpt("-splash", _("Show splash screen on startup (default: 1)"));
482 if (showDebug) {
483 strUsage += HelpMessageOpt("-uiplatform", "Select platform to customize UI for (one of windows, macosx, other; default: platform compiled on)");
487 return strUsage;
490 std::string LicenseInfo()
492 return FormatParagraph(strprintf(_("Copyright (C) 2009-%i The Bitcoin Core Developers"), COPYRIGHT_YEAR)) + "\n" +
493 "\n" +
494 FormatParagraph(_("This is experimental software.")) + "\n" +
495 "\n" +
496 FormatParagraph(_("Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.")) + "\n" +
497 "\n" +
498 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.")) +
499 "\n";
502 static void BlockNotifyCallback(const uint256& hashNewTip)
504 std::string strCmd = GetArg("-blocknotify", "");
506 boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
507 boost::thread t(runCommand, strCmd); // thread runs free
510 struct CImportingNow
512 CImportingNow() {
513 assert(fImporting == false);
514 fImporting = true;
517 ~CImportingNow() {
518 assert(fImporting == true);
519 fImporting = false;
524 // If we're using -prune with -reindex, then delete block files that will be ignored by the
525 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
526 // is missing, do the same here to delete any later block files after a gap. Also delete all
527 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
528 // is in sync with what's actually on disk by the time we start downloading, so that pruning
529 // works correctly.
530 void CleanupBlockRevFiles()
532 using namespace boost::filesystem;
533 map<string, path> mapBlockFiles;
535 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
536 // Remove the rev files immediately and insert the blk file paths into an
537 // ordered map keyed by block file index.
538 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
539 path blocksdir = GetDataDir() / "blocks";
540 for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
541 if (is_regular_file(*it) &&
542 it->path().filename().string().length() == 12 &&
543 it->path().filename().string().substr(8,4) == ".dat")
545 if (it->path().filename().string().substr(0,3) == "blk")
546 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
547 else if (it->path().filename().string().substr(0,3) == "rev")
548 remove(it->path());
552 // Remove all block files that aren't part of a contiguous set starting at
553 // zero by walking the ordered map (keys are block file indices) by
554 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
555 // start removing block files.
556 int nContigCounter = 0;
557 BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) {
558 if (atoi(item.first) == nContigCounter) {
559 nContigCounter++;
560 continue;
562 remove(item.second);
566 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
568 RenameThread("bitcoin-loadblk");
569 // -reindex
570 if (fReindex) {
571 CImportingNow imp;
572 int nFile = 0;
573 while (true) {
574 CDiskBlockPos pos(nFile, 0);
575 if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
576 break; // No block files left to reindex
577 FILE *file = OpenBlockFile(pos, true);
578 if (!file)
579 break; // This error is logged in OpenBlockFile
580 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
581 LoadExternalBlockFile(file, &pos);
582 nFile++;
584 pblocktree->WriteReindexing(false);
585 fReindex = false;
586 LogPrintf("Reindexing finished\n");
587 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
588 InitBlockIndex();
591 // hardcoded $DATADIR/bootstrap.dat
592 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
593 if (boost::filesystem::exists(pathBootstrap)) {
594 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
595 if (file) {
596 CImportingNow imp;
597 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
598 LogPrintf("Importing bootstrap.dat...\n");
599 LoadExternalBlockFile(file);
600 RenameOver(pathBootstrap, pathBootstrapOld);
601 } else {
602 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
606 // -loadblock=
607 BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
608 FILE *file = fopen(path.string().c_str(), "rb");
609 if (file) {
610 CImportingNow imp;
611 LogPrintf("Importing blocks file %s...\n", path.string());
612 LoadExternalBlockFile(file);
613 } else {
614 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
618 if (GetBoolArg("-stopafterblockimport", false)) {
619 LogPrintf("Stopping after block import\n");
620 StartShutdown();
624 /** Sanity checks
625 * Ensure that Bitcoin is running in a usable environment with all
626 * necessary library support.
628 bool InitSanityCheck(void)
630 if(!ECC_InitSanityCheck()) {
631 InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more "
632 "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries");
633 return false;
635 if (!glibc_sanity_test() || !glibcxx_sanity_test())
636 return false;
638 return true;
641 bool AppInitServers(boost::thread_group& threadGroup)
643 RPCServer::OnStopped(&OnRPCStopped);
644 RPCServer::OnPreCommand(&OnRPCPreCommand);
645 if (!InitHTTPServer())
646 return false;
647 if (!StartRPC())
648 return false;
649 if (!StartHTTPRPC())
650 return false;
651 if (GetBoolArg("-rest", false) && !StartREST())
652 return false;
653 if (!StartHTTPServer(threadGroup))
654 return false;
655 return true;
658 /** Initialize bitcoin.
659 * @pre Parameters should be parsed and config file should be read.
661 bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
663 // ********************************************************* Step 1: setup
664 #ifdef _MSC_VER
665 // Turn off Microsoft heap dump noise
666 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
667 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
668 #endif
669 #if _MSC_VER >= 1400
670 // Disable confusing "helpful" text message on abort, Ctrl-C
671 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
672 #endif
673 #ifdef WIN32
674 // Enable Data Execution Prevention (DEP)
675 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
676 // A failure is non-critical and needs no further attention!
677 #ifndef PROCESS_DEP_ENABLE
678 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
679 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
680 #define PROCESS_DEP_ENABLE 0x00000001
681 #endif
682 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
683 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
684 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
685 #endif
687 if (!SetupNetworking())
688 return InitError("Error: Initializing networking failed");
690 #ifndef WIN32
691 if (GetBoolArg("-sysperms", false)) {
692 #ifdef ENABLE_WALLET
693 if (!GetBoolArg("-disablewallet", false))
694 return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
695 #endif
696 } else {
697 umask(077);
700 // Clean shutdown on SIGTERM
701 struct sigaction sa;
702 sa.sa_handler = HandleSIGTERM;
703 sigemptyset(&sa.sa_mask);
704 sa.sa_flags = 0;
705 sigaction(SIGTERM, &sa, NULL);
706 sigaction(SIGINT, &sa, NULL);
708 // Reopen debug.log on SIGHUP
709 struct sigaction sa_hup;
710 sa_hup.sa_handler = HandleSIGHUP;
711 sigemptyset(&sa_hup.sa_mask);
712 sa_hup.sa_flags = 0;
713 sigaction(SIGHUP, &sa_hup, NULL);
715 #if defined (__SVR4) && defined (__sun)
716 // ignore SIGPIPE on Solaris
717 signal(SIGPIPE, SIG_IGN);
718 #endif
719 #endif
721 // ********************************************************* Step 2: parameter interactions
722 const CChainParams& chainparams = Params();
724 // Set this early so that parameter interactions go to console
725 fPrintToConsole = GetBoolArg("-printtoconsole", false);
726 fLogTimestamps = GetBoolArg("-logtimestamps", true);
727 fLogIPs = GetBoolArg("-logips", false);
729 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
730 LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
732 // when specifying an explicit binding address, you want to listen on it
733 // even when -connect or -proxy is specified
734 if (mapArgs.count("-bind")) {
735 if (SoftSetBoolArg("-listen", true))
736 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
738 if (mapArgs.count("-whitebind")) {
739 if (SoftSetBoolArg("-listen", true))
740 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
743 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
744 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
745 if (SoftSetBoolArg("-dnsseed", false))
746 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
747 if (SoftSetBoolArg("-listen", false))
748 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
751 if (mapArgs.count("-proxy")) {
752 // to protect privacy, do not listen by default if a default proxy server is specified
753 if (SoftSetBoolArg("-listen", false))
754 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
755 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
756 // to listen locally, so don't rely on this happening through -listen below.
757 if (SoftSetBoolArg("-upnp", false))
758 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
759 // to protect privacy, do not discover addresses by default
760 if (SoftSetBoolArg("-discover", false))
761 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
764 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
765 // do not map ports or try to retrieve public IP when not listening (pointless)
766 if (SoftSetBoolArg("-upnp", false))
767 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
768 if (SoftSetBoolArg("-discover", false))
769 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
772 if (mapArgs.count("-externalip")) {
773 // if an explicit public IP is specified, do not try to find others
774 if (SoftSetBoolArg("-discover", false))
775 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
778 if (GetBoolArg("-salvagewallet", false)) {
779 // Rewrite just private keys: rescan to find transactions
780 if (SoftSetBoolArg("-rescan", true))
781 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
784 // -zapwallettx implies a rescan
785 if (GetBoolArg("-zapwallettxes", false)) {
786 if (SoftSetBoolArg("-rescan", true))
787 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
790 // if using block pruning, then disable txindex
791 if (GetArg("-prune", 0)) {
792 if (GetBoolArg("-txindex", false))
793 return InitError(_("Prune mode is incompatible with -txindex."));
794 #ifdef ENABLE_WALLET
795 if (GetBoolArg("-rescan", false)) {
796 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
798 #endif
801 // Make sure enough file descriptors are available
802 int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
803 int nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
804 nMaxConnections = std::max(nUserMaxConnections, 0);
806 // Trim requested connection counts, to fit into system limitations
807 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
808 int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
809 if (nFD < MIN_CORE_FILEDESCRIPTORS)
810 return InitError(_("Not enough file descriptors available."));
811 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS, nMaxConnections);
813 if (nMaxConnections < nUserMaxConnections)
814 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
816 // ********************************************************* Step 3: parameter-to-internal-flags
818 fDebug = !mapMultiArgs["-debug"].empty();
819 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
820 const vector<string>& categories = mapMultiArgs["-debug"];
821 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
822 fDebug = false;
824 // Check for -debugnet
825 if (GetBoolArg("-debugnet", false))
826 InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
827 // Check for -socks - as this is a privacy risk to continue, exit here
828 if (mapArgs.count("-socks"))
829 return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
830 // Check for -tor - as this is a privacy risk to continue, exit here
831 if (GetBoolArg("-tor", false))
832 return InitError(_("Error: Unsupported argument -tor found, use -onion."));
834 if (GetBoolArg("-benchmark", false))
835 InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
837 // Checkmempool and checkblockindex default to true in regtest mode
838 mempool.setSanityCheck(GetBoolArg("-checkmempool", chainparams.DefaultConsistencyChecks()));
839 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
840 fCheckpointsEnabled = GetBoolArg("-checkpoints", true);
842 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
843 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
844 if (nScriptCheckThreads <= 0)
845 nScriptCheckThreads += GetNumCores();
846 if (nScriptCheckThreads <= 1)
847 nScriptCheckThreads = 0;
848 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
849 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
851 fServer = GetBoolArg("-server", false);
853 // block pruning; get the amount of disk space (in MB) to allot for block & undo files
854 int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
855 if (nSignedPruneTarget < 0) {
856 return InitError(_("Prune cannot be configured with a negative value."));
858 nPruneTarget = (uint64_t) nSignedPruneTarget;
859 if (nPruneTarget) {
860 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
861 return InitError(strprintf(_("Prune configured below the minimum of %d MB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
863 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
864 fPruneMode = true;
867 #ifdef ENABLE_WALLET
868 bool fDisableWallet = GetBoolArg("-disablewallet", false);
869 #endif
871 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
872 if (nConnectTimeout <= 0)
873 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
875 // Fee-per-kilobyte amount considered the same as "free"
876 // If you are mining, be careful setting this:
877 // if you set it to zero then
878 // a transaction spammer can cheaply fill blocks using
879 // 1-satoshi-fee transactions. It should be set above the real
880 // cost to you of processing a transaction.
881 if (mapArgs.count("-minrelaytxfee"))
883 CAmount n = 0;
884 if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
885 ::minRelayTxFee = CFeeRate(n);
886 else
887 return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
890 fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !Params().RequireStandard());
891 if (Params().RequireStandard() && !fRequireStandard)
892 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
894 #ifdef ENABLE_WALLET
895 if (mapArgs.count("-mintxfee"))
897 CAmount n = 0;
898 if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
899 CWallet::minTxFee = CFeeRate(n);
900 else
901 return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
903 if (mapArgs.count("-paytxfee"))
905 CAmount nFeePerK = 0;
906 if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
907 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
908 if (nFeePerK > nHighTransactionFeeWarning)
909 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
910 payTxFee = CFeeRate(nFeePerK, 1000);
911 if (payTxFee < ::minRelayTxFee)
913 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
914 mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
917 if (mapArgs.count("-maxtxfee"))
919 CAmount nMaxFee = 0;
920 if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
921 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maptxfee"]));
922 if (nMaxFee > nHighTransactionMaxFeeWarning)
923 InitWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction."));
924 maxTxFee = nMaxFee;
925 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
927 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
928 mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
931 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
932 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", true);
933 fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false);
935 std::string strWalletFile = GetArg("-wallet", "wallet.dat");
936 #endif // ENABLE_WALLET
938 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true);
939 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
941 fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
943 // Option to startup with mocktime set (used for regression testing):
944 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
946 if (GetBoolArg("-peerbloomfilters", true))
947 nLocalServices |= NODE_BLOOM;
949 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
951 // Initialize elliptic curve code
952 ECC_Start();
954 // Sanity check
955 if (!InitSanityCheck())
956 return InitError(_("Initialization sanity check failed. Bitcoin Core is shutting down."));
958 std::string strDataDir = GetDataDir().string();
959 #ifdef ENABLE_WALLET
960 // Wallet file must be a plain filename without a directory
961 if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
962 return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
963 #endif
964 // Make sure only a single Bitcoin process is using the data directory.
965 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
966 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
967 if (file) fclose(file);
969 try {
970 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
971 if (!lock.try_lock())
972 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running."), strDataDir));
973 } catch(const boost::interprocess::interprocess_exception& e) {
974 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running.") + " %s.", strDataDir, e.what()));
977 #ifndef WIN32
978 CreatePidFile(GetPidFile(), getpid());
979 #endif
980 if (GetBoolArg("-shrinkdebugfile", !fDebug))
981 ShrinkDebugFile();
983 if (fPrintToDebugLog)
984 OpenDebugLog();
986 LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
987 #ifdef ENABLE_WALLET
988 LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
989 #endif
990 if (!fLogTimestamps)
991 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
992 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
993 LogPrintf("Using data directory %s\n", strDataDir);
994 LogPrintf("Using config file %s\n", GetConfigFile().string());
995 LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
996 std::ostringstream strErrors;
998 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
999 if (nScriptCheckThreads) {
1000 for (int i=0; i<nScriptCheckThreads-1; i++)
1001 threadGroup.create_thread(&ThreadScriptCheck);
1004 // Start the lightweight task scheduler thread
1005 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1006 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1008 /* Start the RPC server already. It will be started in "warmup" mode
1009 * and not really process calls already (but it will signify connections
1010 * that the server is there and will be ready later). Warmup mode will
1011 * be disabled when initialisation is finished.
1013 if (fServer)
1015 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1016 if (!AppInitServers(threadGroup))
1017 return InitError(_("Unable to start HTTP server. See debug log for details."));
1020 int64_t nStart;
1022 // ********************************************************* Step 5: verify wallet database integrity
1023 #ifdef ENABLE_WALLET
1024 if (!fDisableWallet) {
1025 LogPrintf("Using wallet %s\n", strWalletFile);
1026 uiInterface.InitMessage(_("Verifying wallet..."));
1028 std::string warningString;
1029 std::string errorString;
1031 if (!CWallet::Verify(strWalletFile, warningString, errorString))
1032 return false;
1034 if (!warningString.empty())
1035 InitWarning(warningString);
1036 if (!errorString.empty())
1037 return InitError(warningString);
1039 } // (!fDisableWallet)
1040 #endif // ENABLE_WALLET
1041 // ********************************************************* Step 6: network initialization
1043 RegisterNodeSignals(GetNodeSignals());
1045 // format user agent, check total size
1046 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, mapMultiArgs.count("-uacomment") ? mapMultiArgs["-uacomment"] : std::vector<string>());
1047 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1048 return InitError(strprintf("Total length of network version string %i exceeds maximum of %i characters. Reduce the number and/or size of uacomments.",
1049 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1052 if (mapArgs.count("-onlynet")) {
1053 std::set<enum Network> nets;
1054 BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) {
1055 enum Network net = ParseNetwork(snet);
1056 if (net == NET_UNROUTABLE)
1057 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1058 nets.insert(net);
1060 for (int n = 0; n < NET_MAX; n++) {
1061 enum Network net = (enum Network)n;
1062 if (!nets.count(net))
1063 SetLimited(net);
1067 if (mapArgs.count("-whitelist")) {
1068 BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
1069 CSubNet subnet(net);
1070 if (!subnet.IsValid())
1071 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1072 CNode::AddWhitelistedRange(subnet);
1076 bool proxyRandomize = GetBoolArg("-proxyrandomize", true);
1077 // -proxy sets a proxy for all outgoing network traffic
1078 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1079 std::string proxyArg = GetArg("-proxy", "");
1080 if (proxyArg != "" && proxyArg != "0") {
1081 proxyType addrProxy = proxyType(CService(proxyArg, 9050), proxyRandomize);
1082 if (!addrProxy.IsValid())
1083 return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
1085 SetProxy(NET_IPV4, addrProxy);
1086 SetProxy(NET_IPV6, addrProxy);
1087 SetProxy(NET_TOR, addrProxy);
1088 SetNameProxy(addrProxy);
1089 SetReachable(NET_TOR); // by default, -proxy sets onion as reachable, unless -noonion later
1092 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1093 // -noonion (or -onion=0) disables connecting to .onion entirely
1094 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1095 std::string onionArg = GetArg("-onion", "");
1096 if (onionArg != "") {
1097 if (onionArg == "0") { // Handle -noonion/-onion=0
1098 SetReachable(NET_TOR, false); // set onions as unreachable
1099 } else {
1100 proxyType addrOnion = proxyType(CService(onionArg, 9050), proxyRandomize);
1101 if (!addrOnion.IsValid())
1102 return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
1103 SetProxy(NET_TOR, addrOnion);
1104 SetReachable(NET_TOR);
1108 // see Step 2: parameter interactions for more information about these
1109 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1110 fDiscover = GetBoolArg("-discover", true);
1111 fNameLookup = GetBoolArg("-dns", true);
1113 bool fBound = false;
1114 if (fListen) {
1115 if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
1116 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
1117 CService addrBind;
1118 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1119 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
1120 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1122 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
1123 CService addrBind;
1124 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1125 return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
1126 if (addrBind.GetPort() == 0)
1127 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1128 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1131 else {
1132 struct in_addr inaddr_any;
1133 inaddr_any.s_addr = INADDR_ANY;
1134 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
1135 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1137 if (!fBound)
1138 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1141 if (mapArgs.count("-externalip")) {
1142 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
1143 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
1144 if (!addrLocal.IsValid())
1145 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
1146 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
1150 BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
1151 AddOneShot(strDest);
1153 #if ENABLE_ZMQ
1154 pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
1156 if (pzmqNotificationInterface) {
1157 pzmqNotificationInterface->Initialize();
1158 RegisterValidationInterface(pzmqNotificationInterface);
1160 #endif
1162 // ********************************************************* Step 7: load block chain
1164 fReindex = GetBoolArg("-reindex", false);
1166 // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
1167 boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1168 if (!boost::filesystem::exists(blocksDir))
1170 boost::filesystem::create_directories(blocksDir);
1171 bool linked = false;
1172 for (unsigned int i = 1; i < 10000; i++) {
1173 boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1174 if (!boost::filesystem::exists(source)) break;
1175 boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
1176 try {
1177 boost::filesystem::create_hard_link(source, dest);
1178 LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
1179 linked = true;
1180 } catch (const boost::filesystem::filesystem_error& e) {
1181 // Note: hardlink creation failing is not a disaster, it just means
1182 // blocks will get re-downloaded from peers.
1183 LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
1184 break;
1187 if (linked)
1189 fReindex = true;
1193 // cache size calculations
1194 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1195 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1196 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache
1197 int64_t nBlockTreeDBCache = nTotalCache / 8;
1198 if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
1199 nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
1200 nTotalCache -= nBlockTreeDBCache;
1201 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1202 nTotalCache -= nCoinDBCache;
1203 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1204 LogPrintf("Cache configuration:\n");
1205 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1206 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1207 LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
1209 bool fLoaded = false;
1210 while (!fLoaded) {
1211 bool fReset = fReindex;
1212 std::string strLoadError;
1214 uiInterface.InitMessage(_("Loading block index..."));
1216 nStart = GetTimeMillis();
1217 do {
1218 try {
1219 UnloadBlockIndex();
1220 delete pcoinsTip;
1221 delete pcoinsdbview;
1222 delete pcoinscatcher;
1223 delete pblocktree;
1225 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1226 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
1227 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1228 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1230 if (fReindex) {
1231 pblocktree->WriteReindexing(true);
1232 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1233 if (fPruneMode)
1234 CleanupBlockRevFiles();
1237 if (!LoadBlockIndex()) {
1238 strLoadError = _("Error loading block database");
1239 break;
1242 // If the loaded chain has a wrong genesis, bail out immediately
1243 // (we're likely using a testnet datadir, or the other way around).
1244 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1245 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1247 // Initialize the block index (no-op if non-empty database was already loaded)
1248 if (!InitBlockIndex()) {
1249 strLoadError = _("Error initializing block database");
1250 break;
1253 // Check for changed -txindex state
1254 if (fTxIndex != GetBoolArg("-txindex", false)) {
1255 strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1256 break;
1259 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1260 // in the past, but is now trying to run unpruned.
1261 if (fHavePruned && !fPruneMode) {
1262 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1263 break;
1266 uiInterface.InitMessage(_("Verifying blocks..."));
1267 if (fHavePruned && GetArg("-checkblocks", 288) > MIN_BLOCKS_TO_KEEP) {
1268 LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
1269 MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", 288));
1273 LOCK(cs_main);
1274 CBlockIndex* tip = chainActive.Tip();
1275 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1276 strLoadError = _("The block database contains a block which appears to be from the future. "
1277 "This may be due to your computer's date and time being set incorrectly. "
1278 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1279 break;
1283 if (!CVerifyDB().VerifyDB(pcoinsdbview, GetArg("-checklevel", 3),
1284 GetArg("-checkblocks", 288))) {
1285 strLoadError = _("Corrupted block database detected");
1286 break;
1288 } catch (const std::exception& e) {
1289 if (fDebug) LogPrintf("%s\n", e.what());
1290 strLoadError = _("Error opening block database");
1291 break;
1294 fLoaded = true;
1295 } while(false);
1297 if (!fLoaded) {
1298 // first suggest a reindex
1299 if (!fReset) {
1300 bool fRet = uiInterface.ThreadSafeMessageBox(
1301 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1302 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1303 if (fRet) {
1304 fReindex = true;
1305 fRequestShutdown = false;
1306 } else {
1307 LogPrintf("Aborted block database rebuild. Exiting.\n");
1308 return false;
1310 } else {
1311 return InitError(strLoadError);
1316 // As LoadBlockIndex can take several minutes, it's possible the user
1317 // requested to kill the GUI during the last operation. If so, exit.
1318 // As the program has not fully started yet, Shutdown() is possibly overkill.
1319 if (fRequestShutdown)
1321 LogPrintf("Shutdown requested. Exiting.\n");
1322 return false;
1324 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1326 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1327 CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
1328 // Allowed to fail as this file IS missing on first startup.
1329 if (!est_filein.IsNull())
1330 mempool.ReadFeeEstimates(est_filein);
1331 fFeeEstimatesInitialized = true;
1333 // ********************************************************* Step 8: load wallet
1334 #ifdef ENABLE_WALLET
1335 if (fDisableWallet) {
1336 pwalletMain = NULL;
1337 LogPrintf("Wallet disabled!\n");
1338 } else {
1340 // needed to restore wallet transaction meta data after -zapwallettxes
1341 std::vector<CWalletTx> vWtx;
1343 if (GetBoolArg("-zapwallettxes", false)) {
1344 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
1346 pwalletMain = new CWallet(strWalletFile);
1347 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
1348 if (nZapWalletRet != DB_LOAD_OK) {
1349 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
1350 return false;
1353 delete pwalletMain;
1354 pwalletMain = NULL;
1357 uiInterface.InitMessage(_("Loading wallet..."));
1359 nStart = GetTimeMillis();
1360 bool fFirstRun = true;
1361 pwalletMain = new CWallet(strWalletFile);
1362 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
1363 if (nLoadWalletRet != DB_LOAD_OK)
1365 if (nLoadWalletRet == DB_CORRUPT)
1366 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
1367 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
1369 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
1370 " or address book entries might be missing or incorrect."));
1371 InitWarning(msg);
1373 else if (nLoadWalletRet == DB_TOO_NEW)
1374 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin Core") << "\n";
1375 else if (nLoadWalletRet == DB_NEED_REWRITE)
1377 strErrors << _("Wallet needed to be rewritten: restart Bitcoin Core to complete") << "\n";
1378 LogPrintf("%s", strErrors.str());
1379 return InitError(strErrors.str());
1381 else
1382 strErrors << _("Error loading wallet.dat") << "\n";
1385 if (GetBoolArg("-upgradewallet", fFirstRun))
1387 int nMaxVersion = GetArg("-upgradewallet", 0);
1388 if (nMaxVersion == 0) // the -upgradewallet without argument case
1390 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
1391 nMaxVersion = CLIENT_VERSION;
1392 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
1394 else
1395 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
1396 if (nMaxVersion < pwalletMain->GetVersion())
1397 strErrors << _("Cannot downgrade wallet") << "\n";
1398 pwalletMain->SetMaxVersion(nMaxVersion);
1401 if (fFirstRun)
1403 // Create new keyUser and set as default key
1404 RandAddSeedPerfmon();
1406 CPubKey newDefaultKey;
1407 if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
1408 pwalletMain->SetDefaultKey(newDefaultKey);
1409 if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
1410 strErrors << _("Cannot write default address") << "\n";
1413 pwalletMain->SetBestChain(chainActive.GetLocator());
1416 LogPrintf("%s", strErrors.str());
1417 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
1419 RegisterValidationInterface(pwalletMain);
1421 CBlockIndex *pindexRescan = chainActive.Tip();
1422 if (GetBoolArg("-rescan", false))
1423 pindexRescan = chainActive.Genesis();
1424 else
1426 CWalletDB walletdb(strWalletFile);
1427 CBlockLocator locator;
1428 if (walletdb.ReadBestBlock(locator))
1429 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
1430 else
1431 pindexRescan = chainActive.Genesis();
1433 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
1435 //We can't rescan beyond non-pruned blocks, stop and throw an error
1436 //this might happen if a user uses a old wallet within a pruned node
1437 // or if he ran -disablewallet for a longer time, then decided to re-enable
1438 if (fPruneMode)
1440 CBlockIndex *block = chainActive.Tip();
1441 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
1442 block = block->pprev;
1444 if (pindexRescan != block)
1445 return InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
1448 uiInterface.InitMessage(_("Rescanning..."));
1449 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
1450 nStart = GetTimeMillis();
1451 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
1452 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
1453 pwalletMain->SetBestChain(chainActive.GetLocator());
1454 nWalletDBUpdated++;
1456 // Restore wallet transaction metadata after -zapwallettxes=1
1457 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
1459 CWalletDB walletdb(strWalletFile);
1461 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
1463 uint256 hash = wtxOld.GetHash();
1464 std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
1465 if (mi != pwalletMain->mapWallet.end())
1467 const CWalletTx* copyFrom = &wtxOld;
1468 CWalletTx* copyTo = &mi->second;
1469 copyTo->mapValue = copyFrom->mapValue;
1470 copyTo->vOrderForm = copyFrom->vOrderForm;
1471 copyTo->nTimeReceived = copyFrom->nTimeReceived;
1472 copyTo->nTimeSmart = copyFrom->nTimeSmart;
1473 copyTo->fFromMe = copyFrom->fFromMe;
1474 copyTo->strFromAccount = copyFrom->strFromAccount;
1475 copyTo->nOrderPos = copyFrom->nOrderPos;
1476 copyTo->WriteToDisk(&walletdb);
1481 pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true));
1482 } // (!fDisableWallet)
1483 #else // ENABLE_WALLET
1484 LogPrintf("No wallet support compiled in!\n");
1485 #endif // !ENABLE_WALLET
1487 // ********************************************************* Step 9: data directory maintenance
1489 // if pruning, unset the service bit and perform the initial blockstore prune
1490 // after any wallet rescanning has taken place.
1491 if (fPruneMode) {
1492 uiInterface.InitMessage(_("Pruning blockstore..."));
1493 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1494 nLocalServices &= ~NODE_NETWORK;
1495 if (!fReindex) {
1496 PruneAndFlush();
1500 // ********************************************************* Step 10: import blocks
1502 if (mapArgs.count("-blocknotify"))
1503 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1505 uiInterface.InitMessage(_("Activating best chain..."));
1506 // scan for better chains in the block chain database, that are not yet connected in the active best chain
1507 CValidationState state;
1508 if (!ActivateBestChain(state))
1509 strErrors << "Failed to connect best block";
1511 std::vector<boost::filesystem::path> vImportFiles;
1512 if (mapArgs.count("-loadblock"))
1514 BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
1515 vImportFiles.push_back(strFile);
1517 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1518 if (chainActive.Tip() == NULL) {
1519 LogPrintf("Waiting for genesis block to be imported...\n");
1520 while (!fRequestShutdown && chainActive.Tip() == NULL)
1521 MilliSleep(10);
1524 // ********************************************************* Step 11: start node
1526 if (!CheckDiskSpace())
1527 return false;
1529 if (!strErrors.str().empty())
1530 return InitError(strErrors.str());
1532 RandAddSeedPerfmon();
1534 //// debug print
1535 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1536 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1537 #ifdef ENABLE_WALLET
1538 LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
1539 LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
1540 LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
1541 #endif
1543 StartNode(threadGroup, scheduler);
1545 // Monitor the chain, and alert if we get blocks much quicker or slower than expected
1546 int64_t nPowTargetSpacing = Params().GetConsensus().nPowTargetSpacing;
1547 CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload,
1548 boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing);
1549 scheduler.scheduleEvery(f, nPowTargetSpacing);
1551 // Generate coins in the background
1552 GenerateBitcoins(GetBoolArg("-gen", false), GetArg("-genproclimit", 1), Params());
1554 // ********************************************************* Step 11: finished
1556 SetRPCWarmupFinished();
1557 uiInterface.InitMessage(_("Done loading"));
1559 #ifdef ENABLE_WALLET
1560 if (pwalletMain) {
1561 // Add wallet transactions that aren't already in a block to mapTransactions
1562 pwalletMain->ReacceptWalletTransactions();
1564 // Run a thread to flush wallet periodically
1565 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1567 #endif
1569 return !fRequestShutdown;