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