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