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 https://www.opensource.org/licenses/mit-license.php .
6 #if defined(HAVE_CONFIG_H)
7 #include "config/bitcoin-config.h"
11 #include "crypto/common.h"
12 #include "primitives/block.h"
15 #include "checkpoints.h"
16 #include "compat/sanity.h"
17 #include "consensus/upgrades.h"
18 #include "consensus/validation.h"
19 #include "httpserver.h"
22 #include "notarisationdb.h"
30 #include "rpc/server.h"
31 #include "rpc/pbaasrpc.h"
32 #include "rpc/register.h"
33 #include "script/standard.h"
34 #include "script/sigcache.h"
35 #include "scheduler.h"
37 #include "torcontrol.h"
38 #include "ui_interface.h"
40 #include "utilmoneystr.h"
41 #include "validationinterface.h"
44 #include "wallet/wallet.h"
45 #include "wallet/walletdb.h"
54 #include <boost/algorithm/string/classification.hpp>
55 #include <boost/algorithm/string/predicate.hpp>
56 #include <boost/algorithm/string/replace.hpp>
57 #include <boost/algorithm/string/split.hpp>
58 #include <boost/bind.hpp>
59 #include <boost/filesystem.hpp>
60 #include <boost/function.hpp>
61 #include <boost/interprocess/sync/file_lock.hpp>
62 #include <boost/thread.hpp>
63 #include <openssl/crypto.h>
65 #include <libsnark/common/profiling.hpp>
68 #include "zmq/zmqnotificationinterface.h"
72 #include "amqp/amqpnotificationinterface.h"
75 #include "librustzcash.h"
79 extern void ThreadSendAlert();
80 extern int32_t KOMODO_LOADINGBLOCKS;
81 extern bool VERUS_MINTBLOCKS;
82 extern std::string VERUS_CHEATCATCHER;
84 ZCJoinSplit* pzcashParams = NULL;
87 CWallet* pwalletMain = NULL;
89 bool fFeeEstimatesInitialized = false;
92 static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
96 static AMQPNotificationInterface* pAMQPNotificationInterface = NULL;
100 // Win32 LevelDB doesn't use file descriptors, and the ones used for
101 // accessing block files don't count towards the fd_set size limit
103 #define MIN_CORE_FILEDESCRIPTORS 0
105 #define MIN_CORE_FILEDESCRIPTORS 150
108 /** Used to pass flags to the Bind() function */
111 BF_EXPLICIT = (1U << 0),
112 BF_REPORT_ERROR = (1U << 1),
113 BF_WHITELIST = (1U << 2),
116 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
117 CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h
119 //////////////////////////////////////////////////////////////////////////////
125 // Thread management and startup/shutdown:
127 // The network-processing threads are all part of a thread group
128 // created by AppInit().
130 // A clean exit happens when StartShutdown() or the SIGTERM
131 // signal handler sets fRequestShutdown, which triggers
132 // the DetectShutdownThread(), which interrupts the main thread group.
133 // DetectShutdownThread() then exits, which causes AppInit() to
134 // continue (it .joins the shutdown thread).
135 // Shutdown() is then
136 // called to clean up database connections, and stop other
137 // threads that should only be stopped after the main network-processing
138 // threads have exited.
140 // Note that if running -daemon the parent process returns from AppInit2
141 // before adding any threads to the threadGroup, so .join_all() returns
142 // immediately and the parent exits from main().
145 std::atomic<bool> fRequestShutdown(false);
149 fRequestShutdown = true;
151 bool ShutdownRequested()
153 return fRequestShutdown;
156 class CCoinsViewErrorCatcher : public CCoinsViewBacked
159 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
160 bool GetCoins(const uint256 &txid, CCoins &coins) const {
162 return CCoinsViewBacked::GetCoins(txid, coins);
163 } catch(const std::runtime_error& e) {
164 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
165 LogPrintf("Error reading from database: %s\n", e.what());
166 // Starting the shutdown sequence and returning false to the caller would be
167 // interpreted as 'entry not found' (as opposed to unable to read data), and
168 // could lead to invalid interpretation. Just exit immediately, as we can't
169 // continue anyway, and all writes should be atomic.
173 // Writes do not need similar protection, as failure to write is handled by the caller.
176 static CCoinsViewDB *pcoinsdbview = NULL;
177 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
178 static boost::scoped_ptr<ECCVerifyHandle> globalVerifyHandle;
180 void Interrupt(boost::thread_group& threadGroup)
182 InterruptHTTPServer();
186 InterruptTorControl();
187 threadGroup.interrupt_all();
192 LogPrintf("%s: In progress...\n", __func__);
193 static CCriticalSection cs_Shutdown;
194 TRY_LOCK(cs_Shutdown, lockShutdown);
198 /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
199 /// for example if the data directory was found to be locked.
200 /// Be sure that anything that writes files or flushes caches only does this if the respective
201 /// module was initialized.
202 RenameThread("verus-shutoff");
203 mempool.AddTransactionsUpdated(1);
211 pwalletMain->Flush(false);
216 GenerateBitcoins(false, NULL, 0);
218 GenerateBitcoins(false, 0);
224 UnregisterNodeSignals(GetNodeSignals());
226 if (fFeeEstimatesInitialized)
228 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
229 CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
230 if (!est_fileout.IsNull())
231 mempool.WriteFeeEstimates(est_fileout);
233 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
234 fFeeEstimatesInitialized = false;
239 if (pcoinsTip != NULL) {
244 delete pcoinscatcher;
245 pcoinscatcher = NULL;
253 pwalletMain->Flush(true);
257 if (pzmqNotificationInterface) {
258 UnregisterValidationInterface(pzmqNotificationInterface);
259 delete pzmqNotificationInterface;
260 pzmqNotificationInterface = NULL;
265 if (pAMQPNotificationInterface) {
266 UnregisterValidationInterface(pAMQPNotificationInterface);
267 delete pAMQPNotificationInterface;
268 pAMQPNotificationInterface = NULL;
274 boost::filesystem::remove(GetPidFile());
275 } catch (const boost::filesystem::filesystem_error& e) {
276 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
279 UnregisterAllValidationInterfaces();
286 globalVerifyHandle.reset();
288 LogPrintf("%s: done\n", __func__);
292 * Signal handlers are very limited in what they are allowed to do, so:
294 void HandleSIGTERM(int)
296 fRequestShutdown = true;
299 void HandleSIGHUP(int)
301 fReopenDebugLog = true;
304 bool static InitError(const std::string &str)
306 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
310 bool static InitWarning(const std::string &str)
312 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
316 bool static Bind(const CService &addr, unsigned int flags) {
317 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
319 std::string strError;
320 if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
321 if (flags & BF_REPORT_ERROR)
322 return InitError(strError);
330 cvBlockChange.notify_all();
331 LogPrint("rpc", "RPC stopped.\n");
334 void OnRPCPreCommand(const CRPCCommand& cmd)
337 string strWarning = GetWarnings("rpc");
338 if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
340 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
343 std::string HelpMessage(HelpMessageMode mode)
345 const bool showDebug = GetBoolArg("-help-debug", false);
347 // When adding new options to the categories, please keep and ensure alphabetical ordering.
348 // Do not translate _(...) -help-debug options, many technical terms, and only a very small audience, so is unnecessary stress to translators
350 string strUsage = HelpMessageGroup(_("Options:"));
351 strUsage += HelpMessageOpt("-?", _("This help message"));
352 strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
353 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)"));
354 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
355 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 288));
356 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), 3));
357 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "komodo.conf"));
358 if (mode == HMM_BITCOIND)
361 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
364 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
365 strUsage += HelpMessageOpt("-exportdir=<dir>", _("Specify directory to be used when exporting data"));
366 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
367 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup"));
368 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
369 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)"));
370 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)"),
371 -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
373 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "verusd.pid"));
375 strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode disables wallet support and is incompatible with -txindex. "
376 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
377 "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
378 strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files on startup"));
380 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
382 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
383 strUsage += HelpMessageOpt("-addressindex", strprintf(_("Maintain a full address index, used to query for the balance, txids and unspent outputs for addresses (default: %u)"), DEFAULT_ADDRESSINDEX));
384 strUsage += HelpMessageOpt("-timestampindex", strprintf(_("Maintain a timestamp index for block hashes, used to query blocks hashes by a range of timestamps (default: %u)"), DEFAULT_TIMESTAMPINDEX));
385 strUsage += HelpMessageOpt("-spentindex", strprintf(_("Maintain a full spent index, used to query the spending txid and input index for an outpoint (default: %u)"), DEFAULT_SPENTINDEX));
386 strUsage += HelpMessageGroup(_("Connection options:"));
387 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
388 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100));
389 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400));
390 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
391 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)"));
392 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
393 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)"));
394 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)"));
395 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
396 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0));
397 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
398 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
399 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
400 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000));
401 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000));
402 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
403 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
404 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1));
405 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with Bloom filters (default: %u)"), 1));
407 strUsage += HelpMessageOpt("-enforcenodebloom", strprintf("Enforce minimum protocol version to limit use of Bloom filters (default: %u)", 0));
408 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 7770, 17770));
409 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
410 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1));
411 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
412 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
413 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
414 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
415 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
416 strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
417 " " + _("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"));
420 strUsage += HelpMessageGroup(_("Wallet options:"));
421 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
422 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100));
423 strUsage += HelpMessageOpt("-migration", _("Enable the Sprout to Sapling migration"));
424 strUsage += HelpMessageOpt("-migrationdestaddress=<zaddr>", _("Set the Sapling migration address"));
426 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)",
427 CURRENCY_UNIT, FormatMoney(CWallet::minTxFee.GetFeePerK())));
428 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
429 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
430 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
431 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
432 strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
433 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1));
434 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));
435 strUsage += HelpMessageOpt("-txexpirydelta", strprintf(_("Set the number of blocks after which a transaction that has not been mined will become invalid (min: %u, default: %u (pre-Blossom) or %u (post-Blossom))"), TX_EXPIRING_SOON_THRESHOLD + 1, DEFAULT_PRE_BLOSSOM_TX_EXPIRY_DELTA, DEFAULT_POST_BLOSSOM_TX_EXPIRY_DELTA));
436 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)"),
437 CURRENCY_UNIT, FormatMoney(maxTxFee)));
438 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup"));
439 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
440 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), true));
441 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
442 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
443 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
447 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
448 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
449 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
450 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
451 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
455 strUsage += HelpMessageGroup(_("AMQP 1.0 notification options:"));
456 strUsage += HelpMessageOpt("-amqppubhashblock=<address>", _("Enable publish hash block in <address>"));
457 strUsage += HelpMessageOpt("-amqppubhashtx=<address>", _("Enable publish hash transaction in <address>"));
458 strUsage += HelpMessageOpt("-amqppubrawblock=<address>", _("Enable publish raw block in <address>"));
459 strUsage += HelpMessageOpt("-amqppubrawtx=<address>", _("Enable publish raw transaction in <address>"));
462 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
465 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", 1));
466 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)", 100));
467 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", 0));
468 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", 0));
469 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
470 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
471 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", 1));
472 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", 0));
473 strUsage += HelpMessageOpt("-nuparams=hexBranchId:activationHeight", "Use given activation height for specified network upgrade (regtest-only)");
475 string debugCategories = "addrman, alert, bench, coindb, db, estimatefee, http, libevent, lock, mempool, net, partitioncheck, pow, proxy, prune, "
476 "rand, reindex, rpc, selectcoins, tor, zmq, zrpc, zrpcunsafe (implies zrpc)"; // Don't translate these
477 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
478 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + debugCategories + ".");
479 strUsage += HelpMessageOpt("-experimentalfeatures", _("Enable use of experimental features"));
480 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
481 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
482 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
485 strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
486 strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 0));
487 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
488 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
490 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying (default: %s)"),
491 CURRENCY_UNIT, FormatMoney(::minRelayTxFee.GetFeePerK())));
492 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
495 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", 0));
496 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", 1));
497 strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
498 "This is intended for regression testing tools and app development.");
500 // strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
501 strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
503 strUsage += HelpMessageGroup(_("Node relay options:"));
504 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1));
505 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
507 strUsage += HelpMessageGroup(_("Block creation options:"));
508 strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), 0));
509 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
510 strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
511 if (GetBoolArg("-help-debug", false))
512 strUsage += HelpMessageOpt("-blockversion=<n>", strprintf("Override block version to test forking scenarios (default: %d)", (int)CBlock::CURRENT_VERSION));
515 strUsage += HelpMessageGroup(_("Mining options:"));
516 strUsage += HelpMessageOpt("-mint", strprintf(_("Mint/stake coins automatically (default: %u)"), 0));
517 strUsage += HelpMessageOpt("-gen", strprintf(_("Mine/generate coins (default: %u)"), 0));
518 strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin mining if enabled (-1 = all cores, default: %d)"), 0));
519 strUsage += HelpMessageOpt("-equihashsolver=<name>", _("Specify the Equihash solver to be used if enabled (default: \"default\")"));
520 strUsage += HelpMessageOpt("-mineraddress=<addr>", _("Send mined coins to a specific single address"));
521 strUsage += HelpMessageOpt("-minetolocalwallet", strprintf(
522 _("Require that mined blocks use a coinbase address in the local wallet (default: %u)"),
531 strUsage += HelpMessageGroup(_("RPC server options:"));
532 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
533 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0));
534 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)"));
535 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
536 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
537 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 7771, 17771));
538 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"));
539 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
541 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
542 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
545 // Disabled until we can lock notes and also tune performance of libsnark which by default uses multiple threads
546 //strUsage += HelpMessageOpt("-rpcasyncthreads=<n>", strprintf(_("Set the number of threads to service Async RPC calls (default: %d)"), 1));
548 if (mode == HMM_BITCOIND) {
549 strUsage += HelpMessageGroup(_("Metrics Options (only if -daemon and -printtoconsole are not set):"));
550 strUsage += HelpMessageOpt("-showmetrics", _("Show metrics on stdout (default: 1 if running in a console, 0 otherwise)"));
551 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)"));
552 strUsage += HelpMessageOpt("-metricsrefreshtime", strprintf(_("Number of seconds between metrics refreshes (default: %u if running in a console, %u otherwise)"), 1, 600));
558 static void BlockNotifyCallback(const uint256& hashNewTip)
560 std::string strCmd = GetArg("-blocknotify", "");
562 boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
563 boost::thread t(runCommand, strCmd); // thread runs free
569 assert(fImporting == false);
574 assert(fImporting == true);
580 // If we're using -prune with -reindex, then delete block files that will be ignored by the
581 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
582 // is missing, do the same here to delete any later block files after a gap. Also delete all
583 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
584 // is in sync with what's actually on disk by the time we start downloading, so that pruning
586 void CleanupBlockRevFiles()
588 using namespace boost::filesystem;
589 map<string, path> mapBlockFiles;
591 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
592 // Remove the rev files immediately and insert the blk file paths into an
593 // ordered map keyed by block file index.
594 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
595 path blocksdir = GetDataDir() / "blocks";
596 for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
597 if (is_regular_file(*it) &&
598 it->path().filename().string().length() == 12 &&
599 it->path().filename().string().substr(8,4) == ".dat")
601 if (it->path().filename().string().substr(0,3) == "blk")
602 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
603 else if (it->path().filename().string().substr(0,3) == "rev")
607 path komodostate = GetDataDir() / "komodostate";
609 path minerids = GetDataDir() / "minerids";
611 // Remove all block files that aren't part of a contiguous set starting at
612 // zero by walking the ordered map (keys are block file indices) by
613 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
614 // start removing block files.
615 int nContigCounter = 0;
616 BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) {
617 if (atoi(item.first) == nContigCounter) {
625 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
627 const CChainParams& chainparams = Params();
628 RenameThread("zcash-loadblk");
634 CDiskBlockPos pos(nFile, 0);
635 if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
636 break; // No block files left to reindex
637 FILE *file = OpenBlockFile(pos, true);
639 break; // This error is logged in OpenBlockFile
640 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
641 LoadExternalBlockFile(chainparams, file, &pos);
644 pblocktree->WriteReindexing(false);
646 LogPrintf("Reindexing finished\n");
647 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
648 InitBlockIndex(chainparams);
649 KOMODO_LOADINGBLOCKS = 0;
652 // hardcoded $DATADIR/bootstrap.dat
653 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
654 if (boost::filesystem::exists(pathBootstrap)) {
655 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
658 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
659 LogPrintf("Importing bootstrap.dat...\n");
660 LoadExternalBlockFile(chainparams, file);
661 RenameOver(pathBootstrap, pathBootstrapOld);
663 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
668 BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
669 FILE *file = fopen(path.string().c_str(), "rb");
672 LogPrintf("Importing blocks file %s...\n", path.string());
673 LoadExternalBlockFile(chainparams, file);
675 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
679 if (GetBoolArg("-stopafterblockimport", false)) {
680 LogPrintf("Stopping after block import\n");
685 void ThreadNotifyRecentlyAdded()
688 // Run the notifier on an integer second in the steady clock.
689 auto now = std::chrono::steady_clock::now().time_since_epoch();
690 auto nextFire = std::chrono::duration_cast<std::chrono::seconds>(
691 now + std::chrono::seconds(1));
692 std::this_thread::sleep_until(
693 std::chrono::time_point<std::chrono::steady_clock>(nextFire));
695 boost::this_thread::interruption_point();
697 mempool.NotifyRecentlyAdded();
702 * Ensure that Bitcoin is running in a usable environment with all
703 * necessary library support.
705 bool InitSanityCheck(void)
707 if(!ECC_InitSanityCheck()) {
708 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
711 if (!glibc_sanity_test() || !glibcxx_sanity_test())
718 static void ZC_LoadParams(
719 const CChainParams& chainparams
722 struct timeval tv_start, tv_end;
725 boost::filesystem::path pk_path = ZC_GetParamsDir() / "sprout-proving.key";
726 boost::filesystem::path vk_path = ZC_GetParamsDir() / "sprout-verifying.key";
727 boost::filesystem::path sapling_spend = ZC_GetParamsDir() / "sapling-spend.params";
728 boost::filesystem::path sapling_output = ZC_GetParamsDir() / "sapling-output.params";
729 boost::filesystem::path sprout_groth16 = ZC_GetParamsDir() / "sprout-groth16.params";
732 boost::filesystem::exists(pk_path) &&
733 boost::filesystem::exists(vk_path) &&
734 boost::filesystem::exists(sapling_spend) &&
735 boost::filesystem::exists(sapling_output) &&
736 boost::filesystem::exists(sprout_groth16)
738 uiInterface.ThreadSafeMessageBox(strprintf(
739 _("Cannot find the Zcash network parameters in the following directory:\n"
741 "Please run 'fetch-params' or './zcutil/fetch-params.sh' and then restart."),
743 "", CClientUIInterface::MSG_ERROR);
748 LogPrintf("Loading verifying key from %s\n", vk_path.string().c_str());
749 gettimeofday(&tv_start, 0);
751 pzcashParams = ZCJoinSplit::Prepared(vk_path.string(), pk_path.string());
753 gettimeofday(&tv_end, 0);
754 elapsed = float(tv_end.tv_sec-tv_start.tv_sec) + (tv_end.tv_usec-tv_start.tv_usec)/float(1000000);
755 LogPrintf("Loaded verifying key in %fs seconds.\n", elapsed);
758 sizeof(boost::filesystem::path::value_type) == sizeof(codeunit),
759 "librustzcash not configured correctly");
760 auto sapling_spend_str = sapling_spend.native();
761 auto sapling_output_str = sapling_output.native();
762 auto sprout_groth16_str = sprout_groth16.native();
764 LogPrintf("Loading Sapling (Spend) parameters from %s\n", sapling_spend.string().c_str());
765 LogPrintf("Loading Sapling (Output) parameters from %s\n", sapling_output.string().c_str());
766 LogPrintf("Loading Sapling (Sprout Groth16) parameters from %s\n", sprout_groth16.string().c_str());
767 gettimeofday(&tv_start, 0);
769 librustzcash_init_zksnark_params(
770 reinterpret_cast<const codeunit*>(sapling_spend_str.c_str()),
771 sapling_spend_str.length(),
772 "8270785a1a0d0bc77196f000ee6d221c9c9894f55307bd9357c3f0105d31ca63991ab91324160d8f53e2bbd3c2633a6eb8bdf5205d822e7f3f73edac51b2b70c",
773 reinterpret_cast<const codeunit*>(sapling_output_str.c_str()),
774 sapling_output_str.length(),
775 "657e3d38dbb5cb5e7dd2970e8b03d69b4787dd907285b5a7f0790dcc8072f60bf593b32cc2d1c030e00ff5ae64bf84c5c3beb84ddc841d48264b4a171744d028",
776 reinterpret_cast<const codeunit*>(sprout_groth16_str.c_str()),
777 sprout_groth16_str.length(),
778 "e9b238411bd6c0ec4791e9d04245ec350c9c5744f5610dfcce4365d5ca49dfefd5054e371842b3f88fa1b9d7e8e075249b3ebabd167fa8b0f3161292d36c180a"
781 gettimeofday(&tv_end, 0);
782 elapsed = float(tv_end.tv_sec-tv_start.tv_sec) + (tv_end.tv_usec-tv_start.tv_usec)/float(1000000);
783 LogPrintf("Loaded Sapling parameters in %fs seconds.\n", elapsed);
786 bool AppInitServers(boost::thread_group& threadGroup)
788 RPCServer::OnStopped(&OnRPCStopped);
789 RPCServer::OnPreCommand(&OnRPCPreCommand);
790 if (!InitHTTPServer())
796 if (GetBoolArg("-rest", false) && !StartREST())
798 if (!StartHTTPServer())
803 /** Initialize bitcoin.
804 * @pre Parameters should be parsed and config file should be read.
806 extern int32_t KOMODO_REWIND;
808 bool AppInitNetworking()
810 // ********************************************************* Step 1: setup
812 // Turn off Microsoft heap dump noise
813 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
814 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
817 // Disable confusing "helpful" text message on abort, Ctrl-C
818 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
821 // Enable Data Execution Prevention (DEP)
822 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
823 // A failure is non-critical and needs no further attention!
824 #ifndef PROCESS_DEP_ENABLE
825 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
826 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
827 #define PROCESS_DEP_ENABLE 0x00000001
829 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
830 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
831 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
834 if (!SetupNetworking())
835 return InitError("Error: Initializing networking failed");
840 bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
843 if (GetBoolArg("-sysperms", false)) {
845 if (!GetBoolArg("-disablewallet", false))
846 return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
852 // Clean shutdown on SIGTERM
854 sa.sa_handler = HandleSIGTERM;
855 sigemptyset(&sa.sa_mask);
857 sigaction(SIGTERM, &sa, NULL);
858 sigaction(SIGINT, &sa, NULL);
860 // Reopen debug.log on SIGHUP
861 struct sigaction sa_hup;
862 sa_hup.sa_handler = HandleSIGHUP;
863 sigemptyset(&sa_hup.sa_mask);
865 sigaction(SIGHUP, &sa_hup, NULL);
867 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
868 signal(SIGPIPE, SIG_IGN);
871 std::set_new_handler(new_handler_terminate);
873 // ********************************************************* Step 2: parameter interactions
874 const CChainParams& chainparams = Params();
876 // Set this early so that experimental features are correctly enabled/disabled
877 fExperimentalMode = GetBoolArg("-experimentalfeatures", false);
879 // Fail early if user has set experimental options without the global flag
880 if (!fExperimentalMode) {
881 if (mapArgs.count("-developerencryptwallet")) {
882 return InitError(_("Wallet encryption requires -experimentalfeatures."));
883 } else if (mapArgs.count("-developersetpoolsizezero")) {
884 return InitError(_("Setting the size of shielded pools to zero requires -experimentalfeatures."));
885 } else if (mapArgs.count("-paymentdisclosure")) {
886 return InitError(_("Payment disclosure requires -experimentalfeatures."));
887 } else if (mapArgs.count("-zmergetoaddress")) {
888 return InitError(_("RPC method z_mergetoaddress requires -experimentalfeatures."));
889 } else if (mapArgs.count("-savesproutr1cs")) {
890 return InitError(_("Saving the Sprout R1CS requires -experimentalfeatures."));
894 // Set this early so that parameter interactions go to console
895 fPrintToConsole = GetBoolArg("-printtoconsole", false);
896 fLogTimestamps = GetBoolArg("-logtimestamps", true);
897 fLogIPs = GetBoolArg("-logips", false);
899 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
900 LogPrintf("Zcash version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
902 // when specifying an explicit binding address, you want to listen on it
903 // even when -connect or -proxy is specified
904 if (mapArgs.count("-bind")) {
905 if (SoftSetBoolArg("-listen", true))
906 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
908 if (mapArgs.count("-whitebind")) {
909 if (SoftSetBoolArg("-listen", true))
910 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
913 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
914 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
915 if (SoftSetBoolArg("-dnsseed", false))
916 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
917 if (SoftSetBoolArg("-listen", false))
918 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
921 if (mapArgs.count("-proxy")) {
922 // to protect privacy, do not listen by default if a default proxy server is specified
923 if (SoftSetBoolArg("-listen", false))
924 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
925 // to protect privacy, do not discover addresses by default
926 if (SoftSetBoolArg("-discover", false))
927 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
930 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
931 // do not try to retrieve public IP when not listening (pointless)
932 if (SoftSetBoolArg("-discover", false))
933 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
934 if (SoftSetBoolArg("-listenonion", false))
935 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
938 if (mapArgs.count("-externalip")) {
939 // if an explicit public IP is specified, do not try to find others
940 if (SoftSetBoolArg("-discover", false))
941 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
944 if (GetBoolArg("-salvagewallet", false)) {
945 // Rewrite just private keys: rescan to find transactions
946 if (SoftSetBoolArg("-rescan", true))
947 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
950 // -zapwallettx implies a rescan
951 if (GetBoolArg("-zapwallettxes", false)) {
952 if (SoftSetBoolArg("-rescan", true))
953 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
956 // Make sure enough file descriptors are available
957 int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
958 nMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
959 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
960 int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
961 if (nFD < MIN_CORE_FILEDESCRIPTORS)
962 return InitError(_("Not enough file descriptors available."));
963 if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
964 nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
966 // if using block pruning, then disable txindex
967 // also disable the wallet (for now, until SPV support is implemented in wallet)
968 if (GetArg("-prune", 0)) {
969 if (GetBoolArg("-txindex", true))
970 return InitError(_("Prune mode is incompatible with -txindex."));
972 if (!GetBoolArg("-disablewallet", false)) {
973 if (SoftSetBoolArg("-disablewallet", true))
974 LogPrintf("%s : parameter interaction: -prune -> setting -disablewallet=1\n", __func__);
976 return InitError(_("Can't run with a wallet in prune mode."));
981 // ********************************************************* Step 3: parameter-to-internal-flags
983 fDebug = !mapMultiArgs["-debug"].empty();
984 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
985 const vector<string>& categories = mapMultiArgs["-debug"];
986 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
989 // Special case: if debug=zrpcunsafe, implies debug=zrpc, so add it to debug categories
990 if (find(categories.begin(), categories.end(), string("zrpcunsafe")) != categories.end()) {
991 if (find(categories.begin(), categories.end(), string("zrpc")) == categories.end()) {
992 LogPrintf("%s: parameter interaction: setting -debug=zrpcunsafe -> -debug=zrpc\n", __func__);
993 vector<string>& v = mapMultiArgs["-debug"];
998 // Check for -debugnet
999 if (GetBoolArg("-debugnet", false))
1000 InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
1001 // Check for -socks - as this is a privacy risk to continue, exit here
1002 if (mapArgs.count("-socks"))
1003 return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
1004 // Check for -tor - as this is a privacy risk to continue, exit here
1005 if (GetBoolArg("-tor", false))
1006 return InitError(_("Error: Unsupported argument -tor found, use -onion."));
1008 if (GetBoolArg("-benchmark", false))
1009 InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
1011 // Checkmempool and checkblockindex default to true in regtest mode
1012 int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
1014 mempool.setSanityCheck(1.0 / ratio);
1016 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
1017 fCheckpointsEnabled = GetBoolArg("-checkpoints", true);
1019 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
1020 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
1021 if (nScriptCheckThreads <= 0)
1022 nScriptCheckThreads += GetNumCores();
1023 if (nScriptCheckThreads <= 1)
1024 nScriptCheckThreads = 0;
1025 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
1026 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
1028 fServer = GetBoolArg("-server", false);
1030 // block pruning; get the amount of disk space (in MB) to allot for block & undo files
1031 int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
1032 if (nSignedPruneTarget < 0) {
1033 return InitError(_("Prune cannot be configured with a negative value."));
1035 nPruneTarget = (uint64_t) nSignedPruneTarget;
1037 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
1038 return InitError(strprintf(_("Prune configured below the minimum of %d MB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1040 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1044 RegisterAllCoreRPCCommands(tableRPC);
1045 #ifdef ENABLE_WALLET
1046 bool fDisableWallet = GetBoolArg("-disablewallet", false);
1047 if (!fDisableWallet)
1048 RegisterWalletRPCCommands(tableRPC);
1051 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1052 if (nConnectTimeout <= 0)
1053 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1055 // Fee-per-kilobyte amount considered the same as "free"
1056 // If you are mining, be careful setting this:
1057 // if you set it to zero then
1058 // a transaction spammer can cheaply fill blocks using
1059 // 1-satoshi-fee transactions. It should be set above the real
1060 // cost to you of processing a transaction.
1061 if (mapArgs.count("-minrelaytxfee"))
1064 if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
1065 ::minRelayTxFee = CFeeRate(n);
1067 return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
1070 #ifdef ENABLE_WALLET
1071 if (mapArgs.count("-mintxfee"))
1074 if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
1075 CWallet::minTxFee = CFeeRate(n);
1077 return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
1079 if (mapArgs.count("-paytxfee"))
1081 CAmount nFeePerK = 0;
1082 if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
1083 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
1084 if (nFeePerK > nHighTransactionFeeWarning)
1085 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
1086 payTxFee = CFeeRate(nFeePerK, 1000);
1087 if (payTxFee < ::minRelayTxFee)
1089 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
1090 mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
1093 if (mapArgs.count("-maxtxfee"))
1095 CAmount nMaxFee = 0;
1096 if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
1097 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maptxfee"]));
1098 if (nMaxFee > nHighTransactionMaxFeeWarning)
1099 InitWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction."));
1101 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
1103 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
1104 mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
1107 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
1108 if (mapArgs.count("-txexpirydelta")) {
1109 int64_t expiryDelta = atoi64(mapArgs["-txexpirydelta"]);
1110 uint32_t minExpiryDelta = TX_EXPIRING_SOON_THRESHOLD + 1;
1111 if (expiryDelta < minExpiryDelta) {
1112 return InitError(strprintf(_("Invalid value for -txexpirydelta='%u' (must be least %u)"), expiryDelta, minExpiryDelta));
1114 expiryDeltaArg = expiryDelta;
1116 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", true);
1117 fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false);
1119 std::string strWalletFile = GetArg("-wallet", "wallet.dat");
1120 // Check Sapling migration address if set and is a valid Sapling address
1121 if (mapArgs.count("-migrationdestaddress")) {
1122 std::string migrationDestAddress = mapArgs["-migrationdestaddress"];
1123 libzcash::PaymentAddress address = DecodePaymentAddress(migrationDestAddress);
1124 if (boost::get<libzcash::SaplingPaymentAddress>(&address) == nullptr) {
1125 return InitError(_("-migrationdestaddress must be a valid Sapling address."));
1128 #endif // ENABLE_WALLET
1130 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true);
1131 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1133 fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
1135 // Option to startup with mocktime set (used for regression testing):
1136 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1138 if (GetBoolArg("-peerbloomfilters", true))
1139 nLocalServices |= NODE_BLOOM;
1141 nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1143 #ifdef ENABLE_MINING
1144 if (mapArgs.count("-mineraddress")) {
1145 CTxDestination addr = DecodeDestination(mapArgs["-mineraddress"]);
1146 if (!IsValidDestination(addr)) {
1147 return InitError(strprintf(
1148 _("Invalid address for -mineraddress=<addr>: '%s' (must be a transparent address)"),
1149 mapArgs["-mineraddress"]));
1154 // Default value of 0 for mempooltxinputlimit means no limit is applied
1155 if (mapArgs.count("-mempooltxinputlimit")) {
1156 int64_t limit = GetArg("-mempooltxinputlimit", 0);
1158 return InitError(_("Mempool limit on transparent inputs to a transaction cannot be negative"));
1159 } else if (limit > 0) {
1160 LogPrintf("Mempool configured to reject transactions with greater than %lld transparent inputs\n", limit);
1164 if (!mapMultiArgs["-nuparams"].empty()) {
1165 // Allow overriding network upgrade parameters for testing
1166 if (Params().NetworkIDString() != "regtest") {
1167 return InitError("Network upgrade parameters may only be overridden on regtest.");
1169 const vector<string>& deployments = mapMultiArgs["-nuparams"];
1170 for (auto i : deployments) {
1171 std::vector<std::string> vDeploymentParams;
1172 boost::split(vDeploymentParams, i, boost::is_any_of(":"));
1173 if (vDeploymentParams.size() != 2) {
1174 return InitError("Network upgrade parameters malformed, expecting hexBranchId:activationHeight");
1176 int nActivationHeight;
1177 if (!ParseInt32(vDeploymentParams[1], &nActivationHeight)) {
1178 return InitError(strprintf("Invalid nActivationHeight (%s)", vDeploymentParams[1]));
1181 // Exclude Sprout from upgrades
1182 for (auto i = Consensus::BASE_SPROUT + 1; i < Consensus::MAX_NETWORK_UPGRADES; ++i)
1184 if (vDeploymentParams[0].compare(HexInt(NetworkUpgradeInfo[i].nBranchId)) == 0) {
1185 UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex(i), nActivationHeight);
1187 LogPrintf("Setting network upgrade activation parameters for %s to height=%d\n", vDeploymentParams[0], nActivationHeight);
1192 return InitError(strprintf("Invalid network upgrade (%s)", vDeploymentParams[0]));
1197 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
1199 // Initialize libsodium
1200 if (init_and_check_sodium() == -1) {
1204 // Initialize elliptic curve code
1206 globalVerifyHandle.reset(new ECCVerifyHandle());
1208 // set the hash algorithm to use for this chain
1209 extern uint32_t ASSETCHAINS_ALGO, ASSETCHAINS_VERUSHASH;
1210 if (ASSETCHAINS_ALGO == ASSETCHAINS_VERUSHASH)
1212 // initialize VerusHash
1214 CVerusHashV2::init();
1215 CBlockHeader::SetVerusV2Hash();
1216 if (strcmp(ASSETCHAINS_SYMBOL,"VRSC") == 0)
1218 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV2, 310000);
1219 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV3, 782000);
1223 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV2, 1);
1224 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV3, 110);
1225 //CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV4, 1);
1230 if (!InitSanityCheck())
1231 return InitError(_("Initialization sanity check failed. Komodo is shutting down."));
1233 std::string strDataDir = GetDataDir().string();
1234 #ifdef ENABLE_WALLET
1235 // Wallet file must be a plain filename without a directory
1236 if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
1237 return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
1239 // Make sure only a single Bitcoin process is using the data directory.
1240 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
1241 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
1242 if (file) fclose(file);
1245 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1246 if (!lock.try_lock())
1247 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Komodo is probably already running."), strDataDir));
1248 } catch(const boost::interprocess::interprocess_exception& e) {
1249 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Komodo is probably already running.") + " %s.", strDataDir, e.what()));
1253 CreatePidFile(GetPidFile(), getpid());
1255 if (GetBoolArg("-shrinkdebugfile", !fDebug))
1257 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
1258 LogPrintf("Komodo version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
1260 if (fPrintToDebugLog)
1262 LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
1263 #ifdef ENABLE_WALLET
1264 LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
1266 if (!fLogTimestamps)
1267 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1268 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1269 LogPrintf("Using data directory %s\n", strDataDir);
1270 LogPrintf("Using config file %s\n", GetConfigFile().string());
1271 LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
1272 std::ostringstream strErrors;
1274 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1275 if (nScriptCheckThreads) {
1276 for (int i=0; i<nScriptCheckThreads-1; i++)
1277 threadGroup.create_thread(&ThreadScriptCheck);
1280 // Start the lightweight task scheduler thread
1281 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1282 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1287 if ((chainparams.NetworkIDString() != "regtest") &&
1288 GetBoolArg("-showmetrics", 0) &&
1289 !fPrintToConsole && !GetBoolArg("-daemon", false)) {
1290 // Start the persistent metrics interface
1291 ConnectMetricsScreen();
1292 threadGroup.create_thread(&ThreadShowMetricsScreen);
1295 // These must be disabled for now, they are buggy and we probably don't
1296 // want any of libsnark's profiling in production anyway.
1297 libsnark::inhibit_profiling_info = true;
1298 libsnark::inhibit_profiling_counters = true;
1300 // Initialize Zcash circuit parameters
1301 ZC_LoadParams(chainparams);
1303 if (GetBoolArg("-savesproutr1cs", false)) {
1304 boost::filesystem::path r1cs_path = ZC_GetParamsDir() / "r1cs";
1306 LogPrintf("Saving Sprout R1CS to %s\n", r1cs_path.string());
1308 pzcashParams->saveR1CS(r1cs_path.string());
1311 /* Start the RPC server already. It will be started in "warmup" mode
1312 * and not really process calls already (but it will signify connections
1313 * that the server is there and will be ready later). Warmup mode will
1314 * be disabled when initialisation is finished.
1318 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1319 if (!AppInitServers(threadGroup))
1320 return InitError(_("Unable to start HTTP server. See debug log for details."));
1325 // ********************************************************* Step 5: verify wallet database integrity
1326 #ifdef ENABLE_WALLET
1327 if (!fDisableWallet) {
1328 LogPrintf("Using wallet %s\n", strWalletFile);
1329 uiInterface.InitMessage(_("Verifying wallet..."));
1331 std::string warningString;
1332 std::string errorString;
1334 if (!CWallet::Verify(strWalletFile, warningString, errorString))
1337 if (!warningString.empty())
1338 InitWarning(warningString);
1339 if (!errorString.empty())
1340 return InitError(warningString);
1342 } // (!fDisableWallet)
1343 #endif // ENABLE_WALLET
1344 // ********************************************************* Step 6: network initialization
1346 RegisterNodeSignals(GetNodeSignals());
1348 // sanitize comments per BIP-0014, format user agent and check total size
1349 std::vector<string> uacomments;
1350 BOOST_FOREACH(string cmt, mapMultiArgs["-uacomment"])
1352 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1353 return InitError(strprintf("User Agent comment (%s) contains unsafe characters.", cmt));
1354 uacomments.push_back(SanitizeString(cmt, SAFE_CHARS_UA_COMMENT));
1356 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1357 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1358 return InitError(strprintf("Total length of network version string %i exceeds maximum of %i characters. Reduce the number and/or size of uacomments.",
1359 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1362 if (mapArgs.count("-onlynet")) {
1363 std::set<enum Network> nets;
1364 BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) {
1365 enum Network net = ParseNetwork(snet);
1366 if (net == NET_UNROUTABLE)
1367 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1370 for (int n = 0; n < NET_MAX; n++) {
1371 enum Network net = (enum Network)n;
1372 if (!nets.count(net))
1377 if (mapArgs.count("-whitelist")) {
1378 BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
1379 CSubNet subnet(net);
1380 if (!subnet.IsValid())
1381 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1382 CNode::AddWhitelistedRange(subnet);
1386 bool proxyRandomize = GetBoolArg("-proxyrandomize", true);
1387 // -proxy sets a proxy for all outgoing network traffic
1388 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1389 std::string proxyArg = GetArg("-proxy", "");
1390 SetLimited(NET_TOR);
1391 if (proxyArg != "" && proxyArg != "0") {
1392 proxyType addrProxy = proxyType(CService(proxyArg, 9050), proxyRandomize);
1393 if (!addrProxy.IsValid())
1394 return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
1396 SetProxy(NET_IPV4, addrProxy);
1397 SetProxy(NET_IPV6, addrProxy);
1398 SetProxy(NET_TOR, addrProxy);
1399 SetNameProxy(addrProxy);
1400 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1403 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1404 // -noonion (or -onion=0) disables connecting to .onion entirely
1405 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1406 std::string onionArg = GetArg("-onion", "");
1407 if (onionArg != "") {
1408 if (onionArg == "0") { // Handle -noonion/-onion=0
1409 SetLimited(NET_TOR); // set onions as unreachable
1411 proxyType addrOnion = proxyType(CService(onionArg, 9050), proxyRandomize);
1412 if (!addrOnion.IsValid())
1413 return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
1414 SetProxy(NET_TOR, addrOnion);
1415 SetLimited(NET_TOR, false);
1419 // see Step 2: parameter interactions for more information about these
1420 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1421 fDiscover = GetBoolArg("-discover", true);
1422 fNameLookup = GetBoolArg("-dns", true);
1424 bool fBound = false;
1426 if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
1427 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
1429 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1430 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
1431 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1433 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
1435 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1436 return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
1437 if (addrBind.GetPort() == 0)
1438 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1439 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1443 struct in_addr inaddr_any;
1444 inaddr_any.s_addr = INADDR_ANY;
1445 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
1446 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1449 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1452 if (mapArgs.count("-externalip")) {
1453 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
1454 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
1455 if (!addrLocal.IsValid())
1456 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
1457 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
1461 BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
1462 AddOneShot(strDest);
1465 pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
1467 if (pzmqNotificationInterface) {
1468 RegisterValidationInterface(pzmqNotificationInterface);
1473 pAMQPNotificationInterface = AMQPNotificationInterface::CreateWithArguments(mapArgs);
1475 if (pAMQPNotificationInterface) {
1477 // AMQP support is currently an experimental feature, so fail if user configured AMQP notifications
1478 // without enabling experimental features.
1479 if (!fExperimentalMode) {
1480 return InitError(_("AMQP support requires -experimentalfeatures."));
1483 RegisterValidationInterface(pAMQPNotificationInterface);
1487 // ********************************************************* Step 7: load block chain
1489 fReindex = GetBoolArg("-reindex", false);
1491 // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
1492 boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1493 if (!boost::filesystem::exists(blocksDir))
1495 boost::filesystem::create_directories(blocksDir);
1496 bool linked = false;
1497 for (unsigned int i = 1; i < 10000; i++) {
1498 boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1499 if (!boost::filesystem::exists(source)) break;
1500 boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
1502 boost::filesystem::create_hard_link(source, dest);
1503 LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
1505 } catch (const boost::filesystem::filesystem_error& e) {
1506 // Note: hardlink creation failing is not a disaster, it just means
1507 // blocks will get re-downloaded from peers.
1508 LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
1518 // block tree db settings
1519 int dbMaxOpenFiles = GetArg("-dbmaxopenfiles", DEFAULT_DB_MAX_OPEN_FILES);
1520 bool dbCompression = GetBoolArg("-dbcompression", DEFAULT_DB_COMPRESSION);
1522 LogPrintf("Block index database configuration:\n");
1523 LogPrintf("* Using %d max open files\n", dbMaxOpenFiles);
1524 LogPrintf("* Compression is %s\n", dbCompression ? "enabled" : "disabled");
1526 // cache size calculations
1527 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1528 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1529 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache
1530 int64_t nBlockTreeDBCache = nTotalCache / 8;
1532 if (GetBoolArg("-addressindex", DEFAULT_ADDRESSINDEX) || GetBoolArg("-spentindex", DEFAULT_SPENTINDEX)) {
1533 // enable 3/4 of the cache if addressindex and/or spentindex is enabled
1534 nBlockTreeDBCache = nTotalCache * 3 / 4;
1536 if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false)) {
1537 nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
1540 nTotalCache -= nBlockTreeDBCache;
1541 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1542 nTotalCache -= nCoinDBCache;
1543 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1544 LogPrintf("Cache configuration:\n");
1545 LogPrintf("* Max cache setting possible %.1fMiB\n", nMaxDbCache);
1546 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1547 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1548 LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
1550 if ( fReindex == 0 )
1552 bool checkval,fAddressIndex,fSpentIndex,fTimeStampIndex;
1553 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles);
1555 fAddressIndex = GetBoolArg("-addressindex", DEFAULT_ADDRESSINDEX);
1556 pblocktree->ReadFlag("addressindex", checkval);
1557 if ( checkval != fAddressIndex )
1559 pblocktree->WriteFlag("addressindex", fAddressIndex);
1560 fprintf(stderr,"set addressindex, will reindex. sorry will take a while.\n");
1564 fSpentIndex = GetBoolArg("-spentindex", DEFAULT_SPENTINDEX);
1565 pblocktree->ReadFlag("spentindex", checkval);
1566 if ( checkval != fSpentIndex )
1568 pblocktree->WriteFlag("spentindex", fSpentIndex);
1569 fprintf(stderr,"set spentindex, will reindex. sorry will take a while.\n");
1573 pblocktree->ReadFlag("timestampindex", checkval);
1574 bool defaultState = DEFAULT_TIMESTAMPINDEX ? DEFAULT_TIMESTAMPINDEX : checkval;
1575 fTimeStampIndex = GetBoolArg("-timestampindex", defaultState);
1576 if (checkval != fTimeStampIndex)
1578 pblocktree->WriteFlag("timestampindex", fTimeStampIndex);
1579 fprintf(stderr,"set timestamp index, will reindex. sorry will take a while.\n");
1583 pblocktree->ReadFlag("insightexplorer", checkval);
1584 defaultState = DEFAULT_INSIGHTEXPLORER ? DEFAULT_INSIGHTEXPLORER : checkval;
1585 fInsightExplorer = GetBoolArg("-insightexplorer", defaultState);
1586 if (checkval != fInsightExplorer)
1588 pblocktree->WriteFlag("insightexplorer", fInsightExplorer);
1589 fprintf(stderr,"set main indexes, will reindex. sorry will take a while.\n");
1594 bool clearWitnessCaches = false;
1596 bool fLoaded = false;
1598 bool fReset = fReindex;
1599 std::string strLoadError;
1601 uiInterface.InitMessage(_("Loading block index..."));
1603 nStart = GetTimeMillis();
1608 delete pcoinsdbview;
1609 delete pcoinscatcher;
1611 delete pnotarisations;
1613 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles);
1614 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
1615 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1616 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1617 pnotarisations = new NotarisationDB(100*1024*1024, false, fReindex);
1621 pblocktree->WriteReindexing(true);
1622 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1624 CleanupBlockRevFiles();
1627 if (!LoadBlockIndex()) {
1628 strLoadError = _("Error loading block database");
1632 // If the loaded chain has a wrong genesis, bail out immediately
1633 // (we're likely using a testnet datadir, or the other way around).
1634 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1635 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1637 // Initialize the block index (no-op if non-empty database was already loaded)
1638 if (!InitBlockIndex(chainparams)) {
1639 strLoadError = _("Error initializing block database");
1642 KOMODO_LOADINGBLOCKS = 0;
1643 // Check for changed -txindex state
1644 if (fTxIndex != GetBoolArg("-txindex", true)) {
1645 strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1649 // Check for changed -insightexplorer state
1650 if (fInsightExplorer != GetBoolArg("-insightexplorer", false)) {
1651 strLoadError = _("You need to rebuild the database using -reindex to change -insightexplorer");
1655 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1656 // in the past, but is now trying to run unpruned.
1657 if (fHavePruned && !fPruneMode) {
1658 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1663 uiInterface.InitMessage(_("Rewinding blocks if needed..."));
1664 if (!RewindBlockIndex(chainparams, clearWitnessCaches)) {
1665 strLoadError = _("Unable to rewind the database to a pre-upgrade state. You will need to redownload the blockchain");
1670 uiInterface.InitMessage(_("Verifying blocks..."));
1671 if (fHavePruned && GetArg("-checkblocks", 288) > MIN_BLOCKS_TO_KEEP) {
1672 LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
1673 MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", 288));
1675 if ( KOMODO_REWIND == 0 )
1677 if (!CVerifyDB().VerifyDB(Params(), pcoinsdbview, GetArg("-checklevel", 3),
1678 GetArg("-checkblocks", 288))) {
1679 strLoadError = _("Corrupted block database detected");
1683 } catch (const std::exception& e) {
1684 if (fDebug) LogPrintf("%s\n", e.what());
1685 strLoadError = _("Error opening block database");
1693 // first suggest a reindex
1695 bool fRet = uiInterface.ThreadSafeMessageBox(
1696 strLoadError + ".\n\n" + _("error in HDD data, might just need to update to latest, if that doesnt work, then you need to resync"),
1697 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1700 fRequestShutdown = false;
1702 LogPrintf("Aborted block database rebuild. Exiting.\n");
1706 return InitError(strLoadError);
1710 KOMODO_LOADINGBLOCKS = 0;
1712 // As LoadBlockIndex can take several minutes, it's possible the user
1713 // requested to kill the GUI during the last operation. If so, exit.
1714 // As the program has not fully started yet, Shutdown() is possibly overkill.
1715 if (fRequestShutdown)
1717 LogPrintf("Shutdown requested. Exiting.\n");
1720 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1722 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1723 CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
1724 // Allowed to fail as this file IS missing on first startup.
1725 if (!est_filein.IsNull())
1726 mempool.ReadFeeEstimates(est_filein);
1727 fFeeEstimatesInitialized = true;
1730 // ********************************************************* Step 8: load wallet
1731 #ifdef ENABLE_WALLET
1732 if (fDisableWallet) {
1734 LogPrintf("Wallet disabled!\n");
1737 // needed to restore wallet transaction meta data after -zapwallettxes
1738 std::vector<CWalletTx> vWtx;
1740 if (GetBoolArg("-zapwallettxes", false)) {
1741 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
1743 pwalletMain = new CWallet(strWalletFile);
1744 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
1745 if (nZapWalletRet != DB_LOAD_OK) {
1746 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
1754 uiInterface.InitMessage(_("Loading wallet..."));
1756 nStart = GetTimeMillis();
1757 bool fFirstRun = true;
1758 pwalletMain = new CWallet(strWalletFile);
1759 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
1760 if (nLoadWalletRet != DB_LOAD_OK)
1762 if (nLoadWalletRet == DB_CORRUPT)
1763 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
1764 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
1766 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
1767 " or address book entries might be missing or incorrect."));
1770 else if (nLoadWalletRet == DB_TOO_NEW)
1771 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Komodo") << "\n";
1772 else if (nLoadWalletRet == DB_NEED_REWRITE)
1774 strErrors << _("Wallet needed to be rewritten: restart Zcash to complete") << "\n";
1775 LogPrintf("%s", strErrors.str());
1776 return InitError(strErrors.str());
1779 strErrors << _("Error loading wallet.dat") << "\n";
1782 if (GetBoolArg("-upgradewallet", fFirstRun))
1784 int nMaxVersion = GetArg("-upgradewallet", 0);
1785 if (nMaxVersion == 0) // the -upgradewallet without argument case
1787 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
1788 nMaxVersion = CLIENT_VERSION;
1789 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
1792 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
1793 if (nMaxVersion < pwalletMain->GetVersion())
1794 strErrors << _("Cannot downgrade wallet") << "\n";
1795 pwalletMain->SetMaxVersion(nMaxVersion);
1798 if (!pwalletMain->HaveHDSeed())
1800 // We can't set the new HD seed until the wallet is decrypted.
1801 // https://github.com/zcash/zcash/issues/3607
1802 if (!pwalletMain->IsCrypted()) {
1803 // generate a new HD seed
1804 pwalletMain->GenerateNewSeed();
1808 // Set sapling migration status
1809 pwalletMain->fSaplingMigrationEnabled = GetBoolArg("-migration", false);
1813 // Create new keyUser and set as default key
1814 CPubKey newDefaultKey;
1815 if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
1816 pwalletMain->SetDefaultKey(newDefaultKey);
1817 if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
1818 strErrors << _("Cannot write default address") << "\n";
1821 pwalletMain->SetBestChain(chainActive.GetLocator());
1824 LogPrintf("%s", strErrors.str());
1825 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
1827 RegisterValidationInterface(pwalletMain);
1829 CBlockIndex *pindexRescan = chainActive.Tip();
1830 if (clearWitnessCaches || GetBoolArg("-rescan", false))
1832 pwalletMain->ClearNoteWitnessCache();
1833 pindexRescan = chainActive.Genesis();
1837 CWalletDB walletdb(strWalletFile);
1838 CBlockLocator locator;
1839 if (walletdb.ReadBestBlock(locator))
1840 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
1842 pindexRescan = chainActive.Genesis();
1844 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
1846 uiInterface.InitMessage(_("Rescanning..."));
1847 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->GetHeight(), pindexRescan->GetHeight());
1848 nStart = GetTimeMillis();
1849 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
1850 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
1851 pwalletMain->SetBestChain(chainActive.GetLocator());
1854 // Restore wallet transaction metadata after -zapwallettxes=1
1855 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
1857 CWalletDB walletdb(strWalletFile);
1859 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
1861 uint256 hash = wtxOld.GetHash();
1862 std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
1863 if (mi != pwalletMain->mapWallet.end())
1865 const CWalletTx* copyFrom = &wtxOld;
1866 CWalletTx* copyTo = &mi->second;
1867 copyTo->mapValue = copyFrom->mapValue;
1868 copyTo->vOrderForm = copyFrom->vOrderForm;
1869 copyTo->nTimeReceived = copyFrom->nTimeReceived;
1870 copyTo->nTimeSmart = copyFrom->nTimeSmart;
1871 copyTo->fFromMe = copyFrom->fFromMe;
1872 copyTo->strFromAccount = copyFrom->strFromAccount;
1873 copyTo->nOrderPos = copyFrom->nOrderPos;
1874 copyTo->WriteToDisk(&walletdb);
1879 pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true));
1880 } // (!fDisableWallet)
1881 #else // ENABLE_WALLET
1882 LogPrintf("No wallet support compiled in!\n");
1883 #endif // !ENABLE_WALLET
1885 #ifdef ENABLE_MINING
1886 #ifndef ENABLE_WALLET
1887 if (GetBoolArg("-minetolocalwallet", false)) {
1888 return InitError(_("Zcash was not built with wallet support. Set -minetolocalwallet=0 to use -mineraddress, or rebuild Zcash with wallet support."));
1890 if (GetArg("-mineraddress", "").empty() && GetBoolArg("-gen", false)) {
1891 return InitError(_("Zcash was not built with wallet support. Set -mineraddress, or rebuild Zcash with wallet support."));
1893 #endif // !ENABLE_WALLET
1895 if (mapArgs.count("-mineraddress")) {
1896 #ifdef ENABLE_WALLET
1897 bool minerAddressInLocalWallet = false;
1899 // Address has already been validated
1900 CTxDestination addr = DecodeDestination(mapArgs["-mineraddress"]);
1901 CKeyID keyID = boost::get<CKeyID>(addr);
1902 minerAddressInLocalWallet = pwalletMain->HaveKey(keyID);
1904 if (GetBoolArg("-minetolocalwallet", true) && !minerAddressInLocalWallet) {
1905 return InitError(_("-mineraddress is not in the local wallet. Either use a local address, or set -minetolocalwallet=0"));
1907 #endif // ENABLE_WALLET
1909 // This is leveraging the fact that boost::signals2 executes connected
1910 // handlers in-order. Further up, the wallet is connected to this signal
1911 // if the wallet is enabled. The wallet's ScriptForMining handler does
1912 // nothing if -mineraddress is set, and GetScriptForMinerAddress() does
1913 // nothing if -mineraddress is not set (or set to an invalid address).
1915 // The upshot is that when ScriptForMining(script) is called:
1916 // - If -mineraddress is set (whether or not the wallet is enabled), the
1917 // CScript argument is set to -mineraddress.
1918 // - If the wallet is enabled and -mineraddress is not set, the CScript
1919 // argument is set to a wallet address.
1920 // - If the wallet is disabled and -mineraddress is not set, the CScript
1921 // argument is not modified; in practice this means it is empty, and
1922 // GenerateBitcoins() returns an error.
1923 GetMainSignals().ScriptForMining.connect(GetScriptForMinerAddress);
1925 #endif // ENABLE_MINING
1927 // ********************************************************* Step 9: data directory maintenance
1929 // if pruning, unset the service bit and perform the initial blockstore prune
1930 // after any wallet rescanning has taken place.
1932 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1933 nLocalServices &= ~NODE_NETWORK;
1935 uiInterface.InitMessage(_("Pruning blockstore..."));
1940 // ********************************************************* Step 10: import blocks
1942 if (mapArgs.count("-blocknotify"))
1943 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1944 if ( KOMODO_REWIND >= 0 )
1946 uiInterface.InitMessage(_("Activating best chain..."));
1947 // scan for better chains in the block chain database, that are not yet connected in the active best chain
1948 CValidationState state;
1949 if ( !ActivateBestChain(state, Params()))
1950 strErrors << "Failed to connect best block";
1952 std::vector<boost::filesystem::path> vImportFiles;
1953 if (mapArgs.count("-loadblock"))
1955 BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
1956 vImportFiles.push_back(strFile);
1958 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1959 if (chainActive.Tip() == NULL) {
1960 LogPrintf("Waiting for genesis block to be imported...\n");
1961 while (!fRequestShutdown && chainActive.Tip() == NULL)
1965 // ********************************************************* Step 11: start node
1967 if (!CheckDiskSpace())
1970 if (!strErrors.str().empty())
1971 return InitError(strErrors.str());
1974 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1975 LogPrintf("nBestHeight = %d\n", chainActive.Height());
1976 #ifdef ENABLE_WALLET
1979 LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
1980 LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
1981 LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
1984 // Start the thread that notifies listeners of transactions that have been
1985 // recently added to the mempool.
1986 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "txnotify", &ThreadNotifyRecentlyAdded));
1988 if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1989 StartTorControl(threadGroup, scheduler);
1991 StartNode(threadGroup, scheduler);
1993 VERUS_CHEATCATCHER = GetArg("-cheatcatcher", "");
1994 bool gen = GetBoolArg("-gen", false);
1996 #ifdef ENABLE_MINING
1997 // Generate coins in the background
1998 #ifdef ENABLE_WALLET
1999 VERUS_MINTBLOCKS = GetBoolArg("-mint", false);
2000 mapArgs["-gen"] = gen || VERUS_MINTBLOCKS ? "1" : "0";
2001 mapArgs["-genproclimit"] = itostr(GetArg("-genproclimit", gen ? -1 : 0));
2003 if (pwalletMain || !GetArg("-mineraddress", "").empty())
2004 GenerateBitcoins(gen || VERUS_MINTBLOCKS, pwalletMain, GetArg("-genproclimit", gen ? -1 : 0));
2006 GenerateBitcoins(gen, GetArg("-genproclimit", -1));
2010 // Monitor the chain every minute, and alert if we get blocks much quicker or slower than expected.
2011 CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload,
2012 boost::ref(cs_main), boost::cref(pindexBestHeader));
2013 scheduler.scheduleEvery(f, 60);
2015 // ********************************************************* Step 11: finished
2017 SetRPCWarmupFinished();
2018 uiInterface.InitMessage(_("Done loading"));
2020 #ifdef ENABLE_WALLET
2022 // Add wallet transactions that aren't already in a block to mapTransactions
2023 pwalletMain->ReacceptWalletTransactions();
2025 // Run a thread to flush wallet periodically
2026 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
2031 threadGroup.create_thread(boost::bind(ThreadSendAlert));
2033 return !fRequestShutdown;