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