Merge pull request #6599
[bitcoinplatinum.git] / src / init.cpp
blob085e04fdfd7d5bcc9bcf570dcb2b829462f59c1d
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 "key.h"
20 #include "main.h"
21 #include "miner.h"
22 #include "net.h"
23 #include "policy/policy.h"
24 #include "rpcserver.h"
25 #include "script/standard.h"
26 #include "scheduler.h"
27 #include "txdb.h"
28 #include "txmempool.h"
29 #include "ui_interface.h"
30 #include "util.h"
31 #include "utilmoneystr.h"
32 #include "utilstrencodings.h"
33 #include "validationinterface.h"
34 #ifdef ENABLE_WALLET
35 #include "wallet/db.h"
36 #include "wallet/wallet.h"
37 #include "wallet/walletdb.h"
38 #endif
40 #include <stdint.h>
41 #include <stdio.h>
43 #ifndef WIN32
44 #include <signal.h>
45 #endif
47 #include <boost/algorithm/string/predicate.hpp>
48 #include <boost/algorithm/string/replace.hpp>
49 #include <boost/bind.hpp>
50 #include <boost/filesystem.hpp>
51 #include <boost/function.hpp>
52 #include <boost/interprocess/sync/file_lock.hpp>
53 #include <boost/thread.hpp>
54 #include <openssl/crypto.h>
56 using namespace std;
58 #ifdef ENABLE_WALLET
59 CWallet* pwalletMain = NULL;
60 #endif
61 bool fFeeEstimatesInitialized = false;
63 #ifdef WIN32
64 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
65 // accessing block files don't count towards the fd_set size limit
66 // anyway.
67 #define MIN_CORE_FILEDESCRIPTORS 0
68 #else
69 #define MIN_CORE_FILEDESCRIPTORS 150
70 #endif
72 /** Used to pass flags to the Bind() function */
73 enum BindFlags {
74 BF_NONE = 0,
75 BF_EXPLICIT = (1U << 0),
76 BF_REPORT_ERROR = (1U << 1),
77 BF_WHITELIST = (1U << 2),
80 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
81 CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h
83 //////////////////////////////////////////////////////////////////////////////
85 // Shutdown
89 // Thread management and startup/shutdown:
91 // The network-processing threads are all part of a thread group
92 // created by AppInit() or the Qt main() function.
94 // A clean exit happens when StartShutdown() or the SIGTERM
95 // signal handler sets fRequestShutdown, which triggers
96 // the DetectShutdownThread(), which interrupts the main thread group.
97 // DetectShutdownThread() then exits, which causes AppInit() to
98 // continue (it .joins the shutdown thread).
99 // Shutdown() is then
100 // called to clean up database connections, and stop other
101 // threads that should only be stopped after the main network-processing
102 // threads have exited.
104 // Note that if running -daemon the parent process returns from AppInit2
105 // before adding any threads to the threadGroup, so .join_all() returns
106 // immediately and the parent exits from main().
108 // Shutdown for Qt is very similar, only it uses a QTimer to detect
109 // fRequestShutdown getting set, and then does the normal Qt
110 // shutdown thing.
113 volatile bool fRequestShutdown = false;
115 void StartShutdown()
117 fRequestShutdown = true;
119 bool ShutdownRequested()
121 return fRequestShutdown;
124 class CCoinsViewErrorCatcher : public CCoinsViewBacked
126 public:
127 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
128 bool GetCoins(const uint256 &txid, CCoins &coins) const {
129 try {
130 return CCoinsViewBacked::GetCoins(txid, coins);
131 } catch(const std::runtime_error& e) {
132 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
133 LogPrintf("Error reading from database: %s\n", e.what());
134 // Starting the shutdown sequence and returning false to the caller would be
135 // interpreted as 'entry not found' (as opposed to unable to read data), and
136 // could lead to invalid interpretation. Just exit immediately, as we can't
137 // continue anyway, and all writes should be atomic.
138 abort();
141 // Writes do not need similar protection, as failure to write is handled by the caller.
144 static CCoinsViewDB *pcoinsdbview = NULL;
145 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
147 void Shutdown()
149 LogPrintf("%s: In progress...\n", __func__);
150 static CCriticalSection cs_Shutdown;
151 TRY_LOCK(cs_Shutdown, lockShutdown);
152 if (!lockShutdown)
153 return;
155 /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
156 /// for example if the data directory was found to be locked.
157 /// Be sure that anything that writes files or flushes caches only does this if the respective
158 /// module was initialized.
159 RenameThread("bitcoin-shutoff");
160 mempool.AddTransactionsUpdated(1);
161 StopRPCThreads();
162 #ifdef ENABLE_WALLET
163 if (pwalletMain)
164 pwalletMain->Flush(false);
165 #endif
166 GenerateBitcoins(false, 0, Params());
167 StopNode();
168 UnregisterNodeSignals(GetNodeSignals());
170 if (fFeeEstimatesInitialized)
172 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
173 CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
174 if (!est_fileout.IsNull())
175 mempool.WriteFeeEstimates(est_fileout);
176 else
177 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
178 fFeeEstimatesInitialized = false;
182 LOCK(cs_main);
183 if (pcoinsTip != NULL) {
184 FlushStateToDisk();
186 delete pcoinsTip;
187 pcoinsTip = NULL;
188 delete pcoinscatcher;
189 pcoinscatcher = NULL;
190 delete pcoinsdbview;
191 pcoinsdbview = NULL;
192 delete pblocktree;
193 pblocktree = NULL;
195 #ifdef ENABLE_WALLET
196 if (pwalletMain)
197 pwalletMain->Flush(true);
198 #endif
199 #ifndef WIN32
200 try {
201 boost::filesystem::remove(GetPidFile());
202 } catch (const boost::filesystem::filesystem_error& e) {
203 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
205 #endif
206 UnregisterAllValidationInterfaces();
207 #ifdef ENABLE_WALLET
208 delete pwalletMain;
209 pwalletMain = NULL;
210 #endif
211 ECC_Stop();
212 LogPrintf("%s: done\n", __func__);
216 * Signal handlers are very limited in what they are allowed to do, so:
218 void HandleSIGTERM(int)
220 fRequestShutdown = true;
223 void HandleSIGHUP(int)
225 fReopenDebugLog = true;
228 bool static InitError(const std::string &str)
230 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
231 return false;
234 bool static InitWarning(const std::string &str)
236 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
237 return true;
240 bool static Bind(const CService &addr, unsigned int flags) {
241 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
242 return false;
243 std::string strError;
244 if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
245 if (flags & BF_REPORT_ERROR)
246 return InitError(strError);
247 return false;
249 return true;
252 void OnRPCStopped()
254 cvBlockChange.notify_all();
255 LogPrint("rpc", "RPC stopped.\n");
258 void OnRPCPreCommand(const CRPCCommand& cmd)
260 // Observe safe mode
261 string strWarning = GetWarnings("rpc");
262 if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
263 !cmd.okSafeMode)
264 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
267 std::string HelpMessage(HelpMessageMode mode)
269 const bool showDebug = GetBoolArg("-help-debug", false);
271 // When adding new options to the categories, please keep and ensure alphabetical ordering.
272 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
273 string strUsage = HelpMessageGroup(_("Options:"));
274 strUsage += HelpMessageOpt("-?", _("This help message"));
275 strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
276 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)"));
277 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
278 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 288));
279 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), 3));
280 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "bitcoin.conf"));
281 if (mode == HMM_BITCOIND)
283 #if !defined(WIN32)
284 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
285 #endif
287 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
288 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
289 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup"));
290 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
291 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)"),
292 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
293 #ifndef WIN32
294 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "bitcoind.pid"));
295 #endif
296 strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode disables wallet support and is incompatible with -txindex. "
297 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
298 "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
299 strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files on startup"));
300 #if !defined(WIN32)
301 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
302 #endif
303 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
305 strUsage += HelpMessageGroup(_("Connection options:"));
306 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
307 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100));
308 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400));
309 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
310 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)"));
311 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
312 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)"));
313 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)"));
314 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
315 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0));
316 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
317 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
318 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000));
319 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000));
320 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
321 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
322 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1));
323 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 8333, 18333));
324 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
325 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1));
326 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
327 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
328 #ifdef USE_UPNP
329 #if USE_UPNP
330 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
331 #else
332 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
333 #endif
334 #endif
335 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
336 strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
337 " " + _("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"));
338 strUsage += HelpMessageOpt("-whiteconnections=<n>", strprintf(_("Reserve this many inbound connections for whitelisted peers (default: %d)"), 0));
340 #ifdef ENABLE_WALLET
341 strUsage += HelpMessageGroup(_("Wallet options:"));
342 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
343 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100));
344 if (showDebug)
345 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)",
346 CURRENCY_UNIT, FormatMoney(CWallet::minTxFee.GetFeePerK())));
347 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
348 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
349 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
350 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
351 strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
352 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1));
353 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));
354 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)"),
355 CURRENCY_UNIT, FormatMoney(maxTxFee)));
356 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup"));
357 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
358 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), true));
359 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
360 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
361 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
362 #endif
364 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
365 if (showDebug)
367 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", 1));
368 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)", 100));
369 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", 0));
370 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", 0));
371 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
372 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
373 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", 1));
374 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", 0));
376 string debugCategories = "addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, mempool, mempoolrej, net, proxy, prune"; // Don't translate these and qt below
377 if (mode == HMM_BITCOIN_QT)
378 debugCategories += ", qt";
379 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
380 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
381 strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0));
382 strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
383 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
384 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
385 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
386 if (showDebug)
388 strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
389 strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 1));
390 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> entries (default: %u)", 50000));
392 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying (default: %s)"),
393 CURRENCY_UNIT, FormatMoney(::minRelayTxFee.GetFeePerK())));
394 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
395 if (showDebug)
397 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", 0));
398 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", 1));
399 strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
400 "This is intended for regression testing tools and app development.");
402 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
403 strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
405 strUsage += HelpMessageGroup(_("Node relay options:"));
406 if (showDebug)
407 strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
408 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1));
409 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
411 strUsage += HelpMessageGroup(_("Block creation options:"));
412 strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), 0));
413 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
414 strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
415 if (showDebug)
416 strUsage += HelpMessageOpt("-blockversion=<n>", strprintf("Override block version to test forking scenarios (default: %d)", (int)CBlock::CURRENT_VERSION));
418 strUsage += HelpMessageGroup(_("RPC server options:"));
419 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
420 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0));
421 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)"));
422 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
423 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
424 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 8332, 18332));
425 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"));
426 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), 4));
427 strUsage += HelpMessageOpt("-rpckeepalive", strprintf(_("RPC support for HTTP persistent connections (default: %d)"), 1));
429 strUsage += HelpMessageGroup(_("RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)"));
430 strUsage += HelpMessageOpt("-rpcssl", _("Use OpenSSL (https) for JSON-RPC connections"));
431 strUsage += HelpMessageOpt("-rpcsslcertificatechainfile=<file.cert>", strprintf(_("Server certificate file (default: %s)"), "server.cert"));
432 strUsage += HelpMessageOpt("-rpcsslprivatekeyfile=<file.pem>", strprintf(_("Server private key (default: %s)"), "server.pem"));
433 strUsage += HelpMessageOpt("-rpcsslciphers=<ciphers>", strprintf(_("Acceptable ciphers (default: %s)"), "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH"));
435 if (mode == HMM_BITCOIN_QT)
437 strUsage += HelpMessageGroup(_("UI Options:"));
438 if (showDebug) {
439 strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", "Allow self signed root certificates (default: 0)");
441 strUsage += HelpMessageOpt("-choosedatadir", _("Choose data directory on startup (default: 0)"));
442 strUsage += HelpMessageOpt("-lang=<lang>", _("Set language, for example \"de_DE\" (default: system locale)"));
443 strUsage += HelpMessageOpt("-min", _("Start minimized"));
444 strUsage += HelpMessageOpt("-rootcertificates=<file>", _("Set SSL root certificates for payment request (default: -system-)"));
445 strUsage += HelpMessageOpt("-splash", _("Show splash screen on startup (default: 1)"));
446 if (showDebug) {
447 strUsage += HelpMessageOpt("-uiplatform", "Select platform to customize UI for (one of windows, macosx, other; default: platform compiled on)");
451 return strUsage;
454 std::string LicenseInfo()
456 return FormatParagraph(strprintf(_("Copyright (C) 2009-%i The Bitcoin Core Developers"), COPYRIGHT_YEAR)) + "\n" +
457 "\n" +
458 FormatParagraph(_("This is experimental software.")) + "\n" +
459 "\n" +
460 FormatParagraph(_("Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.")) + "\n" +
461 "\n" +
462 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.")) +
463 "\n";
466 static void BlockNotifyCallback(const uint256& hashNewTip)
468 std::string strCmd = GetArg("-blocknotify", "");
470 boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
471 boost::thread t(runCommand, strCmd); // thread runs free
474 struct CImportingNow
476 CImportingNow() {
477 assert(fImporting == false);
478 fImporting = true;
481 ~CImportingNow() {
482 assert(fImporting == true);
483 fImporting = false;
488 // If we're using -prune with -reindex, then delete block files that will be ignored by the
489 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
490 // is missing, do the same here to delete any later block files after a gap. Also delete all
491 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
492 // is in sync with what's actually on disk by the time we start downloading, so that pruning
493 // works correctly.
494 void CleanupBlockRevFiles()
496 using namespace boost::filesystem;
497 map<string, path> mapBlockFiles;
499 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
500 // Remove the rev files immediately and insert the blk file paths into an
501 // ordered map keyed by block file index.
502 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
503 path blocksdir = GetDataDir() / "blocks";
504 for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
505 if (is_regular_file(*it) &&
506 it->path().filename().string().length() == 12 &&
507 it->path().filename().string().substr(8,4) == ".dat")
509 if (it->path().filename().string().substr(0,3) == "blk")
510 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
511 else if (it->path().filename().string().substr(0,3) == "rev")
512 remove(it->path());
516 // Remove all block files that aren't part of a contiguous set starting at
517 // zero by walking the ordered map (keys are block file indices) by
518 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
519 // start removing block files.
520 int nContigCounter = 0;
521 BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) {
522 if (atoi(item.first) == nContigCounter) {
523 nContigCounter++;
524 continue;
526 remove(item.second);
530 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
532 RenameThread("bitcoin-loadblk");
533 // -reindex
534 if (fReindex) {
535 CImportingNow imp;
536 int nFile = 0;
537 while (true) {
538 CDiskBlockPos pos(nFile, 0);
539 if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
540 break; // No block files left to reindex
541 FILE *file = OpenBlockFile(pos, true);
542 if (!file)
543 break; // This error is logged in OpenBlockFile
544 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
545 LoadExternalBlockFile(file, &pos);
546 nFile++;
548 pblocktree->WriteReindexing(false);
549 fReindex = false;
550 LogPrintf("Reindexing finished\n");
551 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
552 InitBlockIndex();
555 // hardcoded $DATADIR/bootstrap.dat
556 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
557 if (boost::filesystem::exists(pathBootstrap)) {
558 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
559 if (file) {
560 CImportingNow imp;
561 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
562 LogPrintf("Importing bootstrap.dat...\n");
563 LoadExternalBlockFile(file);
564 RenameOver(pathBootstrap, pathBootstrapOld);
565 } else {
566 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
570 // -loadblock=
571 BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
572 FILE *file = fopen(path.string().c_str(), "rb");
573 if (file) {
574 CImportingNow imp;
575 LogPrintf("Importing blocks file %s...\n", path.string());
576 LoadExternalBlockFile(file);
577 } else {
578 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
582 if (GetBoolArg("-stopafterblockimport", false)) {
583 LogPrintf("Stopping after block import\n");
584 StartShutdown();
588 /** Sanity checks
589 * Ensure that Bitcoin is running in a usable environment with all
590 * necessary library support.
592 bool InitSanityCheck(void)
594 if(!ECC_InitSanityCheck()) {
595 InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more "
596 "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries");
597 return false;
599 if (!glibc_sanity_test() || !glibcxx_sanity_test())
600 return false;
602 return true;
605 /** Initialize bitcoin.
606 * @pre Parameters should be parsed and config file should be read.
608 bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
610 // ********************************************************* Step 1: setup
611 #ifdef _MSC_VER
612 // Turn off Microsoft heap dump noise
613 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
614 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
615 #endif
616 #if _MSC_VER >= 1400
617 // Disable confusing "helpful" text message on abort, Ctrl-C
618 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
619 #endif
620 #ifdef WIN32
621 // Enable Data Execution Prevention (DEP)
622 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
623 // A failure is non-critical and needs no further attention!
624 #ifndef PROCESS_DEP_ENABLE
625 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
626 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
627 #define PROCESS_DEP_ENABLE 0x00000001
628 #endif
629 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
630 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
631 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
633 // Initialize Windows Sockets
634 WSADATA wsadata;
635 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
636 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
638 return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
640 #endif
641 #ifndef WIN32
643 if (GetBoolArg("-sysperms", false)) {
644 #ifdef ENABLE_WALLET
645 if (!GetBoolArg("-disablewallet", false))
646 return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
647 #endif
648 } else {
649 umask(077);
652 // Clean shutdown on SIGTERM
653 struct sigaction sa;
654 sa.sa_handler = HandleSIGTERM;
655 sigemptyset(&sa.sa_mask);
656 sa.sa_flags = 0;
657 sigaction(SIGTERM, &sa, NULL);
658 sigaction(SIGINT, &sa, NULL);
660 // Reopen debug.log on SIGHUP
661 struct sigaction sa_hup;
662 sa_hup.sa_handler = HandleSIGHUP;
663 sigemptyset(&sa_hup.sa_mask);
664 sa_hup.sa_flags = 0;
665 sigaction(SIGHUP, &sa_hup, NULL);
667 #if defined (__SVR4) && defined (__sun)
668 // ignore SIGPIPE on Solaris
669 signal(SIGPIPE, SIG_IGN);
670 #endif
671 #endif
673 // ********************************************************* Step 2: parameter interactions
674 const CChainParams& chainparams = Params();
676 // Set this early so that parameter interactions go to console
677 fPrintToConsole = GetBoolArg("-printtoconsole", false);
678 fLogTimestamps = GetBoolArg("-logtimestamps", true);
679 fLogIPs = GetBoolArg("-logips", false);
681 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
682 LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
684 // when specifying an explicit binding address, you want to listen on it
685 // even when -connect or -proxy is specified
686 if (mapArgs.count("-bind")) {
687 if (SoftSetBoolArg("-listen", true))
688 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
690 if (mapArgs.count("-whitebind")) {
691 if (SoftSetBoolArg("-listen", true))
692 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
695 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
696 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
697 if (SoftSetBoolArg("-dnsseed", false))
698 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
699 if (SoftSetBoolArg("-listen", false))
700 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
703 if (mapArgs.count("-proxy")) {
704 // to protect privacy, do not listen by default if a default proxy server is specified
705 if (SoftSetBoolArg("-listen", false))
706 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
707 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
708 // to listen locally, so don't rely on this happening through -listen below.
709 if (SoftSetBoolArg("-upnp", false))
710 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
711 // to protect privacy, do not discover addresses by default
712 if (SoftSetBoolArg("-discover", false))
713 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
716 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
717 // do not map ports or try to retrieve public IP when not listening (pointless)
718 if (SoftSetBoolArg("-upnp", false))
719 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
720 if (SoftSetBoolArg("-discover", false))
721 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
724 if (mapArgs.count("-externalip")) {
725 // if an explicit public IP is specified, do not try to find others
726 if (SoftSetBoolArg("-discover", false))
727 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
730 if (GetBoolArg("-salvagewallet", false)) {
731 // Rewrite just private keys: rescan to find transactions
732 if (SoftSetBoolArg("-rescan", true))
733 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
736 // -zapwallettx implies a rescan
737 if (GetBoolArg("-zapwallettxes", false)) {
738 if (SoftSetBoolArg("-rescan", true))
739 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
742 // if using block pruning, then disable txindex
743 if (GetArg("-prune", 0)) {
744 if (GetBoolArg("-txindex", false))
745 return InitError(_("Prune mode is incompatible with -txindex."));
746 #ifdef ENABLE_WALLET
747 if (GetBoolArg("-rescan", false)) {
748 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
750 #endif
753 // Make sure enough file descriptors are available
754 int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
755 int nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
756 nMaxConnections = std::max(nUserMaxConnections, 0);
757 int nUserWhiteConnections = GetArg("-whiteconnections", 0);
758 nWhiteConnections = std::max(nUserWhiteConnections, 0);
760 if ((mapArgs.count("-whitelist")) || (mapArgs.count("-whitebind"))) {
761 if (!(mapArgs.count("-maxconnections"))) {
762 // User is using whitelist feature,
763 // but did not specify -maxconnections parameter.
764 // Silently increase the default to compensate,
765 // so that the whitelist connection reservation feature
766 // does not inadvertently reduce the default
767 // inbound connection capacity of the network.
768 nMaxConnections += nWhiteConnections;
770 } else {
771 // User not using whitelist feature.
772 // Silently disable connection reservation,
773 // for the same reason as above.
774 nWhiteConnections = 0;
777 // Trim requested connection counts, to fit into system limitations
778 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
779 int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
780 if (nFD < MIN_CORE_FILEDESCRIPTORS)
781 return InitError(_("Not enough file descriptors available."));
782 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS, nMaxConnections);
784 if (nMaxConnections < nUserMaxConnections)
785 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
787 // Connection capacity is prioritized in this order:
788 // outbound connections (hardcoded to 8),
789 // then whitelisted connections,
790 // then non-whitelisted connections get whatever's left (if any).
791 if ((nWhiteConnections > 0) && (nWhiteConnections >= (nMaxConnections - 8)))
792 InitWarning(strprintf(_("All non-whitelisted incoming connections will be dropped, because -whiteconnections is %d and -maxconnections is only %d."), nWhiteConnections, nMaxConnections));
794 // ********************************************************* Step 3: parameter-to-internal-flags
796 fDebug = !mapMultiArgs["-debug"].empty();
797 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
798 const vector<string>& categories = mapMultiArgs["-debug"];
799 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
800 fDebug = false;
802 // Check for -debugnet
803 if (GetBoolArg("-debugnet", false))
804 InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
805 // Check for -socks - as this is a privacy risk to continue, exit here
806 if (mapArgs.count("-socks"))
807 return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
808 // Check for -tor - as this is a privacy risk to continue, exit here
809 if (GetBoolArg("-tor", false))
810 return InitError(_("Error: Unsupported argument -tor found, use -onion."));
812 if (GetBoolArg("-benchmark", false))
813 InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
815 // Checkmempool and checkblockindex default to true in regtest mode
816 mempool.setSanityCheck(GetBoolArg("-checkmempool", chainparams.DefaultConsistencyChecks()));
817 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
818 fCheckpointsEnabled = GetBoolArg("-checkpoints", true);
820 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
821 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
822 if (nScriptCheckThreads <= 0)
823 nScriptCheckThreads += GetNumCores();
824 if (nScriptCheckThreads <= 1)
825 nScriptCheckThreads = 0;
826 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
827 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
829 fServer = GetBoolArg("-server", false);
831 // block pruning; get the amount of disk space (in MB) to allot for block & undo files
832 int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
833 if (nSignedPruneTarget < 0) {
834 return InitError(_("Prune cannot be configured with a negative value."));
836 nPruneTarget = (uint64_t) nSignedPruneTarget;
837 if (nPruneTarget) {
838 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
839 return InitError(strprintf(_("Prune configured below the minimum of %d MB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
841 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
842 fPruneMode = true;
845 #ifdef ENABLE_WALLET
846 bool fDisableWallet = GetBoolArg("-disablewallet", false);
847 #endif
849 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
850 if (nConnectTimeout <= 0)
851 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
853 // Fee-per-kilobyte amount considered the same as "free"
854 // If you are mining, be careful setting this:
855 // if you set it to zero then
856 // a transaction spammer can cheaply fill blocks using
857 // 1-satoshi-fee transactions. It should be set above the real
858 // cost to you of processing a transaction.
859 if (mapArgs.count("-minrelaytxfee"))
861 CAmount n = 0;
862 if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
863 ::minRelayTxFee = CFeeRate(n);
864 else
865 return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
868 fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !Params().RequireStandard());
869 if (Params().RequireStandard() && !fRequireStandard)
870 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
872 #ifdef ENABLE_WALLET
873 if (mapArgs.count("-mintxfee"))
875 CAmount n = 0;
876 if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
877 CWallet::minTxFee = CFeeRate(n);
878 else
879 return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
881 if (mapArgs.count("-paytxfee"))
883 CAmount nFeePerK = 0;
884 if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
885 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
886 if (nFeePerK > nHighTransactionFeeWarning)
887 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
888 payTxFee = CFeeRate(nFeePerK, 1000);
889 if (payTxFee < ::minRelayTxFee)
891 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
892 mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
895 if (mapArgs.count("-maxtxfee"))
897 CAmount nMaxFee = 0;
898 if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
899 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maptxfee"]));
900 if (nMaxFee > nHighTransactionMaxFeeWarning)
901 InitWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction."));
902 maxTxFee = nMaxFee;
903 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
905 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
906 mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
909 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
910 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", true);
911 fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false);
913 std::string strWalletFile = GetArg("-wallet", "wallet.dat");
914 #endif // ENABLE_WALLET
916 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true);
917 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
919 fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
921 // Option to startup with mocktime set (used for regression testing):
922 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
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 if (nWhiteConnections > 0)
972 LogPrintf("Reserving %i of these connections for whitelisted inbound peers\n", nWhiteConnections);
973 std::ostringstream strErrors;
975 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
976 if (nScriptCheckThreads) {
977 for (int i=0; i<nScriptCheckThreads-1; i++)
978 threadGroup.create_thread(&ThreadScriptCheck);
981 // Start the lightweight task scheduler thread
982 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
983 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
985 /* Start the RPC server already. It will be started in "warmup" mode
986 * and not really process calls already (but it will signify connections
987 * that the server is there and will be ready later). Warmup mode will
988 * be disabled when initialisation is finished.
990 if (fServer)
992 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
993 RPCServer::OnStopped(&OnRPCStopped);
994 RPCServer::OnPreCommand(&OnRPCPreCommand);
995 StartRPCThreads();
998 int64_t nStart;
1000 // ********************************************************* Step 5: verify wallet database integrity
1001 #ifdef ENABLE_WALLET
1002 if (!fDisableWallet) {
1003 LogPrintf("Using wallet %s\n", strWalletFile);
1004 uiInterface.InitMessage(_("Verifying wallet..."));
1006 std::string warningString;
1007 std::string errorString;
1009 if (!CWallet::Verify(strWalletFile, warningString, errorString))
1010 return false;
1012 if (!warningString.empty())
1013 InitWarning(warningString);
1014 if (!errorString.empty())
1015 return InitError(warningString);
1017 } // (!fDisableWallet)
1018 #endif // ENABLE_WALLET
1019 // ********************************************************* Step 6: network initialization
1021 RegisterNodeSignals(GetNodeSignals());
1023 // format user agent, check total size
1024 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, mapMultiArgs.count("-uacomment") ? mapMultiArgs["-uacomment"] : std::vector<string>());
1025 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1026 return InitError(strprintf("Total length of network version string %i exceeds maximum of %i characters. Reduce the number and/or size of uacomments.",
1027 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1030 if (mapArgs.count("-onlynet")) {
1031 std::set<enum Network> nets;
1032 BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) {
1033 enum Network net = ParseNetwork(snet);
1034 if (net == NET_UNROUTABLE)
1035 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1036 nets.insert(net);
1038 for (int n = 0; n < NET_MAX; n++) {
1039 enum Network net = (enum Network)n;
1040 if (!nets.count(net))
1041 SetLimited(net);
1045 if (mapArgs.count("-whitelist")) {
1046 BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
1047 CSubNet subnet(net);
1048 if (!subnet.IsValid())
1049 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1050 CNode::AddWhitelistedRange(subnet);
1054 bool proxyRandomize = GetBoolArg("-proxyrandomize", true);
1055 // -proxy sets a proxy for all outgoing network traffic
1056 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1057 std::string proxyArg = GetArg("-proxy", "");
1058 if (proxyArg != "" && proxyArg != "0") {
1059 proxyType addrProxy = proxyType(CService(proxyArg, 9050), proxyRandomize);
1060 if (!addrProxy.IsValid())
1061 return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
1063 SetProxy(NET_IPV4, addrProxy);
1064 SetProxy(NET_IPV6, addrProxy);
1065 SetProxy(NET_TOR, addrProxy);
1066 SetNameProxy(addrProxy);
1067 SetReachable(NET_TOR); // by default, -proxy sets onion as reachable, unless -noonion later
1070 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1071 // -noonion (or -onion=0) disables connecting to .onion entirely
1072 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1073 std::string onionArg = GetArg("-onion", "");
1074 if (onionArg != "") {
1075 if (onionArg == "0") { // Handle -noonion/-onion=0
1076 SetReachable(NET_TOR, false); // set onions as unreachable
1077 } else {
1078 proxyType addrOnion = proxyType(CService(onionArg, 9050), proxyRandomize);
1079 if (!addrOnion.IsValid())
1080 return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
1081 SetProxy(NET_TOR, addrOnion);
1082 SetReachable(NET_TOR);
1086 // see Step 2: parameter interactions for more information about these
1087 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1088 fDiscover = GetBoolArg("-discover", true);
1089 fNameLookup = GetBoolArg("-dns", true);
1091 bool fBound = false;
1092 if (fListen) {
1093 if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
1094 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
1095 CService addrBind;
1096 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1097 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
1098 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1100 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
1101 CService addrBind;
1102 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1103 return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
1104 if (addrBind.GetPort() == 0)
1105 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1106 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1109 else {
1110 struct in_addr inaddr_any;
1111 inaddr_any.s_addr = INADDR_ANY;
1112 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
1113 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1115 if (!fBound)
1116 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1119 if (mapArgs.count("-externalip")) {
1120 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
1121 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
1122 if (!addrLocal.IsValid())
1123 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
1124 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
1128 BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
1129 AddOneShot(strDest);
1131 // ********************************************************* Step 7: load block chain
1133 fReindex = GetBoolArg("-reindex", false);
1135 // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
1136 boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1137 if (!boost::filesystem::exists(blocksDir))
1139 boost::filesystem::create_directories(blocksDir);
1140 bool linked = false;
1141 for (unsigned int i = 1; i < 10000; i++) {
1142 boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1143 if (!boost::filesystem::exists(source)) break;
1144 boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
1145 try {
1146 boost::filesystem::create_hard_link(source, dest);
1147 LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
1148 linked = true;
1149 } catch (const boost::filesystem::filesystem_error& e) {
1150 // Note: hardlink creation failing is not a disaster, it just means
1151 // blocks will get re-downloaded from peers.
1152 LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
1153 break;
1156 if (linked)
1158 fReindex = true;
1162 // cache size calculations
1163 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1164 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1165 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache
1166 int64_t nBlockTreeDBCache = nTotalCache / 8;
1167 if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
1168 nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
1169 nTotalCache -= nBlockTreeDBCache;
1170 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1171 nTotalCache -= nCoinDBCache;
1172 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1173 LogPrintf("Cache configuration:\n");
1174 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1175 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1176 LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
1178 bool fLoaded = false;
1179 while (!fLoaded) {
1180 bool fReset = fReindex;
1181 std::string strLoadError;
1183 uiInterface.InitMessage(_("Loading block index..."));
1185 nStart = GetTimeMillis();
1186 do {
1187 try {
1188 UnloadBlockIndex();
1189 delete pcoinsTip;
1190 delete pcoinsdbview;
1191 delete pcoinscatcher;
1192 delete pblocktree;
1194 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1195 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
1196 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1197 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1199 if (fReindex) {
1200 pblocktree->WriteReindexing(true);
1201 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1202 if (fPruneMode)
1203 CleanupBlockRevFiles();
1206 if (!LoadBlockIndex()) {
1207 strLoadError = _("Error loading block database");
1208 break;
1211 // If the loaded chain has a wrong genesis, bail out immediately
1212 // (we're likely using a testnet datadir, or the other way around).
1213 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1214 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1216 // Initialize the block index (no-op if non-empty database was already loaded)
1217 if (!InitBlockIndex()) {
1218 strLoadError = _("Error initializing block database");
1219 break;
1222 // Check for changed -txindex state
1223 if (fTxIndex != GetBoolArg("-txindex", false)) {
1224 strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1225 break;
1228 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1229 // in the past, but is now trying to run unpruned.
1230 if (fHavePruned && !fPruneMode) {
1231 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1232 break;
1235 uiInterface.InitMessage(_("Verifying blocks..."));
1236 if (fHavePruned && GetArg("-checkblocks", 288) > MIN_BLOCKS_TO_KEEP) {
1237 LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
1238 MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", 288));
1242 LOCK(cs_main);
1243 CBlockIndex* tip = chainActive.Tip();
1244 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1245 strLoadError = _("The block database contains a block which appears to be from the future. "
1246 "This may be due to your computer's date and time being set incorrectly. "
1247 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1248 break;
1252 if (!CVerifyDB().VerifyDB(pcoinsdbview, GetArg("-checklevel", 3),
1253 GetArg("-checkblocks", 288))) {
1254 strLoadError = _("Corrupted block database detected");
1255 break;
1257 } catch (const std::exception& e) {
1258 if (fDebug) LogPrintf("%s\n", e.what());
1259 strLoadError = _("Error opening block database");
1260 break;
1263 fLoaded = true;
1264 } while(false);
1266 if (!fLoaded) {
1267 // first suggest a reindex
1268 if (!fReset) {
1269 bool fRet = uiInterface.ThreadSafeMessageBox(
1270 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1271 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1272 if (fRet) {
1273 fReindex = true;
1274 fRequestShutdown = false;
1275 } else {
1276 LogPrintf("Aborted block database rebuild. Exiting.\n");
1277 return false;
1279 } else {
1280 return InitError(strLoadError);
1285 // As LoadBlockIndex can take several minutes, it's possible the user
1286 // requested to kill the GUI during the last operation. If so, exit.
1287 // As the program has not fully started yet, Shutdown() is possibly overkill.
1288 if (fRequestShutdown)
1290 LogPrintf("Shutdown requested. Exiting.\n");
1291 return false;
1293 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1295 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1296 CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
1297 // Allowed to fail as this file IS missing on first startup.
1298 if (!est_filein.IsNull())
1299 mempool.ReadFeeEstimates(est_filein);
1300 fFeeEstimatesInitialized = true;
1302 // ********************************************************* Step 8: load wallet
1303 #ifdef ENABLE_WALLET
1304 if (fDisableWallet) {
1305 pwalletMain = NULL;
1306 LogPrintf("Wallet disabled!\n");
1307 } else {
1309 // needed to restore wallet transaction meta data after -zapwallettxes
1310 std::vector<CWalletTx> vWtx;
1312 if (GetBoolArg("-zapwallettxes", false)) {
1313 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
1315 pwalletMain = new CWallet(strWalletFile);
1316 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
1317 if (nZapWalletRet != DB_LOAD_OK) {
1318 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
1319 return false;
1322 delete pwalletMain;
1323 pwalletMain = NULL;
1326 uiInterface.InitMessage(_("Loading wallet..."));
1328 nStart = GetTimeMillis();
1329 bool fFirstRun = true;
1330 pwalletMain = new CWallet(strWalletFile);
1331 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
1332 if (nLoadWalletRet != DB_LOAD_OK)
1334 if (nLoadWalletRet == DB_CORRUPT)
1335 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
1336 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
1338 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
1339 " or address book entries might be missing or incorrect."));
1340 InitWarning(msg);
1342 else if (nLoadWalletRet == DB_TOO_NEW)
1343 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin Core") << "\n";
1344 else if (nLoadWalletRet == DB_NEED_REWRITE)
1346 strErrors << _("Wallet needed to be rewritten: restart Bitcoin Core to complete") << "\n";
1347 LogPrintf("%s", strErrors.str());
1348 return InitError(strErrors.str());
1350 else
1351 strErrors << _("Error loading wallet.dat") << "\n";
1354 if (GetBoolArg("-upgradewallet", fFirstRun))
1356 int nMaxVersion = GetArg("-upgradewallet", 0);
1357 if (nMaxVersion == 0) // the -upgradewallet without argument case
1359 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
1360 nMaxVersion = CLIENT_VERSION;
1361 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
1363 else
1364 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
1365 if (nMaxVersion < pwalletMain->GetVersion())
1366 strErrors << _("Cannot downgrade wallet") << "\n";
1367 pwalletMain->SetMaxVersion(nMaxVersion);
1370 if (fFirstRun)
1372 // Create new keyUser and set as default key
1373 RandAddSeedPerfmon();
1375 CPubKey newDefaultKey;
1376 if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
1377 pwalletMain->SetDefaultKey(newDefaultKey);
1378 if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
1379 strErrors << _("Cannot write default address") << "\n";
1382 pwalletMain->SetBestChain(chainActive.GetLocator());
1385 LogPrintf("%s", strErrors.str());
1386 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
1388 RegisterValidationInterface(pwalletMain);
1390 CBlockIndex *pindexRescan = chainActive.Tip();
1391 if (GetBoolArg("-rescan", false))
1392 pindexRescan = chainActive.Genesis();
1393 else
1395 CWalletDB walletdb(strWalletFile);
1396 CBlockLocator locator;
1397 if (walletdb.ReadBestBlock(locator))
1398 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
1399 else
1400 pindexRescan = chainActive.Genesis();
1402 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
1404 //We can't rescan beyond non-pruned blocks, stop and throw an error
1405 //this might happen if a user uses a old wallet within a pruned node
1406 // or if he ran -disablewallet for a longer time, then decided to re-enable
1407 if (fPruneMode)
1409 CBlockIndex *block = chainActive.Tip();
1410 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
1411 block = block->pprev;
1413 if (pindexRescan != block)
1414 return InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
1417 uiInterface.InitMessage(_("Rescanning..."));
1418 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
1419 nStart = GetTimeMillis();
1420 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
1421 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
1422 pwalletMain->SetBestChain(chainActive.GetLocator());
1423 nWalletDBUpdated++;
1425 // Restore wallet transaction metadata after -zapwallettxes=1
1426 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
1428 CWalletDB walletdb(strWalletFile);
1430 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
1432 uint256 hash = wtxOld.GetHash();
1433 std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
1434 if (mi != pwalletMain->mapWallet.end())
1436 const CWalletTx* copyFrom = &wtxOld;
1437 CWalletTx* copyTo = &mi->second;
1438 copyTo->mapValue = copyFrom->mapValue;
1439 copyTo->vOrderForm = copyFrom->vOrderForm;
1440 copyTo->nTimeReceived = copyFrom->nTimeReceived;
1441 copyTo->nTimeSmart = copyFrom->nTimeSmart;
1442 copyTo->fFromMe = copyFrom->fFromMe;
1443 copyTo->strFromAccount = copyFrom->strFromAccount;
1444 copyTo->nOrderPos = copyFrom->nOrderPos;
1445 copyTo->WriteToDisk(&walletdb);
1450 pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true));
1451 } // (!fDisableWallet)
1452 #else // ENABLE_WALLET
1453 LogPrintf("No wallet support compiled in!\n");
1454 #endif // !ENABLE_WALLET
1456 // ********************************************************* Step 9: data directory maintenance
1458 // if pruning, unset the service bit and perform the initial blockstore prune
1459 // after any wallet rescanning has taken place.
1460 if (fPruneMode) {
1461 uiInterface.InitMessage(_("Pruning blockstore..."));
1462 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1463 nLocalServices &= ~NODE_NETWORK;
1464 if (!fReindex) {
1465 PruneAndFlush();
1469 // ********************************************************* Step 10: import blocks
1471 if (mapArgs.count("-blocknotify"))
1472 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1474 uiInterface.InitMessage(_("Activating best chain..."));
1475 // scan for better chains in the block chain database, that are not yet connected in the active best chain
1476 CValidationState state;
1477 if (!ActivateBestChain(state))
1478 strErrors << "Failed to connect best block";
1480 std::vector<boost::filesystem::path> vImportFiles;
1481 if (mapArgs.count("-loadblock"))
1483 BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
1484 vImportFiles.push_back(strFile);
1486 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1487 if (chainActive.Tip() == NULL) {
1488 LogPrintf("Waiting for genesis block to be imported...\n");
1489 while (!fRequestShutdown && chainActive.Tip() == NULL)
1490 MilliSleep(10);
1493 // ********************************************************* Step 11: start node
1495 if (!CheckDiskSpace())
1496 return false;
1498 if (!strErrors.str().empty())
1499 return InitError(strErrors.str());
1501 RandAddSeedPerfmon();
1503 //// debug print
1504 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1505 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1506 #ifdef ENABLE_WALLET
1507 LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
1508 LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
1509 LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
1510 #endif
1512 StartNode(threadGroup, scheduler);
1514 // Monitor the chain, and alert if we get blocks much quicker or slower than expected
1515 int64_t nPowTargetSpacing = Params().GetConsensus().nPowTargetSpacing;
1516 CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload,
1517 boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing);
1518 scheduler.scheduleEvery(f, nPowTargetSpacing);
1520 // Generate coins in the background
1521 GenerateBitcoins(GetBoolArg("-gen", false), GetArg("-genproclimit", 1), Params());
1523 // ********************************************************* Step 11: finished
1525 SetRPCWarmupFinished();
1526 uiInterface.InitMessage(_("Done loading"));
1528 #ifdef ENABLE_WALLET
1529 if (pwalletMain) {
1530 // Add wallet transactions that aren't already in a block to mapTransactions
1531 pwalletMain->ReacceptWalletTransactions();
1533 // Run a thread to flush wallet periodically
1534 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1536 #endif
1538 return !fRequestShutdown;