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"
28 #include "rpc/server.h"
29 #include "rpc/pbaasrpc.h"
30 #include "rpc/register.h"
31 #include "script/standard.h"
32 #include "script/sigcache.h"
33 #include "scheduler.h"
35 #include "torcontrol.h"
36 #include "ui_interface.h"
38 #include "utilmoneystr.h"
39 #include "validationinterface.h"
42 #include "wallet/wallet.h"
43 #include "wallet/walletdb.h"
52 #include <boost/algorithm/string/classification.hpp>
53 #include <boost/algorithm/string/predicate.hpp>
54 #include <boost/algorithm/string/replace.hpp>
55 #include <boost/algorithm/string/split.hpp>
56 #include <boost/bind.hpp>
57 #include <boost/filesystem.hpp>
58 #include <boost/function.hpp>
59 #include <boost/interprocess/sync/file_lock.hpp>
60 #include <boost/thread.hpp>
61 #include <openssl/crypto.h>
63 #include <libsnark/common/profiling.hpp>
66 #include "zmq/zmqnotificationinterface.h"
70 #include "amqp/amqpnotificationinterface.h"
73 #include "librustzcash.h"
77 extern void ThreadSendAlert();
78 extern int32_t KOMODO_LOADINGBLOCKS;
79 extern bool VERUS_MINTBLOCKS;
80 extern std::string VERUS_DEFAULT_ZADDR;
82 ZCJoinSplit* pzcashParams = NULL;
85 CWallet* pwalletMain = NULL;
87 bool fFeeEstimatesInitialized = false;
90 static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
94 static AMQPNotificationInterface* pAMQPNotificationInterface = NULL;
98 // Win32 LevelDB doesn't use file descriptors, and the ones used for
99 // accessing block files don't count towards the fd_set size limit
101 #define MIN_CORE_FILEDESCRIPTORS 0
103 #define MIN_CORE_FILEDESCRIPTORS 150
106 /** Used to pass flags to the Bind() function */
109 BF_EXPLICIT = (1U << 0),
110 BF_REPORT_ERROR = (1U << 1),
111 BF_WHITELIST = (1U << 2),
114 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
115 CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h
117 //////////////////////////////////////////////////////////////////////////////
123 // Thread management and startup/shutdown:
125 // The network-processing threads are all part of a thread group
126 // created by AppInit().
128 // A clean exit happens when StartShutdown() or the SIGTERM
129 // signal handler sets fRequestShutdown, which triggers
130 // the DetectShutdownThread(), which interrupts the main thread group.
131 // DetectShutdownThread() then exits, which causes AppInit() to
132 // continue (it .joins the shutdown thread).
133 // Shutdown() is then
134 // called to clean up database connections, and stop other
135 // threads that should only be stopped after the main network-processing
136 // threads have exited.
138 // Note that if running -daemon the parent process returns from AppInit2
139 // before adding any threads to the threadGroup, so .join_all() returns
140 // immediately and the parent exits from main().
143 std::atomic<bool> fRequestShutdown(false);
147 fRequestShutdown = true;
149 bool ShutdownRequested()
151 return fRequestShutdown;
154 class CCoinsViewErrorCatcher : public CCoinsViewBacked
157 CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
158 bool GetCoins(const uint256 &txid, CCoins &coins) const {
160 return CCoinsViewBacked::GetCoins(txid, coins);
161 } catch(const std::runtime_error& e) {
162 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
163 LogPrintf("Error reading from database: %s\n", e.what());
164 // Starting the shutdown sequence and returning false to the caller would be
165 // interpreted as 'entry not found' (as opposed to unable to read data), and
166 // could lead to invalid interpretation. Just exit immediately, as we can't
167 // continue anyway, and all writes should be atomic.
171 // Writes do not need similar protection, as failure to write is handled by the caller.
174 static CCoinsViewDB *pcoinsdbview = NULL;
175 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
176 static boost::scoped_ptr<ECCVerifyHandle> globalVerifyHandle;
178 void Interrupt(boost::thread_group& threadGroup)
180 InterruptHTTPServer();
184 InterruptTorControl();
185 threadGroup.interrupt_all();
190 LogPrintf("%s: In progress...\n", __func__);
191 static CCriticalSection cs_Shutdown;
192 TRY_LOCK(cs_Shutdown, lockShutdown);
196 /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
197 /// for example if the data directory was found to be locked.
198 /// Be sure that anything that writes files or flushes caches only does this if the respective
199 /// module was initialized.
200 RenameThread("verus-shutoff");
201 mempool.AddTransactionsUpdated(1);
209 pwalletMain->Flush(false);
214 GenerateBitcoins(false, NULL, 0);
216 GenerateBitcoins(false, 0);
222 UnregisterNodeSignals(GetNodeSignals());
224 if (fFeeEstimatesInitialized)
226 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
227 CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
228 if (!est_fileout.IsNull())
229 mempool.WriteFeeEstimates(est_fileout);
231 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
232 fFeeEstimatesInitialized = false;
237 if (pcoinsTip != NULL) {
242 delete pcoinscatcher;
243 pcoinscatcher = NULL;
251 pwalletMain->Flush(true);
255 if (pzmqNotificationInterface) {
256 UnregisterValidationInterface(pzmqNotificationInterface);
257 delete pzmqNotificationInterface;
258 pzmqNotificationInterface = NULL;
263 if (pAMQPNotificationInterface) {
264 UnregisterValidationInterface(pAMQPNotificationInterface);
265 delete pAMQPNotificationInterface;
266 pAMQPNotificationInterface = NULL;
272 boost::filesystem::remove(GetPidFile());
273 } catch (const boost::filesystem::filesystem_error& e) {
274 LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
277 UnregisterAllValidationInterfaces();
284 globalVerifyHandle.reset();
286 LogPrintf("%s: done\n", __func__);
290 * Signal handlers are very limited in what they are allowed to do, so:
292 void HandleSIGTERM(int)
294 fRequestShutdown = true;
297 void HandleSIGHUP(int)
299 fReopenDebugLog = true;
302 bool static InitError(const std::string &str)
304 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
308 bool static InitWarning(const std::string &str)
310 uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
314 bool static Bind(const CService &addr, unsigned int flags) {
315 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
317 std::string strError;
318 if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
319 if (flags & BF_REPORT_ERROR)
320 return InitError(strError);
328 cvBlockChange.notify_all();
329 LogPrint("rpc", "RPC stopped.\n");
332 void OnRPCPreCommand(const CRPCCommand& cmd)
335 string strWarning = GetWarnings("rpc");
336 if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
338 throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
341 std::string HelpMessage(HelpMessageMode mode)
343 const bool showDebug = GetBoolArg("-help-debug", false);
345 // When adding new options to the categories, please keep and ensure alphabetical ordering.
346 // Do not translate _(...) -help-debug options, many technical terms, and only a very small audience, so is unnecessary stress to translators
348 string strUsage = HelpMessageGroup(_("Options:"));
349 strUsage += HelpMessageOpt("-?", _("This help message"));
350 strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
351 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)"));
352 strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
353 strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 288));
354 strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), 3));
355 strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "komodo.conf"));
356 if (mode == HMM_BITCOIND)
359 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
362 strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
363 strUsage += HelpMessageOpt("-exportdir=<dir>", _("Specify directory to be used when exporting data"));
364 strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
365 strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup"));
366 strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
367 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)"));
368 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)"),
369 -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
371 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "verusd.pid"));
373 strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode disables wallet support and is incompatible with -txindex. "
374 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
375 "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
376 strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files on startup"));
378 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
380 strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
381 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));
382 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));
383 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));
384 strUsage += HelpMessageGroup(_("Connection options:"));
385 strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
386 strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100));
387 strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400));
388 strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
389 strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)"));
390 strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
391 strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)"));
392 strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)"));
393 strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
394 strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0));
395 strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
396 strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
397 strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
398 strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000));
399 strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000));
400 strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
401 strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
402 strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1));
403 strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with Bloom filters (default: %u)"), 1));
405 strUsage += HelpMessageOpt("-enforcenodebloom", strprintf("Enforce minimum protocol version to limit use of Bloom filters (default: %u)", 0));
406 strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 7770, 17770));
407 strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
408 strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1));
409 strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
410 strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
411 strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
412 strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
413 strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
414 strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
415 " " + _("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"));
418 strUsage += HelpMessageGroup(_("Wallet options:"));
419 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
420 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100));
421 strUsage += HelpMessageOpt("-migration", _("Enable the Sprout to Sapling migration"));
422 strUsage += HelpMessageOpt("-migrationdestaddress=<zaddr>", _("Set the Sapling migration address"));
424 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)",
425 CURRENCY_UNIT, FormatMoney(CWallet::minTxFee.GetFeePerK())));
426 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
427 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
428 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
429 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
430 strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
431 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1));
432 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));
433 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));
434 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)"),
435 CURRENCY_UNIT, FormatMoney(maxTxFee)));
436 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup"));
437 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
438 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), true));
439 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
440 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
441 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
445 strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
446 strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
447 strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
448 strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
449 strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
453 strUsage += HelpMessageGroup(_("AMQP 1.0 notification options:"));
454 strUsage += HelpMessageOpt("-amqppubhashblock=<address>", _("Enable publish hash block in <address>"));
455 strUsage += HelpMessageOpt("-amqppubhashtx=<address>", _("Enable publish hash transaction in <address>"));
456 strUsage += HelpMessageOpt("-amqppubrawblock=<address>", _("Enable publish raw block in <address>"));
457 strUsage += HelpMessageOpt("-amqppubrawtx=<address>", _("Enable publish raw transaction in <address>"));
460 strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
463 strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", 1));
464 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)", 100));
465 strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", 0));
466 strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", 0));
467 strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
468 strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
469 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", 1));
470 strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", 0));
471 strUsage += HelpMessageOpt("-nuparams=hexBranchId:activationHeight", "Use given activation height for specified network upgrade (regtest-only)");
473 string debugCategories = "addrman, alert, bench, coindb, db, estimatefee, http, libevent, lock, mempool, net, partitioncheck, pow, proxy, prune, "
474 "rand, reindex, rpc, selectcoins, tor, zmq, zrpc, zrpcunsafe (implies zrpc)"; // Don't translate these
475 strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
476 _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + debugCategories + ".");
477 strUsage += HelpMessageOpt("-experimentalfeatures", _("Enable use of experimental features"));
478 strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
479 strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
480 strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
483 strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", 15));
484 strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", 0));
485 strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
486 strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
488 strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying (default: %s)"),
489 CURRENCY_UNIT, FormatMoney(::minRelayTxFee.GetFeePerK())));
490 strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
493 strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", 0));
494 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", 1));
495 strUsage += HelpMessageOpt("-regtest", "Enter regression test mode, which uses a special chain in which blocks can be solved instantly. "
496 "This is intended for regression testing tools and app development.");
498 // strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
499 strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
501 strUsage += HelpMessageGroup(_("Node relay options:"));
502 strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1));
503 strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
505 strUsage += HelpMessageGroup(_("Block creation options:"));
506 strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), 0));
507 strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
508 strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
509 if (GetBoolArg("-help-debug", false))
510 strUsage += HelpMessageOpt("-blockversion=<n>", strprintf("Override block version to test forking scenarios (default: %d)", (int)CBlock::CURRENT_VERSION));
513 strUsage += HelpMessageGroup(_("Mining options:"));
514 strUsage += HelpMessageOpt("-mint", strprintf(_("Mint/stake coins automatically (default: %u)"), 0));
515 strUsage += HelpMessageOpt("-gen", strprintf(_("Mine/generate coins (default: %u)"), 0));
516 strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin mining if enabled (-1 = all cores, default: %d)"), 0));
517 strUsage += HelpMessageOpt("-equihashsolver=<name>", _("Specify the Equihash solver to be used if enabled (default: \"default\")"));
518 strUsage += HelpMessageOpt("-mineraddress=<addr>", _("Send mined coins to a specific single address"));
519 strUsage += HelpMessageOpt("-minetolocalwallet", strprintf(
520 _("Require that mined blocks use a coinbase address in the local wallet (default: %u)"),
529 strUsage += HelpMessageGroup(_("RPC server options:"));
530 strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
531 strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0));
532 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)"));
533 strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
534 strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
535 strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 7771, 17771));
536 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"));
537 strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
539 strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
540 strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
543 // Disabled until we can lock notes and also tune performance of libsnark which by default uses multiple threads
544 //strUsage += HelpMessageOpt("-rpcasyncthreads=<n>", strprintf(_("Set the number of threads to service Async RPC calls (default: %d)"), 1));
546 if (mode == HMM_BITCOIND) {
547 strUsage += HelpMessageGroup(_("Metrics Options (only if -daemon and -printtoconsole are not set):"));
548 strUsage += HelpMessageOpt("-showmetrics", _("Show metrics on stdout (default: 1 if running in a console, 0 otherwise)"));
549 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)"));
550 strUsage += HelpMessageOpt("-metricsrefreshtime", strprintf(_("Number of seconds between metrics refreshes (default: %u if running in a console, %u otherwise)"), 1, 600));
556 static void BlockNotifyCallback(const uint256& hashNewTip)
558 std::string strCmd = GetArg("-blocknotify", "");
560 boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
561 boost::thread t(runCommand, strCmd); // thread runs free
567 assert(fImporting == false);
572 assert(fImporting == true);
578 // If we're using -prune with -reindex, then delete block files that will be ignored by the
579 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
580 // is missing, do the same here to delete any later block files after a gap. Also delete all
581 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
582 // is in sync with what's actually on disk by the time we start downloading, so that pruning
584 void CleanupBlockRevFiles()
586 using namespace boost::filesystem;
587 map<string, path> mapBlockFiles;
589 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
590 // Remove the rev files immediately and insert the blk file paths into an
591 // ordered map keyed by block file index.
592 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
593 path blocksdir = GetDataDir() / "blocks";
594 for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
595 if (is_regular_file(*it) &&
596 it->path().filename().string().length() == 12 &&
597 it->path().filename().string().substr(8,4) == ".dat")
599 if (it->path().filename().string().substr(0,3) == "blk")
600 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
601 else if (it->path().filename().string().substr(0,3) == "rev")
605 path komodostate = GetDataDir() / "komodostate";
607 path minerids = GetDataDir() / "minerids";
609 // Remove all block files that aren't part of a contiguous set starting at
610 // zero by walking the ordered map (keys are block file indices) by
611 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
612 // start removing block files.
613 int nContigCounter = 0;
614 BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) {
615 if (atoi(item.first) == nContigCounter) {
623 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
625 const CChainParams& chainparams = Params();
626 RenameThread("zcash-loadblk");
632 CDiskBlockPos pos(nFile, 0);
633 if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
634 break; // No block files left to reindex
635 FILE *file = OpenBlockFile(pos, true);
637 break; // This error is logged in OpenBlockFile
638 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
639 LoadExternalBlockFile(chainparams, file, &pos);
642 pblocktree->WriteReindexing(false);
644 LogPrintf("Reindexing finished\n");
645 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
646 InitBlockIndex(chainparams);
647 KOMODO_LOADINGBLOCKS = 0;
650 // hardcoded $DATADIR/bootstrap.dat
651 boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
652 if (boost::filesystem::exists(pathBootstrap)) {
653 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
656 boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
657 LogPrintf("Importing bootstrap.dat...\n");
658 LoadExternalBlockFile(chainparams, file);
659 RenameOver(pathBootstrap, pathBootstrapOld);
661 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
666 BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
667 FILE *file = fopen(path.string().c_str(), "rb");
670 LogPrintf("Importing blocks file %s...\n", path.string());
671 LoadExternalBlockFile(chainparams, file);
673 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
677 if (GetBoolArg("-stopafterblockimport", false)) {
678 LogPrintf("Stopping after block import\n");
683 void ThreadNotifyRecentlyAdded()
686 // Run the notifier on an integer second in the steady clock.
687 auto now = std::chrono::steady_clock::now().time_since_epoch();
688 auto nextFire = std::chrono::duration_cast<std::chrono::seconds>(
689 now + std::chrono::seconds(1));
690 std::this_thread::sleep_until(
691 std::chrono::time_point<std::chrono::steady_clock>(nextFire));
693 boost::this_thread::interruption_point();
695 mempool.NotifyRecentlyAdded();
700 * Ensure that Bitcoin is running in a usable environment with all
701 * necessary library support.
703 bool InitSanityCheck(void)
705 if(!ECC_InitSanityCheck()) {
706 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
709 if (!glibc_sanity_test() || !glibcxx_sanity_test())
716 static void ZC_LoadParams(
717 const CChainParams& chainparams
720 struct timeval tv_start, tv_end;
723 boost::filesystem::path pk_path = ZC_GetParamsDir() / "sprout-proving.key";
724 boost::filesystem::path vk_path = ZC_GetParamsDir() / "sprout-verifying.key";
725 boost::filesystem::path sapling_spend = ZC_GetParamsDir() / "sapling-spend.params";
726 boost::filesystem::path sapling_output = ZC_GetParamsDir() / "sapling-output.params";
727 boost::filesystem::path sprout_groth16 = ZC_GetParamsDir() / "sprout-groth16.params";
730 boost::filesystem::exists(pk_path) &&
731 boost::filesystem::exists(vk_path) &&
732 boost::filesystem::exists(sapling_spend) &&
733 boost::filesystem::exists(sapling_output) &&
734 boost::filesystem::exists(sprout_groth16)
736 uiInterface.ThreadSafeMessageBox(strprintf(
737 _("Cannot find the Zcash network parameters in the following directory:\n"
739 "Please run 'fetch-params' or './zcutil/fetch-params.sh' and then restart."),
741 "", CClientUIInterface::MSG_ERROR);
746 LogPrintf("Loading verifying key from %s\n", vk_path.string().c_str());
747 gettimeofday(&tv_start, 0);
749 pzcashParams = ZCJoinSplit::Prepared(vk_path.string(), pk_path.string());
751 gettimeofday(&tv_end, 0);
752 elapsed = float(tv_end.tv_sec-tv_start.tv_sec) + (tv_end.tv_usec-tv_start.tv_usec)/float(1000000);
753 LogPrintf("Loaded verifying key in %fs seconds.\n", elapsed);
756 sizeof(boost::filesystem::path::value_type) == sizeof(codeunit),
757 "librustzcash not configured correctly");
758 auto sapling_spend_str = sapling_spend.native();
759 auto sapling_output_str = sapling_output.native();
760 auto sprout_groth16_str = sprout_groth16.native();
762 LogPrintf("Loading Sapling (Spend) parameters from %s\n", sapling_spend.string().c_str());
763 LogPrintf("Loading Sapling (Output) parameters from %s\n", sapling_output.string().c_str());
764 LogPrintf("Loading Sapling (Sprout Groth16) parameters from %s\n", sprout_groth16.string().c_str());
765 gettimeofday(&tv_start, 0);
767 librustzcash_init_zksnark_params(
768 reinterpret_cast<const codeunit*>(sapling_spend_str.c_str()),
769 sapling_spend_str.length(),
770 "8270785a1a0d0bc77196f000ee6d221c9c9894f55307bd9357c3f0105d31ca63991ab91324160d8f53e2bbd3c2633a6eb8bdf5205d822e7f3f73edac51b2b70c",
771 reinterpret_cast<const codeunit*>(sapling_output_str.c_str()),
772 sapling_output_str.length(),
773 "657e3d38dbb5cb5e7dd2970e8b03d69b4787dd907285b5a7f0790dcc8072f60bf593b32cc2d1c030e00ff5ae64bf84c5c3beb84ddc841d48264b4a171744d028",
774 reinterpret_cast<const codeunit*>(sprout_groth16_str.c_str()),
775 sprout_groth16_str.length(),
776 "e9b238411bd6c0ec4791e9d04245ec350c9c5744f5610dfcce4365d5ca49dfefd5054e371842b3f88fa1b9d7e8e075249b3ebabd167fa8b0f3161292d36c180a"
779 gettimeofday(&tv_end, 0);
780 elapsed = float(tv_end.tv_sec-tv_start.tv_sec) + (tv_end.tv_usec-tv_start.tv_usec)/float(1000000);
781 LogPrintf("Loaded Sapling parameters in %fs seconds.\n", elapsed);
784 bool AppInitServers(boost::thread_group& threadGroup)
786 RPCServer::OnStopped(&OnRPCStopped);
787 RPCServer::OnPreCommand(&OnRPCPreCommand);
788 if (!InitHTTPServer())
794 if (GetBoolArg("-rest", false) && !StartREST())
796 if (!StartHTTPServer())
801 /** Initialize bitcoin.
802 * @pre Parameters should be parsed and config file should be read.
804 extern int32_t KOMODO_REWIND;
806 bool AppInitNetworking()
808 // ********************************************************* Step 1: setup
810 // Turn off Microsoft heap dump noise
811 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
812 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
815 // Disable confusing "helpful" text message on abort, Ctrl-C
816 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
819 // Enable Data Execution Prevention (DEP)
820 // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
821 // A failure is non-critical and needs no further attention!
822 #ifndef PROCESS_DEP_ENABLE
823 // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
824 // which is not correct. Can be removed, when GCCs winbase.h is fixed!
825 #define PROCESS_DEP_ENABLE 0x00000001
827 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
828 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
829 if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
832 if (!SetupNetworking())
833 return InitError("Error: Initializing networking failed");
838 bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
841 if (GetBoolArg("-sysperms", false)) {
843 if (!GetBoolArg("-disablewallet", false))
844 return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
850 // Clean shutdown on SIGTERM
852 sa.sa_handler = HandleSIGTERM;
853 sigemptyset(&sa.sa_mask);
855 sigaction(SIGTERM, &sa, NULL);
856 sigaction(SIGINT, &sa, NULL);
858 // Reopen debug.log on SIGHUP
859 struct sigaction sa_hup;
860 sa_hup.sa_handler = HandleSIGHUP;
861 sigemptyset(&sa_hup.sa_mask);
863 sigaction(SIGHUP, &sa_hup, NULL);
865 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
866 signal(SIGPIPE, SIG_IGN);
869 std::set_new_handler(new_handler_terminate);
871 // ********************************************************* Step 2: parameter interactions
872 const CChainParams& chainparams = Params();
874 // Set this early so that experimental features are correctly enabled/disabled
875 fExperimentalMode = GetBoolArg("-experimentalfeatures", false);
877 // Fail early if user has set experimental options without the global flag
878 if (!fExperimentalMode) {
879 if (mapArgs.count("-developerencryptwallet")) {
880 return InitError(_("Wallet encryption requires -experimentalfeatures."));
881 } else if (mapArgs.count("-developersetpoolsizezero")) {
882 return InitError(_("Setting the size of shielded pools to zero requires -experimentalfeatures."));
883 } else if (mapArgs.count("-paymentdisclosure")) {
884 return InitError(_("Payment disclosure requires -experimentalfeatures."));
885 } else if (mapArgs.count("-zmergetoaddress")) {
886 return InitError(_("RPC method z_mergetoaddress requires -experimentalfeatures."));
887 } else if (mapArgs.count("-savesproutr1cs")) {
888 return InitError(_("Saving the Sprout R1CS requires -experimentalfeatures."));
892 // Set this early so that parameter interactions go to console
893 fPrintToConsole = GetBoolArg("-printtoconsole", false);
894 fLogTimestamps = GetBoolArg("-logtimestamps", true);
895 fLogIPs = GetBoolArg("-logips", false);
897 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
898 LogPrintf("Zcash version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
900 // when specifying an explicit binding address, you want to listen on it
901 // even when -connect or -proxy is specified
902 if (mapArgs.count("-bind")) {
903 if (SoftSetBoolArg("-listen", true))
904 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
906 if (mapArgs.count("-whitebind")) {
907 if (SoftSetBoolArg("-listen", true))
908 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
911 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
912 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
913 if (SoftSetBoolArg("-dnsseed", false))
914 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
915 if (SoftSetBoolArg("-listen", false))
916 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
919 if (mapArgs.count("-proxy")) {
920 // to protect privacy, do not listen by default if a default proxy server is specified
921 if (SoftSetBoolArg("-listen", false))
922 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
923 // to protect privacy, do not discover addresses by default
924 if (SoftSetBoolArg("-discover", false))
925 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
928 if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
929 // do not try to retrieve public IP when not listening (pointless)
930 if (SoftSetBoolArg("-discover", false))
931 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
932 if (SoftSetBoolArg("-listenonion", false))
933 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
936 if (mapArgs.count("-externalip")) {
937 // if an explicit public IP is specified, do not try to find others
938 if (SoftSetBoolArg("-discover", false))
939 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
942 if (GetBoolArg("-salvagewallet", false)) {
943 // Rewrite just private keys: rescan to find transactions
944 if (SoftSetBoolArg("-rescan", true))
945 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
948 // -zapwallettx implies a rescan
949 if (GetBoolArg("-zapwallettxes", false)) {
950 if (SoftSetBoolArg("-rescan", true))
951 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
954 // Make sure enough file descriptors are available
955 int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
956 nMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
957 nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
958 int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
959 if (nFD < MIN_CORE_FILEDESCRIPTORS)
960 return InitError(_("Not enough file descriptors available."));
961 if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
962 nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
964 // if using block pruning, then disable txindex
965 // also disable the wallet (for now, until SPV support is implemented in wallet)
966 if (GetArg("-prune", 0)) {
967 if (GetBoolArg("-txindex", true))
968 return InitError(_("Prune mode is incompatible with -txindex."));
970 if (!GetBoolArg("-disablewallet", false)) {
971 if (SoftSetBoolArg("-disablewallet", true))
972 LogPrintf("%s : parameter interaction: -prune -> setting -disablewallet=1\n", __func__);
974 return InitError(_("Can't run with a wallet in prune mode."));
979 // ********************************************************* Step 3: parameter-to-internal-flags
981 fDebug = !mapMultiArgs["-debug"].empty();
982 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
983 const vector<string>& categories = mapMultiArgs["-debug"];
984 if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
987 // Special case: if debug=zrpcunsafe, implies debug=zrpc, so add it to debug categories
988 if (find(categories.begin(), categories.end(), string("zrpcunsafe")) != categories.end()) {
989 if (find(categories.begin(), categories.end(), string("zrpc")) == categories.end()) {
990 LogPrintf("%s: parameter interaction: setting -debug=zrpcunsafe -> -debug=zrpc\n", __func__);
991 vector<string>& v = mapMultiArgs["-debug"];
996 // Check for -debugnet
997 if (GetBoolArg("-debugnet", false))
998 InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
999 // Check for -socks - as this is a privacy risk to continue, exit here
1000 if (mapArgs.count("-socks"))
1001 return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
1002 // Check for -tor - as this is a privacy risk to continue, exit here
1003 if (GetBoolArg("-tor", false))
1004 return InitError(_("Error: Unsupported argument -tor found, use -onion."));
1006 if (GetBoolArg("-benchmark", false))
1007 InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
1009 // Checkmempool and checkblockindex default to true in regtest mode
1010 int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
1012 mempool.setSanityCheck(1.0 / ratio);
1014 fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
1015 fCheckpointsEnabled = GetBoolArg("-checkpoints", true);
1017 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
1018 nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
1019 if (nScriptCheckThreads <= 0)
1020 nScriptCheckThreads += GetNumCores();
1021 if (nScriptCheckThreads <= 1)
1022 nScriptCheckThreads = 0;
1023 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
1024 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
1026 fServer = GetBoolArg("-server", false);
1028 // block pruning; get the amount of disk space (in MB) to allot for block & undo files
1029 int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
1030 if (nSignedPruneTarget < 0) {
1031 return InitError(_("Prune cannot be configured with a negative value."));
1033 nPruneTarget = (uint64_t) nSignedPruneTarget;
1035 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
1036 return InitError(strprintf(_("Prune configured below the minimum of %d MB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1038 LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1042 RegisterAllCoreRPCCommands(tableRPC);
1043 #ifdef ENABLE_WALLET
1044 bool fDisableWallet = GetBoolArg("-disablewallet", false);
1045 if (!fDisableWallet)
1046 RegisterWalletRPCCommands(tableRPC);
1049 nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1050 if (nConnectTimeout <= 0)
1051 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1053 // Fee-per-kilobyte amount considered the same as "free"
1054 // If you are mining, be careful setting this:
1055 // if you set it to zero then
1056 // a transaction spammer can cheaply fill blocks using
1057 // 1-satoshi-fee transactions. It should be set above the real
1058 // cost to you of processing a transaction.
1059 if (mapArgs.count("-minrelaytxfee"))
1062 if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
1063 ::minRelayTxFee = CFeeRate(n);
1065 return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
1068 #ifdef ENABLE_WALLET
1069 if (mapArgs.count("-mintxfee"))
1072 if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
1073 CWallet::minTxFee = CFeeRate(n);
1075 return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
1077 if (mapArgs.count("-paytxfee"))
1079 CAmount nFeePerK = 0;
1080 if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
1081 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
1082 if (nFeePerK > nHighTransactionFeeWarning)
1083 InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
1084 payTxFee = CFeeRate(nFeePerK, 1000);
1085 if (payTxFee < ::minRelayTxFee)
1087 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
1088 mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
1091 if (mapArgs.count("-maxtxfee"))
1093 CAmount nMaxFee = 0;
1094 if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
1095 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maptxfee"]));
1096 if (nMaxFee > nHighTransactionMaxFeeWarning)
1097 InitWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction."));
1099 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
1101 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
1102 mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
1105 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
1106 if (mapArgs.count("-txexpirydelta")) {
1107 int64_t expiryDelta = atoi64(mapArgs["-txexpirydelta"]);
1108 uint32_t minExpiryDelta = TX_EXPIRING_SOON_THRESHOLD + 1;
1109 if (expiryDelta < minExpiryDelta) {
1110 return InitError(strprintf(_("Invalid value for -txexpirydelta='%u' (must be least %u)"), expiryDelta, minExpiryDelta));
1112 expiryDeltaArg = expiryDelta;
1114 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", true);
1115 fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false);
1117 std::string strWalletFile = GetArg("-wallet", "wallet.dat");
1118 // Check Sapling migration address if set and is a valid Sapling address
1119 if (mapArgs.count("-migrationdestaddress")) {
1120 std::string migrationDestAddress = mapArgs["-migrationdestaddress"];
1121 libzcash::PaymentAddress address = DecodePaymentAddress(migrationDestAddress);
1122 if (boost::get<libzcash::SaplingPaymentAddress>(&address) == nullptr) {
1123 return InitError(_("-migrationdestaddress must be a valid Sapling address."));
1126 #endif // ENABLE_WALLET
1128 fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true);
1129 nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1131 fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
1133 // Option to startup with mocktime set (used for regression testing):
1134 SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1136 if (GetBoolArg("-peerbloomfilters", true))
1137 nLocalServices |= NODE_BLOOM;
1139 nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1141 #ifdef ENABLE_MINING
1142 if (mapArgs.count("-mineraddress")) {
1143 CTxDestination addr = DecodeDestination(mapArgs["-mineraddress"]);
1144 if (!IsValidDestination(addr)) {
1145 return InitError(strprintf(
1146 _("Invalid address for -mineraddress=<addr>: '%s' (must be a transparent address)"),
1147 mapArgs["-mineraddress"]));
1152 // Default value of 0 for mempooltxinputlimit means no limit is applied
1153 if (mapArgs.count("-mempooltxinputlimit")) {
1154 int64_t limit = GetArg("-mempooltxinputlimit", 0);
1156 return InitError(_("Mempool limit on transparent inputs to a transaction cannot be negative"));
1157 } else if (limit > 0) {
1158 LogPrintf("Mempool configured to reject transactions with greater than %lld transparent inputs\n", limit);
1162 if (!mapMultiArgs["-nuparams"].empty()) {
1163 // Allow overriding network upgrade parameters for testing
1164 if (Params().NetworkIDString() != "regtest") {
1165 return InitError("Network upgrade parameters may only be overridden on regtest.");
1167 const vector<string>& deployments = mapMultiArgs["-nuparams"];
1168 for (auto i : deployments) {
1169 std::vector<std::string> vDeploymentParams;
1170 boost::split(vDeploymentParams, i, boost::is_any_of(":"));
1171 if (vDeploymentParams.size() != 2) {
1172 return InitError("Network upgrade parameters malformed, expecting hexBranchId:activationHeight");
1174 int nActivationHeight;
1175 if (!ParseInt32(vDeploymentParams[1], &nActivationHeight)) {
1176 return InitError(strprintf("Invalid nActivationHeight (%s)", vDeploymentParams[1]));
1179 // Exclude Sprout from upgrades
1180 for (auto i = Consensus::BASE_SPROUT + 1; i < Consensus::MAX_NETWORK_UPGRADES; ++i)
1182 if (vDeploymentParams[0].compare(HexInt(NetworkUpgradeInfo[i].nBranchId)) == 0) {
1183 UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex(i), nActivationHeight);
1185 LogPrintf("Setting network upgrade activation parameters for %s to height=%d\n", vDeploymentParams[0], nActivationHeight);
1190 return InitError(strprintf("Invalid network upgrade (%s)", vDeploymentParams[0]));
1195 // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
1197 // Initialize libsodium
1198 if (init_and_check_sodium() == -1) {
1202 // Initialize elliptic curve code
1204 globalVerifyHandle.reset(new ECCVerifyHandle());
1206 // set the hash algorithm to use for this chain
1207 extern uint32_t ASSETCHAINS_ALGO, ASSETCHAINS_VERUSHASH;
1208 if (ASSETCHAINS_ALGO == ASSETCHAINS_VERUSHASH)
1210 // initialize VerusHash
1212 CVerusHashV2::init();
1213 CBlockHeader::SetVerusV2Hash();
1214 if (strcmp(ASSETCHAINS_SYMBOL,"VRSC") == 0)
1216 COptCCParams::AddFeeCurrency(CCrossChainRPCData::GetID("dai.eth."));
1217 COptCCParams::AddFeeCurrency(CCrossChainRPCData::GetID("rbtc.eth."));
1218 COptCCParams::AddFeeCurrency(CCrossChainRPCData::GetID("wbtc.eth."));
1219 COptCCParams::AddFeeCurrency(CCrossChainRPCData::GetID("eth."));
1220 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV2, 310000);
1221 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV3, 800200);
1222 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV4, 800200);
1223 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV5, 1053660);
1224 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV5_1, 1053660);
1226 else if (strcmp(ASSETCHAINS_SYMBOL,"VRSCTEST") == 0)
1228 COptCCParams::AddFeeCurrency(CCrossChainRPCData::GetID("usd"));
1229 COptCCParams::AddFeeCurrency(CCrossChainRPCData::GetID("btc"));
1230 COptCCParams::AddFeeCurrency(CCrossChainRPCData::GetID("eth"));
1231 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV2, 1);
1232 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV3, 1);
1233 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV4, 1);
1234 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV5, 1);
1235 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV5_1, 1);
1236 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV6, 1);
1242 COptCCParams::AddFeeCurrency(CCrossChainRPCData::GetID("vrsctest"));
1246 COptCCParams::AddFeeCurrency(CCrossChainRPCData::GetID("vrsc"));
1249 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV2, 1);
1250 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV3, 1);
1251 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV4, 1);
1252 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV5, 1);
1253 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV5_1, 1);
1254 CConstVerusSolutionVector::activationHeight.SetActivationHeight(CActivationHeight::SOLUTION_VERUSV6, 1);
1258 // get default IDs and addresses
1259 auto defaultIDDest = DecodeDestination(GetArg("-defaultid", ""));
1260 VERUS_DEFAULTID = defaultIDDest.which() == COptCCParams::ADDRTYPE_ID ? CIdentityID(GetDestinationID(defaultIDDest)) : CIdentityID();
1261 auto notaryIDDest = DecodeDestination(GetArg("-notaryid", ""));
1262 VERUS_NOTARYID = notaryIDDest.which() == COptCCParams::ADDRTYPE_ID ? CIdentityID(GetDestinationID(notaryIDDest)) : CIdentityID();
1263 auto nodeIDDest = DecodeDestination(GetArg("-nodeid", ""));
1264 VERUS_NODEID = nodeIDDest.which() == COptCCParams::ADDRTYPE_ID ? GetDestinationID(nodeIDDest) : uint160();
1265 VERUS_DEFAULT_ZADDR = GetArg("-cheatcatcher", "");
1266 VERUS_DEFAULT_ZADDR = GetArg("-defaultzaddr", VERUS_DEFAULT_ZADDR);
1268 // if we are supposed to catch stake cheaters, there must be a valid sapling parameter, we need it at
1269 // initialization, and this is the first time we can get it. store the Sapling address here
1270 extern boost::optional<libzcash::SaplingPaymentAddress> defaultSaplingDest;
1271 libzcash::PaymentAddress addr = DecodePaymentAddress(VERUS_DEFAULT_ZADDR);
1272 if (VERUS_DEFAULT_ZADDR.size() > 0 && IsValidPaymentAddress(addr))
1276 defaultSaplingDest = boost::get<libzcash::SaplingPaymentAddress>(addr);
1282 VERUS_PRIVATECHANGE = GetBoolArg("-privatechange", GetArg("-defaultzaddr", VERUS_DEFAULT_ZADDR).empty());
1285 if (!InitSanityCheck())
1286 return InitError(_("Initialization sanity check failed. Verus is shutting down."));
1288 std::string strDataDir = GetDataDir().string();
1289 #ifdef ENABLE_WALLET
1290 // Wallet file must be a plain filename without a directory
1291 if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
1292 return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
1294 // Make sure only a single Bitcoin process is using the data directory.
1295 boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
1296 FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
1297 if (file) fclose(file);
1300 static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1301 if (!lock.try_lock())
1302 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Verus is probably already running."), strDataDir));
1303 } catch(const boost::interprocess::interprocess_exception& e) {
1304 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Verus is probably already running.") + " %s.", strDataDir, e.what()));
1308 CreatePidFile(GetPidFile(), getpid());
1310 if (GetBoolArg("-shrinkdebugfile", !fDebug))
1312 LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
1313 LogPrintf("Verus version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
1315 if (fPrintToDebugLog)
1317 LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
1318 #ifdef ENABLE_WALLET
1319 LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
1321 if (!fLogTimestamps)
1322 LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1323 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1324 LogPrintf("Using data directory %s\n", strDataDir);
1325 LogPrintf("Using config file %s\n", GetConfigFile().string());
1326 LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
1327 std::ostringstream strErrors;
1329 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1330 if (nScriptCheckThreads) {
1331 for (int i=0; i<nScriptCheckThreads-1; i++)
1332 threadGroup.create_thread(&ThreadScriptCheck);
1335 // Start the lightweight task scheduler thread
1336 CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1337 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1342 if ((chainparams.NetworkIDString() != "regtest") &&
1343 GetBoolArg("-showmetrics", 0) &&
1344 !fPrintToConsole && !GetBoolArg("-daemon", false)) {
1345 // Start the persistent metrics interface
1346 ConnectMetricsScreen();
1347 threadGroup.create_thread(&ThreadShowMetricsScreen);
1350 // These must be disabled for now, they are buggy and we probably don't
1351 // want any of libsnark's profiling in production anyway.
1352 libsnark::inhibit_profiling_info = true;
1353 libsnark::inhibit_profiling_counters = true;
1355 // Initialize Zcash circuit parameters
1356 ZC_LoadParams(chainparams);
1358 if (GetBoolArg("-savesproutr1cs", false)) {
1359 boost::filesystem::path r1cs_path = ZC_GetParamsDir() / "r1cs";
1361 LogPrintf("Saving Sprout R1CS to %s\n", r1cs_path.string());
1363 pzcashParams->saveR1CS(r1cs_path.string());
1366 /* Start the RPC server already. It will be started in "warmup" mode
1367 * and not really process calls already (but it will signify connections
1368 * that the server is there and will be ready later). Warmup mode will
1369 * be disabled when initialisation is finished.
1373 uiInterface.InitMessage.connect(SetRPCWarmupStatus);
1374 if (!AppInitServers(threadGroup))
1375 return InitError(_("Unable to start HTTP server. See debug log for details."));
1380 // ********************************************************* Step 5: verify wallet database integrity
1381 #ifdef ENABLE_WALLET
1382 if (!fDisableWallet) {
1383 LogPrintf("Using wallet %s\n", strWalletFile);
1384 uiInterface.InitMessage(_("Verifying wallet..."));
1386 std::string warningString;
1387 std::string errorString;
1389 if (!CWallet::Verify(strWalletFile, warningString, errorString))
1392 if (!warningString.empty())
1393 InitWarning(warningString);
1394 if (!errorString.empty())
1395 return InitError(warningString);
1397 } // (!fDisableWallet)
1398 #endif // ENABLE_WALLET
1399 // ********************************************************* Step 6: network initialization
1401 RegisterNodeSignals(GetNodeSignals());
1403 // sanitize comments per BIP-0014, format user agent and check total size
1404 std::vector<string> uacomments;
1405 BOOST_FOREACH(string cmt, mapMultiArgs["-uacomment"])
1407 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1408 return InitError(strprintf("User Agent comment (%s) contains unsafe characters.", cmt));
1409 uacomments.push_back(SanitizeString(cmt, SAFE_CHARS_UA_COMMENT));
1411 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1412 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1413 return InitError(strprintf("Total length of network version string %i exceeds maximum of %i characters. Reduce the number and/or size of uacomments.",
1414 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1417 if (mapArgs.count("-onlynet")) {
1418 std::set<enum Network> nets;
1419 BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) {
1420 enum Network net = ParseNetwork(snet);
1421 if (net == NET_UNROUTABLE)
1422 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1425 for (int n = 0; n < NET_MAX; n++) {
1426 enum Network net = (enum Network)n;
1427 if (!nets.count(net))
1432 if (mapArgs.count("-whitelist")) {
1433 BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
1434 CSubNet subnet(net);
1435 if (!subnet.IsValid())
1436 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1437 CNode::AddWhitelistedRange(subnet);
1441 bool proxyRandomize = GetBoolArg("-proxyrandomize", true);
1442 // -proxy sets a proxy for all outgoing network traffic
1443 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1444 std::string proxyArg = GetArg("-proxy", "");
1445 SetLimited(NET_TOR);
1446 if (proxyArg != "" && proxyArg != "0") {
1447 proxyType addrProxy = proxyType(CService(proxyArg, 9050), proxyRandomize);
1448 if (!addrProxy.IsValid())
1449 return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
1451 SetProxy(NET_IPV4, addrProxy);
1452 SetProxy(NET_IPV6, addrProxy);
1453 SetProxy(NET_TOR, addrProxy);
1454 SetNameProxy(addrProxy);
1455 SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1458 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1459 // -noonion (or -onion=0) disables connecting to .onion entirely
1460 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1461 std::string onionArg = GetArg("-onion", "");
1462 if (onionArg != "") {
1463 if (onionArg == "0") { // Handle -noonion/-onion=0
1464 SetLimited(NET_TOR); // set onions as unreachable
1466 proxyType addrOnion = proxyType(CService(onionArg, 9050), proxyRandomize);
1467 if (!addrOnion.IsValid())
1468 return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
1469 SetProxy(NET_TOR, addrOnion);
1470 SetLimited(NET_TOR, false);
1474 // see Step 2: parameter interactions for more information about these
1475 fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1476 fDiscover = GetBoolArg("-discover", true);
1477 fNameLookup = GetBoolArg("-dns", true);
1479 bool fBound = false;
1481 if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
1482 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
1484 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1485 return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
1486 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1488 BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
1490 if (!Lookup(strBind.c_str(), addrBind, 0, false))
1491 return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
1492 if (addrBind.GetPort() == 0)
1493 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1494 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1498 struct in_addr inaddr_any;
1499 inaddr_any.s_addr = INADDR_ANY;
1500 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
1501 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1504 return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1507 if (mapArgs.count("-externalip")) {
1508 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
1509 CService addrLocal(strAddr, GetListenPort(), fNameLookup);
1510 if (!addrLocal.IsValid())
1511 return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
1512 AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
1516 BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
1517 AddOneShot(strDest);
1520 pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
1522 if (pzmqNotificationInterface) {
1523 RegisterValidationInterface(pzmqNotificationInterface);
1528 pAMQPNotificationInterface = AMQPNotificationInterface::CreateWithArguments(mapArgs);
1530 if (pAMQPNotificationInterface) {
1532 // AMQP support is currently an experimental feature, so fail if user configured AMQP notifications
1533 // without enabling experimental features.
1534 if (!fExperimentalMode) {
1535 return InitError(_("AMQP support requires -experimentalfeatures."));
1538 RegisterValidationInterface(pAMQPNotificationInterface);
1542 // ********************************************************* Step 7: load block chain
1544 fReindex = GetBoolArg("-reindex", false);
1546 // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
1547 boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1548 if (!boost::filesystem::exists(blocksDir))
1550 boost::filesystem::create_directories(blocksDir);
1551 bool linked = false;
1552 for (unsigned int i = 1; i < 10000; i++) {
1553 boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1554 if (!boost::filesystem::exists(source)) break;
1555 boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
1557 boost::filesystem::create_hard_link(source, dest);
1558 LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
1560 } catch (const boost::filesystem::filesystem_error& e) {
1561 // Note: hardlink creation failing is not a disaster, it just means
1562 // blocks will get re-downloaded from peers.
1563 LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
1573 // block tree db settings
1574 int dbMaxOpenFiles = GetArg("-dbmaxopenfiles", DEFAULT_DB_MAX_OPEN_FILES);
1575 bool dbCompression = GetBoolArg("-dbcompression", DEFAULT_DB_COMPRESSION);
1577 LogPrintf("Block index database configuration:\n");
1578 LogPrintf("* Using %d max open files\n", dbMaxOpenFiles);
1579 LogPrintf("* Compression is %s\n", dbCompression ? "enabled" : "disabled");
1581 // cache size calculations
1582 int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1583 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1584 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache
1585 int64_t nBlockTreeDBCache = nTotalCache / 8;
1587 if (GetBoolArg("-addressindex", DEFAULT_ADDRESSINDEX) || GetBoolArg("-spentindex", DEFAULT_SPENTINDEX)) {
1588 // enable 3/4 of the cache if addressindex and/or spentindex is enabled
1589 nBlockTreeDBCache = nTotalCache * 3 / 4;
1591 if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false)) {
1592 nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
1595 nTotalCache -= nBlockTreeDBCache;
1596 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1597 nTotalCache -= nCoinDBCache;
1598 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1599 LogPrintf("Cache configuration:\n");
1600 LogPrintf("* Max cache setting possible %.1fMiB\n", nMaxDbCache);
1601 LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1602 LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1603 LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
1605 if ( fReindex == 0 )
1607 bool checkval,fAddressIndex,fSpentIndex,fTimeStampIndex;
1608 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles);
1610 fAddressIndex = true;
1611 pblocktree->ReadFlag("addressindex", checkval);
1612 if ( checkval != fAddressIndex )
1614 pblocktree->WriteFlag("addressindex", fAddressIndex);
1615 fprintf(stderr,"set addressindex, will reindex. sorry will take a while.\n");
1620 pblocktree->ReadFlag("spentindex", checkval);
1621 if ( checkval != fSpentIndex )
1623 pblocktree->WriteFlag("spentindex", fSpentIndex);
1624 fprintf(stderr,"set spentindex, will reindex. sorry will take a while.\n");
1628 fInsightExplorer = GetBoolArg("-insightexplorer", DEFAULT_INSIGHTEXPLORER);
1629 pblocktree->ReadFlag("insightexplorer", checkval);
1630 if ( checkval != fInsightExplorer )
1632 pblocktree->WriteFlag("insightexplorer", fInsightExplorer);
1633 fprintf(stderr,"set insightexplorer, will reindex. sorry will take a while.\n");
1637 fTimeStampIndex = GetBoolArg("-timestampindex", DEFAULT_TIMESTAMPINDEX);
1638 pblocktree->ReadFlag("timestampindex", checkval);
1639 if ( checkval != fTimeStampIndex )
1641 pblocktree->WriteFlag("timestampindex", fTimeStampIndex);
1642 fprintf(stderr,"set timestampindex, will reindex. sorry will take a while.\n");
1647 bool clearWitnessCaches = false;
1649 bool fLoaded = false;
1651 bool fReset = fReindex;
1652 std::string strLoadError;
1654 uiInterface.InitMessage(_("Loading block index..."));
1656 nStart = GetTimeMillis();
1661 delete pcoinsdbview;
1662 delete pcoinscatcher;
1664 delete pnotarisations;
1666 pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles);
1667 pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
1668 pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1669 pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1670 pnotarisations = new NotarisationDB(100*1024*1024, false, fReindex);
1674 pblocktree->WriteReindexing(true);
1675 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1677 CleanupBlockRevFiles();
1680 if (!LoadBlockIndex()) {
1681 strLoadError = _("Error loading block database");
1685 // If the loaded chain has a wrong genesis, bail out immediately
1686 // (we're likely using a testnet datadir, or the other way around).
1687 if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1688 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1690 // Initialize the block index (no-op if non-empty database was already loaded)
1691 if (!InitBlockIndex(chainparams)) {
1692 strLoadError = _("Error initializing block database");
1695 KOMODO_LOADINGBLOCKS = 0;
1697 // Check for changed -txindex state
1698 if (!fReindex && fTxIndex != GetBoolArg("-txindex", true)) {
1699 strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1703 // Check for changed -insightexplorer state
1704 if (!fReindex && fInsightExplorer != GetBoolArg("-insightexplorer", DEFAULT_INSIGHTEXPLORER) ) {
1705 strLoadError = _("You need to rebuild the database using -reindex to change -insightexplorer");
1709 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1710 // in the past, but is now trying to run unpruned.
1711 if (!fReindex && fHavePruned && !fPruneMode) {
1712 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1717 uiInterface.InitMessage(_("Rewinding blocks if needed..."));
1718 if (!RewindBlockIndex(chainparams, clearWitnessCaches)) {
1719 strLoadError = _("Unable to rewind the database to a pre-upgrade state. You will need to redownload the blockchain");
1724 uiInterface.InitMessage(_("Verifying blocks..."));
1725 if (fHavePruned && GetArg("-checkblocks", 288) > MIN_BLOCKS_TO_KEEP) {
1726 LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
1727 MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", 288));
1729 if ( KOMODO_REWIND == 0 )
1731 if (!CVerifyDB().VerifyDB(Params(), pcoinsdbview, GetArg("-checklevel", 3),
1732 GetArg("-checkblocks", 288))) {
1733 strLoadError = _("Corrupted block database detected");
1737 } catch (const std::exception& e) {
1738 if (fDebug) LogPrintf("%s\n", e.what());
1739 strLoadError = _("Error opening block database");
1747 // first suggest a reindex
1749 bool fRet = uiInterface.ThreadSafeMessageBox(
1750 strLoadError + ".\n\n" + _("error in HDD data, might just need to update to latest, if that doesnt work, then you need to resync"),
1751 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1754 fRequestShutdown = false;
1756 LogPrintf("Aborted block database rebuild. Exiting.\n");
1760 return InitError(strLoadError);
1764 KOMODO_LOADINGBLOCKS = 0;
1766 // As LoadBlockIndex can take several minutes, it's possible the user
1767 // requested to kill the GUI during the last operation. If so, exit.
1768 // As the program has not fully started yet, Shutdown() is possibly overkill.
1769 if (fRequestShutdown)
1771 LogPrintf("Shutdown requested. Exiting.\n");
1774 LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1776 boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1777 CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
1778 // Allowed to fail as this file IS missing on first startup.
1779 if (!est_filein.IsNull())
1780 mempool.ReadFeeEstimates(est_filein);
1781 fFeeEstimatesInitialized = true;
1784 // ********************************************************* Step 8: load wallet
1785 #ifdef ENABLE_WALLET
1786 if (fDisableWallet) {
1788 LogPrintf("Wallet disabled!\n");
1791 // needed to restore wallet transaction meta data after -zapwallettxes
1792 std::vector<CWalletTx> vWtx;
1794 if (GetBoolArg("-zapwallettxes", false)) {
1795 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
1797 pwalletMain = new CWallet(strWalletFile);
1798 DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
1799 if (nZapWalletRet != DB_LOAD_OK) {
1800 uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
1808 uiInterface.InitMessage(_("Loading wallet..."));
1810 nStart = GetTimeMillis();
1811 bool fFirstRun = true;
1812 pwalletMain = new CWallet(strWalletFile);
1813 DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
1814 if (nLoadWalletRet != DB_LOAD_OK)
1816 if (nLoadWalletRet == DB_CORRUPT)
1817 strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
1818 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
1820 string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
1821 " or address book entries might be missing or incorrect."));
1824 else if (nLoadWalletRet == DB_TOO_NEW)
1825 strErrors << _("Error loading wallet.dat: Wallet requires newer version of Komodo") << "\n";
1826 else if (nLoadWalletRet == DB_NEED_REWRITE)
1828 strErrors << _("Wallet needed to be rewritten: restart Zcash to complete") << "\n";
1829 LogPrintf("%s", strErrors.str());
1830 return InitError(strErrors.str());
1833 strErrors << _("Error loading wallet.dat") << "\n";
1836 if (GetBoolArg("-upgradewallet", fFirstRun))
1838 int nMaxVersion = GetArg("-upgradewallet", 0);
1839 if (nMaxVersion == 0) // the -upgradewallet without argument case
1841 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
1842 nMaxVersion = CLIENT_VERSION;
1843 pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
1846 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
1847 if (nMaxVersion < pwalletMain->GetVersion())
1848 strErrors << _("Cannot downgrade wallet") << "\n";
1849 pwalletMain->SetMaxVersion(nMaxVersion);
1852 if (!pwalletMain->HaveHDSeed())
1854 // We can't set the new HD seed until the wallet is decrypted.
1855 // https://github.com/zcash/zcash/issues/3607
1856 if (!pwalletMain->IsCrypted()) {
1857 // generate a new HD seed
1858 pwalletMain->GenerateNewSeed();
1862 // Set sapling migration status
1863 pwalletMain->fSaplingMigrationEnabled = GetBoolArg("-migration", false);
1867 // Create new keyUser and set as default key
1868 CPubKey newDefaultKey;
1869 if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
1870 pwalletMain->SetDefaultKey(newDefaultKey);
1871 if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
1872 strErrors << _("Cannot write default address") << "\n";
1875 pwalletMain->SetBestChain(chainActive.GetLocator());
1878 LogPrintf("%s", strErrors.str());
1879 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
1881 RegisterValidationInterface(pwalletMain);
1883 CBlockIndex *pindexRescan = chainActive.Tip();
1884 if (clearWitnessCaches || GetBoolArg("-rescan", false))
1886 pwalletMain->ClearNoteWitnessCache();
1887 // zap and rescan clears IDs
1888 if (GetArg("-zapwallettxes", false))
1890 pwalletMain->ClearIdentities();
1892 pindexRescan = chainActive.Genesis();
1896 CWalletDB walletdb(strWalletFile);
1897 CBlockLocator locator;
1898 if (walletdb.ReadBestBlock(locator))
1899 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
1901 pindexRescan = chainActive.Genesis();
1903 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
1905 uiInterface.InitMessage(_("Rescanning..."));
1906 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->GetHeight(), pindexRescan->GetHeight());
1907 nStart = GetTimeMillis();
1908 pwalletMain->ScanForWalletTransactions(pindexRescan, true);
1909 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
1910 pwalletMain->SetBestChain(chainActive.GetLocator());
1913 // Restore wallet transaction metadata after -zapwallettxes=1
1914 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
1916 CWalletDB walletdb(strWalletFile);
1918 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
1920 uint256 hash = wtxOld.GetHash();
1921 std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
1922 if (mi != pwalletMain->mapWallet.end())
1924 const CWalletTx* copyFrom = &wtxOld;
1925 CWalletTx* copyTo = &mi->second;
1926 copyTo->mapValue = copyFrom->mapValue;
1927 copyTo->vOrderForm = copyFrom->vOrderForm;
1928 copyTo->nTimeReceived = copyFrom->nTimeReceived;
1929 copyTo->nTimeSmart = copyFrom->nTimeSmart;
1930 copyTo->fFromMe = copyFrom->fFromMe;
1931 copyTo->strFromAccount = copyFrom->strFromAccount;
1932 copyTo->nOrderPos = copyFrom->nOrderPos;
1933 copyTo->WriteToDisk(&walletdb);
1938 pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", true));
1939 } // (!fDisableWallet)
1940 #else // ENABLE_WALLET
1941 LogPrintf("No wallet support compiled in!\n");
1942 #endif // !ENABLE_WALLET
1944 #ifdef ENABLE_MINING
1945 #ifndef ENABLE_WALLET
1946 if (GetBoolArg("-minetolocalwallet", false)) {
1947 return InitError(_("Verus was not built with wallet support. Set -minetolocalwallet=0 to use -mineraddress, or rebuild Verus with wallet support."));
1949 if (GetArg("-mineraddress", "").empty() && GetBoolArg("-gen", false)) {
1950 return InitError(_("Verus was not built with wallet support. Set -mineraddress, or rebuild Verus with wallet support."));
1952 #endif // !ENABLE_WALLET
1954 if (mapArgs.count("-mineraddress")) {
1955 #ifdef ENABLE_WALLET
1956 bool minerAddressInLocalWallet = false;
1958 // Address has already been validated
1959 CTxDestination addr = DecodeDestination(mapArgs["-mineraddress"]);
1960 if (addr.which() == COptCCParams::ADDRTYPE_ID)
1962 std::pair<CIdentityMapKey, CIdentityMapValue> keyAndIdentity;
1963 minerAddressInLocalWallet = pwalletMain->GetIdentity(GetDestinationID(addr), keyAndIdentity) &&
1964 keyAndIdentity.first.CanSpend();
1968 CKeyID keyID = boost::get<CKeyID>(addr);
1969 minerAddressInLocalWallet = pwalletMain->HaveKey(keyID);
1972 if (GetBoolArg("-minetolocalwallet", true) && !minerAddressInLocalWallet) {
1973 return InitError(_("-mineraddress is not in the local wallet. Either use a local address, or set -minetolocalwallet=0"));
1975 #endif // ENABLE_WALLET
1977 // This is leveraging the fact that boost::signals2 executes connected
1978 // handlers in-order. Further up, the wallet is connected to this signal
1979 // if the wallet is enabled. The wallet's ScriptForMining handler does
1980 // nothing if -mineraddress is set, and GetScriptForMinerAddress() does
1981 // nothing if -mineraddress is not set (or set to an invalid address).
1983 // The upshot is that when ScriptForMining(script) is called:
1984 // - If -mineraddress is set (whether or not the wallet is enabled), the
1985 // CScript argument is set to -mineraddress.
1986 // - If the wallet is enabled and -mineraddress is not set, the CScript
1987 // argument is set to a wallet address.
1988 // - If the wallet is disabled and -mineraddress is not set, the CScript
1989 // argument is not modified; in practice this means it is empty, and
1990 // GenerateBitcoins() returns an error.
1991 GetMainSignals().ScriptForMining.connect(GetScriptForMinerAddress);
1993 #endif // ENABLE_MINING
1995 // ********************************************************* Step 9: data directory maintenance
1997 // if pruning, unset the service bit and perform the initial blockstore prune
1998 // after any wallet rescanning has taken place.
2000 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
2001 nLocalServices &= ~NODE_NETWORK;
2003 uiInterface.InitMessage(_("Pruning blockstore..."));
2008 // ********************************************************* Step 10: import blocks
2010 if (mapArgs.count("-blocknotify"))
2011 uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
2012 if ( KOMODO_REWIND >= 0 )
2014 uiInterface.InitMessage(_("Activating best chain..."));
2015 // scan for better chains in the block chain database, that are not yet connected in the active best chain
2016 CValidationState state;
2017 if ( !ActivateBestChain(state, Params()))
2018 strErrors << "Failed to connect best block";
2020 InitializePremineSupply();
2021 std::vector<boost::filesystem::path> vImportFiles;
2022 if (mapArgs.count("-loadblock"))
2024 BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
2025 vImportFiles.push_back(strFile);
2027 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
2028 if (chainActive.Tip() == NULL) {
2029 LogPrintf("Waiting for genesis block to be imported...\n");
2030 while (!fRequestShutdown && chainActive.Tip() == NULL)
2034 // ********************************************************* Step 11: start node
2036 if (!CheckDiskSpace())
2039 if (!strErrors.str().empty())
2040 return InitError(strErrors.str());
2043 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
2044 LogPrintf("nBestHeight = %d\n", chainActive.Height());
2045 #ifdef ENABLE_WALLET
2048 LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
2049 LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
2050 LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
2053 // Start the thread that notifies listeners of transactions that have been
2054 // recently added to the mempool.
2055 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "txnotify", &ThreadNotifyRecentlyAdded));
2057 if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
2058 StartTorControl(threadGroup, scheduler);
2060 StartNode(threadGroup, scheduler);
2062 bool gen = GetBoolArg("-gen", false);
2064 #ifdef ENABLE_MINING
2065 // Generate coins in the background
2066 #ifdef ENABLE_WALLET
2067 VERUS_MINTBLOCKS = GetBoolArg("-mint", false);
2068 mapArgs["-gen"] = gen || VERUS_MINTBLOCKS ? "1" : "0";
2069 mapArgs["-genproclimit"] = itostr(GetArg("-genproclimit", gen ? -1 : 0));
2071 if (pwalletMain || !GetArg("-mineraddress", "").empty())
2072 GenerateBitcoins(gen || VERUS_MINTBLOCKS, pwalletMain, GetArg("-genproclimit", gen ? -1 : 0));
2074 GenerateBitcoins(gen, GetArg("-genproclimit", -1));
2078 // Monitor the chain every minute, and alert if we get blocks much quicker or slower than expected.
2079 CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload,
2080 boost::ref(cs_main), boost::cref(pindexBestHeader));
2081 scheduler.scheduleEvery(f, 60);
2083 // ********************************************************* Step 11: finished
2085 SetRPCWarmupFinished();
2086 uiInterface.InitMessage(_("Done loading"));
2088 #ifdef ENABLE_WALLET
2090 // Add wallet transactions that aren't already in a block to mapTransactions
2091 pwalletMain->ReacceptWalletTransactions();
2093 // Run a thread to flush wallet periodically
2094 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
2099 threadGroup.create_thread(boost::bind(ThreadSendAlert));
2101 return !fRequestShutdown;