]> Git Repo - VerusCoin.git/blame - src/init.cpp
Transplant of libzcash.
[VerusCoin.git] / src / init.cpp
CommitLineData
69d605f4 1// Copyright (c) 2009-2010 Satoshi Nakamoto
f914f1a7 2// Copyright (c) 2009-2014 The Bitcoin Core developers
c5b390b6 3// Distributed under the MIT software license, see the accompanying
3a25a2b9 4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5350ea41 5
35b8af92 6#if defined(HAVE_CONFIG_H)
f3967bcc 7#include "config/bitcoin-config.h"
35b8af92
CF
8#endif
9
663224c2 10#include "init.h"
6806256b 11#include "sodium.h"
51ed9ec9
BD
12
13#include "addrman.h"
eda37330 14#include "amount.h"
51ed9ec9 15#include "checkpoints.h"
611116d4 16#include "compat/sanity.h"
da29ecbc 17#include "consensus/validation.h"
4a09e1df 18#include "key.h"
a9a37c8b 19#include "main.h"
d247a5d1 20#include "miner.h"
51ed9ec9 21#include "net.h"
a9a37c8b 22#include "rpcserver.h"
2aa63292 23#include "script/standard.h"
ddd0acd3 24#include "scheduler.h"
51ed9ec9 25#include "txdb.h"
ed6d0b5f 26#include "ui_interface.h"
51ed9ec9 27#include "util.h"
ad49c256 28#include "utilmoneystr.h"
cbb2cf55 29#include "validationinterface.h"
48ba56cd 30#ifdef ENABLE_WALLET
50c72f23
JS
31#include "wallet/wallet.h"
32#include "wallet/walletdb.h"
48ba56cd 33#endif
5350ea41 34
51ed9ec9 35#include <stdint.h>
283e405c 36#include <stdio.h>
69d605f4 37
ed6d0b5f
PW
38#ifndef WIN32
39#include <signal.h>
52d3a481 40#endif
5f2e76b8 41
51ed9ec9 42#include <boost/algorithm/string/predicate.hpp>
e9dd83f0 43#include <boost/algorithm/string/replace.hpp>
36cba8f1 44#include <boost/bind.hpp>
51ed9ec9 45#include <boost/filesystem.hpp>
36cba8f1 46#include <boost/function.hpp>
51ed9ec9 47#include <boost/interprocess/sync/file_lock.hpp>
ad49c256 48#include <boost/thread.hpp>
51ed9ec9
BD
49#include <openssl/crypto.h>
50
d66877af
SB
51#include "libsnark/common/profiling.hpp"
52
00d1980b 53using namespace std;
69d605f4 54
2dc35992 55ZCJoinSplit* pzcashParams = NULL;
4f1c3798 56
48ba56cd 57#ifdef ENABLE_WALLET
20a11ffa 58CWallet* pwalletMain = NULL;
48ba56cd 59#endif
94064710 60bool fFeeEstimatesInitialized = false;
e8ef3da7 61
ba29a559
PW
62#ifdef WIN32
63// Win32 LevelDB doesn't use filedescriptors, and the ones used for
7e6d23b1 64// accessing block files don't count towards the fd_set size limit
ba29a559
PW
65// anyway.
66#define MIN_CORE_FILEDESCRIPTORS 0
67#else
68#define MIN_CORE_FILEDESCRIPTORS 150
69#endif
70
c5b390b6 71/** Used to pass flags to the Bind() function */
c73323ee 72enum BindFlags {
29e214aa
PK
73 BF_NONE = 0,
74 BF_EXPLICIT = (1U << 0),
dc942e6f
PW
75 BF_REPORT_ERROR = (1U << 1),
76 BF_WHITELIST = (1U << 2),
c73323ee
PK
77};
78
171ca774 79static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
b74dcb3b 80CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h
4751d07e 81
69d605f4
WL
82//////////////////////////////////////////////////////////////////////////////
83//
84// Shutdown
85//
86
b31499ec
GA
87//
88// Thread management and startup/shutdown:
89//
90// The network-processing threads are all part of a thread group
91// created by AppInit() or the Qt main() function.
92//
93// A clean exit happens when StartShutdown() or the SIGTERM
94// signal handler sets fRequestShutdown, which triggers
95// the DetectShutdownThread(), which interrupts the main thread group.
96// DetectShutdownThread() then exits, which causes AppInit() to
97// continue (it .joins the shutdown thread).
98// Shutdown() is then
99// called to clean up database connections, and stop other
100// threads that should only be stopped after the main network-processing
101// threads have exited.
102//
103// Note that if running -daemon the parent process returns from AppInit2
104// before adding any threads to the threadGroup, so .join_all() returns
105// immediately and the parent exits from main().
106//
107// Shutdown for Qt is very similar, only it uses a QTimer to detect
723035bb
GA
108// fRequestShutdown getting set, and then does the normal Qt
109// shutdown thing.
b31499ec
GA
110//
111
112volatile bool fRequestShutdown = false;
69d605f4 113
9247134e
PK
114void StartShutdown()
115{
b31499ec 116 fRequestShutdown = true;
9247134e 117}
723035bb
GA
118bool ShutdownRequested()
119{
120 return fRequestShutdown;
121}
9247134e 122
13cdce43
PW
123class CCoinsViewErrorCatcher : public CCoinsViewBacked
124{
125public:
126 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
127 bool GetCoins(const uint256 &txid, CCoins &coins) const {
128 try {
129 return CCoinsViewBacked::GetCoins(txid, coins);
130 } catch(const std::runtime_error& e) {
131 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
132 LogPrintf("Error reading from database: %s\n", e.what());
133 // Starting the shutdown sequence and returning false to the caller would be
134 // interpreted as 'entry not found' (as opposed to unable to read data), and
c0692346 135 // could lead to invalid interpretation. Just exit immediately, as we can't
13cdce43
PW
136 // continue anyway, and all writes should be atomic.
137 abort();
138 }
139 }
140 // Writes do not need similar protection, as failure to write is handled by the caller.
141};
142
20a11ffa 143static CCoinsViewDB *pcoinsdbview = NULL;
13cdce43 144static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
ae8bfd12 145
b31499ec 146void Shutdown()
69d605f4 147{
00d1980b 148 LogPrintf("%s: In progress...\n", __func__);
69d605f4 149 static CCriticalSection cs_Shutdown;
b31499ec 150 TRY_LOCK(cs_Shutdown, lockShutdown);
00d1980b
PK
151 if (!lockShutdown)
152 return;
96931d6f 153
94064710
WL
154 /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
155 /// for example if the data directory was found to be locked.
156 /// Be sure that anything that writes files or flushes caches only does this if the respective
157 /// module was initialized.
96931d6f 158 RenameThread("bitcoin-shutoff");
319b1160 159 mempool.AddTransactionsUpdated(1);
21eb5ada 160 StopRPCThreads();
4a85e067 161#ifdef ENABLE_WALLET
b0730874 162 if (pwalletMain)
2bb1c877 163 pwalletMain->Flush(false);
c8b74258 164 GenerateBitcoins(false, NULL, 0);
48ba56cd 165#endif
21eb5ada 166 StopNode();
b2864d2f 167 UnregisterNodeSignals(GetNodeSignals());
171ca774 168
94064710 169 if (fFeeEstimatesInitialized)
09c744c2
PW
170 {
171 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
172 CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
a8738238 173 if (!est_fileout.IsNull())
09c744c2
PW
174 mempool.WriteFeeEstimates(est_fileout);
175 else
176 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
94064710 177 fFeeEstimatesInitialized = false;
09c744c2 178 }
171ca774 179
69d605f4 180 {
b31499ec 181 LOCK(cs_main);
51ce901a
PW
182 if (pcoinsTip != NULL) {
183 FlushStateToDisk();
184 }
00d1980b
PK
185 delete pcoinsTip;
186 pcoinsTip = NULL;
13cdce43
PW
187 delete pcoinscatcher;
188 pcoinscatcher = NULL;
00d1980b
PK
189 delete pcoinsdbview;
190 pcoinsdbview = NULL;
191 delete pblocktree;
192 pblocktree = NULL;
69d605f4 193 }
48ba56cd 194#ifdef ENABLE_WALLET
b0730874 195 if (pwalletMain)
2bb1c877 196 pwalletMain->Flush(true);
48ba56cd 197#endif
d6712db3 198#ifndef WIN32
ffdda4e8
AW
199 try {
200 boost::filesystem::remove(GetPidFile());
201 } catch (const boost::filesystem::filesystem_error& e) {
202 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
203 }
d6712db3 204#endif
a96d1139 205 UnregisterAllValidationInterfaces();
48ba56cd 206#ifdef ENABLE_WALLET
20a11ffa
PK
207 delete pwalletMain;
208 pwalletMain = NULL;
48ba56cd 209#endif
a56054be 210 ECC_Stop();
00d1980b 211 LogPrintf("%s: done\n", __func__);
69d605f4
WL
212}
213
c5b390b6
MF
214/**
215 * Signal handlers are very limited in what they are allowed to do, so:
216 */
69d605f4
WL
217void HandleSIGTERM(int)
218{
219 fRequestShutdown = true;
220}
221
9af080c3
MH
222void HandleSIGHUP(int)
223{
224 fReopenDebugLog = true;
225}
69d605f4 226
ac7c7ab9
PW
227bool static InitError(const std::string &str)
228{
49d57125 229 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
ac7c7ab9 230 return false;
ac7c7ab9
PW
231}
232
233bool static InitWarning(const std::string &str)
234{
49d57125 235 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
ac7c7ab9
PW
236 return true;
237}
238
29e214aa 239bool static Bind(const CService &addr, unsigned int flags) {
c73323ee 240 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
8f10a288
PW
241 return false;
242 std::string strError;
8d657a65 243 if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
c73323ee 244 if (flags & BF_REPORT_ERROR)
587f929c
PW
245 return InitError(strError);
246 return false;
247 }
8f10a288
PW
248 return true;
249}
250
4401b2d7
EL
251void OnRPCStopped()
252{
253 cvBlockChange.notify_all();
254 LogPrint("rpc", "RPC stopped.\n");
255}
256
257void OnRPCPreCommand(const CRPCCommand& cmd)
258{
4401b2d7
EL
259 // Observe safe mode
260 string strWarning = GetWarnings("rpc");
261 if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
262 !cmd.okSafeMode)
263 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
264}
265
1020f599 266std::string HelpMessage(HelpMessageMode mode)
9f5b11e6 267{
94cd7051 268 const bool showDebug = GetBoolArg("-help-debug", false);
1fdb9fa3 269
1020f599 270 // When adding new options to the categories, please keep and ensure alphabetical ordering.
94cd7051
WL
271 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators
272
1fdb9fa3
LV
273 string strUsage = HelpMessageGroup(_("Options:"));
274 strUsage += HelpMessageOpt("-?", _("This help message"));
4d9c7fe6 275 strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
1fdb9fa3
LV
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));
aaf64959 280 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "zcash.conf"));
1020f599 281 if (mode == HMM_BITCOIND)
7398f4a7
CL
282 {
283#if !defined(WIN32)
1fdb9fa3 284 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
7398f4a7
CL
285#endif
286 }
1fdb9fa3
LV
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 -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
d6712db3 293#ifndef WIN32
aaf64959 294 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "zcashd.pid"));
d6712db3 295#endif
fc44231c
WL
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));
a1d0ec44 299 strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files on startup"));
bdd5b587 300#if !defined(WIN32)
1fdb9fa3 301 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
bdd5b587 302#endif
1fdb9fa3
LV
303 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
304
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)"), 125));
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"));
67a79493 325 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1));
1fdb9fa3
LV
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));
9f5b11e6
WL
328#ifdef USE_UPNP
329#if USE_UPNP
1fdb9fa3 330 strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening)"));
9f5b11e6 331#else
1fdb9fa3 332 strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
2a03a390 333#endif
9f5b11e6 334#endif
1fdb9fa3
LV
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
7398f4a7
CL
339
340#ifdef ENABLE_WALLET
1fdb9fa3
LV
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));
94cd7051
WL
344 if (showDebug)
345 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf("Fees (in BTC/Kb) smaller than this are considered zero fee for transaction creation (default: %s)",
1fdb9fa3
LV
346 FormatMoney(CWallet::minTxFee.GetFeePerK())));
347 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in BTC/kB) to add to transactions you send (default: %s)"), FormatMoney(payTxFee.GetFeePerK())));
348 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
349 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
350 strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
351 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1));
77ed59df 352 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));
7e6d23b1 353 strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees to use in a single wallet transaction; setting this too low may abort large transactions (default: %s)"),
1fdb9fa3
LV
354 FormatMoney(maxTxFee)));
355 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup"));
356 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
6f252627 357 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), true));
1fdb9fa3
LV
358 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
359 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
360 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
361
7398f4a7
CL
362#endif
363
1fdb9fa3 364 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
94cd7051 365 if (showDebug)
7398f4a7 366 {
94cd7051
WL
367 strUsage += HelpMessageOpt("-checkpoints", strprintf("Only accept block chain matching built-in checkpoints (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));
7398f4a7 375 }
f9ec3f0f 376 string debugCategories = "addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, mempool, net, proxy, prune"; // Don't translate these and qt below
1020f599 377 if (mode == HMM_BITCOIN_QT)
1fdb9fa3
LV
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, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
a7e1d503 381#ifdef ENABLE_WALLET
1fdb9fa3
LV
382 strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0));
383 strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
a7e1d503 384#endif
1fdb9fa3
LV
385 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
386 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
387 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
94cd7051 388 if (showDebug)
3b570559 389 {
94cd7051
WL
390 strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
391 strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 1));
392 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> entries (default: %u)", 50000));
3b570559 393 }
1fdb9fa3
LV
394 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in BTC/Kb) smaller than this are considered zero fee for relaying (default: %s)"), FormatMoney(::minRelayTxFee.GetFeePerK())));
395 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
94cd7051 396 if (showDebug)
3b570559 397 {
94cd7051
WL
398 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", 0));
399 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", 1));
400 strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
401 "This is intended for regression testing tools and app development.");
3b570559 402 }
1fdb9fa3
LV
403 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
404 strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
405
406 strUsage += HelpMessageGroup(_("Node relay options:"));
407 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1));
408 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
409
410 strUsage += HelpMessageGroup(_("Block creation options:"));
411 strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), 0));
412 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
413 strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
414
415 strUsage += HelpMessageGroup(_("RPC server options:"));
416 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
417 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0));
418 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)"));
419 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
420 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
421 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 8332, 18332));
422 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"));
423 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), 4));
424 strUsage += HelpMessageOpt("-rpckeepalive", strprintf(_("RPC support for HTTP persistent connections (default: %d)"), 1));
425
426 strUsage += HelpMessageGroup(_("RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)"));
427 strUsage += HelpMessageOpt("-rpcssl", _("Use OpenSSL (https) for JSON-RPC connections"));
428 strUsage += HelpMessageOpt("-rpcsslcertificatechainfile=<file.cert>", strprintf(_("Server certificate file (default: %s)"), "server.cert"));
429 strUsage += HelpMessageOpt("-rpcsslprivatekeyfile=<file.pem>", strprintf(_("Server private key (default: %s)"), "server.pem"));
430 strUsage += HelpMessageOpt("-rpcsslciphers=<ciphers>", strprintf(_("Acceptable ciphers (default: %s)"), "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH"));
9f5b11e6 431
f7547079
LV
432 if (mode == HMM_BITCOIN_QT)
433 {
434 strUsage += HelpMessageGroup(_("UI Options:"));
94cd7051
WL
435 if (showDebug) {
436 strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", "Allow self signed root certificates (default: 0)");
f7547079
LV
437 }
438 strUsage += HelpMessageOpt("-choosedatadir", _("Choose data directory on startup (default: 0)"));
439 strUsage += HelpMessageOpt("-lang=<lang>", _("Set language, for example \"de_DE\" (default: system locale)"));
440 strUsage += HelpMessageOpt("-min", _("Start minimized"));
441 strUsage += HelpMessageOpt("-rootcertificates=<file>", _("Set SSL root certificates for payment request (default: -system-)"));
442 strUsage += HelpMessageOpt("-splash", _("Show splash screen on startup (default: 1)"));
443 }
444
9f5b11e6
WL
445 return strUsage;
446}
447
45615af2
WL
448std::string LicenseInfo()
449{
450 return FormatParagraph(strprintf(_("Copyright (C) 2009-%i The Bitcoin Core Developers"), COPYRIGHT_YEAR)) + "\n" +
451 "\n" +
452 FormatParagraph(_("This is experimental software.")) + "\n" +
453 "\n" +
1b2600a1 454 FormatParagraph(_("Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.")) + "\n" +
45615af2
WL
455 "\n" +
456 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.")) +
457 "\n";
458}
459
c7b6117d
JG
460static void BlockNotifyCallback(const uint256& hashNewTip)
461{
462 std::string strCmd = GetArg("-blocknotify", "");
463
464 boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
465 boost::thread t(runCommand, strCmd); // thread runs free
466}
467
7a5b7535
PW
468struct CImportingNow
469{
470 CImportingNow() {
471 assert(fImporting == false);
472 fImporting = true;
473 }
474
475 ~CImportingNow() {
476 assert(fImporting == true);
477 fImporting = false;
478 }
479};
480
f9ec3f0f 481
482// If we're using -prune with -reindex, then delete block files that will be ignored by the
483// reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
6cb70ca4
AW
484// is missing, do the same here to delete any later block files after a gap. Also delete all
485// rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
486// is in sync with what's actually on disk by the time we start downloading, so that pruning
487// works correctly.
488void CleanupBlockRevFiles()
f9ec3f0f 489{
6cb70ca4
AW
490 using namespace boost::filesystem;
491 map<string, path> mapBlockFiles;
492
493 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
494 // Remove the rev files immediately and insert the blk file paths into an
495 // ordered map keyed by block file index.
496 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
497 path blocksdir = GetDataDir() / "blocks";
498 for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
499 if (is_regular_file(*it) &&
500 it->path().filename().string().length() == 12 &&
501 it->path().filename().string().substr(8,4) == ".dat")
502 {
503 if (it->path().filename().string().substr(0,3) == "blk")
504 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
505 else if (it->path().filename().string().substr(0,3) == "rev")
506 remove(it->path());
507 }
508 }
f9ec3f0f 509
6cb70ca4
AW
510 // Remove all block files that aren't part of a contiguous set starting at
511 // zero by walking the ordered map (keys are block file indices) by
512 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
513 // start removing block files.
514 int nContigCounter = 0;
515 BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) {
516 if (atoi(item.first) == nContigCounter) {
517 nContigCounter++;
518 continue;
f9ec3f0f 519 }
6cb70ca4 520 remove(item.second);
f9ec3f0f 521 }
522}
523
21eb5ada
GA
524void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
525{
7a5b7535 526 RenameThread("bitcoin-loadblk");
7fea4846
PW
527 // -reindex
528 if (fReindex) {
529 CImportingNow imp;
530 int nFile = 0;
21eb5ada 531 while (true) {
a8a4b967 532 CDiskBlockPos pos(nFile, 0);
ec7eb0fa
SD
533 if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
534 break; // No block files left to reindex
7fea4846
PW
535 FILE *file = OpenBlockFile(pos, true);
536 if (!file)
ec7eb0fa 537 break; // This error is logged in OpenBlockFile
881a85a2 538 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
7fea4846
PW
539 LoadExternalBlockFile(file, &pos);
540 nFile++;
541 }
21eb5ada
GA
542 pblocktree->WriteReindexing(false);
543 fReindex = false;
881a85a2 544 LogPrintf("Reindexing finished\n");
21eb5ada
GA
545 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
546 InitBlockIndex();
7a5b7535
PW
547 }
548
549 // hardcoded $DATADIR/bootstrap.dat
a3241998
CF
550 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
551 if (boost::filesystem::exists(pathBootstrap)) {
7a5b7535
PW
552 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
553 if (file) {
7fea4846 554 CImportingNow imp;
a3241998 555 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
881a85a2 556 LogPrintf("Importing bootstrap.dat...\n");
7a5b7535
PW
557 LoadExternalBlockFile(file);
558 RenameOver(pathBootstrap, pathBootstrapOld);
d54e819f
WL
559 } else {
560 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
7a5b7535
PW
561 }
562 }
563
7fea4846 564 // -loadblock=
21eb5ada 565 BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
7fea4846
PW
566 FILE *file = fopen(path.string().c_str(), "rb");
567 if (file) {
568 CImportingNow imp;
d54e819f 569 LogPrintf("Importing blocks file %s...\n", path.string());
7fea4846 570 LoadExternalBlockFile(file);
d54e819f
WL
571 } else {
572 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
7fea4846
PW
573 }
574 }
1569353b
WL
575
576 if (GetBoolArg("-stopafterblockimport", false)) {
577 LogPrintf("Stopping after block import\n");
578 StartShutdown();
579 }
7a5b7535
PW
580}
581
4a09e1df
AP
582/** Sanity checks
583 * Ensure that Bitcoin is running in a usable environment with all
584 * necessary library support.
585 */
586bool InitSanityCheck(void)
587{
588 if(!ECC_InitSanityCheck()) {
589 InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more "
590 "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries");
591 return false;
592 }
92a62207
CF
593 if (!glibc_sanity_test() || !glibcxx_sanity_test())
594 return false;
4a09e1df
AP
595
596 return true;
597}
598
4f1c3798
SB
599
600static void ZC_LoadParams()
601{
602 struct timeval tv_start, tv_end;
603 float elapsed;
604
605 boost::filesystem::path pk_path = ZC_GetParamsDir() / "zc-testnet-public-alpha-proving.key";
606 boost::filesystem::path vk_path = ZC_GetParamsDir() / "zc-testnet-public-alpha-verification.key";
607
2dc35992 608 pzcashParams = ZCJoinSplit::Unopened();
4f1c3798
SB
609
610 LogPrintf("Loading verification key from %s\n", vk_path.string().c_str());
611 gettimeofday(&tv_start, 0);
2dc35992
SB
612
613 pzcashParams->loadVerifyingKey(vk_path.string());
614
4f1c3798
SB
615 gettimeofday(&tv_end, 0);
616 elapsed = float(tv_end.tv_sec-tv_start.tv_sec) + (tv_end.tv_usec-tv_start.tv_usec)/float(1000000);
617 LogPrintf("Loaded verification key in %fs seconds.\n", elapsed);
618
2dc35992 619 pzcashParams->setProvingKeyPath(pk_path.string());
4f1c3798
SB
620}
621
9f5b11e6
WL
622/** Initialize bitcoin.
623 * @pre Parameters should be parsed and config file should be read.
624 */
ddd0acd3 625bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
69d605f4 626{
6806256b
SB
627 // Perform libsodium initialization
628 if (sodium_init() == -1) {
629 return false;
630 }
631
9bab3e89
TH
632 // ********************************************************* Step 0: Load zcash params
633 ZC_LoadParams();
634
7d80d2e3 635 // ********************************************************* Step 1: setup
69d605f4 636#ifdef _MSC_VER
814efd6f 637 // Turn off Microsoft heap dump noise
69d605f4
WL
638 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
639 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
640#endif
641#if _MSC_VER >= 1400
814efd6f 642 // Disable confusing "helpful" text message on abort, Ctrl-C
69d605f4
WL
643 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
644#endif
3d88c9b4
PK
645#ifdef WIN32
646 // Enable Data Execution Prevention (DEP)
647 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
648 // A failure is non-critical and needs no further attention!
649#ifndef PROCESS_DEP_ENABLE
f65dddc7
PK
650 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
651 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
3d88c9b4
PK
652#define PROCESS_DEP_ENABLE 0x00000001
653#endif
654 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
655 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
656 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
d23fa49c
WL
657
658 // Initialize Windows Sockets
659 WSADATA wsadata;
660 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
110257a6 661 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
d23fa49c 662 {
110257a6 663 return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
d23fa49c 664 }
69d605f4 665#endif
6853e627 666#ifndef WIN32
bdd5b587
RS
667
668 if (GetBoolArg("-sysperms", false)) {
669#ifdef ENABLE_WALLET
670 if (!GetBoolArg("-disablewallet", false))
671 return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
672#endif
673 } else {
674 umask(077);
675 }
3d88c9b4 676
69d605f4
WL
677 // Clean shutdown on SIGTERM
678 struct sigaction sa;
679 sa.sa_handler = HandleSIGTERM;
680 sigemptyset(&sa.sa_mask);
681 sa.sa_flags = 0;
682 sigaction(SIGTERM, &sa, NULL);
683 sigaction(SIGINT, &sa, NULL);
9af080c3
MH
684
685 // Reopen debug.log on SIGHUP
686 struct sigaction sa_hup;
687 sa_hup.sa_handler = HandleSIGHUP;
688 sigemptyset(&sa_hup.sa_mask);
689 sa_hup.sa_flags = 0;
690 sigaction(SIGHUP, &sa_hup, NULL);
b34255b7 691
692#if defined (__SVR4) && defined (__sun)
693 // ignore SIGPIPE on Solaris
694 signal(SIGPIPE, SIG_IGN);
695#endif
69d605f4
WL
696#endif
697
7d80d2e3 698 // ********************************************************* Step 2: parameter interactions
4e382177 699 const CChainParams& chainparams = Params();
13f90318 700
eadcd0c8
MC
701 // Set this early so that parameter interactions go to console
702 fPrintToConsole = GetBoolArg("-printtoconsole", false);
703 fLogTimestamps = GetBoolArg("-logtimestamps", true);
704 fLogIPs = GetBoolArg("-logips", false);
7d80d2e3 705
13f90318
PK
706 // when specifying an explicit binding address, you want to listen on it
707 // even when -connect or -proxy is specified
708 if (mapArgs.count("-bind")) {
709 if (SoftSetBoolArg("-listen", true))
710 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
711 }
712 if (mapArgs.count("-whitebind")) {
df966d1b 713 if (SoftSetBoolArg("-listen", true))
13f90318 714 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
587f929c 715 }
7d80d2e3 716
f161a2c2 717 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
587f929c 718 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
df966d1b 719 if (SoftSetBoolArg("-dnsseed", false))
13f90318 720 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
df966d1b 721 if (SoftSetBoolArg("-listen", false))
13f90318 722 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
587f929c
PW
723 }
724
725 if (mapArgs.count("-proxy")) {
df966d1b
PK
726 // to protect privacy, do not listen by default if a default proxy server is specified
727 if (SoftSetBoolArg("-listen", false))
13f90318 728 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
8c35b6f3
WL
729 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
730 // to listen locally, so don't rely on this happening through -listen below.
731 if (SoftSetBoolArg("-upnp", false))
732 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
845c86d1
GM
733 // to protect privacy, do not discover addresses by default
734 if (SoftSetBoolArg("-discover", false))
13f90318 735 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
587f929c
PW
736 }
737
13f90318 738 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
587f929c 739 // do not map ports or try to retrieve public IP when not listening (pointless)
df966d1b 740 if (SoftSetBoolArg("-upnp", false))
13f90318 741 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
df966d1b 742 if (SoftSetBoolArg("-discover", false))
13f90318 743 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
7d80d2e3
PW
744 }
745
587f929c
PW
746 if (mapArgs.count("-externalip")) {
747 // if an explicit public IP is specified, do not try to find others
df966d1b 748 if (SoftSetBoolArg("-discover", false))
13f90318 749 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
587f929c
PW
750 }
751
3260b4c0 752 if (GetBoolArg("-salvagewallet", false)) {
eed1785f 753 // Rewrite just private keys: rescan to find transactions
df966d1b 754 if (SoftSetBoolArg("-rescan", true))
13f90318 755 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
eed1785f
GA
756 }
757
518f3bda
JG
758 // -zapwallettx implies a rescan
759 if (GetBoolArg("-zapwallettxes", false)) {
760 if (SoftSetBoolArg("-rescan", true))
13f90318 761 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
518f3bda
JG
762 }
763
ba29a559 764 // Make sure enough file descriptors are available
dc942e6f 765 int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
ba29a559 766 nMaxConnections = GetArg("-maxconnections", 125);
03f49808 767 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
ba29a559
PW
768 int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
769 if (nFD < MIN_CORE_FILEDESCRIPTORS)
770 return InitError(_("Not enough file descriptors available."));
771 if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
772 nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
773
f9ec3f0f 774 // if using block pruning, then disable txindex
775 // also disable the wallet (for now, until SPV support is implemented in wallet)
776 if (GetArg("-prune", 0)) {
777 if (GetBoolArg("-txindex", false))
778 return InitError(_("Prune mode is incompatible with -txindex."));
779#ifdef ENABLE_WALLET
780 if (!GetBoolArg("-disablewallet", false)) {
781 if (SoftSetBoolArg("-disablewallet", true))
782 LogPrintf("%s : parameter interaction: -prune -> setting -disablewallet=1\n", __func__);
783 else
784 return InitError(_("Can't run with a wallet in prune mode."));
785 }
786#endif
787 }
788
7d80d2e3
PW
789 // ********************************************************* Step 3: parameter-to-internal-flags
790
3b570559
PK
791 fDebug = !mapMultiArgs["-debug"].empty();
792 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
793 const vector<string>& categories = mapMultiArgs["-debug"];
794 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
795 fDebug = false;
796
00d1980b 797 // Check for -debugnet
3b570559 798 if (GetBoolArg("-debugnet", false))
00d1980b 799 InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
a339a37b
PK
800 // Check for -socks - as this is a privacy risk to continue, exit here
801 if (mapArgs.count("-socks"))
802 return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
1c750dbd
PK
803 // Check for -tor - as this is a privacy risk to continue, exit here
804 if (GetBoolArg("-tor", false))
805 return InitError(_("Error: Unsupported argument -tor found, use -onion."));
3b570559 806
d70bc52e
PW
807 if (GetBoolArg("-benchmark", false))
808 InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
809
3fcfbc8a 810 // Checkmempool and checkblockindex default to true in regtest mode
4e382177
JT
811 mempool.setSanityCheck(GetBoolArg("-checkmempool", chainparams.DefaultConsistencyChecks()));
812 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
a8cdaf5c 813 fCheckpointsEnabled = GetBoolArg("-checkpoints", true);
d07eaba1 814
f9cae832 815 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
5409404d 816 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
ebd7e8bf
DS
817 if (nScriptCheckThreads <= 0)
818 nScriptCheckThreads += boost::thread::hardware_concurrency();
69e07747 819 if (nScriptCheckThreads <= 1)
f9cae832
PW
820 nScriptCheckThreads = 0;
821 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
822 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
823
8b9adca4 824 fServer = GetBoolArg("-server", false);
f9ec3f0f 825
826 // block pruning; get the amount of disk space (in MB) to allot for block & undo files
827 int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
828 if (nSignedPruneTarget < 0) {
829 return InitError(_("Prune cannot be configured with a negative value."));
830 }
831 nPruneTarget = (uint64_t) nSignedPruneTarget;
832 if (nPruneTarget) {
833 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
834 return InitError(strprintf(_("Prune configured below the minimum of %d MB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
835 }
836 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
837 fPruneMode = true;
838 }
839
48ba56cd 840#ifdef ENABLE_WALLET
e6b7e3dc 841 bool fDisableWallet = GetBoolArg("-disablewallet", false);
48ba56cd 842#endif
69d605f4 843
de10efd1
PK
844 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
845 if (nConnectTimeout <= 0)
846 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
7d80d2e3 847
000dc551
GA
848 // Fee-per-kilobyte amount considered the same as "free"
849 // If you are mining, be careful setting this:
850 // if you set it to zero then
851 // a transaction spammer can cheaply fill blocks using
852 // 1-satoshi-fee transactions. It should be set above the real
853 // cost to you of processing a transaction.
000dc551
GA
854 if (mapArgs.count("-minrelaytxfee"))
855 {
a372168e 856 CAmount n = 0;
000dc551 857 if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
13fc83c7 858 ::minRelayTxFee = CFeeRate(n);
000dc551 859 else
7d9d134b 860 return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
000dc551 861 }
7d80d2e3 862
cd7fa8bb 863#ifdef ENABLE_WALLET
13fc83c7
GA
864 if (mapArgs.count("-mintxfee"))
865 {
a372168e 866 CAmount n = 0;
13fc83c7
GA
867 if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
868 CWallet::minTxFee = CFeeRate(n);
869 else
870 return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
871 }
7d80d2e3
PW
872 if (mapArgs.count("-paytxfee"))
873 {
a372168e 874 CAmount nFeePerK = 0;
c6cb21d1 875 if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
7d9d134b 876 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
c6cb21d1 877 if (nFeePerK > nHighTransactionFeeWarning)
e6bc9c35 878 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
c6cb21d1 879 payTxFee = CFeeRate(nFeePerK, 1000);
13fc83c7 880 if (payTxFee < ::minRelayTxFee)
b33d1f5e
GA
881 {
882 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
13fc83c7 883 mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
b33d1f5e 884 }
7d80d2e3 885 }
aa279d61
GM
886 if (mapArgs.count("-maxtxfee"))
887 {
888 CAmount nMaxFee = 0;
889 if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
890 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maptxfee"]));
891 if (nMaxFee > nHighTransactionMaxFeeWarning)
892 InitWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction."));
893 maxTxFee = nMaxFee;
894 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
895 {
896 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
897 mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
898 }
899 }
77ed59df 900 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
472b4c5d
AM
901 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", true);
902 fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false);
7d80d2e3 903
7d4dda76 904 std::string strWalletFile = GetArg("-wallet", "wallet.dat");
3da434a2
JG
905#endif // ENABLE_WALLET
906
472b4c5d 907 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true);
2aa63292 908 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
3da434a2 909
4d9c7fe6
WL
910 fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
911
7d80d2e3 912 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
20a11ffa 913
a56054be
PW
914 // Initialize elliptic curve code
915 ECC_Start();
916
4a09e1df
AP
917 // Sanity check
918 if (!InitSanityCheck())
919 return InitError(_("Initialization sanity check failed. Bitcoin Core is shutting down."));
7d80d2e3 920
22bb0490 921 std::string strDataDir = GetDataDir().string();
48ba56cd 922#ifdef ENABLE_WALLET
674cb304
NS
923 // Wallet file must be a plain filename without a directory
924 if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
7d9d134b 925 return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
48ba56cd 926#endif
7d80d2e3
PW
927 // Make sure only a single Bitcoin process is using the data directory.
928 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
929 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
930 if (file) fclose(file);
ffdda4e8
AW
931
932 try {
933 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
934 if (!lock.try_lock())
935 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running."), strDataDir));
936 } catch(const boost::interprocess::interprocess_exception& e) {
937 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin Core is probably already running.") + " %s.", strDataDir, e.what()));
938 }
939
d6712db3
WL
940#ifndef WIN32
941 CreatePidFile(GetPidFile(), getpid());
942#endif
7f1de3fe 943 if (GetBoolArg("-shrinkdebugfile", !fDebug))
69d605f4 944 ShrinkDebugFile();
881a85a2 945 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
7d9d134b 946 LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
881a85a2 947 LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
d0a2e2eb
WL
948#ifdef ENABLE_WALLET
949 LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
950#endif
dcb14198 951 if (!fLogTimestamps)
7d9d134b
WL
952 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
953 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
954 LogPrintf("Using data directory %s\n", strDataDir);
5bd02cf7 955 LogPrintf("Using config file %s\n", GetConfigFile().string());
881a85a2 956 LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
7d80d2e3 957 std::ostringstream strErrors;
69d605f4 958
9bdec760 959 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
f9cae832 960 if (nScriptCheckThreads) {
f9cae832 961 for (int i=0; i<nScriptCheckThreads-1; i++)
21eb5ada 962 threadGroup.create_thread(&ThreadScriptCheck);
f9cae832
PW
963 }
964
ddd0acd3
GA
965 // Start the lightweight task scheduler thread
966 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
967 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
968
af82884a
DK
969 /* Start the RPC server already. It will be started in "warmup" mode
970 * and not really process calls already (but it will signify connections
971 * that the server is there and will be ready later). Warmup mode will
972 * be disabled when initialisation is finished.
973 */
974 if (fServer)
975 {
976 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
4401b2d7
EL
977 RPCServer::OnStopped(&OnRPCStopped);
978 RPCServer::OnPreCommand(&OnRPCPreCommand);
af82884a
DK
979 StartRPCThreads();
980 }
981
51ed9ec9 982 int64_t nStart;
7d80d2e3 983
06494cab 984 // ********************************************************* Step 5: verify wallet database integrity
48ba56cd 985#ifdef ENABLE_WALLET
e6b7e3dc 986 if (!fDisableWallet) {
8a6894ca 987 LogPrintf("Using wallet %s\n", strWalletFile);
f9ee7a03 988 uiInterface.InitMessage(_("Verifying wallet..."));
eed1785f 989
2bb1c877
JS
990 std::string warningString;
991 std::string errorString;
992
993 if (!CWallet::Verify(strWalletFile, warningString, errorString))
994 return false;
995
996 if (!warningString.empty())
997 InitWarning(warningString);
998 if (!errorString.empty())
999 return InitError(warningString);
1000
e6b7e3dc 1001 } // (!fDisableWallet)
48ba56cd 1002#endif // ENABLE_WALLET
eed1785f 1003 // ********************************************************* Step 6: network initialization
7d80d2e3 1004
501da250 1005 RegisterNodeSignals(GetNodeSignals());
0e4b3175 1006
7d80d2e3
PW
1007 if (mapArgs.count("-onlynet")) {
1008 std::set<enum Network> nets;
1009 BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
1010 enum Network net = ParseNetwork(snet);
1011 if (net == NET_UNROUTABLE)
7d9d134b 1012 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
7d80d2e3
PW
1013 nets.insert(net);
1014 }
1015 for (int n = 0; n < NET_MAX; n++) {
1016 enum Network net = (enum Network)n;
1017 if (!nets.count(net))
1018 SetLimited(net);
1019 }
1020 }
1021
dc942e6f
PW
1022 if (mapArgs.count("-whitelist")) {
1023 BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
1024 CSubNet subnet(net);
1025 if (!subnet.IsValid())
1026 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1027 CNode::AddWhitelistedRange(subnet);
1028 }
1029 }
1030
67a79493 1031 proxyType addrProxy;
54ce3bad 1032 bool fProxy = false;
587f929c 1033 if (mapArgs.count("-proxy")) {
472b4c5d 1034 addrProxy = proxyType(CService(mapArgs["-proxy"], 9050), GetBoolArg("-proxyrandomize", true));
587f929c 1035 if (!addrProxy.IsValid())
7d9d134b 1036 return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"]));
587f929c 1037
3c777141
GM
1038 SetProxy(NET_IPV4, addrProxy);
1039 SetProxy(NET_IPV6, addrProxy);
0127a9be 1040 SetNameProxy(addrProxy);
54ce3bad
PW
1041 fProxy = true;
1042 }
1043
67a79493 1044 // -onion can override normal proxy, -noonion disables connecting to .onion entirely
102518fd 1045 if (!(mapArgs.count("-onion") && mapArgs["-onion"] == "0") &&
1c750dbd 1046 (fProxy || mapArgs.count("-onion"))) {
67a79493 1047 proxyType addrOnion;
1c750dbd 1048 if (!mapArgs.count("-onion"))
54ce3bad
PW
1049 addrOnion = addrProxy;
1050 else
472b4c5d 1051 addrOnion = proxyType(CService(mapArgs["-onion"], 9050), GetBoolArg("-proxyrandomize", true));
54ce3bad 1052 if (!addrOnion.IsValid())
1c750dbd 1053 return InitError(strprintf(_("Invalid -onion address: '%s'"), mapArgs["-onion"]));
0127a9be 1054 SetProxy(NET_TOR, addrOnion);
54ce3bad 1055 SetReachable(NET_TOR);
587f929c
PW
1056 }
1057
1058 // see Step 2: parameter interactions for more information about these
56b07d2d 1059 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
587f929c
PW
1060 fDiscover = GetBoolArg("-discover", true);
1061 fNameLookup = GetBoolArg("-dns", true);
928d3a01 1062
7d80d2e3 1063 bool fBound = false;
53a08815 1064 if (fListen) {
dc942e6f 1065 if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
7d80d2e3
PW
1066 BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
1067 CService addrBind;
1068 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
7d9d134b 1069 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
c73323ee 1070 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
7d80d2e3 1071 }
dc942e6f
PW
1072 BOOST_FOREACH(std::string strBind, mapMultiArgs["-whitebind"]) {
1073 CService addrBind;
1074 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1075 return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
1076 if (addrBind.GetPort() == 0)
1077 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1078 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1079 }
c73323ee
PK
1080 }
1081 else {
7d80d2e3
PW
1082 struct in_addr inaddr_any;
1083 inaddr_any.s_addr = INADDR_ANY;
c73323ee 1084 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
c73323ee 1085 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
7d80d2e3
PW
1086 }
1087 if (!fBound)
587f929c 1088 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
928d3a01
JG
1089 }
1090
c73323ee 1091 if (mapArgs.count("-externalip")) {
7d80d2e3
PW
1092 BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
1093 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
1094 if (!addrLocal.IsValid())
7d9d134b 1095 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
7d80d2e3
PW
1096 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
1097 }
1098 }
1099
587f929c
PW
1100 BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
1101 AddOneShot(strDest);
1102
729b1806 1103 // ********************************************************* Step 7: load block chain
7d80d2e3 1104
3260b4c0 1105 fReindex = GetBoolArg("-reindex", false);
7fea4846 1106
f4445f99 1107 // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
a3241998
CF
1108 boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1109 if (!boost::filesystem::exists(blocksDir))
f4445f99 1110 {
a3241998 1111 boost::filesystem::create_directories(blocksDir);
f4445f99
GA
1112 bool linked = false;
1113 for (unsigned int i = 1; i < 10000; i++) {
a3241998
CF
1114 boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1115 if (!boost::filesystem::exists(source)) break;
1116 boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
f4445f99 1117 try {
a3241998 1118 boost::filesystem::create_hard_link(source, dest);
7d9d134b 1119 LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
f4445f99 1120 linked = true;
a3241998 1121 } catch (const boost::filesystem::filesystem_error& e) {
f4445f99
GA
1122 // Note: hardlink creation failing is not a disaster, it just means
1123 // blocks will get re-downloaded from peers.
5262fde0 1124 LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
f4445f99
GA
1125 break;
1126 }
1127 }
1128 if (linked)
1129 {
1130 fReindex = true;
1131 }
1132 }
1133
1c83b0a3 1134 // cache size calculations
b3ed4236
PW
1135 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1136 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1137 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache
1138 int64_t nBlockTreeDBCache = nTotalCache / 8;
2d1fa42e 1139 if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
1c83b0a3
PW
1140 nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
1141 nTotalCache -= nBlockTreeDBCache;
b3ed4236 1142 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1c83b0a3 1143 nTotalCache -= nCoinDBCache;
b3ed4236
PW
1144 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1145 LogPrintf("Cache configuration:\n");
1146 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1147 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1148 LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
1c83b0a3 1149
f7f3a96b
PW
1150 bool fLoaded = false;
1151 while (!fLoaded) {
1152 bool fReset = fReindex;
1153 std::string strLoadError;
bb41a87d 1154
f7f3a96b 1155 uiInterface.InitMessage(_("Loading block index..."));
ae8bfd12 1156
f7f3a96b
PW
1157 nStart = GetTimeMillis();
1158 do {
1159 try {
1160 UnloadBlockIndex();
1161 delete pcoinsTip;
1162 delete pcoinsdbview;
13cdce43 1163 delete pcoinscatcher;
f7f3a96b
PW
1164 delete pblocktree;
1165
1166 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1167 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
13cdce43
PW
1168 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1169 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
f7f3a96b 1170
f9ec3f0f 1171 if (fReindex) {
f7f3a96b 1172 pblocktree->WriteReindexing(true);
6cb70ca4 1173 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
f9ec3f0f 1174 if (fPruneMode)
6cb70ca4 1175 CleanupBlockRevFiles();
f9ec3f0f 1176 }
f7f3a96b
PW
1177
1178 if (!LoadBlockIndex()) {
1179 strLoadError = _("Error loading block database");
1180 break;
1181 }
1182
5d274c99
PW
1183 // If the loaded chain has a wrong genesis, bail out immediately
1184 // (we're likely using a testnet datadir, or the other way around).
4e382177 1185 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
5d274c99
PW
1186 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1187
f7f3a96b
PW
1188 // Initialize the block index (no-op if non-empty database was already loaded)
1189 if (!InitBlockIndex()) {
1190 strLoadError = _("Error initializing block database");
1191 break;
1192 }
1193
067a6092
PW
1194 // Check for changed -txindex state
1195 if (fTxIndex != GetBoolArg("-txindex", false)) {
1196 strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1197 break;
1198 }
1199
f9ec3f0f 1200 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1201 // in the past, but is now trying to run unpruned.
1202 if (fHavePruned && !fPruneMode) {
1203 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1204 break;
1205 }
1206
e1ca89df 1207 uiInterface.InitMessage(_("Verifying blocks..."));
f9ec3f0f 1208 if (fHavePruned && GetArg("-checkblocks", 288) > MIN_BLOCKS_TO_KEEP) {
1209 LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
1210 MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", 288));
1211 }
2e280311 1212 if (!CVerifyDB().VerifyDB(pcoinsdbview, GetArg("-checklevel", 3),
d78900cc 1213 GetArg("-checkblocks", 288))) {
f7f3a96b
PW
1214 strLoadError = _("Corrupted block database detected");
1215 break;
1216 }
27df4123 1217 } catch (const std::exception& e) {
881a85a2 1218 if (fDebug) LogPrintf("%s\n", e.what());
f7f3a96b
PW
1219 strLoadError = _("Error opening block database");
1220 break;
1221 }
1f355b66 1222
f7f3a96b
PW
1223 fLoaded = true;
1224 } while(false);
1225
1226 if (!fLoaded) {
1227 // first suggest a reindex
1228 if (!fReset) {
1229 bool fRet = uiInterface.ThreadSafeMessageBox(
0206e38d 1230 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
f7f3a96b
PW
1231 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1232 if (fRet) {
1233 fReindex = true;
1234 fRequestShutdown = false;
1235 } else {
881a85a2 1236 LogPrintf("Aborted block database rebuild. Exiting.\n");
f7f3a96b
PW
1237 return false;
1238 }
1239 } else {
1240 return InitError(strLoadError);
1241 }
1242 }
1243 }
871c3557 1244
46469d0f
PK
1245 // As LoadBlockIndex can take several minutes, it's possible the user
1246 // requested to kill the GUI during the last operation. If so, exit.
871c3557
B
1247 // As the program has not fully started yet, Shutdown() is possibly overkill.
1248 if (fRequestShutdown)
1249 {
881a85a2 1250 LogPrintf("Shutdown requested. Exiting.\n");
871c3557
B
1251 return false;
1252 }
f48742c2 1253 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
69d605f4 1254
171ca774 1255 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
eee030f6 1256 CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
00d1980b 1257 // Allowed to fail as this file IS missing on first startup.
a8738238 1258 if (!est_filein.IsNull())
171ca774 1259 mempool.ReadFeeEstimates(est_filein);
94064710 1260 fFeeEstimatesInitialized = true;
171ca774 1261
d66877af
SB
1262 // These must be disabled for now, they are buggy and we probably don't
1263 // want any of libsnark's profiling in production anyway.
1264 libsnark::inhibit_profiling_info = true;
1265 libsnark::inhibit_profiling_counters = true;
1266
eed1785f 1267 // ********************************************************* Step 8: load wallet
48ba56cd 1268#ifdef ENABLE_WALLET
e6b7e3dc
JG
1269 if (fDisableWallet) {
1270 pwalletMain = NULL;
1271 LogPrintf("Wallet disabled!\n");
1272 } else {
77cbd462
CL
1273
1274 // needed to restore wallet transaction meta data after -zapwallettxes
1275 std::vector<CWalletTx> vWtx;
1276
518f3bda
JG
1277 if (GetBoolArg("-zapwallettxes", false)) {
1278 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
1279
1280 pwalletMain = new CWallet(strWalletFile);
77cbd462 1281 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
518f3bda
JG
1282 if (nZapWalletRet != DB_LOAD_OK) {
1283 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
1284 return false;
1285 }
1286
1287 delete pwalletMain;
1288 pwalletMain = NULL;
1289 }
1290
f9ee7a03 1291 uiInterface.InitMessage(_("Loading wallet..."));
bb41a87d 1292
f9ee7a03
JG
1293 nStart = GetTimeMillis();
1294 bool fFirstRun = true;
1295 pwalletMain = new CWallet(strWalletFile);
1296 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
1297 if (nLoadWalletRet != DB_LOAD_OK)
eed1785f 1298 {
f9ee7a03
JG
1299 if (nLoadWalletRet == DB_CORRUPT)
1300 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
1301 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
1302 {
1303 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
1304 " or address book entries might be missing or incorrect."));
1305 InitWarning(msg);
1306 }
1307 else if (nLoadWalletRet == DB_TOO_NEW)
2b410c2f 1308 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin Core") << "\n";
f9ee7a03
JG
1309 else if (nLoadWalletRet == DB_NEED_REWRITE)
1310 {
2b410c2f 1311 strErrors << _("Wallet needed to be rewritten: restart Bitcoin Core to complete") << "\n";
7d9d134b 1312 LogPrintf("%s", strErrors.str());
f9ee7a03
JG
1313 return InitError(strErrors.str());
1314 }
1315 else
1316 strErrors << _("Error loading wallet.dat") << "\n";
eed1785f 1317 }
f9ee7a03
JG
1318
1319 if (GetBoolArg("-upgradewallet", fFirstRun))
d764d916 1320 {
f9ee7a03
JG
1321 int nMaxVersion = GetArg("-upgradewallet", 0);
1322 if (nMaxVersion == 0) // the -upgradewallet without argument case
1323 {
1324 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
1325 nMaxVersion = CLIENT_VERSION;
1326 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
1327 }
1328 else
1329 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
1330 if (nMaxVersion < pwalletMain->GetVersion())
1331 strErrors << _("Cannot downgrade wallet") << "\n";
1332 pwalletMain->SetMaxVersion(nMaxVersion);
d764d916 1333 }
439e1497 1334
f9ee7a03 1335 if (fFirstRun)
439e1497 1336 {
f9ee7a03
JG
1337 // Create new keyUser and set as default key
1338 RandAddSeedPerfmon();
1339
1340 CPubKey newDefaultKey;
1341 if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
1342 pwalletMain->SetDefaultKey(newDefaultKey);
1343 if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
1344 strErrors << _("Cannot write default address") << "\n";
1345 }
439e1497 1346
f9ee7a03 1347 pwalletMain->SetBestChain(chainActive.GetLocator());
360cfe14 1348 }
95c7db3d 1349
7d9d134b 1350 LogPrintf("%s", strErrors.str());
f48742c2 1351 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
69d605f4 1352
a96d1139 1353 RegisterValidationInterface(pwalletMain);
e8ef3da7 1354
f9ee7a03
JG
1355 CBlockIndex *pindexRescan = chainActive.Tip();
1356 if (GetBoolArg("-rescan", false))
4c6d41b8 1357 pindexRescan = chainActive.Genesis();
f9ee7a03
JG
1358 else
1359 {
1360 CWalletDB walletdb(strWalletFile);
1361 CBlockLocator locator;
1362 if (walletdb.ReadBestBlock(locator))
6db83db3 1363 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
f9ee7a03
JG
1364 else
1365 pindexRescan = chainActive.Genesis();
1366 }
1367 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
1368 {
1369 uiInterface.InitMessage(_("Rescanning..."));
1370 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
1371 nStart = GetTimeMillis();
1372 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
f48742c2 1373 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
f9ee7a03
JG
1374 pwalletMain->SetBestChain(chainActive.GetLocator());
1375 nWalletDBUpdated++;
77cbd462
CL
1376
1377 // Restore wallet transaction metadata after -zapwallettxes=1
1378 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
1379 {
44bc988e
CL
1380 CWalletDB walletdb(strWalletFile);
1381
77cbd462
CL
1382 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
1383 {
1384 uint256 hash = wtxOld.GetHash();
1385 std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
1386 if (mi != pwalletMain->mapWallet.end())
1387 {
1388 const CWalletTx* copyFrom = &wtxOld;
1389 CWalletTx* copyTo = &mi->second;
1390 copyTo->mapValue = copyFrom->mapValue;
1391 copyTo->vOrderForm = copyFrom->vOrderForm;
1392 copyTo->nTimeReceived = copyFrom->nTimeReceived;
1393 copyTo->nTimeSmart = copyFrom->nTimeSmart;
1394 copyTo->fFromMe = copyFrom->fFromMe;
1395 copyTo->strFromAccount = copyFrom->strFromAccount;
1396 copyTo->nOrderPos = copyFrom->nOrderPos;
44bc988e 1397 copyTo->WriteToDisk(&walletdb);
77cbd462
CL
1398 }
1399 }
1400 }
f9ee7a03 1401 }
6f252627 1402 pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true));
e6b7e3dc 1403 } // (!fDisableWallet)
48ba56cd 1404#else // ENABLE_WALLET
a60bfd81 1405 LogPrintf("No wallet support compiled in!\n");
48ba56cd 1406#endif // !ENABLE_WALLET
e6adac7b
AW
1407
1408 // ********************************************************* Step 9: data directory maintenance
1409
1410 // if pruning, unset the service bit and perform the initial blockstore prune
1411 // after any wallet rescanning has taken place.
1412 if (fPruneMode) {
e6adac7b
AW
1413 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1414 nLocalServices &= ~NODE_NETWORK;
1415 if (!fReindex) {
dfe55bdc 1416 uiInterface.InitMessage(_("Pruning blockstore..."));
e6adac7b
AW
1417 PruneAndFlush();
1418 }
1419 }
1420
1421 // ********************************************************* Step 10: import blocks
0fcf91ea 1422
c7b6117d
JG
1423 if (mapArgs.count("-blocknotify"))
1424 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1425
04140457 1426 uiInterface.InitMessage(_("Activating best chain..."));
4fea06db 1427 // scan for better chains in the block chain database, that are not yet connected in the active best chain
ef3988ca 1428 CValidationState state;
75f51f2a 1429 if (!ActivateBestChain(state))
857c61df 1430 strErrors << "Failed to connect best block";
4fea06db 1431
21eb5ada 1432 std::vector<boost::filesystem::path> vImportFiles;
7d80d2e3 1433 if (mapArgs.count("-loadblock"))
69d605f4 1434 {
7d80d2e3 1435 BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
21eb5ada 1436 vImportFiles.push_back(strFile);
52c90a2b 1437 }
21eb5ada 1438 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
ff09e31a
MC
1439 if (chainActive.Tip() == NULL) {
1440 LogPrintf("Waiting for genesis block to be imported...\n");
1441 while (!fRequestShutdown && chainActive.Tip() == NULL)
1442 MilliSleep(10);
1443 }
52c90a2b 1444
e6adac7b 1445 // ********************************************************* Step 11: start node
69d605f4 1446
69d605f4
WL
1447 if (!CheckDiskSpace())
1448 return false;
1449
d605bc4c
GA
1450 if (!strErrors.str().empty())
1451 return InitError(strErrors.str());
1452
69d605f4
WL
1453 RandAddSeedPerfmon();
1454
7d80d2e3 1455 //// debug print
783b182c 1456 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
4c6d41b8 1457 LogPrintf("nBestHeight = %d\n", chainActive.Height());
48ba56cd 1458#ifdef ENABLE_WALLET
783b182c
WL
1459 LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
1460 LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
1461 LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
48ba56cd 1462#endif
7d80d2e3 1463
9a1dcea2 1464 StartNode(threadGroup, scheduler);
e6334f4a 1465
36cba8f1
GA
1466 // Monitor the chain, and alert if we get blocks much quicker or slower than expected
1467 int64_t nPowTargetSpacing = Params().GetConsensus().nPowTargetSpacing;
1468 CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload,
fce474c9 1469 boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing);
36cba8f1 1470 scheduler.scheduleEvery(f, nPowTargetSpacing);
e6334f4a 1471
48ba56cd 1472#ifdef ENABLE_WALLET
a0cafb79 1473 // Generate coins in the background
b0730874 1474 if (pwalletMain)
f654f004 1475 GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 1));
48ba56cd 1476#endif
a0cafb79 1477
94064710 1478 // ********************************************************* Step 11: finished
7d80d2e3 1479
af82884a 1480 SetRPCWarmupFinished();
7d80d2e3 1481 uiInterface.InitMessage(_("Done loading"));
7d80d2e3 1482
48ba56cd 1483#ifdef ENABLE_WALLET
b0730874
JG
1484 if (pwalletMain) {
1485 // Add wallet transactions that aren't already in a block to mapTransactions
1486 pwalletMain->ReacceptWalletTransactions();
7d80d2e3 1487
b0730874
JG
1488 // Run a thread to flush wallet periodically
1489 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1490 }
48ba56cd 1491#endif
69d605f4 1492
b31499ec 1493 return !fRequestShutdown;
69d605f4 1494}
This page took 0.518951 seconds and 4 git commands to generate.