]> Git Repo - VerusCoin.git/blame - src/init.cpp
Network upgrade activation mechanism
[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"
2902ac7c 11#include "crypto/common.h"
51ed9ec9 12#include "addrman.h"
eda37330 13#include "amount.h"
8e8b6d70
JG
14#ifdef ENABLE_MINING
15#include "base58.h"
16#endif
51ed9ec9 17#include "checkpoints.h"
611116d4 18#include "compat/sanity.h"
da29ecbc 19#include "consensus/validation.h"
afd64f76
WL
20#include "httpserver.h"
21#include "httprpc.h"
4a09e1df 22#include "key.h"
a9a37c8b 23#include "main.h"
a6df7ab5 24#include "metrics.h"
d247a5d1 25#include "miner.h"
51ed9ec9 26#include "net.h"
a9a37c8b 27#include "rpcserver.h"
2aa63292 28#include "script/standard.h"
ddd0acd3 29#include "scheduler.h"
51ed9ec9 30#include "txdb.h"
eb5f63fe 31#include "torcontrol.h"
ed6d0b5f 32#include "ui_interface.h"
51ed9ec9 33#include "util.h"
ad49c256 34#include "utilmoneystr.h"
cbb2cf55 35#include "validationinterface.h"
48ba56cd 36#ifdef ENABLE_WALLET
50c72f23
JS
37#include "wallet/wallet.h"
38#include "wallet/walletdb.h"
48ba56cd 39#endif
51ed9ec9 40#include <stdint.h>
283e405c 41#include <stdio.h>
69d605f4 42
ed6d0b5f
PW
43#ifndef WIN32
44#include <signal.h>
52d3a481 45#endif
5f2e76b8 46
51ed9ec9 47#include <boost/algorithm/string/predicate.hpp>
e9dd83f0 48#include <boost/algorithm/string/replace.hpp>
36cba8f1 49#include <boost/bind.hpp>
51ed9ec9 50#include <boost/filesystem.hpp>
36cba8f1 51#include <boost/function.hpp>
51ed9ec9 52#include <boost/interprocess/sync/file_lock.hpp>
ad49c256 53#include <boost/thread.hpp>
51ed9ec9
BD
54#include <openssl/crypto.h>
55
fee88353 56#include <libsnark/common/profiling.hpp>
d66877af 57
f200002c
JG
58#if ENABLE_ZMQ
59#include "zmq/zmqnotificationinterface.h"
60#endif
61
99eb947a
S
62#if ENABLE_PROTON
63#include "amqp/amqpnotificationinterface.h"
64#endif
65
00d1980b 66using namespace std;
69d605f4 67
b39e1bdb
S
68extern void ThreadSendAlert();
69
2dc35992 70ZCJoinSplit* pzcashParams = NULL;
4f1c3798 71
48ba56cd 72#ifdef ENABLE_WALLET
20a11ffa 73CWallet* pwalletMain = NULL;
48ba56cd 74#endif
94064710 75bool fFeeEstimatesInitialized = false;
e8ef3da7 76
f200002c
JG
77#if ENABLE_ZMQ
78static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
79#endif
80
99eb947a
S
81#if ENABLE_PROTON
82static AMQPNotificationInterface* pAMQPNotificationInterface = NULL;
83#endif
84
ba29a559 85#ifdef WIN32
df22af00 86// Win32 LevelDB doesn't use file descriptors, and the ones used for
7e6d23b1 87// accessing block files don't count towards the fd_set size limit
ba29a559
PW
88// anyway.
89#define MIN_CORE_FILEDESCRIPTORS 0
90#else
91#define MIN_CORE_FILEDESCRIPTORS 150
92#endif
93
c5b390b6 94/** Used to pass flags to the Bind() function */
c73323ee 95enum BindFlags {
29e214aa
PK
96 BF_NONE = 0,
97 BF_EXPLICIT = (1U << 0),
dc942e6f
PW
98 BF_REPORT_ERROR = (1U << 1),
99 BF_WHITELIST = (1U << 2),
c73323ee
PK
100};
101
171ca774 102static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
b74dcb3b 103CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h
4751d07e 104
69d605f4
WL
105//////////////////////////////////////////////////////////////////////////////
106//
107// Shutdown
108//
109
b31499ec
GA
110//
111// Thread management and startup/shutdown:
112//
113// The network-processing threads are all part of a thread group
07cf4264 114// created by AppInit().
b31499ec
GA
115//
116// A clean exit happens when StartShutdown() or the SIGTERM
117// signal handler sets fRequestShutdown, which triggers
118// the DetectShutdownThread(), which interrupts the main thread group.
119// DetectShutdownThread() then exits, which causes AppInit() to
120// continue (it .joins the shutdown thread).
121// Shutdown() is then
122// called to clean up database connections, and stop other
123// threads that should only be stopped after the main network-processing
124// threads have exited.
125//
126// Note that if running -daemon the parent process returns from AppInit2
127// before adding any threads to the threadGroup, so .join_all() returns
128// immediately and the parent exits from main().
129//
b31499ec 130
bf673640 131std::atomic<bool> fRequestShutdown(false);
69d605f4 132
9247134e
PK
133void StartShutdown()
134{
b31499ec 135 fRequestShutdown = true;
9247134e 136}
723035bb
GA
137bool ShutdownRequested()
138{
139 return fRequestShutdown;
140}
9247134e 141
13cdce43
PW
142class CCoinsViewErrorCatcher : public CCoinsViewBacked
143{
144public:
145 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
146 bool GetCoins(const uint256 &txid, CCoins &coins) const {
147 try {
148 return CCoinsViewBacked::GetCoins(txid, coins);
149 } catch(const std::runtime_error& e) {
150 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
151 LogPrintf("Error reading from database: %s\n", e.what());
152 // Starting the shutdown sequence and returning false to the caller would be
153 // interpreted as 'entry not found' (as opposed to unable to read data), and
c0692346 154 // could lead to invalid interpretation. Just exit immediately, as we can't
13cdce43
PW
155 // continue anyway, and all writes should be atomic.
156 abort();
157 }
158 }
159 // Writes do not need similar protection, as failure to write is handled by the caller.
160};
161
20a11ffa 162static CCoinsViewDB *pcoinsdbview = NULL;
13cdce43 163static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
3d02d0f6 164static boost::scoped_ptr<ECCVerifyHandle> globalVerifyHandle;
ae8bfd12 165
afd64f76
WL
166void Interrupt(boost::thread_group& threadGroup)
167{
168 InterruptHTTPServer();
169 InterruptHTTPRPC();
170 InterruptRPC();
171 InterruptREST();
975dc649 172 InterruptTorControl();
afd64f76
WL
173 threadGroup.interrupt_all();
174}
175
b31499ec 176void Shutdown()
69d605f4 177{
00d1980b 178 LogPrintf("%s: In progress...\n", __func__);
69d605f4 179 static CCriticalSection cs_Shutdown;
b31499ec 180 TRY_LOCK(cs_Shutdown, lockShutdown);
00d1980b
PK
181 if (!lockShutdown)
182 return;
96931d6f 183
94064710
WL
184 /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
185 /// for example if the data directory was found to be locked.
186 /// Be sure that anything that writes files or flushes caches only does this if the respective
187 /// module was initialized.
7662d72b 188 RenameThread("zcash-shutoff");
319b1160 189 mempool.AddTransactionsUpdated(1);
afd64f76
WL
190
191 StopHTTPRPC();
192 StopREST();
193 StopRPC();
194 StopHTTPServer();
4a85e067 195#ifdef ENABLE_WALLET
b0730874 196 if (pwalletMain)
2bb1c877 197 pwalletMain->Flush(false);
8e8b6d70
JG
198#endif
199#ifdef ENABLE_MINING
200 #ifdef ENABLE_WALLET
c8b74258 201 GenerateBitcoins(false, NULL, 0);
8e8b6d70
JG
202 #else
203 GenerateBitcoins(false, 0);
2cc0a252 204 #endif
48ba56cd 205#endif
21eb5ada 206 StopNode();
eb5f63fe 207 StopTorControl();
b2864d2f 208 UnregisterNodeSignals(GetNodeSignals());
171ca774 209
94064710 210 if (fFeeEstimatesInitialized)
09c744c2
PW
211 {
212 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
213 CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
a8738238 214 if (!est_fileout.IsNull())
09c744c2
PW
215 mempool.WriteFeeEstimates(est_fileout);
216 else
217 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
94064710 218 fFeeEstimatesInitialized = false;
09c744c2 219 }
171ca774 220
69d605f4 221 {
b31499ec 222 LOCK(cs_main);
51ce901a
PW
223 if (pcoinsTip != NULL) {
224 FlushStateToDisk();
225 }
00d1980b
PK
226 delete pcoinsTip;
227 pcoinsTip = NULL;
13cdce43
PW
228 delete pcoinscatcher;
229 pcoinscatcher = NULL;
00d1980b
PK
230 delete pcoinsdbview;
231 pcoinsdbview = NULL;
232 delete pblocktree;
233 pblocktree = NULL;
69d605f4 234 }
48ba56cd 235#ifdef ENABLE_WALLET
b0730874 236 if (pwalletMain)
2bb1c877 237 pwalletMain->Flush(true);
48ba56cd 238#endif
f200002c
JG
239
240#if ENABLE_ZMQ
241 if (pzmqNotificationInterface) {
242 UnregisterValidationInterface(pzmqNotificationInterface);
f200002c
JG
243 delete pzmqNotificationInterface;
244 pzmqNotificationInterface = NULL;
245 }
246#endif
247
99eb947a
S
248#if ENABLE_PROTON
249 if (pAMQPNotificationInterface) {
250 UnregisterValidationInterface(pAMQPNotificationInterface);
251 delete pAMQPNotificationInterface;
252 pAMQPNotificationInterface = NULL;
253 }
254#endif
255
d6712db3 256#ifndef WIN32
ffdda4e8
AW
257 try {
258 boost::filesystem::remove(GetPidFile());
259 } catch (const boost::filesystem::filesystem_error& e) {
260 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
261 }
d6712db3 262#endif
a96d1139 263 UnregisterAllValidationInterfaces();
48ba56cd 264#ifdef ENABLE_WALLET
20a11ffa
PK
265 delete pwalletMain;
266 pwalletMain = NULL;
48ba56cd 267#endif
7ee82c43
SB
268 delete pzcashParams;
269 pzcashParams = NULL;
3d02d0f6 270 globalVerifyHandle.reset();
a56054be 271 ECC_Stop();
00d1980b 272 LogPrintf("%s: done\n", __func__);
69d605f4
WL
273}
274
c5b390b6
MF
275/**
276 * Signal handlers are very limited in what they are allowed to do, so:
277 */
69d605f4
WL
278void HandleSIGTERM(int)
279{
280 fRequestShutdown = true;
281}
282
9af080c3
MH
283void HandleSIGHUP(int)
284{
285 fReopenDebugLog = true;
286}
69d605f4 287
ac7c7ab9
PW
288bool static InitError(const std::string &str)
289{
49d57125 290 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
ac7c7ab9 291 return false;
ac7c7ab9
PW
292}
293
294bool static InitWarning(const std::string &str)
295{
49d57125 296 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
ac7c7ab9
PW
297 return true;
298}
299
29e214aa 300bool static Bind(const CService &addr, unsigned int flags) {
c73323ee 301 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
8f10a288
PW
302 return false;
303 std::string strError;
8d657a65 304 if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
c73323ee 305 if (flags & BF_REPORT_ERROR)
587f929c
PW
306 return InitError(strError);
307 return false;
308 }
8f10a288
PW
309 return true;
310}
311
4401b2d7
EL
312void OnRPCStopped()
313{
314 cvBlockChange.notify_all();
315 LogPrint("rpc", "RPC stopped.\n");
316}
317
318void OnRPCPreCommand(const CRPCCommand& cmd)
319{
4401b2d7
EL
320 // Observe safe mode
321 string strWarning = GetWarnings("rpc");
322 if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
323 !cmd.okSafeMode)
324 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
325}
326
1020f599 327std::string HelpMessage(HelpMessageMode mode)
9f5b11e6 328{
94cd7051 329 const bool showDebug = GetBoolArg("-help-debug", false);
1fdb9fa3 330
1020f599 331 // When adding new options to the categories, please keep and ensure alphabetical ordering.
94cd7051
WL
332 // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators
333
1fdb9fa3
LV
334 string strUsage = HelpMessageGroup(_("Options:"));
335 strUsage += HelpMessageOpt("-?", _("This help message"));
4d9c7fe6 336 strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
1fdb9fa3
LV
337 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)"));
338 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
339 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 288));
340 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), 3));
aaf64959 341 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "zcash.conf"));
1020f599 342 if (mode == HMM_BITCOIND)
7398f4a7
CL
343 {
344#if !defined(WIN32)
1fdb9fa3 345 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
7398f4a7
CL
346#endif
347 }
1fdb9fa3 348 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
5b3bc971
JG
349 strUsage += HelpMessageOpt("-disabledeprecation=<version>", strprintf(_("Disable block-height node deprecation and automatic shutdown (example: -disabledeprecation=%s)"),
350 FormatVersion(CLIENT_VERSION)));
9064d73b 351 strUsage += HelpMessageOpt("-exportdir=<dir>", _("Specify directory to be used when exporting data"));
1fdb9fa3
LV
352 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
353 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup"));
354 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
da6d9391 355 strUsage += HelpMessageOpt("-mempooltxinputlimit=<n>", _("Set the maximum number of transparent inputs in a transaction that the mempool will accept (default: 0 = no limit applied)"));
1fdb9fa3 356 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)"),
da1357e6 357 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
d6712db3 358#ifndef WIN32
aaf64959 359 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "zcashd.pid"));
d6712db3 360#endif
fc44231c
WL
361 strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode disables wallet support and is incompatible with -txindex. "
362 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
363 "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
a1d0ec44 364 strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files on startup"));
bdd5b587 365#if !defined(WIN32)
1fdb9fa3 366 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
bdd5b587 367#endif
1fdb9fa3
LV
368 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
369
370 strUsage += HelpMessageGroup(_("Connection options:"));
371 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
372 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100));
373 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400));
374 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
375 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)"));
376 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
377 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)"));
378 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)"));
379 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
380 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0));
381 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
eb5f63fe 382 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
8a5ae3c7 383 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
1fdb9fa3
LV
384 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000));
385 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000));
386 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
387 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
388 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1));
3985a40d 389 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 8233, 18233));
1fdb9fa3 390 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
67a79493 391 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1));
1fdb9fa3
LV
392 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
393 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
eb5f63fe 394 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
975dc649 395 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
1fdb9fa3
LV
396 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
397 strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
398 " " + _("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"));
7398f4a7
CL
399
400#ifdef ENABLE_WALLET
1fdb9fa3
LV
401 strUsage += HelpMessageGroup(_("Wallet options:"));
402 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
403 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100));
94cd7051 404 if (showDebug)
091b2116
RN
405 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)",
406 CURRENCY_UNIT, FormatMoney(CWallet::minTxFee.GetFeePerK())));
407 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
408 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
409 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
1fdb9fa3
LV
410 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
411 strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
412 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1));
77ed59df 413 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));
091b2116
RN
414 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)"),
415 CURRENCY_UNIT, FormatMoney(maxTxFee)));
1fdb9fa3
LV
416 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup"));
417 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
6f252627 418 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), true));
1fdb9fa3
LV
419 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
420 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
421 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
7398f4a7
CL
422#endif
423
f200002c
JG
424#if ENABLE_ZMQ
425 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
426 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
57c6ef01 427 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
f200002c 428 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
57c6ef01 429 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
f200002c
JG
430#endif
431
99eb947a
S
432#if ENABLE_PROTON
433 strUsage += HelpMessageGroup(_("AMQP 1.0 notification options:"));
434 strUsage += HelpMessageOpt("-amqppubhashblock=<address>", _("Enable publish hash block in <address>"));
435 strUsage += HelpMessageOpt("-amqppubhashtx=<address>", _("Enable publish hash transaction in <address>"));
436 strUsage += HelpMessageOpt("-amqppubrawblock=<address>", _("Enable publish raw block in <address>"));
437 strUsage += HelpMessageOpt("-amqppubrawtx=<address>", _("Enable publish raw transaction in <address>"));
438#endif
439
1fdb9fa3 440 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
94cd7051 441 if (showDebug)
7398f4a7 442 {
bfa832c7 443 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", 1));
94cd7051
WL
444 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)", 100));
445 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", 0));
446 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", 0));
447 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
448 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
449 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", 1));
450 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", 0));
7398f4a7 451 }
a659991a 452 string debugCategories = "addrman, alert, bench, coindb, db, estimatefee, http, libevent, lock, mempool, net, partitioncheck, pow, proxy, prune, "
65fd8eb1 453 "rand, reindex, rpc, selectcoins, tor, zmq, zrpc, zrpcunsafe (implies zrpc)"; // Don't translate these
1fdb9fa3 454 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
53e9a6a0 455 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + debugCategories + ".");
1f015f6a 456 strUsage += HelpMessageOpt("-experimentalfeatures", _("Enable use of experimental features"));
1fdb9fa3
LV
457 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
458 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
459 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
94cd7051 460 if (showDebug)
3b570559 461 {
94cd7051 462 strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
a5150a15 463 strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 0));
94cd7051 464 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> entries (default: %u)", 50000));
3b570559 465 }
091b2116
RN
466 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying (default: %s)"),
467 CURRENCY_UNIT, FormatMoney(::minRelayTxFee.GetFeePerK())));
1fdb9fa3 468 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
94cd7051 469 if (showDebug)
3b570559 470 {
94cd7051
WL
471 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", 0));
472 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", 1));
473 strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
474 "This is intended for regression testing tools and app development.");
3b570559 475 }
1fdb9fa3
LV
476 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
477 strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
478
479 strUsage += HelpMessageGroup(_("Node relay options:"));
480 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1));
481 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
482
483 strUsage += HelpMessageGroup(_("Block creation options:"));
484 strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), 0));
485 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
486 strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
fbbd3cc6
PK
487 if (GetBoolArg("-help-debug", false))
488 strUsage += HelpMessageOpt("-blockversion=<n>", strprintf("Override block version to test forking scenarios (default: %d)", (int)CBlock::CURRENT_VERSION));
1fdb9fa3 489
78ba3472
JG
490#ifdef ENABLE_MINING
491 strUsage += HelpMessageGroup(_("Mining options:"));
492 strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0));
493 strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
494 strUsage += HelpMessageOpt("-equihashsolver=<name>", _("Specify the Equihash solver to be used if enabled (default: \"default\")"));
495 strUsage += HelpMessageOpt("-mineraddress=<addr>", _("Send mined coins to a specific single address"));
f49bcdf9
JG
496 strUsage += HelpMessageOpt("-minetolocalwallet", strprintf(
497 _("Require that mined blocks use a coinbase address in the local wallet (default: %u)"),
498 #ifdef ENABLE_WALLET
499 1
500 #else
501 0
502 #endif
503 ));
78ba3472
JG
504#endif
505
1fdb9fa3
LV
506 strUsage += HelpMessageGroup(_("RPC server options:"));
507 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
508 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0));
509 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)"));
510 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
511 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
3985a40d 512 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 8232, 18232));
1fdb9fa3 513 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"));
9fb5b94e
WL
514 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
515 if (showDebug) {
516 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
89bccddc 517 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
9fb5b94e 518 }
008fccfa
S
519
520 // Disabled until we can lock notes and also tune performance of libsnark which by default uses multiple threads
521 //strUsage += HelpMessageOpt("-rpcasyncthreads=<n>", strprintf(_("Set the number of threads to service Async RPC calls (default: %d)"), 1));
1fdb9fa3 522
07cf4264 523 if (mode == HMM_BITCOIND) {
18f656d2 524 strUsage += HelpMessageGroup(_("Metrics Options (only if -daemon and -printtoconsole are not set):"));
0076a80a
JG
525 strUsage += HelpMessageOpt("-showmetrics", _("Show metrics on stdout (default: 1 if running in a console, 0 otherwise)"));
526 strUsage += HelpMessageOpt("-metricsui", _("Set to 1 for a persistent metrics screen, 0 for sequential metrics output (default: 1 if running in a console, 0 otherwise)"));
527 strUsage += HelpMessageOpt("-metricsrefreshtime", strprintf(_("Number of seconds between metrics refreshes (default: %u if running in a console, %u otherwise)"), 1, 600));
f7547079
LV
528 }
529
9f5b11e6
WL
530 return strUsage;
531}
532
c7b6117d
JG
533static void BlockNotifyCallback(const uint256& hashNewTip)
534{
535 std::string strCmd = GetArg("-blocknotify", "");
536
537 boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
538 boost::thread t(runCommand, strCmd); // thread runs free
539}
540
7a5b7535
PW
541struct CImportingNow
542{
543 CImportingNow() {
544 assert(fImporting == false);
545 fImporting = true;
546 }
547
548 ~CImportingNow() {
549 assert(fImporting == true);
550 fImporting = false;
551 }
552};
553
f9ec3f0f 554
555// If we're using -prune with -reindex, then delete block files that will be ignored by the
556// reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
6cb70ca4
AW
557// is missing, do the same here to delete any later block files after a gap. Also delete all
558// rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
559// is in sync with what's actually on disk by the time we start downloading, so that pruning
560// works correctly.
561void CleanupBlockRevFiles()
f9ec3f0f 562{
6cb70ca4
AW
563 using namespace boost::filesystem;
564 map<string, path> mapBlockFiles;
565
566 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
567 // Remove the rev files immediately and insert the blk file paths into an
568 // ordered map keyed by block file index.
569 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
570 path blocksdir = GetDataDir() / "blocks";
571 for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
572 if (is_regular_file(*it) &&
573 it->path().filename().string().length() == 12 &&
574 it->path().filename().string().substr(8,4) == ".dat")
575 {
576 if (it->path().filename().string().substr(0,3) == "blk")
577 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
578 else if (it->path().filename().string().substr(0,3) == "rev")
579 remove(it->path());
580 }
581 }
f9ec3f0f 582
6cb70ca4
AW
583 // Remove all block files that aren't part of a contiguous set starting at
584 // zero by walking the ordered map (keys are block file indices) by
585 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
586 // start removing block files.
587 int nContigCounter = 0;
588 BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) {
589 if (atoi(item.first) == nContigCounter) {
590 nContigCounter++;
591 continue;
f9ec3f0f 592 }
6cb70ca4 593 remove(item.second);
f9ec3f0f 594 }
595}
596
21eb5ada
GA
597void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
598{
7662d72b 599 RenameThread("zcash-loadblk");
7fea4846
PW
600 // -reindex
601 if (fReindex) {
602 CImportingNow imp;
603 int nFile = 0;
21eb5ada 604 while (true) {
a8a4b967 605 CDiskBlockPos pos(nFile, 0);
ec7eb0fa
SD
606 if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
607 break; // No block files left to reindex
7fea4846
PW
608 FILE *file = OpenBlockFile(pos, true);
609 if (!file)
ec7eb0fa 610 break; // This error is logged in OpenBlockFile
881a85a2 611 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
7fea4846
PW
612 LoadExternalBlockFile(file, &pos);
613 nFile++;
614 }
21eb5ada
GA
615 pblocktree->WriteReindexing(false);
616 fReindex = false;
881a85a2 617 LogPrintf("Reindexing finished\n");
21eb5ada
GA
618 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
619 InitBlockIndex();
7a5b7535
PW
620 }
621
622 // hardcoded $DATADIR/bootstrap.dat
a3241998
CF
623 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
624 if (boost::filesystem::exists(pathBootstrap)) {
7a5b7535
PW
625 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
626 if (file) {
7fea4846 627 CImportingNow imp;
a3241998 628 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
881a85a2 629 LogPrintf("Importing bootstrap.dat...\n");
7a5b7535
PW
630 LoadExternalBlockFile(file);
631 RenameOver(pathBootstrap, pathBootstrapOld);
d54e819f
WL
632 } else {
633 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
7a5b7535
PW
634 }
635 }
636
7fea4846 637 // -loadblock=
db954a65 638 BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
7fea4846
PW
639 FILE *file = fopen(path.string().c_str(), "rb");
640 if (file) {
641 CImportingNow imp;
d54e819f 642 LogPrintf("Importing blocks file %s...\n", path.string());
7fea4846 643 LoadExternalBlockFile(file);
d54e819f
WL
644 } else {
645 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
7fea4846
PW
646 }
647 }
1569353b
WL
648
649 if (GetBoolArg("-stopafterblockimport", false)) {
650 LogPrintf("Stopping after block import\n");
651 StartShutdown();
652 }
7a5b7535
PW
653}
654
4a09e1df
AP
655/** Sanity checks
656 * Ensure that Bitcoin is running in a usable environment with all
657 * necessary library support.
658 */
659bool InitSanityCheck(void)
660{
661 if(!ECC_InitSanityCheck()) {
3d02d0f6 662 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
4a09e1df
AP
663 return false;
664 }
92a62207
CF
665 if (!glibc_sanity_test() || !glibcxx_sanity_test())
666 return false;
4a09e1df
AP
667
668 return true;
669}
670
4f1c3798
SB
671
672static void ZC_LoadParams()
673{
674 struct timeval tv_start, tv_end;
675 float elapsed;
676
27e3f362
SB
677 boost::filesystem::path pk_path = ZC_GetParamsDir() / "sprout-proving.key";
678 boost::filesystem::path vk_path = ZC_GetParamsDir() / "sprout-verifying.key";
4f1c3798 679
bddf4079
JG
680 if (!(boost::filesystem::exists(pk_path) && boost::filesystem::exists(vk_path))) {
681 uiInterface.ThreadSafeMessageBox(strprintf(
682 _("Cannot find the Zcash network parameters in the following directory:\n"
683 "%s\n"
0b0a48c8 684 "Please run 'zcash-fetch-params' or './zcutil/fetch-params.sh' and then restart."),
bddf4079
JG
685 ZC_GetParamsDir()),
686 "", CClientUIInterface::MSG_ERROR);
687 StartShutdown();
688 return;
689 }
690
f4091941 691 LogPrintf("Loading verifying key from %s\n", vk_path.string().c_str());
4f1c3798 692 gettimeofday(&tv_start, 0);
2dc35992 693
1a9543d0 694 pzcashParams = ZCJoinSplit::Prepared(vk_path.string(), pk_path.string());
2dc35992 695
4f1c3798
SB
696 gettimeofday(&tv_end, 0);
697 elapsed = float(tv_end.tv_sec-tv_start.tv_sec) + (tv_end.tv_usec-tv_start.tv_usec)/float(1000000);
f4091941 698 LogPrintf("Loaded verifying key in %fs seconds.\n", elapsed);
4f1c3798
SB
699}
700
afd64f76
WL
701bool AppInitServers(boost::thread_group& threadGroup)
702{
703 RPCServer::OnStopped(&OnRPCStopped);
704 RPCServer::OnPreCommand(&OnRPCPreCommand);
116503c0 705 if (!InitHTTPServer())
afd64f76
WL
706 return false;
707 if (!StartRPC())
708 return false;
709 if (!StartHTTPRPC())
710 return false;
711 if (GetBoolArg("-rest", false) && !StartREST())
712 return false;
c7f77e28 713 if (!StartHTTPServer())
116503c0 714 return false;
afd64f76
WL
715 return true;
716}
717
9f5b11e6
WL
718/** Initialize bitcoin.
719 * @pre Parameters should be parsed and config file should be read.
720 */
ddd0acd3 721bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
69d605f4 722{
7d80d2e3 723 // ********************************************************* Step 1: setup
69d605f4 724#ifdef _MSC_VER
814efd6f 725 // Turn off Microsoft heap dump noise
69d605f4
WL
726 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
727 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
728#endif
729#if _MSC_VER >= 1400
814efd6f 730 // Disable confusing "helpful" text message on abort, Ctrl-C
69d605f4
WL
731 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
732#endif
3d88c9b4
PK
733#ifdef WIN32
734 // Enable Data Execution Prevention (DEP)
735 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
736 // A failure is non-critical and needs no further attention!
737#ifndef PROCESS_DEP_ENABLE
f65dddc7
PK
738 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
739 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
3d88c9b4
PK
740#define PROCESS_DEP_ENABLE 0x00000001
741#endif
742 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
743 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
744 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
69d605f4 745#endif
bdd5b587 746
167b6231
WL
747 if (!SetupNetworking())
748 return InitError("Error: Initializing networking failed");
749
750#ifndef WIN32
bdd5b587
RS
751 if (GetBoolArg("-sysperms", false)) {
752#ifdef ENABLE_WALLET
753 if (!GetBoolArg("-disablewallet", false))
754 return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
755#endif
756 } else {
757 umask(077);
758 }
3d88c9b4 759
69d605f4
WL
760 // Clean shutdown on SIGTERM
761 struct sigaction sa;
762 sa.sa_handler = HandleSIGTERM;
763 sigemptyset(&sa.sa_mask);
764 sa.sa_flags = 0;
765 sigaction(SIGTERM, &sa, NULL);
766 sigaction(SIGINT, &sa, NULL);
9af080c3
MH
767
768 // Reopen debug.log on SIGHUP
769 struct sigaction sa_hup;
770 sa_hup.sa_handler = HandleSIGHUP;
771 sigemptyset(&sa_hup.sa_mask);
772 sa_hup.sa_flags = 0;
773 sigaction(SIGHUP, &sa_hup, NULL);
b34255b7 774
7ed4d40c 775 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
b34255b7 776 signal(SIGPIPE, SIG_IGN);
69d605f4
WL
777#endif
778
7d80d2e3 779 // ********************************************************* Step 2: parameter interactions
4e382177 780 const CChainParams& chainparams = Params();
13f90318 781
1f015f6a
JG
782 // Set this early so that experimental features are correctly enabled/disabled
783 fExperimentalMode = GetBoolArg("-experimentalfeatures", false);
784
b8eb3775
JG
785 // Fail early if user has set experimental options without the global flag
786 if (!fExperimentalMode) {
787 if (mapArgs.count("-developerencryptwallet")) {
788 return InitError(_("Wallet encryption requires -experimentalfeatures."));
789 }
45232b19
S
790 else if (mapArgs.count("-paymentdisclosure")) {
791 return InitError(_("Payment disclosure requires -experimentalfeatures."));
792 }
b8eb3775
JG
793 }
794
eadcd0c8
MC
795 // Set this early so that parameter interactions go to console
796 fPrintToConsole = GetBoolArg("-printtoconsole", false);
797 fLogTimestamps = GetBoolArg("-logtimestamps", true);
798 fLogIPs = GetBoolArg("-logips", false);
7d80d2e3 799
8550bcfe
AW
800 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
801 LogPrintf("Zcash version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
802
13f90318
PK
803 // when specifying an explicit binding address, you want to listen on it
804 // even when -connect or -proxy is specified
805 if (mapArgs.count("-bind")) {
806 if (SoftSetBoolArg("-listen", true))
807 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
808 }
809 if (mapArgs.count("-whitebind")) {
df966d1b 810 if (SoftSetBoolArg("-listen", true))
13f90318 811 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
587f929c 812 }
7d80d2e3 813
f161a2c2 814 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
587f929c 815 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
df966d1b 816 if (SoftSetBoolArg("-dnsseed", false))
13f90318 817 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
df966d1b 818 if (SoftSetBoolArg("-listen", false))
13f90318 819 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
587f929c
PW
820 }
821
822 if (mapArgs.count("-proxy")) {
df966d1b
PK
823 // to protect privacy, do not listen by default if a default proxy server is specified
824 if (SoftSetBoolArg("-listen", false))
13f90318 825 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
845c86d1
GM
826 // to protect privacy, do not discover addresses by default
827 if (SoftSetBoolArg("-discover", false))
13f90318 828 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
587f929c
PW
829 }
830
13f90318 831 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
506a2185 832 // do not try to retrieve public IP when not listening (pointless)
df966d1b 833 if (SoftSetBoolArg("-discover", false))
13f90318 834 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
eb5f63fe
WL
835 if (SoftSetBoolArg("-listenonion", false))
836 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
7d80d2e3
PW
837 }
838
587f929c
PW
839 if (mapArgs.count("-externalip")) {
840 // if an explicit public IP is specified, do not try to find others
df966d1b 841 if (SoftSetBoolArg("-discover", false))
13f90318 842 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
587f929c
PW
843 }
844
3260b4c0 845 if (GetBoolArg("-salvagewallet", false)) {
eed1785f 846 // Rewrite just private keys: rescan to find transactions
df966d1b 847 if (SoftSetBoolArg("-rescan", true))
13f90318 848 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
eed1785f
GA
849 }
850
518f3bda
JG
851 // -zapwallettx implies a rescan
852 if (GetBoolArg("-zapwallettxes", false)) {
853 if (SoftSetBoolArg("-rescan", true))
13f90318 854 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
518f3bda
JG
855 }
856
ba29a559 857 // Make sure enough file descriptors are available
dc942e6f 858 int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
8a5ae3c7 859 nMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
03f49808 860 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
ba29a559
PW
861 int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
862 if (nFD < MIN_CORE_FILEDESCRIPTORS)
863 return InitError(_("Not enough file descriptors available."));
864 if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
865 nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
866
f9ec3f0f 867 // if using block pruning, then disable txindex
868 // also disable the wallet (for now, until SPV support is implemented in wallet)
869 if (GetArg("-prune", 0)) {
870 if (GetBoolArg("-txindex", false))
871 return InitError(_("Prune mode is incompatible with -txindex."));
872#ifdef ENABLE_WALLET
873 if (!GetBoolArg("-disablewallet", false)) {
874 if (SoftSetBoolArg("-disablewallet", true))
875 LogPrintf("%s : parameter interaction: -prune -> setting -disablewallet=1\n", __func__);
876 else
877 return InitError(_("Can't run with a wallet in prune mode."));
878 }
879#endif
880 }
881
7d80d2e3
PW
882 // ********************************************************* Step 3: parameter-to-internal-flags
883
3b570559
PK
884 fDebug = !mapMultiArgs["-debug"].empty();
885 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
886 const vector<string>& categories = mapMultiArgs["-debug"];
887 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
888 fDebug = false;
889
3307124a
S
890 // Special case: if debug=zrpcunsafe, implies debug=zrpc, so add it to debug categories
891 if (find(categories.begin(), categories.end(), string("zrpcunsafe")) != categories.end()) {
892 if (find(categories.begin(), categories.end(), string("zrpc")) == categories.end()) {
43b67537 893 LogPrintf("%s: parameter interaction: setting -debug=zrpcunsafe -> -debug=zrpc\n", __func__);
3307124a
S
894 vector<string>& v = mapMultiArgs["-debug"];
895 v.push_back("zrpc");
896 }
897 }
898
00d1980b 899 // Check for -debugnet
3b570559 900 if (GetBoolArg("-debugnet", false))
00d1980b 901 InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
a339a37b
PK
902 // Check for -socks - as this is a privacy risk to continue, exit here
903 if (mapArgs.count("-socks"))
904 return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
1c750dbd
PK
905 // Check for -tor - as this is a privacy risk to continue, exit here
906 if (GetBoolArg("-tor", false))
907 return InitError(_("Error: Unsupported argument -tor found, use -onion."));
3b570559 908
d70bc52e
PW
909 if (GetBoolArg("-benchmark", false))
910 InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
911
3fcfbc8a 912 // Checkmempool and checkblockindex default to true in regtest mode
4e382177
JT
913 mempool.setSanityCheck(GetBoolArg("-checkmempool", chainparams.DefaultConsistencyChecks()));
914 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
a8cdaf5c 915 fCheckpointsEnabled = GetBoolArg("-checkpoints", true);
d07eaba1 916
f9cae832 917 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
5409404d 918 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
ebd7e8bf 919 if (nScriptCheckThreads <= 0)
da1357e6 920 nScriptCheckThreads += GetNumCores();
69e07747 921 if (nScriptCheckThreads <= 1)
f9cae832
PW
922 nScriptCheckThreads = 0;
923 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
924 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
925
8b9adca4 926 fServer = GetBoolArg("-server", false);
f9ec3f0f 927
928 // block pruning; get the amount of disk space (in MB) to allot for block & undo files
929 int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
930 if (nSignedPruneTarget < 0) {
931 return InitError(_("Prune cannot be configured with a negative value."));
932 }
933 nPruneTarget = (uint64_t) nSignedPruneTarget;
934 if (nPruneTarget) {
935 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
936 return InitError(strprintf(_("Prune configured below the minimum of %d MB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
937 }
938 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
939 fPruneMode = true;
940 }
941
48ba56cd 942#ifdef ENABLE_WALLET
e6b7e3dc 943 bool fDisableWallet = GetBoolArg("-disablewallet", false);
48ba56cd 944#endif
69d605f4 945
de10efd1
PK
946 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
947 if (nConnectTimeout <= 0)
948 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
7d80d2e3 949
000dc551
GA
950 // Fee-per-kilobyte amount considered the same as "free"
951 // If you are mining, be careful setting this:
952 // if you set it to zero then
953 // a transaction spammer can cheaply fill blocks using
954 // 1-satoshi-fee transactions. It should be set above the real
955 // cost to you of processing a transaction.
000dc551
GA
956 if (mapArgs.count("-minrelaytxfee"))
957 {
a372168e 958 CAmount n = 0;
000dc551 959 if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
13fc83c7 960 ::minRelayTxFee = CFeeRate(n);
000dc551 961 else
7d9d134b 962 return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
000dc551 963 }
7d80d2e3 964
cd7fa8bb 965#ifdef ENABLE_WALLET
13fc83c7
GA
966 if (mapArgs.count("-mintxfee"))
967 {
a372168e 968 CAmount n = 0;
13fc83c7
GA
969 if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
970 CWallet::minTxFee = CFeeRate(n);
971 else
972 return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
973 }
7d80d2e3
PW
974 if (mapArgs.count("-paytxfee"))
975 {
a372168e 976 CAmount nFeePerK = 0;
c6cb21d1 977 if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
7d9d134b 978 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
c6cb21d1 979 if (nFeePerK > nHighTransactionFeeWarning)
e6bc9c35 980 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
c6cb21d1 981 payTxFee = CFeeRate(nFeePerK, 1000);
13fc83c7 982 if (payTxFee < ::minRelayTxFee)
b33d1f5e
GA
983 {
984 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
13fc83c7 985 mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
b33d1f5e 986 }
7d80d2e3 987 }
aa279d61
GM
988 if (mapArgs.count("-maxtxfee"))
989 {
990 CAmount nMaxFee = 0;
991 if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
992 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maptxfee"]));
993 if (nMaxFee > nHighTransactionMaxFeeWarning)
994 InitWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction."));
995 maxTxFee = nMaxFee;
996 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
997 {
998 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
999 mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
1000 }
1001 }
77ed59df 1002 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
472b4c5d
AM
1003 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", true);
1004 fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false);
7d80d2e3 1005
7d4dda76 1006 std::string strWalletFile = GetArg("-wallet", "wallet.dat");
3da434a2
JG
1007#endif // ENABLE_WALLET
1008
472b4c5d 1009 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true);
2aa63292 1010 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
3da434a2 1011
4d9c7fe6
WL
1012 fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
1013
abb0e8cc
GA
1014 // Option to startup with mocktime set (used for regression testing):
1015 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1016
8e8b6d70
JG
1017#ifdef ENABLE_MINING
1018 if (mapArgs.count("-mineraddress")) {
1019 CBitcoinAddress addr;
1020 if (!addr.SetString(mapArgs["-mineraddress"])) {
1021 return InitError(strprintf(
1022 _("Invalid address for -mineraddress=<addr>: '%s' (must be a transparent address)"),
1023 mapArgs["-mineraddress"]));
1024 }
1025 }
1026#endif
1027
da6d9391
S
1028 // Default value of 0 for mempooltxinputlimit means no limit is applied
1029 if (mapArgs.count("-mempooltxinputlimit")) {
1030 int64_t limit = GetArg("-mempooltxinputlimit", 0);
1031 if (limit < 0) {
1032 return InitError(_("Mempool limit on transparent inputs to a transaction cannot be negative"));
1033 } else if (limit > 0) {
1034 LogPrintf("Mempool configured to reject transactions with greater than %lld transparent inputs\n", limit);
1035 }
1036 }
1037
1038
7d80d2e3 1039 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
20a11ffa 1040
f4091941 1041 // Initialize libsodium
2902ac7c 1042 if (init_and_check_sodium() == -1) {
f4091941
SB
1043 return false;
1044 }
1045
a56054be
PW
1046 // Initialize elliptic curve code
1047 ECC_Start();
3d02d0f6 1048 globalVerifyHandle.reset(new ECCVerifyHandle());
a56054be 1049
4a09e1df
AP
1050 // Sanity check
1051 if (!InitSanityCheck())
7662d72b 1052 return InitError(_("Initialization sanity check failed. Zcash is shutting down."));
7d80d2e3 1053
22bb0490 1054 std::string strDataDir = GetDataDir().string();
48ba56cd 1055#ifdef ENABLE_WALLET
674cb304
NS
1056 // Wallet file must be a plain filename without a directory
1057 if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
7d9d134b 1058 return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
48ba56cd 1059#endif
7d80d2e3
PW
1060 // Make sure only a single Bitcoin process is using the data directory.
1061 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
1062 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
1063 if (file) fclose(file);
ffdda4e8
AW
1064
1065 try {
1066 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1067 if (!lock.try_lock())
7662d72b 1068 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Zcash is probably already running."), strDataDir));
ffdda4e8 1069 } catch(const boost::interprocess::interprocess_exception& e) {
7662d72b 1070 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Zcash is probably already running.") + " %s.", strDataDir, e.what()));
ffdda4e8
AW
1071 }
1072
d6712db3
WL
1073#ifndef WIN32
1074 CreatePidFile(GetPidFile(), getpid());
1075#endif
7f1de3fe 1076 if (GetBoolArg("-shrinkdebugfile", !fDebug))
69d605f4 1077 ShrinkDebugFile();
8550bcfe
AW
1078
1079 if (fPrintToDebugLog)
1080 OpenDebugLog();
1081
881a85a2 1082 LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
d0a2e2eb
WL
1083#ifdef ENABLE_WALLET
1084 LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
1085#endif
dcb14198 1086 if (!fLogTimestamps)
7d9d134b
WL
1087 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1088 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1089 LogPrintf("Using data directory %s\n", strDataDir);
5bd02cf7 1090 LogPrintf("Using config file %s\n", GetConfigFile().string());
881a85a2 1091 LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
7d80d2e3 1092 std::ostringstream strErrors;
69d605f4 1093
9bdec760 1094 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
f9cae832 1095 if (nScriptCheckThreads) {
f9cae832 1096 for (int i=0; i<nScriptCheckThreads-1; i++)
21eb5ada 1097 threadGroup.create_thread(&ThreadScriptCheck);
f9cae832
PW
1098 }
1099
ddd0acd3
GA
1100 // Start the lightweight task scheduler thread
1101 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1102 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1103
000499ae
JG
1104 // Count uptime
1105 MarkStartTime();
1106
d35172fb 1107 if ((chainparams.NetworkIDString() != "regtest") &&
57724029 1108 GetBoolArg("-showmetrics", isatty(STDOUT_FILENO)) &&
d35172fb 1109 !fPrintToConsole && !GetBoolArg("-daemon", false)) {
a6df7ab5 1110 // Start the persistent metrics interface
4ace963c 1111 ConnectMetricsScreen();
a6df7ab5
JG
1112 threadGroup.create_thread(&ThreadShowMetricsScreen);
1113 }
1114
f4091941
SB
1115 // These must be disabled for now, they are buggy and we probably don't
1116 // want any of libsnark's profiling in production anyway.
1117 libsnark::inhibit_profiling_info = true;
1118 libsnark::inhibit_profiling_counters = true;
1119
226a6b32
SB
1120 // Initialize Zcash circuit parameters
1121 ZC_LoadParams();
1122
af82884a
DK
1123 /* Start the RPC server already. It will be started in "warmup" mode
1124 * and not really process calls already (but it will signify connections
1125 * that the server is there and will be ready later). Warmup mode will
1126 * be disabled when initialisation is finished.
1127 */
1128 if (fServer)
1129 {
1130 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
afd64f76
WL
1131 if (!AppInitServers(threadGroup))
1132 return InitError(_("Unable to start HTTP server. See debug log for details."));
af82884a
DK
1133 }
1134
51ed9ec9 1135 int64_t nStart;
7d80d2e3 1136
06494cab 1137 // ********************************************************* Step 5: verify wallet database integrity
48ba56cd 1138#ifdef ENABLE_WALLET
e6b7e3dc 1139 if (!fDisableWallet) {
8a6894ca 1140 LogPrintf("Using wallet %s\n", strWalletFile);
f9ee7a03 1141 uiInterface.InitMessage(_("Verifying wallet..."));
eed1785f 1142
2bb1c877
JS
1143 std::string warningString;
1144 std::string errorString;
db954a65 1145
2bb1c877
JS
1146 if (!CWallet::Verify(strWalletFile, warningString, errorString))
1147 return false;
db954a65 1148
2bb1c877
JS
1149 if (!warningString.empty())
1150 InitWarning(warningString);
1151 if (!errorString.empty())
1152 return InitError(warningString);
db954a65 1153
e6b7e3dc 1154 } // (!fDisableWallet)
48ba56cd 1155#endif // ENABLE_WALLET
eed1785f 1156 // ********************************************************* Step 6: network initialization
7d80d2e3 1157
501da250 1158 RegisterNodeSignals(GetNodeSignals());
0e4b3175 1159
7d80d2e3
PW
1160 if (mapArgs.count("-onlynet")) {
1161 std::set<enum Network> nets;
db954a65 1162 BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) {
7d80d2e3
PW
1163 enum Network net = ParseNetwork(snet);
1164 if (net == NET_UNROUTABLE)
7d9d134b 1165 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
7d80d2e3
PW
1166 nets.insert(net);
1167 }
1168 for (int n = 0; n < NET_MAX; n++) {
1169 enum Network net = (enum Network)n;
1170 if (!nets.count(net))
1171 SetLimited(net);
1172 }
1173 }
1174
dc942e6f
PW
1175 if (mapArgs.count("-whitelist")) {
1176 BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
1177 CSubNet subnet(net);
1178 if (!subnet.IsValid())
1179 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1180 CNode::AddWhitelistedRange(subnet);
1181 }
1182 }
1183
8d9719e0
WL
1184 bool proxyRandomize = GetBoolArg("-proxyrandomize", true);
1185 // -proxy sets a proxy for all outgoing network traffic
1186 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1187 std::string proxyArg = GetArg("-proxy", "");
a05be280 1188 SetLimited(NET_TOR);
8d9719e0
WL
1189 if (proxyArg != "" && proxyArg != "0") {
1190 proxyType addrProxy = proxyType(CService(proxyArg, 9050), proxyRandomize);
587f929c 1191 if (!addrProxy.IsValid())
8d9719e0 1192 return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
587f929c 1193
3c777141
GM
1194 SetProxy(NET_IPV4, addrProxy);
1195 SetProxy(NET_IPV6, addrProxy);
8d9719e0 1196 SetProxy(NET_TOR, addrProxy);
0127a9be 1197 SetNameProxy(addrProxy);
a05be280 1198 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
54ce3bad
PW
1199 }
1200
8d9719e0
WL
1201 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1202 // -noonion (or -onion=0) disables connecting to .onion entirely
1203 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1204 std::string onionArg = GetArg("-onion", "");
1205 if (onionArg != "") {
1206 if (onionArg == "0") { // Handle -noonion/-onion=0
a05be280 1207 SetLimited(NET_TOR); // set onions as unreachable
8d9719e0
WL
1208 } else {
1209 proxyType addrOnion = proxyType(CService(onionArg, 9050), proxyRandomize);
1210 if (!addrOnion.IsValid())
1211 return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
1212 SetProxy(NET_TOR, addrOnion);
a05be280 1213 SetLimited(NET_TOR, false);
8d9719e0 1214 }
587f929c
PW
1215 }
1216
1217 // see Step 2: parameter interactions for more information about these
56b07d2d 1218 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
587f929c
PW
1219 fDiscover = GetBoolArg("-discover", true);
1220 fNameLookup = GetBoolArg("-dns", true);
928d3a01 1221
7d80d2e3 1222 bool fBound = false;
53a08815 1223 if (fListen) {
dc942e6f 1224 if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
db954a65 1225 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
7d80d2e3
PW
1226 CService addrBind;
1227 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
7d9d134b 1228 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
c73323ee 1229 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
7d80d2e3 1230 }
db954a65 1231 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
dc942e6f
PW
1232 CService addrBind;
1233 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1234 return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
1235 if (addrBind.GetPort() == 0)
1236 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1237 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1238 }
c73323ee
PK
1239 }
1240 else {
7d80d2e3
PW
1241 struct in_addr inaddr_any;
1242 inaddr_any.s_addr = INADDR_ANY;
c73323ee 1243 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
c73323ee 1244 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
7d80d2e3
PW
1245 }
1246 if (!fBound)
587f929c 1247 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
928d3a01
JG
1248 }
1249
c73323ee 1250 if (mapArgs.count("-externalip")) {
db954a65 1251 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
7d80d2e3
PW
1252 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
1253 if (!addrLocal.IsValid())
7d9d134b 1254 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
7d80d2e3
PW
1255 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
1256 }
1257 }
1258
db954a65 1259 BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
587f929c
PW
1260 AddOneShot(strDest);
1261
f200002c
JG
1262#if ENABLE_ZMQ
1263 pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
1264
1265 if (pzmqNotificationInterface) {
f200002c
JG
1266 RegisterValidationInterface(pzmqNotificationInterface);
1267 }
1268#endif
1269
99eb947a
S
1270#if ENABLE_PROTON
1271 pAMQPNotificationInterface = AMQPNotificationInterface::CreateWithArguments(mapArgs);
1272
1273 if (pAMQPNotificationInterface) {
1274
1275 // AMQP support is currently an experimental feature, so fail if user configured AMQP notifications
1276 // without enabling experimental features.
1277 if (!fExperimentalMode) {
1278 return InitError(_("AMQP support requires -experimentalfeatures."));
1279 }
1280
1281 RegisterValidationInterface(pAMQPNotificationInterface);
1282 }
1283#endif
1284
729b1806 1285 // ********************************************************* Step 7: load block chain
7d80d2e3 1286
3260b4c0 1287 fReindex = GetBoolArg("-reindex", false);
7fea4846 1288
f4445f99 1289 // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
a3241998
CF
1290 boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1291 if (!boost::filesystem::exists(blocksDir))
f4445f99 1292 {
a3241998 1293 boost::filesystem::create_directories(blocksDir);
f4445f99
GA
1294 bool linked = false;
1295 for (unsigned int i = 1; i < 10000; i++) {
a3241998
CF
1296 boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1297 if (!boost::filesystem::exists(source)) break;
1298 boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
f4445f99 1299 try {
a3241998 1300 boost::filesystem::create_hard_link(source, dest);
7d9d134b 1301 LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
f4445f99 1302 linked = true;
a3241998 1303 } catch (const boost::filesystem::filesystem_error& e) {
f4445f99
GA
1304 // Note: hardlink creation failing is not a disaster, it just means
1305 // blocks will get re-downloaded from peers.
5262fde0 1306 LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
f4445f99
GA
1307 break;
1308 }
1309 }
1310 if (linked)
1311 {
1312 fReindex = true;
1313 }
1314 }
1315
1c83b0a3 1316 // cache size calculations
b3ed4236
PW
1317 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1318 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1319 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache
1320 int64_t nBlockTreeDBCache = nTotalCache / 8;
2d1fa42e 1321 if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
1c83b0a3
PW
1322 nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
1323 nTotalCache -= nBlockTreeDBCache;
b3ed4236 1324 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1c83b0a3 1325 nTotalCache -= nCoinDBCache;
b3ed4236
PW
1326 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1327 LogPrintf("Cache configuration:\n");
1328 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1329 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1330 LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
1c83b0a3 1331
f7f3a96b
PW
1332 bool fLoaded = false;
1333 while (!fLoaded) {
1334 bool fReset = fReindex;
1335 std::string strLoadError;
bb41a87d 1336
f7f3a96b 1337 uiInterface.InitMessage(_("Loading block index..."));
ae8bfd12 1338
f7f3a96b
PW
1339 nStart = GetTimeMillis();
1340 do {
1341 try {
1342 UnloadBlockIndex();
1343 delete pcoinsTip;
1344 delete pcoinsdbview;
13cdce43 1345 delete pcoinscatcher;
f7f3a96b
PW
1346 delete pblocktree;
1347
1348 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1349 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
13cdce43
PW
1350 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1351 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
f7f3a96b 1352
f9ec3f0f 1353 if (fReindex) {
f7f3a96b 1354 pblocktree->WriteReindexing(true);
6cb70ca4 1355 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
f9ec3f0f 1356 if (fPruneMode)
6cb70ca4 1357 CleanupBlockRevFiles();
f9ec3f0f 1358 }
f7f3a96b
PW
1359
1360 if (!LoadBlockIndex()) {
1361 strLoadError = _("Error loading block database");
1362 break;
1363 }
1364
5d274c99
PW
1365 // If the loaded chain has a wrong genesis, bail out immediately
1366 // (we're likely using a testnet datadir, or the other way around).
4e382177 1367 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
5d274c99
PW
1368 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1369
f7f3a96b
PW
1370 // Initialize the block index (no-op if non-empty database was already loaded)
1371 if (!InitBlockIndex()) {
1372 strLoadError = _("Error initializing block database");
1373 break;
1374 }
1375
067a6092
PW
1376 // Check for changed -txindex state
1377 if (fTxIndex != GetBoolArg("-txindex", false)) {
1378 strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1379 break;
1380 }
1381
f9ec3f0f 1382 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1383 // in the past, but is now trying to run unpruned.
1384 if (fHavePruned && !fPruneMode) {
1385 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1386 break;
1387 }
1388
e1ca89df 1389 uiInterface.InitMessage(_("Verifying blocks..."));
f9ec3f0f 1390 if (fHavePruned && GetArg("-checkblocks", 288) > MIN_BLOCKS_TO_KEEP) {
1391 LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
1392 MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", 288));
1393 }
2e280311 1394 if (!CVerifyDB().VerifyDB(pcoinsdbview, GetArg("-checklevel", 3),
d78900cc 1395 GetArg("-checkblocks", 288))) {
f7f3a96b
PW
1396 strLoadError = _("Corrupted block database detected");
1397 break;
1398 }
27df4123 1399 } catch (const std::exception& e) {
881a85a2 1400 if (fDebug) LogPrintf("%s\n", e.what());
f7f3a96b
PW
1401 strLoadError = _("Error opening block database");
1402 break;
1403 }
1f355b66 1404
f7f3a96b
PW
1405 fLoaded = true;
1406 } while(false);
1407
1408 if (!fLoaded) {
1409 // first suggest a reindex
1410 if (!fReset) {
5d66d0a1 1411 bool fRet = uiInterface.ThreadSafeQuestion(
0206e38d 1412 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
f42cde3c 1413 strLoadError + ".\nPlease restart with -reindex to recover.",
f7f3a96b
PW
1414 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1415 if (fRet) {
1416 fReindex = true;
1417 fRequestShutdown = false;
1418 } else {
881a85a2 1419 LogPrintf("Aborted block database rebuild. Exiting.\n");
f7f3a96b
PW
1420 return false;
1421 }
1422 } else {
1423 return InitError(strLoadError);
1424 }
1425 }
1426 }
871c3557 1427
46469d0f
PK
1428 // As LoadBlockIndex can take several minutes, it's possible the user
1429 // requested to kill the GUI during the last operation. If so, exit.
871c3557
B
1430 // As the program has not fully started yet, Shutdown() is possibly overkill.
1431 if (fRequestShutdown)
1432 {
881a85a2 1433 LogPrintf("Shutdown requested. Exiting.\n");
871c3557
B
1434 return false;
1435 }
f48742c2 1436 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
69d605f4 1437
171ca774 1438 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
eee030f6 1439 CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
00d1980b 1440 // Allowed to fail as this file IS missing on first startup.
a8738238 1441 if (!est_filein.IsNull())
171ca774 1442 mempool.ReadFeeEstimates(est_filein);
94064710 1443 fFeeEstimatesInitialized = true;
171ca774 1444
d66877af 1445
eed1785f 1446 // ********************************************************* Step 8: load wallet
48ba56cd 1447#ifdef ENABLE_WALLET
e6b7e3dc
JG
1448 if (fDisableWallet) {
1449 pwalletMain = NULL;
1450 LogPrintf("Wallet disabled!\n");
1451 } else {
77cbd462
CL
1452
1453 // needed to restore wallet transaction meta data after -zapwallettxes
1454 std::vector<CWalletTx> vWtx;
1455
518f3bda
JG
1456 if (GetBoolArg("-zapwallettxes", false)) {
1457 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
1458
1459 pwalletMain = new CWallet(strWalletFile);
77cbd462 1460 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
518f3bda
JG
1461 if (nZapWalletRet != DB_LOAD_OK) {
1462 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
1463 return false;
1464 }
1465
1466 delete pwalletMain;
1467 pwalletMain = NULL;
1468 }
1469
f9ee7a03 1470 uiInterface.InitMessage(_("Loading wallet..."));
bb41a87d 1471
f9ee7a03
JG
1472 nStart = GetTimeMillis();
1473 bool fFirstRun = true;
1474 pwalletMain = new CWallet(strWalletFile);
1475 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
1476 if (nLoadWalletRet != DB_LOAD_OK)
eed1785f 1477 {
f9ee7a03
JG
1478 if (nLoadWalletRet == DB_CORRUPT)
1479 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
1480 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
1481 {
1482 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
1483 " or address book entries might be missing or incorrect."));
1484 InitWarning(msg);
1485 }
1486 else if (nLoadWalletRet == DB_TOO_NEW)
d2c1e4a8 1487 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Zcash") << "\n";
f9ee7a03
JG
1488 else if (nLoadWalletRet == DB_NEED_REWRITE)
1489 {
d2c1e4a8 1490 strErrors << _("Wallet needed to be rewritten: restart Zcash to complete") << "\n";
7d9d134b 1491 LogPrintf("%s", strErrors.str());
f9ee7a03
JG
1492 return InitError(strErrors.str());
1493 }
1494 else
1495 strErrors << _("Error loading wallet.dat") << "\n";
eed1785f 1496 }
f9ee7a03
JG
1497
1498 if (GetBoolArg("-upgradewallet", fFirstRun))
d764d916 1499 {
f9ee7a03
JG
1500 int nMaxVersion = GetArg("-upgradewallet", 0);
1501 if (nMaxVersion == 0) // the -upgradewallet without argument case
1502 {
1503 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
1504 nMaxVersion = CLIENT_VERSION;
1505 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
1506 }
1507 else
1508 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
1509 if (nMaxVersion < pwalletMain->GetVersion())
1510 strErrors << _("Cannot downgrade wallet") << "\n";
1511 pwalletMain->SetMaxVersion(nMaxVersion);
d764d916 1512 }
439e1497 1513
f9ee7a03 1514 if (fFirstRun)
439e1497 1515 {
f9ee7a03 1516 // Create new keyUser and set as default key
f9ee7a03
JG
1517 CPubKey newDefaultKey;
1518 if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
1519 pwalletMain->SetDefaultKey(newDefaultKey);
1520 if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
1521 strErrors << _("Cannot write default address") << "\n";
1522 }
439e1497 1523
f9ee7a03 1524 pwalletMain->SetBestChain(chainActive.GetLocator());
360cfe14 1525 }
95c7db3d 1526
7d9d134b 1527 LogPrintf("%s", strErrors.str());
f48742c2 1528 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
69d605f4 1529
a96d1139 1530 RegisterValidationInterface(pwalletMain);
e8ef3da7 1531
f9ee7a03
JG
1532 CBlockIndex *pindexRescan = chainActive.Tip();
1533 if (GetBoolArg("-rescan", false))
03f83b9b
JG
1534 {
1535 pwalletMain->ClearNoteWitnessCache();
4c6d41b8 1536 pindexRescan = chainActive.Genesis();
03f83b9b 1537 }
f9ee7a03
JG
1538 else
1539 {
1540 CWalletDB walletdb(strWalletFile);
1541 CBlockLocator locator;
1542 if (walletdb.ReadBestBlock(locator))
6db83db3 1543 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
f9ee7a03
JG
1544 else
1545 pindexRescan = chainActive.Genesis();
1546 }
1547 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
1548 {
1549 uiInterface.InitMessage(_("Rescanning..."));
1550 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
1551 nStart = GetTimeMillis();
1552 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
f48742c2 1553 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
f9ee7a03
JG
1554 pwalletMain->SetBestChain(chainActive.GetLocator());
1555 nWalletDBUpdated++;
77cbd462
CL
1556
1557 // Restore wallet transaction metadata after -zapwallettxes=1
1558 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
1559 {
44bc988e
CL
1560 CWalletDB walletdb(strWalletFile);
1561
77cbd462
CL
1562 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
1563 {
805344dc 1564 uint256 hash = wtxOld.GetHash();
77cbd462
CL
1565 std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
1566 if (mi != pwalletMain->mapWallet.end())
1567 {
1568 const CWalletTx* copyFrom = &wtxOld;
1569 CWalletTx* copyTo = &mi->second;
1570 copyTo->mapValue = copyFrom->mapValue;
1571 copyTo->vOrderForm = copyFrom->vOrderForm;
1572 copyTo->nTimeReceived = copyFrom->nTimeReceived;
1573 copyTo->nTimeSmart = copyFrom->nTimeSmart;
1574 copyTo->fFromMe = copyFrom->fFromMe;
1575 copyTo->strFromAccount = copyFrom->strFromAccount;
1576 copyTo->nOrderPos = copyFrom->nOrderPos;
44bc988e 1577 copyTo->WriteToDisk(&walletdb);
77cbd462
CL
1578 }
1579 }
1580 }
f9ee7a03 1581 }
6f252627 1582 pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true));
e6b7e3dc 1583 } // (!fDisableWallet)
48ba56cd 1584#else // ENABLE_WALLET
a60bfd81 1585 LogPrintf("No wallet support compiled in!\n");
48ba56cd 1586#endif // !ENABLE_WALLET
e6adac7b 1587
f49bcdf9 1588#ifdef ENABLE_MINING
9bba9b37 1589 #ifndef ENABLE_WALLET
3df7c4c8 1590 if (GetBoolArg("-minetolocalwallet", false)) {
9bba9b37
DH
1591 return InitError(_("Zcash was not built with wallet support. Set -minetolocalwallet=0 to use -mineraddress, or rebuild Zcash with wallet support."));
1592 }
3df7c4c8 1593 if (GetArg("-mineraddress", "").empty() && GetBoolArg("-gen", false)) {
9bba9b37
DH
1594 return InitError(_("Zcash was not built with wallet support. Set -mineraddress, or rebuild Zcash with wallet support."));
1595 }
1596 #endif // !ENABLE_WALLET
1597
f49bcdf9 1598 if (mapArgs.count("-mineraddress")) {
9bba9b37 1599 #ifdef ENABLE_WALLET
f49bcdf9
JG
1600 bool minerAddressInLocalWallet = false;
1601 if (pwalletMain) {
1602 // Address has alreday been validated
1603 CBitcoinAddress addr(mapArgs["-mineraddress"]);
1604 CKeyID keyID;
1605 addr.GetKeyID(keyID);
1606 minerAddressInLocalWallet = pwalletMain->HaveKey(keyID);
1607 }
3df7c4c8 1608 if (GetBoolArg("-minetolocalwallet", true) && !minerAddressInLocalWallet) {
f49bcdf9
JG
1609 return InitError(_("-mineraddress is not in the local wallet. Either use a local address, or set -minetolocalwallet=0"));
1610 }
9bba9b37 1611 #endif // ENABLE_WALLET
f49bcdf9
JG
1612 }
1613#endif // ENABLE_MINING
1614
e6adac7b
AW
1615 // ********************************************************* Step 9: data directory maintenance
1616
1617 // if pruning, unset the service bit and perform the initial blockstore prune
1618 // after any wallet rescanning has taken place.
1619 if (fPruneMode) {
e6adac7b
AW
1620 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1621 nLocalServices &= ~NODE_NETWORK;
1622 if (!fReindex) {
dfe55bdc 1623 uiInterface.InitMessage(_("Pruning blockstore..."));
e6adac7b
AW
1624 PruneAndFlush();
1625 }
1626 }
1627
1628 // ********************************************************* Step 10: import blocks
0fcf91ea 1629
c7b6117d
JG
1630 if (mapArgs.count("-blocknotify"))
1631 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1632
04140457 1633 uiInterface.InitMessage(_("Activating best chain..."));
4fea06db 1634 // scan for better chains in the block chain database, that are not yet connected in the active best chain
ef3988ca 1635 CValidationState state;
75f51f2a 1636 if (!ActivateBestChain(state))
857c61df 1637 strErrors << "Failed to connect best block";
4fea06db 1638
21eb5ada 1639 std::vector<boost::filesystem::path> vImportFiles;
7d80d2e3 1640 if (mapArgs.count("-loadblock"))
69d605f4 1641 {
db954a65 1642 BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
21eb5ada 1643 vImportFiles.push_back(strFile);
52c90a2b 1644 }
21eb5ada 1645 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
ff09e31a
MC
1646 if (chainActive.Tip() == NULL) {
1647 LogPrintf("Waiting for genesis block to be imported...\n");
1648 while (!fRequestShutdown && chainActive.Tip() == NULL)
1649 MilliSleep(10);
1650 }
52c90a2b 1651
e6adac7b 1652 // ********************************************************* Step 11: start node
69d605f4 1653
69d605f4
WL
1654 if (!CheckDiskSpace())
1655 return false;
1656
d605bc4c
GA
1657 if (!strErrors.str().empty())
1658 return InitError(strErrors.str());
1659
7d80d2e3 1660 //// debug print
783b182c 1661 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
4c6d41b8 1662 LogPrintf("nBestHeight = %d\n", chainActive.Height());
48ba56cd 1663#ifdef ENABLE_WALLET
783b182c
WL
1664 LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
1665 LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
1666 LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
48ba56cd 1667#endif
7d80d2e3 1668
eb5f63fe
WL
1669 if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1670 StartTorControl(threadGroup, scheduler);
1671
9a1dcea2 1672 StartNode(threadGroup, scheduler);
e6334f4a 1673
36cba8f1
GA
1674 // Monitor the chain, and alert if we get blocks much quicker or slower than expected
1675 int64_t nPowTargetSpacing = Params().GetConsensus().nPowTargetSpacing;
1676 CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload,
fce474c9 1677 boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing);
36cba8f1 1678 scheduler.scheduleEvery(f, nPowTargetSpacing);
e6334f4a 1679
8e8b6d70 1680#ifdef ENABLE_MINING
a0cafb79 1681 // Generate coins in the background
8e8b6d70
JG
1682 #ifdef ENABLE_WALLET
1683 if (pwalletMain || !GetArg("-mineraddress", "").empty())
f654f004 1684 GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 1));
8e8b6d70
JG
1685 #else
1686 GenerateBitcoins(GetBoolArg("-gen", false), GetArg("-genproclimit", 1));
1687 #endif
48ba56cd 1688#endif
a0cafb79 1689
94064710 1690 // ********************************************************* Step 11: finished
7d80d2e3 1691
af82884a 1692 SetRPCWarmupFinished();
7d80d2e3 1693 uiInterface.InitMessage(_("Done loading"));
7d80d2e3 1694
48ba56cd 1695#ifdef ENABLE_WALLET
b0730874
JG
1696 if (pwalletMain) {
1697 // Add wallet transactions that aren't already in a block to mapTransactions
1698 pwalletMain->ReacceptWalletTransactions();
7d80d2e3 1699
b0730874
JG
1700 // Run a thread to flush wallet periodically
1701 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1702 }
48ba56cd 1703#endif
69d605f4 1704
b39e1bdb
S
1705 // SENDALERT
1706 threadGroup.create_thread(boost::bind(ThreadSendAlert));
1707
b31499ec 1708 return !fRequestShutdown;
69d605f4 1709}
This page took 0.631474 seconds and 4 git commands to generate.