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