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