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