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