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.
6 #if defined(HAVE_CONFIG_H)
7 #include "config/bitcoin-config.h"
11 #include "crypto/common.h"
14 #include "checkpoints.h"
15 #include "compat/sanity.h"
16 #include "consensus/upgrades.h"
17 #include "consensus/validation.h"
18 #include "httpserver.h"
28 #include "rpcserver.h"
29 #include "script/standard.h"
30 #include "scheduler.h"
32 #include "torcontrol.h"
33 #include "ui_interface.h"
35 #include "utilmoneystr.h"
36 #include "validationinterface.h"
38 #include "wallet/wallet.h"
39 #include "wallet/walletdb.h"
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>
59 #include <libsnark/common/profiling.hpp>
62 #include "zmq/zmqnotificationinterface.h"
66 #include "amqp/amqpnotificationinterface.h"
69 #include "librustzcash.h"
73 extern void ThreadSendAlert();
75 ZCJoinSplit* pzcashParams = NULL;
78 CWallet* pwalletMain = NULL;
80 bool fFeeEstimatesInitialized = false;
83 static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
87 static AMQPNotificationInterface* pAMQPNotificationInterface = NULL;
91 // Win32 LevelDB doesn't use file descriptors, and the ones used for
92 // accessing block files don't count towards the fd_set size limit
94 #define MIN_CORE_FILEDESCRIPTORS 0
96 #define MIN_CORE_FILEDESCRIPTORS 150
99 /** Used to pass flags to the Bind() function */
102 BF_EXPLICIT = (1U << 0),
103 BF_REPORT_ERROR = (1U << 1),
104 BF_WHITELIST = (1U << 2),
107 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
108 CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h
110 //////////////////////////////////////////////////////////////////////////////
116 // Thread management and startup/shutdown:
118 // The network-processing threads are all part of a thread group
119 // created by AppInit().
121 // A clean exit happens when StartShutdown() or the SIGTERM
122 // signal handler sets fRequestShutdown, which triggers
123 // the DetectShutdownThread(), which interrupts the main thread group.
124 // DetectShutdownThread() then exits, which causes AppInit() to
125 // continue (it .joins the shutdown thread).
126 // Shutdown() is then
127 // called to clean up database connections, and stop other
128 // threads that should only be stopped after the main network-processing
129 // threads have exited.
131 // Note that if running -daemon the parent process returns from AppInit2
132 // before adding any threads to the threadGroup, so .join_all() returns
133 // immediately and the parent exits from main().
136 std::atomic<bool> fRequestShutdown(false);
140 fRequestShutdown = true;
142 bool ShutdownRequested()
144 return fRequestShutdown;
147 class CCoinsViewErrorCatcher : public CCoinsViewBacked
150 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
151 bool GetCoins(const uint256 &txid, CCoins &coins) const {
153 return CCoinsViewBacked::GetCoins(txid, coins);
154 } catch(const std::runtime_error& e) {
155 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
156 LogPrintf("Error reading from database: %s\n", e.what());
157 // Starting the shutdown sequence and returning false to the caller would be
158 // interpreted as 'entry not found' (as opposed to unable to read data), and
159 // could lead to invalid interpretation. Just exit immediately, as we can't
160 // continue anyway, and all writes should be atomic.
164 // Writes do not need similar protection, as failure to write is handled by the caller.
167 static CCoinsViewDB *pcoinsdbview = NULL;
168 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
169 static boost::scoped_ptr<ECCVerifyHandle> globalVerifyHandle;
171 void Interrupt(boost::thread_group& threadGroup)
173 InterruptHTTPServer();
177 InterruptTorControl();
178 threadGroup.interrupt_all();
183 LogPrintf("%s: In progress...\n", __func__);
184 static CCriticalSection cs_Shutdown;
185 TRY_LOCK(cs_Shutdown, lockShutdown);
189 /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
190 /// for example if the data directory was found to be locked.
191 /// Be sure that anything that writes files or flushes caches only does this if the respective
192 /// module was initialized.
193 RenameThread("zcash-shutoff");
194 mempool.AddTransactionsUpdated(1);
202 pwalletMain->Flush(false);
206 GenerateBitcoins(false, NULL, 0);
208 GenerateBitcoins(false, 0);
213 UnregisterNodeSignals(GetNodeSignals());
215 if (fFeeEstimatesInitialized)
217 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
218 CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
219 if (!est_fileout.IsNull())
220 mempool.WriteFeeEstimates(est_fileout);
222 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
223 fFeeEstimatesInitialized = false;
228 if (pcoinsTip != NULL) {
233 delete pcoinscatcher;
234 pcoinscatcher = NULL;
242 pwalletMain->Flush(true);
246 if (pzmqNotificationInterface) {
247 UnregisterValidationInterface(pzmqNotificationInterface);
248 delete pzmqNotificationInterface;
249 pzmqNotificationInterface = NULL;
254 if (pAMQPNotificationInterface) {
255 UnregisterValidationInterface(pAMQPNotificationInterface);
256 delete pAMQPNotificationInterface;
257 pAMQPNotificationInterface = NULL;
263 boost::filesystem::remove(GetPidFile());
264 } catch (const boost::filesystem::filesystem_error& e) {
265 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
268 UnregisterAllValidationInterfaces();
275 globalVerifyHandle.reset();
277 LogPrintf("%s: done\n", __func__);
281 * Signal handlers are very limited in what they are allowed to do, so:
283 void HandleSIGTERM(int)
285 fRequestShutdown = true;
288 void HandleSIGHUP(int)
290 fReopenDebugLog = true;
293 bool static InitError(const std::string &str)
295 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
299 bool static InitWarning(const std::string &str)
301 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
305 bool static Bind(const CService &addr, unsigned int flags) {
306 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
308 std::string strError;
309 if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
310 if (flags & BF_REPORT_ERROR)
311 return InitError(strError);
319 cvBlockChange.notify_all();
320 LogPrint("rpc", "RPC stopped.\n");
323 void OnRPCPreCommand(const CRPCCommand& cmd)
326 string strWarning = GetWarnings("rpc");
327 if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
329 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
332 std::string HelpMessage(HelpMessageMode mode)
334 const bool showDebug = GetBoolArg("-help-debug", false);
336 // When adding new options to the categories, please keep and ensure alphabetical ordering.
337 // Do not translate _(...) -help-debug options, many technical terms, and only a very small audience, so is unnecessary stress to translators
339 string strUsage = HelpMessageGroup(_("Options:"));
340 strUsage += HelpMessageOpt("-?", _("This help message"));
341 strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
342 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)"));
343 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
344 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 288));
345 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), 3));
346 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "zcash.conf"));
347 if (mode == HMM_BITCOIND)
350 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
353 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
354 strUsage += HelpMessageOpt("-exportdir=<dir>", _("Specify directory to be used when exporting data"));
355 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
356 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup"));
357 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
358 strUsage += HelpMessageOpt("-mempooltxinputlimit=<n>", _("[DEPRECATED FROM OVERWINTER] Set the maximum number of transparent inputs in a transaction that the mempool will accept (default: 0 = no limit applied)"));
359 strUsage += HelpMessageOpt("-par=<n>", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"),
360 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
362 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "zcashd.pid"));
364 strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode disables wallet support and is incompatible with -txindex. "
365 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
366 "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
367 strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files on startup"));
369 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
371 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
373 strUsage += HelpMessageGroup(_("Connection options:"));
374 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
375 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100));
376 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400));
377 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
378 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)"));
379 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
380 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)"));
381 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)"));
382 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
383 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0));
384 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
385 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
386 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
387 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000));
388 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000));
389 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
390 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
391 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1));
392 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with Bloom filters (default: %u)"), 1));
394 strUsage += HelpMessageOpt("-enforcenodebloom", strprintf("Enforce minimum protocol version to limit use of Bloom filters (default: %u)", 0));
395 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 8233, 18233));
396 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
397 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1));
398 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
399 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
400 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
401 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
402 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
403 strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
404 " " + _("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"));
407 strUsage += HelpMessageGroup(_("Wallet options:"));
408 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
409 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100));
411 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)",
412 CURRENCY_UNIT, FormatMoney(CWallet::minTxFee.GetFeePerK())));
413 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
414 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
415 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
416 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
417 strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
418 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1));
419 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));
420 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));
421 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)"),
422 CURRENCY_UNIT, FormatMoney(maxTxFee)));
423 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup"));
424 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
425 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), true));
426 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
427 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
428 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
432 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
433 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
434 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
435 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
436 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
440 strUsage += HelpMessageGroup(_("AMQP 1.0 notification options:"));
441 strUsage += HelpMessageOpt("-amqppubhashblock=<address>", _("Enable publish hash block in <address>"));
442 strUsage += HelpMessageOpt("-amqppubhashtx=<address>", _("Enable publish hash transaction in <address>"));
443 strUsage += HelpMessageOpt("-amqppubrawblock=<address>", _("Enable publish raw block in <address>"));
444 strUsage += HelpMessageOpt("-amqppubrawtx=<address>", _("Enable publish raw transaction in <address>"));
447 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
450 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", 1));
451 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)", 100));
452 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", 0));
453 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", 0));
454 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
455 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
456 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", 1));
457 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", 0));
458 strUsage += HelpMessageOpt("-nuparams=hexBranchId:activationHeight", "Use given activation height for specified network upgrade (regtest-only)");
460 string debugCategories = "addrman, alert, bench, coindb, db, estimatefee, http, libevent, lock, mempool, net, partitioncheck, pow, proxy, prune, "
461 "rand, reindex, rpc, selectcoins, tor, zmq, zrpc, zrpcunsafe (implies zrpc)"; // Don't translate these
462 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
463 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + debugCategories + ".");
464 strUsage += HelpMessageOpt("-experimentalfeatures", _("Enable use of experimental features"));
465 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
466 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
467 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
470 strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
471 strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 0));
472 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> entries (default: %u)", 50000));
473 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
475 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying (default: %s)"),
476 CURRENCY_UNIT, FormatMoney(::minRelayTxFee.GetFeePerK())));
477 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
480 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", 0));
481 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", 1));
482 strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
483 "This is intended for regression testing tools and app development.");
485 strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
486 strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
488 strUsage += HelpMessageGroup(_("Node relay options:"));
489 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1));
490 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
492 strUsage += HelpMessageGroup(_("Block creation options:"));
493 strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), 0));
494 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
495 strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
496 if (GetBoolArg("-help-debug", false))
497 strUsage += HelpMessageOpt("-blockversion=<n>", strprintf("Override block version to test forking scenarios (default: %d)", (int)CBlock::CURRENT_VERSION));
500 strUsage += HelpMessageGroup(_("Mining options:"));
501 strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0));
502 strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
503 strUsage += HelpMessageOpt("-equihashsolver=<name>", _("Specify the Equihash solver to be used if enabled (default: \"default\")"));
504 strUsage += HelpMessageOpt("-mineraddress=<addr>", _("Send mined coins to a specific single address"));
505 strUsage += HelpMessageOpt("-minetolocalwallet", strprintf(
506 _("Require that mined blocks use a coinbase address in the local wallet (default: %u)"),
515 strUsage += HelpMessageGroup(_("RPC server options:"));
516 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
517 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0));
518 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)"));
519 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
520 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
521 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 8232, 18232));
522 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"));
523 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
525 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
526 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
529 // Disabled until we can lock notes and also tune performance of libsnark which by default uses multiple threads
530 //strUsage += HelpMessageOpt("-rpcasyncthreads=<n>", strprintf(_("Set the number of threads to service Async RPC calls (default: %d)"), 1));
532 if (mode == HMM_BITCOIND) {
533 strUsage += HelpMessageGroup(_("Metrics Options (only if -daemon and -printtoconsole are not set):"));
534 strUsage += HelpMessageOpt("-showmetrics", _("Show metrics on stdout (default: 1 if running in a console, 0 otherwise)"));
535 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)"));
536 strUsage += HelpMessageOpt("-metricsrefreshtime", strprintf(_("Number of seconds between metrics refreshes (default: %u if running in a console, %u otherwise)"), 1, 600));
542 static void BlockNotifyCallback(const uint256& hashNewTip)
544 std::string strCmd = GetArg("-blocknotify", "");
546 boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
547 boost::thread t(runCommand, strCmd); // thread runs free
553 assert(fImporting == false);
558 assert(fImporting == true);
564 // If we're using -prune with -reindex, then delete block files that will be ignored by the
565 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
566 // is missing, do the same here to delete any later block files after a gap. Also delete all
567 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
568 // is in sync with what's actually on disk by the time we start downloading, so that pruning
570 void CleanupBlockRevFiles()
572 using namespace boost::filesystem;
573 map<string, path> mapBlockFiles;
575 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
576 // Remove the rev files immediately and insert the blk file paths into an
577 // ordered map keyed by block file index.
578 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
579 path blocksdir = GetDataDir() / "blocks";
580 for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
581 if (is_regular_file(*it) &&
582 it->path().filename().string().length() == 12 &&
583 it->path().filename().string().substr(8,4) == ".dat")
585 if (it->path().filename().string().substr(0,3) == "blk")
586 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
587 else if (it->path().filename().string().substr(0,3) == "rev")
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) {
606 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
608 RenameThread("zcash-loadblk");
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);
619 break; // This error is logged in OpenBlockFile
620 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
621 LoadExternalBlockFile(file, &pos);
624 pblocktree->WriteReindexing(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):
631 // hardcoded $DATADIR/bootstrap.dat
632 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
633 if (boost::filesystem::exists(pathBootstrap)) {
634 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
637 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
638 LogPrintf("Importing bootstrap.dat...\n");
639 LoadExternalBlockFile(file);
640 RenameOver(pathBootstrap, pathBootstrapOld);
642 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
647 BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
648 FILE *file = fopen(path.string().c_str(), "rb");
651 LogPrintf("Importing blocks file %s...\n", path.string());
652 LoadExternalBlockFile(file);
654 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
658 if (GetBoolArg("-stopafterblockimport", false)) {
659 LogPrintf("Stopping after block import\n");
665 * Ensure that Bitcoin is running in a usable environment with all
666 * necessary library support.
668 bool InitSanityCheck(void)
670 if(!ECC_InitSanityCheck()) {
671 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
674 if (!glibc_sanity_test() || !glibcxx_sanity_test())
681 static void ZC_LoadParams(
682 const CChainParams& chainparams
685 struct timeval tv_start, tv_end;
688 boost::filesystem::path pk_path = ZC_GetParamsDir() / "sprout-proving.key";
689 boost::filesystem::path vk_path = ZC_GetParamsDir() / "sprout-verifying.key";
690 boost::filesystem::path sapling_spend = ZC_GetParamsDir() / "sapling-spend-testnet.params";
691 boost::filesystem::path sapling_output = ZC_GetParamsDir() / "sapling-output-testnet.params";
692 boost::filesystem::path sprout_groth16 = ZC_GetParamsDir() / "sprout-groth16-testnet.params";
694 bool sapling_paths_valid = true;
696 // We don't load Sapling zk-SNARK params if mainnet is configured
697 if (chainparams.NetworkIDString() != "main") {
698 sapling_paths_valid =
699 boost::filesystem::exists(sapling_spend) &&
700 boost::filesystem::exists(sapling_output) &&
701 boost::filesystem::exists(sprout_groth16);
705 boost::filesystem::exists(pk_path) &&
706 boost::filesystem::exists(vk_path) &&
709 uiInterface.ThreadSafeMessageBox(strprintf(
710 _("Cannot find the Zcash network parameters in the following directory:\n"
712 "Please run 'zcash-fetch-params' or './zcutil/fetch-params.sh' and then restart."),
714 "", CClientUIInterface::MSG_ERROR);
719 LogPrintf("Loading verifying key from %s\n", vk_path.string().c_str());
720 gettimeofday(&tv_start, 0);
722 pzcashParams = ZCJoinSplit::Prepared(vk_path.string(), pk_path.string());
724 gettimeofday(&tv_end, 0);
725 elapsed = float(tv_end.tv_sec-tv_start.tv_sec) + (tv_end.tv_usec-tv_start.tv_usec)/float(1000000);
726 LogPrintf("Loaded verifying key in %fs seconds.\n", elapsed);
728 if (chainparams.NetworkIDString() != "main") {
729 std::string sapling_spend_str = sapling_spend.string();
730 std::string sapling_output_str = sapling_output.string();
731 std::string sprout_groth16_str = sprout_groth16.string();
733 LogPrintf("Loading Sapling (Spend) parameters from %s\n", sapling_spend_str.c_str());
734 LogPrintf("Loading Sapling (Output) parameters from %s\n", sapling_output_str.c_str());
735 LogPrintf("Loading Sapling (Sprout Groth16) parameters from %s\n", sprout_groth16_str.c_str());
736 gettimeofday(&tv_start, 0);
738 librustzcash_init_zksnark_params(
739 sapling_spend_str.c_str(),
740 sapling_output_str.c_str(),
741 sprout_groth16_str.c_str()
744 gettimeofday(&tv_end, 0);
745 elapsed = float(tv_end.tv_sec-tv_start.tv_sec) + (tv_end.tv_usec-tv_start.tv_usec)/float(1000000);
746 LogPrintf("Loaded Sapling parameters in %fs seconds.\n", elapsed);
748 LogPrintf("Not loading Sapling parameters in mainnet\n");
752 bool AppInitServers(boost::thread_group& threadGroup)
754 RPCServer::OnStopped(&OnRPCStopped);
755 RPCServer::OnPreCommand(&OnRPCPreCommand);
756 if (!InitHTTPServer())
762 if (GetBoolArg("-rest", false) && !StartREST())
764 if (!StartHTTPServer())
769 /** Initialize bitcoin.
770 * @pre Parameters should be parsed and config file should be read.
772 bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
774 // ********************************************************* Step 1: setup
776 // Turn off Microsoft heap dump noise
777 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
778 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
781 // Disable confusing "helpful" text message on abort, Ctrl-C
782 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
785 // Enable Data Execution Prevention (DEP)
786 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
787 // A failure is non-critical and needs no further attention!
788 #ifndef PROCESS_DEP_ENABLE
789 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
790 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
791 #define PROCESS_DEP_ENABLE 0x00000001
793 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
794 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
795 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
798 if (!SetupNetworking())
799 return InitError("Error: Initializing networking failed");
802 if (GetBoolArg("-sysperms", false)) {
804 if (!GetBoolArg("-disablewallet", false))
805 return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
811 // Clean shutdown on SIGTERM
813 sa.sa_handler = HandleSIGTERM;
814 sigemptyset(&sa.sa_mask);
816 sigaction(SIGTERM, &sa, NULL);
817 sigaction(SIGINT, &sa, NULL);
819 // Reopen debug.log on SIGHUP
820 struct sigaction sa_hup;
821 sa_hup.sa_handler = HandleSIGHUP;
822 sigemptyset(&sa_hup.sa_mask);
824 sigaction(SIGHUP, &sa_hup, NULL);
826 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
827 signal(SIGPIPE, SIG_IGN);
830 std::set_new_handler(new_handler_terminate);
832 // ********************************************************* Step 2: parameter interactions
833 const CChainParams& chainparams = Params();
835 // Set this early so that experimental features are correctly enabled/disabled
836 fExperimentalMode = GetBoolArg("-experimentalfeatures", false);
838 // Fail early if user has set experimental options without the global flag
839 if (!fExperimentalMode) {
840 if (mapArgs.count("-developerencryptwallet")) {
841 return InitError(_("Wallet encryption requires -experimentalfeatures."));
843 else if (mapArgs.count("-paymentdisclosure")) {
844 return InitError(_("Payment disclosure requires -experimentalfeatures."));
845 } else if (mapArgs.count("-zmergetoaddress")) {
846 return InitError(_("RPC method z_mergetoaddress requires -experimentalfeatures."));
850 // Set this early so that parameter interactions go to console
851 fPrintToConsole = GetBoolArg("-printtoconsole", false);
852 fLogTimestamps = GetBoolArg("-logtimestamps", true);
853 fLogIPs = GetBoolArg("-logips", false);
855 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
856 LogPrintf("Zcash version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
858 // when specifying an explicit binding address, you want to listen on it
859 // even when -connect or -proxy is specified
860 if (mapArgs.count("-bind")) {
861 if (SoftSetBoolArg("-listen", true))
862 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
864 if (mapArgs.count("-whitebind")) {
865 if (SoftSetBoolArg("-listen", true))
866 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
869 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
870 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
871 if (SoftSetBoolArg("-dnsseed", false))
872 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
873 if (SoftSetBoolArg("-listen", false))
874 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
877 if (mapArgs.count("-proxy")) {
878 // to protect privacy, do not listen by default if a default proxy server is specified
879 if (SoftSetBoolArg("-listen", false))
880 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
881 // to protect privacy, do not discover addresses by default
882 if (SoftSetBoolArg("-discover", false))
883 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
886 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
887 // do not try to retrieve public IP when not listening (pointless)
888 if (SoftSetBoolArg("-discover", false))
889 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
890 if (SoftSetBoolArg("-listenonion", false))
891 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
894 if (mapArgs.count("-externalip")) {
895 // if an explicit public IP is specified, do not try to find others
896 if (SoftSetBoolArg("-discover", false))
897 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
900 if (GetBoolArg("-salvagewallet", false)) {
901 // Rewrite just private keys: rescan to find transactions
902 if (SoftSetBoolArg("-rescan", true))
903 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
906 // -zapwallettx implies a rescan
907 if (GetBoolArg("-zapwallettxes", false)) {
908 if (SoftSetBoolArg("-rescan", true))
909 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
912 // Make sure enough file descriptors are available
913 int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
914 nMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
915 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
916 int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
917 if (nFD < MIN_CORE_FILEDESCRIPTORS)
918 return InitError(_("Not enough file descriptors available."));
919 if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
920 nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
922 // if using block pruning, then disable txindex
923 // also disable the wallet (for now, until SPV support is implemented in wallet)
924 if (GetArg("-prune", 0)) {
925 if (GetBoolArg("-txindex", false))
926 return InitError(_("Prune mode is incompatible with -txindex."));
928 if (!GetBoolArg("-disablewallet", false)) {
929 if (SoftSetBoolArg("-disablewallet", true))
930 LogPrintf("%s : parameter interaction: -prune -> setting -disablewallet=1\n", __func__);
932 return InitError(_("Can't run with a wallet in prune mode."));
937 // ********************************************************* Step 3: parameter-to-internal-flags
939 fDebug = !mapMultiArgs["-debug"].empty();
940 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
941 const vector<string>& categories = mapMultiArgs["-debug"];
942 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
945 // Special case: if debug=zrpcunsafe, implies debug=zrpc, so add it to debug categories
946 if (find(categories.begin(), categories.end(), string("zrpcunsafe")) != categories.end()) {
947 if (find(categories.begin(), categories.end(), string("zrpc")) == categories.end()) {
948 LogPrintf("%s: parameter interaction: setting -debug=zrpcunsafe -> -debug=zrpc\n", __func__);
949 vector<string>& v = mapMultiArgs["-debug"];
954 // Check for -debugnet
955 if (GetBoolArg("-debugnet", false))
956 InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
957 // Check for -socks - as this is a privacy risk to continue, exit here
958 if (mapArgs.count("-socks"))
959 return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
960 // Check for -tor - as this is a privacy risk to continue, exit here
961 if (GetBoolArg("-tor", false))
962 return InitError(_("Error: Unsupported argument -tor found, use -onion."));
964 if (GetBoolArg("-benchmark", false))
965 InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
967 // Checkmempool and checkblockindex default to true in regtest mode
968 int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
970 mempool.setSanityCheck(1.0 / ratio);
972 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
973 fCheckpointsEnabled = GetBoolArg("-checkpoints", true);
975 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
976 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
977 if (nScriptCheckThreads <= 0)
978 nScriptCheckThreads += GetNumCores();
979 if (nScriptCheckThreads <= 1)
980 nScriptCheckThreads = 0;
981 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
982 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
984 fServer = GetBoolArg("-server", false);
986 // block pruning; get the amount of disk space (in MB) to allot for block & undo files
987 int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
988 if (nSignedPruneTarget < 0) {
989 return InitError(_("Prune cannot be configured with a negative value."));
991 nPruneTarget = (uint64_t) nSignedPruneTarget;
993 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
994 return InitError(strprintf(_("Prune configured below the minimum of %d MB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
996 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1000 #ifdef ENABLE_WALLET
1001 bool fDisableWallet = GetBoolArg("-disablewallet", false);
1004 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1005 if (nConnectTimeout <= 0)
1006 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1008 // Fee-per-kilobyte amount considered the same as "free"
1009 // If you are mining, be careful setting this:
1010 // if you set it to zero then
1011 // a transaction spammer can cheaply fill blocks using
1012 // 1-satoshi-fee transactions. It should be set above the real
1013 // cost to you of processing a transaction.
1014 if (mapArgs.count("-minrelaytxfee"))
1017 if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
1018 ::minRelayTxFee = CFeeRate(n);
1020 return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
1023 #ifdef ENABLE_WALLET
1024 if (mapArgs.count("-mintxfee"))
1027 if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
1028 CWallet::minTxFee = CFeeRate(n);
1030 return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
1032 if (mapArgs.count("-paytxfee"))
1034 CAmount nFeePerK = 0;
1035 if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
1036 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
1037 if (nFeePerK > nHighTransactionFeeWarning)
1038 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
1039 payTxFee = CFeeRate(nFeePerK, 1000);
1040 if (payTxFee < ::minRelayTxFee)
1042 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
1043 mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
1046 if (mapArgs.count("-maxtxfee"))
1048 CAmount nMaxFee = 0;
1049 if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
1050 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maptxfee"]));
1051 if (nMaxFee > nHighTransactionMaxFeeWarning)
1052 InitWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction."));
1054 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
1056 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
1057 mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
1060 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
1061 expiryDelta = GetArg("-txexpirydelta", DEFAULT_TX_EXPIRY_DELTA);
1062 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", true);
1063 fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false);
1065 std::string strWalletFile = GetArg("-wallet", "wallet.dat");
1066 #endif // ENABLE_WALLET
1068 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true);
1069 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1071 fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
1073 // Option to startup with mocktime set (used for regression testing):
1074 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1076 if (GetBoolArg("-peerbloomfilters", true))
1077 nLocalServices |= NODE_BLOOM;
1079 nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1081 #ifdef ENABLE_MINING
1082 if (mapArgs.count("-mineraddress")) {
1083 CTxDestination addr = DecodeDestination(mapArgs["-mineraddress"]);
1084 if (!IsValidDestination(addr)) {
1085 return InitError(strprintf(
1086 _("Invalid address for -mineraddress=<addr>: '%s' (must be a transparent address)"),
1087 mapArgs["-mineraddress"]));
1092 // Default value of 0 for mempooltxinputlimit means no limit is applied
1093 if (mapArgs.count("-mempooltxinputlimit")) {
1094 int64_t limit = GetArg("-mempooltxinputlimit", 0);
1096 return InitError(_("Mempool limit on transparent inputs to a transaction cannot be negative"));
1097 } else if (limit > 0) {
1098 LogPrintf("Mempool configured to reject transactions with greater than %lld transparent inputs\n", limit);
1102 if (!mapMultiArgs["-nuparams"].empty()) {
1103 // Allow overriding network upgrade parameters for testing
1104 if (Params().NetworkIDString() != "regtest") {
1105 return InitError("Network upgrade parameters may only be overridden on regtest.");
1107 const vector<string>& deployments = mapMultiArgs["-nuparams"];
1108 for (auto i : deployments) {
1109 std::vector<std::string> vDeploymentParams;
1110 boost::split(vDeploymentParams, i, boost::is_any_of(":"));
1111 if (vDeploymentParams.size() != 2) {
1112 return InitError("Network upgrade parameters malformed, expecting hexBranchId:activationHeight");
1114 int nActivationHeight;
1115 if (!ParseInt32(vDeploymentParams[1], &nActivationHeight)) {
1116 return InitError(strprintf("Invalid nActivationHeight (%s)", vDeploymentParams[1]));
1119 // Exclude Sprout from upgrades
1120 for (auto i = Consensus::BASE_SPROUT + 1; i < Consensus::MAX_NETWORK_UPGRADES; ++i)
1122 if (vDeploymentParams[0].compare(HexInt(NetworkUpgradeInfo[i].nBranchId)) == 0) {
1123 UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex(i), nActivationHeight);
1125 LogPrintf("Setting network upgrade activation parameters for %s to height=%d\n", vDeploymentParams[0], nActivationHeight);
1130 return InitError(strprintf("Invalid network upgrade (%s)", vDeploymentParams[0]));
1135 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
1137 // Initialize libsodium
1138 if (init_and_check_sodium() == -1) {
1142 // Initialize elliptic curve code
1144 globalVerifyHandle.reset(new ECCVerifyHandle());
1147 if (!InitSanityCheck())
1148 return InitError(_("Initialization sanity check failed. Zcash is shutting down."));
1150 std::string strDataDir = GetDataDir().string();
1151 #ifdef ENABLE_WALLET
1152 // Wallet file must be a plain filename without a directory
1153 if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
1154 return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
1156 // Make sure only a single Bitcoin process is using the data directory.
1157 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
1158 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
1159 if (file) fclose(file);
1162 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1163 if (!lock.try_lock())
1164 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Zcash is probably already running."), strDataDir));
1165 } catch(const boost::interprocess::interprocess_exception& e) {
1166 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Zcash is probably already running.") + " %s.", strDataDir, e.what()));
1170 CreatePidFile(GetPidFile(), getpid());
1172 if (GetBoolArg("-shrinkdebugfile", !fDebug))
1175 if (fPrintToDebugLog)
1178 LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
1179 #ifdef ENABLE_WALLET
1180 LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
1182 if (!fLogTimestamps)
1183 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1184 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1185 LogPrintf("Using data directory %s\n", strDataDir);
1186 LogPrintf("Using config file %s\n", GetConfigFile().string());
1187 LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
1188 std::ostringstream strErrors;
1190 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1191 if (nScriptCheckThreads) {
1192 for (int i=0; i<nScriptCheckThreads-1; i++)
1193 threadGroup.create_thread(&ThreadScriptCheck);
1196 // Start the lightweight task scheduler thread
1197 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1198 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1203 if ((chainparams.NetworkIDString() != "regtest") &&
1204 GetBoolArg("-showmetrics", isatty(STDOUT_FILENO)) &&
1205 !fPrintToConsole && !GetBoolArg("-daemon", false)) {
1206 // Start the persistent metrics interface
1207 ConnectMetricsScreen();
1208 threadGroup.create_thread(&ThreadShowMetricsScreen);
1211 // These must be disabled for now, they are buggy and we probably don't
1212 // want any of libsnark's profiling in production anyway.
1213 libsnark::inhibit_profiling_info = true;
1214 libsnark::inhibit_profiling_counters = true;
1216 // Initialize Zcash circuit parameters
1217 ZC_LoadParams(chainparams);
1219 /* Start the RPC server already. It will be started in "warmup" mode
1220 * and not really process calls already (but it will signify connections
1221 * that the server is there and will be ready later). Warmup mode will
1222 * be disabled when initialisation is finished.
1226 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1227 if (!AppInitServers(threadGroup))
1228 return InitError(_("Unable to start HTTP server. See debug log for details."));
1233 // ********************************************************* Step 5: verify wallet database integrity
1234 #ifdef ENABLE_WALLET
1235 if (!fDisableWallet) {
1236 LogPrintf("Using wallet %s\n", strWalletFile);
1237 uiInterface.InitMessage(_("Verifying wallet..."));
1239 std::string warningString;
1240 std::string errorString;
1242 if (!CWallet::Verify(strWalletFile, warningString, errorString))
1245 if (!warningString.empty())
1246 InitWarning(warningString);
1247 if (!errorString.empty())
1248 return InitError(warningString);
1250 } // (!fDisableWallet)
1251 #endif // ENABLE_WALLET
1252 // ********************************************************* Step 6: network initialization
1254 RegisterNodeSignals(GetNodeSignals());
1256 // sanitize comments per BIP-0014, format user agent and check total size
1257 std::vector<string> uacomments;
1258 BOOST_FOREACH(string cmt, mapMultiArgs["-uacomment"])
1260 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1261 return InitError(strprintf("User Agent comment (%s) contains unsafe characters.", cmt));
1262 uacomments.push_back(SanitizeString(cmt, SAFE_CHARS_UA_COMMENT));
1264 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1265 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1266 return InitError(strprintf("Total length of network version string %i exceeds maximum of %i characters. Reduce the number and/or size of uacomments.",
1267 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1270 if (mapArgs.count("-onlynet")) {
1271 std::set<enum Network> nets;
1272 BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) {
1273 enum Network net = ParseNetwork(snet);
1274 if (net == NET_UNROUTABLE)
1275 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1278 for (int n = 0; n < NET_MAX; n++) {
1279 enum Network net = (enum Network)n;
1280 if (!nets.count(net))
1285 if (mapArgs.count("-whitelist")) {
1286 BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
1287 CSubNet subnet(net);
1288 if (!subnet.IsValid())
1289 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1290 CNode::AddWhitelistedRange(subnet);
1294 bool proxyRandomize = GetBoolArg("-proxyrandomize", true);
1295 // -proxy sets a proxy for all outgoing network traffic
1296 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1297 std::string proxyArg = GetArg("-proxy", "");
1298 SetLimited(NET_TOR);
1299 if (proxyArg != "" && proxyArg != "0") {
1300 proxyType addrProxy = proxyType(CService(proxyArg, 9050), proxyRandomize);
1301 if (!addrProxy.IsValid())
1302 return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
1304 SetProxy(NET_IPV4, addrProxy);
1305 SetProxy(NET_IPV6, addrProxy);
1306 SetProxy(NET_TOR, addrProxy);
1307 SetNameProxy(addrProxy);
1308 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1311 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1312 // -noonion (or -onion=0) disables connecting to .onion entirely
1313 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1314 std::string onionArg = GetArg("-onion", "");
1315 if (onionArg != "") {
1316 if (onionArg == "0") { // Handle -noonion/-onion=0
1317 SetLimited(NET_TOR); // set onions as unreachable
1319 proxyType addrOnion = proxyType(CService(onionArg, 9050), proxyRandomize);
1320 if (!addrOnion.IsValid())
1321 return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
1322 SetProxy(NET_TOR, addrOnion);
1323 SetLimited(NET_TOR, false);
1327 // see Step 2: parameter interactions for more information about these
1328 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1329 fDiscover = GetBoolArg("-discover", true);
1330 fNameLookup = GetBoolArg("-dns", true);
1332 bool fBound = false;
1334 if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
1335 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
1337 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1338 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
1339 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1341 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
1343 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1344 return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
1345 if (addrBind.GetPort() == 0)
1346 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1347 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1351 struct in_addr inaddr_any;
1352 inaddr_any.s_addr = INADDR_ANY;
1353 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
1354 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1357 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1360 if (mapArgs.count("-externalip")) {
1361 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
1362 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
1363 if (!addrLocal.IsValid())
1364 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
1365 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
1369 BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
1370 AddOneShot(strDest);
1373 pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
1375 if (pzmqNotificationInterface) {
1376 RegisterValidationInterface(pzmqNotificationInterface);
1381 pAMQPNotificationInterface = AMQPNotificationInterface::CreateWithArguments(mapArgs);
1383 if (pAMQPNotificationInterface) {
1385 // AMQP support is currently an experimental feature, so fail if user configured AMQP notifications
1386 // without enabling experimental features.
1387 if (!fExperimentalMode) {
1388 return InitError(_("AMQP support requires -experimentalfeatures."));
1391 RegisterValidationInterface(pAMQPNotificationInterface);
1395 // ********************************************************* Step 7: load block chain
1397 fReindex = GetBoolArg("-reindex", false);
1399 // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
1400 boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1401 if (!boost::filesystem::exists(blocksDir))
1403 boost::filesystem::create_directories(blocksDir);
1404 bool linked = false;
1405 for (unsigned int i = 1; i < 10000; i++) {
1406 boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1407 if (!boost::filesystem::exists(source)) break;
1408 boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
1410 boost::filesystem::create_hard_link(source, dest);
1411 LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
1413 } catch (const boost::filesystem::filesystem_error& e) {
1414 // Note: hardlink creation failing is not a disaster, it just means
1415 // blocks will get re-downloaded from peers.
1416 LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
1426 // cache size calculations
1427 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1428 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1429 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache
1430 int64_t nBlockTreeDBCache = nTotalCache / 8;
1431 if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
1432 nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
1433 nTotalCache -= nBlockTreeDBCache;
1434 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1435 nTotalCache -= nCoinDBCache;
1436 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1437 LogPrintf("Cache configuration:\n");
1438 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1439 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1440 LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
1442 bool fLoaded = false;
1444 bool fReset = fReindex;
1445 std::string strLoadError;
1447 uiInterface.InitMessage(_("Loading block index..."));
1449 nStart = GetTimeMillis();
1454 delete pcoinsdbview;
1455 delete pcoinscatcher;
1458 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1459 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
1460 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1461 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1464 pblocktree->WriteReindexing(true);
1465 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1467 CleanupBlockRevFiles();
1470 if (!LoadBlockIndex()) {
1471 strLoadError = _("Error loading block database");
1475 // If the loaded chain has a wrong genesis, bail out immediately
1476 // (we're likely using a testnet datadir, or the other way around).
1477 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1478 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1480 // Initialize the block index (no-op if non-empty database was already loaded)
1481 if (!InitBlockIndex()) {
1482 strLoadError = _("Error initializing block database");
1486 // Check for changed -txindex state
1487 if (fTxIndex != GetBoolArg("-txindex", false)) {
1488 strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1492 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1493 // in the past, but is now trying to run unpruned.
1494 if (fHavePruned && !fPruneMode) {
1495 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1500 uiInterface.InitMessage(_("Rewinding blocks if needed..."));
1501 if (!RewindBlockIndex(chainparams)) {
1502 strLoadError = _("Unable to rewind the database to a pre-upgrade state. You will need to redownload the blockchain");
1507 uiInterface.InitMessage(_("Verifying blocks..."));
1508 if (fHavePruned && GetArg("-checkblocks", 288) > MIN_BLOCKS_TO_KEEP) {
1509 LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
1510 MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", 288));
1512 if (!CVerifyDB().VerifyDB(pcoinsdbview, GetArg("-checklevel", 3),
1513 GetArg("-checkblocks", 288))) {
1514 strLoadError = _("Corrupted block database detected");
1517 } catch (const std::exception& e) {
1518 if (fDebug) LogPrintf("%s\n", e.what());
1519 strLoadError = _("Error opening block database");
1527 // first suggest a reindex
1529 bool fRet = uiInterface.ThreadSafeQuestion(
1530 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1531 strLoadError + ".\nPlease restart with -reindex to recover.",
1532 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1535 fRequestShutdown = false;
1537 LogPrintf("Aborted block database rebuild. Exiting.\n");
1541 return InitError(strLoadError);
1546 // As LoadBlockIndex can take several minutes, it's possible the user
1547 // requested to kill the GUI during the last operation. If so, exit.
1548 // As the program has not fully started yet, Shutdown() is possibly overkill.
1549 if (fRequestShutdown)
1551 LogPrintf("Shutdown requested. Exiting.\n");
1554 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1556 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1557 CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
1558 // Allowed to fail as this file IS missing on first startup.
1559 if (!est_filein.IsNull())
1560 mempool.ReadFeeEstimates(est_filein);
1561 fFeeEstimatesInitialized = true;
1564 // ********************************************************* Step 8: load wallet
1565 #ifdef ENABLE_WALLET
1566 if (fDisableWallet) {
1568 LogPrintf("Wallet disabled!\n");
1571 // needed to restore wallet transaction meta data after -zapwallettxes
1572 std::vector<CWalletTx> vWtx;
1574 if (GetBoolArg("-zapwallettxes", false)) {
1575 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
1577 pwalletMain = new CWallet(strWalletFile);
1578 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
1579 if (nZapWalletRet != DB_LOAD_OK) {
1580 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
1588 uiInterface.InitMessage(_("Loading wallet..."));
1590 nStart = GetTimeMillis();
1591 bool fFirstRun = true;
1592 pwalletMain = new CWallet(strWalletFile);
1593 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
1594 if (nLoadWalletRet != DB_LOAD_OK)
1596 if (nLoadWalletRet == DB_CORRUPT)
1597 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
1598 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
1600 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
1601 " or address book entries might be missing or incorrect."));
1604 else if (nLoadWalletRet == DB_TOO_NEW)
1605 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Zcash") << "\n";
1606 else if (nLoadWalletRet == DB_NEED_REWRITE)
1608 strErrors << _("Wallet needed to be rewritten: restart Zcash to complete") << "\n";
1609 LogPrintf("%s", strErrors.str());
1610 return InitError(strErrors.str());
1613 strErrors << _("Error loading wallet.dat") << "\n";
1616 if (GetBoolArg("-upgradewallet", fFirstRun))
1618 int nMaxVersion = GetArg("-upgradewallet", 0);
1619 if (nMaxVersion == 0) // the -upgradewallet without argument case
1621 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
1622 nMaxVersion = CLIENT_VERSION;
1623 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
1626 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
1627 if (nMaxVersion < pwalletMain->GetVersion())
1628 strErrors << _("Cannot downgrade wallet") << "\n";
1629 pwalletMain->SetMaxVersion(nMaxVersion);
1634 // Create new keyUser and set as default key
1635 CPubKey newDefaultKey;
1636 if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
1637 pwalletMain->SetDefaultKey(newDefaultKey);
1638 if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
1639 strErrors << _("Cannot write default address") << "\n";
1642 pwalletMain->SetBestChain(chainActive.GetLocator());
1645 LogPrintf("%s", strErrors.str());
1646 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
1648 RegisterValidationInterface(pwalletMain);
1650 CBlockIndex *pindexRescan = chainActive.Tip();
1651 if (GetBoolArg("-rescan", false))
1653 pwalletMain->ClearNoteWitnessCache();
1654 pindexRescan = chainActive.Genesis();
1658 CWalletDB walletdb(strWalletFile);
1659 CBlockLocator locator;
1660 if (walletdb.ReadBestBlock(locator))
1661 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
1663 pindexRescan = chainActive.Genesis();
1665 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
1667 uiInterface.InitMessage(_("Rescanning..."));
1668 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
1669 nStart = GetTimeMillis();
1670 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
1671 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
1672 pwalletMain->SetBestChain(chainActive.GetLocator());
1675 // Restore wallet transaction metadata after -zapwallettxes=1
1676 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
1678 CWalletDB walletdb(strWalletFile);
1680 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
1682 uint256 hash = wtxOld.GetHash();
1683 std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
1684 if (mi != pwalletMain->mapWallet.end())
1686 const CWalletTx* copyFrom = &wtxOld;
1687 CWalletTx* copyTo = &mi->second;
1688 copyTo->mapValue = copyFrom->mapValue;
1689 copyTo->vOrderForm = copyFrom->vOrderForm;
1690 copyTo->nTimeReceived = copyFrom->nTimeReceived;
1691 copyTo->nTimeSmart = copyFrom->nTimeSmart;
1692 copyTo->fFromMe = copyFrom->fFromMe;
1693 copyTo->strFromAccount = copyFrom->strFromAccount;
1694 copyTo->nOrderPos = copyFrom->nOrderPos;
1695 copyTo->WriteToDisk(&walletdb);
1700 pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true));
1701 } // (!fDisableWallet)
1702 #else // ENABLE_WALLET
1703 LogPrintf("No wallet support compiled in!\n");
1704 #endif // !ENABLE_WALLET
1706 #ifdef ENABLE_MINING
1707 #ifndef ENABLE_WALLET
1708 if (GetBoolArg("-minetolocalwallet", false)) {
1709 return InitError(_("Zcash was not built with wallet support. Set -minetolocalwallet=0 to use -mineraddress, or rebuild Zcash with wallet support."));
1711 if (GetArg("-mineraddress", "").empty() && GetBoolArg("-gen", false)) {
1712 return InitError(_("Zcash was not built with wallet support. Set -mineraddress, or rebuild Zcash with wallet support."));
1714 #endif // !ENABLE_WALLET
1716 if (mapArgs.count("-mineraddress")) {
1717 #ifdef ENABLE_WALLET
1718 bool minerAddressInLocalWallet = false;
1720 // Address has alreday been validated
1721 CTxDestination addr = DecodeDestination(mapArgs["-mineraddress"]);
1722 CKeyID keyID = boost::get<CKeyID>(addr);
1723 minerAddressInLocalWallet = pwalletMain->HaveKey(keyID);
1725 if (GetBoolArg("-minetolocalwallet", true) && !minerAddressInLocalWallet) {
1726 return InitError(_("-mineraddress is not in the local wallet. Either use a local address, or set -minetolocalwallet=0"));
1728 #endif // ENABLE_WALLET
1730 #endif // ENABLE_MINING
1732 // ********************************************************* Step 9: data directory maintenance
1734 // if pruning, unset the service bit and perform the initial blockstore prune
1735 // after any wallet rescanning has taken place.
1737 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1738 nLocalServices &= ~NODE_NETWORK;
1740 uiInterface.InitMessage(_("Pruning blockstore..."));
1745 // ********************************************************* Step 10: import blocks
1747 if (mapArgs.count("-blocknotify"))
1748 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1750 uiInterface.InitMessage(_("Activating best chain..."));
1751 // scan for better chains in the block chain database, that are not yet connected in the active best chain
1752 CValidationState state;
1753 if (!ActivateBestChain(state))
1754 strErrors << "Failed to connect best block";
1756 std::vector<boost::filesystem::path> vImportFiles;
1757 if (mapArgs.count("-loadblock"))
1759 BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
1760 vImportFiles.push_back(strFile);
1762 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1763 if (chainActive.Tip() == NULL) {
1764 LogPrintf("Waiting for genesis block to be imported...\n");
1765 while (!fRequestShutdown && chainActive.Tip() == NULL)
1769 // ********************************************************* Step 11: start node
1771 if (!CheckDiskSpace())
1774 if (!strErrors.str().empty())
1775 return InitError(strErrors.str());
1778 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1779 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1780 #ifdef ENABLE_WALLET
1781 LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
1782 LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
1783 LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
1786 if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1787 StartTorControl(threadGroup, scheduler);
1789 StartNode(threadGroup, scheduler);
1791 // Monitor the chain, and alert if we get blocks much quicker or slower than expected
1792 int64_t nPowTargetSpacing = Params().GetConsensus().nPowTargetSpacing;
1793 CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload,
1794 boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing);
1795 scheduler.scheduleEvery(f, nPowTargetSpacing);
1797 #ifdef ENABLE_MINING
1798 // Generate coins in the background
1799 #ifdef ENABLE_WALLET
1800 if (pwalletMain || !GetArg("-mineraddress", "").empty())
1801 GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 1));
1803 GenerateBitcoins(GetBoolArg("-gen", false), GetArg("-genproclimit", 1));
1807 // ********************************************************* Step 11: finished
1809 SetRPCWarmupFinished();
1810 uiInterface.InitMessage(_("Done loading"));
1812 #ifdef ENABLE_WALLET
1814 // Add wallet transactions that aren't already in a block to mapTransactions
1815 pwalletMain->ReacceptWalletTransactions();
1817 // Run a thread to flush wallet periodically
1818 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1823 threadGroup.create_thread(boost::bind(ThreadSendAlert));
1825 return !fRequestShutdown;