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