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