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