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