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