Dash Core  0.12.2.1
P2P Digital Currency
init.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin Core developers
3 // Copyright (c) 2014-2017 The Dash Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #if defined(HAVE_CONFIG_H)
8 #include "config/dash-config.h"
9 #endif
10 
11 #include "init.h"
12 
13 #include "addrman.h"
14 #include "amount.h"
15 #include "chain.h"
16 #include "chainparams.h"
17 #include "checkpoints.h"
18 #include "compat/sanity.h"
19 #include "consensus/validation.h"
20 #include "httpserver.h"
21 #include "httprpc.h"
22 #include "key.h"
23 #include "validation.h"
24 #include "miner.h"
25 #include "netbase.h"
26 #include "net.h"
27 #include "netfulfilledman.h"
28 #include "net_processing.h"
29 #include "policy/policy.h"
30 #include "rpc/server.h"
31 #include "script/standard.h"
32 #include "script/sigcache.h"
33 #include "scheduler.h"
34 #include "txdb.h"
35 #include "txmempool.h"
36 #include "torcontrol.h"
37 #include "ui_interface.h"
38 #include "util.h"
39 #include "utilmoneystr.h"
40 #include "utilstrencodings.h"
41 #include "validationinterface.h"
42 #ifdef ENABLE_WALLET
43 #include "wallet/db.h"
44 #include "wallet/wallet.h"
45 #include "wallet/walletdb.h"
46 #endif
47 
48 #include "activemasternode.h"
50 #include "flat-database.h"
51 #include "governance.h"
52 #include "instantx.h"
53 #ifdef ENABLE_WALLET
54 #include "keepass.h"
55 #endif
56 #include "masternode-payments.h"
57 #include "masternode-sync.h"
58 #include "masternodeman.h"
59 #include "masternodeconfig.h"
60 #include "messagesigner.h"
61 #include "netfulfilledman.h"
62 #include "privatesend-client.h"
63 #include "privatesend-server.h"
64 #include "spork.h"
65 
66 #include <stdint.h>
67 #include <stdio.h>
68 #include <memory>
69 
70 #ifndef WIN32
71 #include <signal.h>
72 #endif
73 
74 #include <boost/algorithm/string/classification.hpp>
75 #include <boost/algorithm/string/predicate.hpp>
76 #include <boost/algorithm/string/replace.hpp>
77 #include <boost/algorithm/string/split.hpp>
78 #include <boost/bind.hpp>
79 #include <boost/filesystem.hpp>
80 #include <boost/function.hpp>
81 #include <boost/interprocess/sync/file_lock.hpp>
82 #include <boost/thread.hpp>
83 #include <openssl/crypto.h>
84 
85 #if ENABLE_ZMQ
87 #endif
88 
89 using namespace std;
90 
91 extern void ThreadSendAlert(CConnman& connman);
92 
93 #ifdef ENABLE_WALLET
94 CWallet* pwalletMain = NULL;
95 #endif
97 bool fRestartRequested = false; // true: restart false: shutdown
98 static const bool DEFAULT_PROXYRANDOMIZE = true;
99 static const bool DEFAULT_REST_ENABLE = false;
100 static const bool DEFAULT_DISABLE_SAFEMODE = false;
101 static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
102 
103 std::unique_ptr<CConnman> g_connman;
104 std::unique_ptr<PeerLogicValidation> peerLogic;
105 
106 #if ENABLE_ZMQ
107 static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
108 #endif
109 
111 
112 #ifdef WIN32
113 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
114 // accessing block files don't count towards the fd_set size limit
115 // anyway.
116 #define MIN_CORE_FILEDESCRIPTORS 0
117 #else
118 #define MIN_CORE_FILEDESCRIPTORS 150
119 #endif
120 
122 enum BindFlags {
123  BF_NONE = 0,
124  BF_EXPLICIT = (1U << 0),
125  BF_REPORT_ERROR = (1U << 1),
126  BF_WHITELIST = (1U << 2),
127 };
128 
129 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
130 CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h
131 
133 //
134 // Shutdown
135 //
136 
137 //
138 // Thread management and startup/shutdown:
139 //
140 // The network-processing threads are all part of a thread group
141 // created by AppInit() or the Qt main() function.
142 //
143 // A clean exit happens when StartShutdown() or the SIGTERM
144 // signal handler sets fRequestShutdown, which triggers
145 // the DetectShutdownThread(), which interrupts the main thread group.
146 // DetectShutdownThread() then exits, which causes AppInit() to
147 // continue (it .joins the shutdown thread).
148 // Shutdown() is then
149 // called to clean up database connections, and stop other
150 // threads that should only be stopped after the main network-processing
151 // threads have exited.
152 //
153 // Note that if running -daemon the parent process returns from AppInit2
154 // before adding any threads to the threadGroup, so .join_all() returns
155 // immediately and the parent exits from main().
156 //
157 // Shutdown for Qt is very similar, only it uses a QTimer to detect
158 // fRequestShutdown getting set, and then does the normal Qt
159 // shutdown thing.
160 //
161 
162 volatile bool fRequestShutdown = false;
163 
165 {
166  fRequestShutdown = true;
167 }
169 {
171 }
172 
174 {
175 public:
177  bool GetCoins(const uint256 &txid, CCoins &coins) const {
178  try {
179  return CCoinsViewBacked::GetCoins(txid, coins);
180  } catch(const std::runtime_error& e) {
181  uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
182  LogPrintf("Error reading from database: %s\n", e.what());
183  // Starting the shutdown sequence and returning false to the caller would be
184  // interpreted as 'entry not found' (as opposed to unable to read data), and
185  // could lead to invalid interpretation. Just exit immediately, as we can't
186  // continue anyway, and all writes should be atomic.
187  abort();
188  }
189  }
190  // Writes do not need similar protection, as failure to write is handled by the caller.
191 };
192 
193 static CCoinsViewDB *pcoinsdbview = NULL;
195 static boost::scoped_ptr<ECCVerifyHandle> globalVerifyHandle;
196 
197 void Interrupt(boost::thread_group& threadGroup)
198 {
201  InterruptRPC();
202  InterruptREST();
204  if (g_connman)
205  g_connman->Interrupt();
206  threadGroup.interrupt_all();
207 }
208 
211 {
212  fRequestShutdown = true; // Needed when we shutdown the wallet
213  fRestartRequested = true; // Needed when we restart the wallet
214  LogPrintf("%s: In progress...\n", __func__);
215  static CCriticalSection cs_Shutdown;
216  TRY_LOCK(cs_Shutdown, lockShutdown);
217  if (!lockShutdown)
218  return;
219 
224  RenameThread("dash-shutoff");
226  StopHTTPRPC();
227  StopREST();
228  StopRPC();
229  StopHTTPServer();
230 #ifdef ENABLE_WALLET
231  if (pwalletMain)
232  pwalletMain->Flush(false);
233 #endif
234  GenerateBitcoins(false, 0, Params(), *g_connman);
235  MapPort(false);
237  peerLogic.reset();
238  g_connman.reset();
239 
240  // STORE DATA CACHES INTO SERIALIZED DAT FILES
241  CFlatDB<CMasternodeMan> flatdb1("mncache.dat", "magicMasternodeCache");
242  flatdb1.Dump(mnodeman);
243  CFlatDB<CMasternodePayments> flatdb2("mnpayments.dat", "magicMasternodePaymentsCache");
244  flatdb2.Dump(mnpayments);
245  CFlatDB<CGovernanceManager> flatdb3("governance.dat", "magicGovernanceCache");
246  flatdb3.Dump(governance);
247  CFlatDB<CNetFulfilledRequestManager> flatdb4("netfulfilled.dat", "magicFulfilledCache");
248  flatdb4.Dump(netfulfilledman);
249 
251 
253  {
254  boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
255  CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
256  if (!est_fileout.IsNull())
257  mempool.WriteFeeEstimates(est_fileout);
258  else
259  LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
260  fFeeEstimatesInitialized = false;
261  }
262 
263  {
264  LOCK(cs_main);
265  if (pcoinsTip != NULL) {
267  }
268  delete pcoinsTip;
269  pcoinsTip = NULL;
270  delete pcoinscatcher;
271  pcoinscatcher = NULL;
272  delete pcoinsdbview;
273  pcoinsdbview = NULL;
274  delete pblocktree;
275  pblocktree = NULL;
276  }
277 #ifdef ENABLE_WALLET
278  if (pwalletMain)
279  pwalletMain->Flush(true);
280 #endif
281 
282 #if ENABLE_ZMQ
283  if (pzmqNotificationInterface) {
284  UnregisterValidationInterface(pzmqNotificationInterface);
285  delete pzmqNotificationInterface;
286  pzmqNotificationInterface = NULL;
287  }
288 #endif
289 
294  }
295 
296 #ifndef WIN32
297  try {
298  boost::filesystem::remove(GetPidFile());
299  } catch (const boost::filesystem::filesystem_error& e) {
300  LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
301  }
302 #endif
304 }
305 
315 void Shutdown()
316 {
317  // Shutdown part 1: prepare shutdown
318  if(!fRestartRequested){
319  PrepareShutdown();
320  }
321  // Shutdown part 2: Stop TOR thread and delete wallet instance
322  StopTorControl();
323 #ifdef ENABLE_WALLET
324  delete pwalletMain;
325  pwalletMain = NULL;
326 #endif
327  globalVerifyHandle.reset();
328  ECC_Stop();
329  LogPrintf("%s: done\n", __func__);
330 }
331 
335 void HandleSIGTERM(int)
336 {
337  fRequestShutdown = true;
338 }
339 
340 void HandleSIGHUP(int)
341 {
342  fReopenDebugLog = true;
343 }
344 
345 bool static InitError(const std::string &str)
346 {
348  return false;
349 }
350 
351 bool static InitWarning(const std::string &str)
352 {
354  return true;
355 }
356 
357 bool static Bind(CConnman& connman, const CService &addr, unsigned int flags) {
358  if (!(flags & BF_EXPLICIT) && IsLimited(addr))
359  return false;
360  std::string strError;
361  if (!connman.BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
362  if (flags & BF_REPORT_ERROR)
363  return InitError(strError);
364  return false;
365  }
366  return true;
367 }
368 
370 {
371  cvBlockChange.notify_all();
372  LogPrint("rpc", "RPC stopped.\n");
373 }
374 
375 void OnRPCPreCommand(const CRPCCommand& cmd)
376 {
377  // Observe safe mode
378  string strWarning = GetWarnings("rpc");
379  if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
380  !cmd.okSafeMode)
381  throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
382 }
383 
384 std::string HelpMessage(HelpMessageMode mode)
385 {
386  const bool showDebug = GetBoolArg("-help-debug", false);
387 
388  // When adding new options to the categories, please keep and ensure alphabetical ordering.
389  // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
390  string strUsage = HelpMessageGroup(_("Options:"));
391  strUsage += HelpMessageOpt("-?", _("This help message"));
392  strUsage += HelpMessageOpt("-version", _("Print version and exit"));
393  strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
394  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)"));
395  strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
396  if (showDebug)
397  strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
398  strUsage +=HelpMessageOpt("-assumevalid=<hex>", strprintf(_("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s)"), Params(CBaseChainParams::MAIN).GetConsensus().defaultAssumeValid.GetHex(), Params(CBaseChainParams::TESTNET).GetConsensus().defaultAssumeValid.GetHex()));
399  strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
400  if (mode == HMM_BITCOIND)
401  {
402 #ifndef WIN32
403  strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
404 #endif
405  }
406  strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
407  strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
408  strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
409  strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
410  strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
411  strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
412  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)"),
414 #ifndef WIN32
415  strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
416 #endif
417  strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. "
418  "Warning: Reverting this setting requires re-downloading the entire blockchain. "
419  "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
420  strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
421  strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
422 #ifndef WIN32
423  strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
424 #endif
425  strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
426 
427  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));
428  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));
429  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));
430 
431  strUsage += HelpMessageGroup(_("Connection options:"));
432  strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
433  strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
434  strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
435  strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
436  strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)"));
437  strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
438  strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
439  strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)"));
440  strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
441  strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
442  strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
443  strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
444  strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (temporary service connections excluded) (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
445  strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
446  strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
447  strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
448  strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
449  strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
450  strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), 1));
451  if (showDebug)
452  strUsage += HelpMessageOpt("-enforcenodebloom", strprintf("Enforce minimum protocol version to limit use of bloom filters (default: %u)", 0));
453  strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), Params(CBaseChainParams::MAIN).GetDefaultPort(), Params(CBaseChainParams::TESTNET).GetDefaultPort()));
454  strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
455  strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
456  strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
457  strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
458  strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
459  strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
460 #ifdef USE_UPNP
461 #if USE_UPNP
462  strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
463 #else
464  strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
465 #endif
466 #endif
467  strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
468  strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
469  " " + _("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"));
470  strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
471  strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
472  strUsage += HelpMessageOpt("-maxuploadtarget=<n>", strprintf(_("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)"), DEFAULT_MAX_UPLOAD_TARGET));
473 
474 #ifdef ENABLE_WALLET
475  strUsage += HelpMessageGroup(_("Wallet options:"));
476  strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
477  strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
478  strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
480  strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
482  strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
484  strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
485  strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat on startup"));
486  strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), DEFAULT_SEND_FREE_TRANSACTIONS));
487  strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
488  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));
489  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)"),
491  strUsage += HelpMessageOpt("-usehd", _("Use hierarchical deterministic key generation (HD) after bip39/bip44. Only has effect during wallet creation/first start") + " " + strprintf(_("(default: %u)"), DEFAULT_USE_HD_WALLET));
492  strUsage += HelpMessageOpt("-mnemonic", _("User defined mnemonic for HD wallet (bip39). Only has effect during wallet creation/first start (default: randomly generated)"));
493  strUsage += HelpMessageOpt("-mnemonicpassphrase", _("User defined mnemonic passphrase for HD wallet (bip39). Only has effect during wallet creation/first start (default: empty string)"));
494  strUsage += HelpMessageOpt("-hdseed", _("User defined seed for HD wallet (should be in hex). Only has effect during wallet creation/first start (default: randomly generated)"));
495  strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
496  strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
497  strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
498  strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
499  strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
500  " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
501  strUsage += HelpMessageOpt("-createwalletbackups=<n>", strprintf(_("Number of automatic wallet backups (default: %u)"), nWalletBackups));
502  strUsage += HelpMessageOpt("-walletbackupsdir=<dir>", _("Specify full path to directory for automatic wallet backups (must exist)"));
503  strUsage += HelpMessageOpt("-keepass", strprintf(_("Use KeePass 2 integration using KeePassHttp plugin (default: %u)"), 0));
504  strUsage += HelpMessageOpt("-keepassport=<port>", strprintf(_("Connect to KeePassHttp on port <port> (default: %u)"), DEFAULT_KEEPASS_HTTP_PORT));
505  strUsage += HelpMessageOpt("-keepasskey=<key>", _("KeePassHttp key for AES encrypted communication with KeePass"));
506  strUsage += HelpMessageOpt("-keepassid=<name>", _("KeePassHttp id for the established association"));
507  strUsage += HelpMessageOpt("-keepassname=<name>", _("Name to construct url for KeePass entry that stores the wallet passphrase"));
508  if (mode == HMM_BITCOIN_QT)
509  strUsage += HelpMessageOpt("-windowtitle=<name>", _("Wallet window title"));
510 #endif
511 
512 #if ENABLE_ZMQ
513  strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
514  strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
515  strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
516  strUsage += HelpMessageOpt("-zmqpubhashtxlock=<address>", _("Enable publish hash transaction (locked via InstantSend) in <address>"));
517  strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
518  strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
519  strUsage += HelpMessageOpt("-zmqpubrawtxlock=<address>", _("Enable publish raw transaction (locked via InstantSend) in <address>"));
520 #endif
521 
522  strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
523  strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
524  if (showDebug)
525  {
526  strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
527  strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
528  strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
529  strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
530  strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
531 #ifdef ENABLE_WALLET
532  strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
533 #endif
534  strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
535  strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
536  strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
537  strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
538 #ifdef ENABLE_WALLET
539  strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
540 #endif
541  strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
542  strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
543  strUsage += HelpMessageOpt("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT));
544  strUsage += HelpMessageOpt("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT));
545  strUsage += HelpMessageOpt("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT));
546  }
547  string debugCategories = "addrman, alert, bench, coindb, db, http, libevent, lock, mempool, mempoolrej, net, proxy, prune, rand, reindex, rpc, selectcoins, tor, zmq, "
548  "dash (or specifically: gobject, instantsend, keepass, masternode, mnpayments, mnsync, privatesend, spork)"; // Don't translate these and qt below
549  if (mode == HMM_BITCOIN_QT)
550  debugCategories += ", qt";
551  strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
552  _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
553  if (showDebug)
554  strUsage += HelpMessageOpt("-nodebug", "Turn off debugging messages, same as -debug=0");
555  strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), DEFAULT_GENERATE));
556  strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), DEFAULT_GENERATE_THREADS));
557  strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
558  strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
559  strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
560  if (showDebug)
561  {
562  strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
563  strUsage += HelpMessageOpt("-logthreadnames", strprintf("Add thread names to debug messages (default: %u)", DEFAULT_LOGTHREADNAMES));
564  strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
565  strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", DEFAULT_LIMITFREERELAY));
566  strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", DEFAULT_RELAYPRIORITY));
567  strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
568  }
569  strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
571  strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
572  strUsage += HelpMessageOpt("-printtodebuglog", strprintf(_("Send trace/debug info to debug.log file (default: %u)"), 1));
573  if (showDebug)
574  {
575  strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
576 #ifdef ENABLE_WALLET
577  strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
578 #endif
579  }
580  strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
581  AppendParamsHelpMessages(strUsage, showDebug);
582  strUsage += HelpMessageOpt("-litemode=<n>", strprintf(_("Disable all Dash specific functionality (Masternodes, PrivateSend, InstantSend, Governance) (0-1, default: %u)"), 0));
583 
584  strUsage += HelpMessageGroup(_("Masternode options:"));
585  strUsage += HelpMessageOpt("-masternode=<n>", strprintf(_("Enable the client to act as a masternode (0-1, default: %u)"), 0));
586  strUsage += HelpMessageOpt("-mnconf=<file>", strprintf(_("Specify masternode configuration file (default: %s)"), "masternode.conf"));
587  strUsage += HelpMessageOpt("-mnconflock=<n>", strprintf(_("Lock masternodes from masternode configuration file (default: %u)"), 1));
588  strUsage += HelpMessageOpt("-masternodeprivkey=<n>", _("Set the masternode private key"));
589 
590  strUsage += HelpMessageGroup(_("PrivateSend options:"));
591  strUsage += HelpMessageOpt("-enableprivatesend=<n>", strprintf(_("Enable use of automated PrivateSend for funds stored in this wallet (0-1, default: %u)"), 0));
592  strUsage += HelpMessageOpt("-privatesendmultisession=<n>", strprintf(_("Enable multiple PrivateSend mixing sessions per block, experimental (0-1, default: %u)"), DEFAULT_PRIVATESEND_MULTISESSION));
593  strUsage += HelpMessageOpt("-privatesendrounds=<n>", strprintf(_("Use N separate masternodes for each denominated input to mix funds (2-16, default: %u)"), DEFAULT_PRIVATESEND_ROUNDS));
594  strUsage += HelpMessageOpt("-privatesendamount=<n>", strprintf(_("Keep N DASH anonymized (default: %u)"), DEFAULT_PRIVATESEND_AMOUNT));
595  strUsage += HelpMessageOpt("-liquidityprovider=<n>", strprintf(_("Provide liquidity to PrivateSend by infrequently mixing coins on a continual basis (0-100, default: %u, 1=very frequent, high fees, 100=very infrequent, low fees)"), DEFAULT_PRIVATESEND_LIQUIDITY));
596 
597  strUsage += HelpMessageGroup(_("InstantSend options:"));
598  strUsage += HelpMessageOpt("-enableinstantsend=<n>", strprintf(_("Enable InstantSend, show confirmations for locked transactions (0-1, default: %u)"), 1));
599  strUsage += HelpMessageOpt("-instantsenddepth=<n>", strprintf(_("Show N confirmations for a successfully locked transaction (0-9999, default: %u)"), DEFAULT_INSTANTSEND_DEPTH));
600  strUsage += HelpMessageOpt("-instantsendnotify=<cmd>", _("Execute command when a wallet InstantSend transaction is successfully locked (%s in cmd is replaced by TxID)"));
601 
602 
603  strUsage += HelpMessageGroup(_("Node relay options:"));
604  if (showDebug)
605  strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
606  strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Minimum bytes per sigop in transactions we relay and mine (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
607  strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
608  strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
609  strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
610 
611  strUsage += HelpMessageGroup(_("Block creation options:"));
612  strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), DEFAULT_BLOCK_MIN_SIZE));
613  strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
614  strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
615  if (showDebug)
616  strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
617 
618  strUsage += HelpMessageGroup(_("RPC server options:"));
619  strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
620  strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
621  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)"));
622  strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
623  strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
624  strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
625  strUsage += HelpMessageOpt("-rpcauth=<userpw>", _("Username and hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcuser. This option can be specified multiple times"));
626  strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort()));
627  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"));
628  strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
629  if (showDebug) {
630  strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
631  strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
632  }
633 
634  return strUsage;
635 }
636 
637 std::string LicenseInfo()
638 {
639  // todo: remove urls from translations on next change
640  return FormatParagraph(strprintf(_("Copyright (C) 2009-%i The Bitcoin Core Developers"), COPYRIGHT_YEAR)) + "\n" +
641  "\n" +
642  FormatParagraph(strprintf(_("Copyright (C) 2014-%i The Dash Core Developers"), COPYRIGHT_YEAR)) + "\n" +
643  "\n" +
644  FormatParagraph(_("This is experimental software.")) + "\n" +
645  "\n" +
646  FormatParagraph(_("Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.")) + "\n" +
647  "\n" +
648  FormatParagraph(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.")) +
649  "\n";
650 }
651 
652 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
653 {
654  if (initialSync || !pBlockIndex)
655  return;
656 
657  std::string strCmd = GetArg("-blocknotify", "");
658 
659  boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
660  boost::thread t(runCommand, strCmd); // thread runs free
661 }
662 
664 {
666  assert(fImporting == false);
667  fImporting = true;
668  }
669 
671  assert(fImporting == true);
672  fImporting = false;
673  }
674 };
675 
676 
677 // If we're using -prune with -reindex, then delete block files that will be ignored by the
678 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
679 // is missing, do the same here to delete any later block files after a gap. Also delete all
680 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
681 // is in sync with what's actually on disk by the time we start downloading, so that pruning
682 // works correctly.
684 {
685  using namespace boost::filesystem;
686  map<string, path> mapBlockFiles;
687 
688  // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
689  // Remove the rev files immediately and insert the blk file paths into an
690  // ordered map keyed by block file index.
691  LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
692  path blocksdir = GetDataDir() / "blocks";
693  for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
694  if (is_regular_file(*it) &&
695  it->path().filename().string().length() == 12 &&
696  it->path().filename().string().substr(8,4) == ".dat")
697  {
698  if (it->path().filename().string().substr(0,3) == "blk")
699  mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
700  else if (it->path().filename().string().substr(0,3) == "rev")
701  remove(it->path());
702  }
703  }
704 
705  // Remove all block files that aren't part of a contiguous set starting at
706  // zero by walking the ordered map (keys are block file indices) by
707  // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
708  // start removing block files.
709  int nContigCounter = 0;
710  BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) {
711  if (atoi(item.first) == nContigCounter) {
712  nContigCounter++;
713  continue;
714  }
715  remove(item.second);
716  }
717 }
718 
719 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
720 {
721  const CChainParams& chainparams = Params();
722  RenameThread("dash-loadblk");
723  CImportingNow imp;
724 
725  // -reindex
726  if (fReindex) {
727  int nFile = 0;
728  while (true) {
729  CDiskBlockPos pos(nFile, 0);
730  if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
731  break; // No block files left to reindex
732  FILE *file = OpenBlockFile(pos, true);
733  if (!file)
734  break; // This error is logged in OpenBlockFile
735  LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
736  LoadExternalBlockFile(chainparams, file, &pos);
737  nFile++;
738  }
739  pblocktree->WriteReindexing(false);
740  fReindex = false;
741  LogPrintf("Reindexing finished\n");
742  // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
743  InitBlockIndex(chainparams);
744  }
745 
746  // hardcoded $DATADIR/bootstrap.dat
747  boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
748  if (boost::filesystem::exists(pathBootstrap)) {
749  FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
750  if (file) {
751  boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
752  LogPrintf("Importing bootstrap.dat...\n");
753  LoadExternalBlockFile(chainparams, file);
754  RenameOver(pathBootstrap, pathBootstrapOld);
755  } else {
756  LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
757  }
758  }
759 
760  // -loadblock=
761  BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
762  FILE *file = fopen(path.string().c_str(), "rb");
763  if (file) {
764  LogPrintf("Importing blocks file %s...\n", path.string());
765  LoadExternalBlockFile(chainparams, file);
766  } else {
767  LogPrintf("Warning: Could not open blocks file %s\n", path.string());
768  }
769  }
770 
771  // scan for better chains in the block chain database, that are not yet connected in the active best chain
772  CValidationState state;
773  if (!ActivateBestChain(state, chainparams)) {
774  LogPrintf("Failed to connect best block");
775  StartShutdown();
776  }
777 
778  if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
779  LogPrintf("Stopping after block import\n");
780  StartShutdown();
781  }
782 }
783 
788 bool InitSanityCheck(void)
789 {
790  if(!ECC_InitSanityCheck()) {
791  InitError("Elliptic curve cryptography sanity check failure. Aborting.");
792  return false;
793  }
795  return false;
796 
797  return true;
798 }
799 
800 bool AppInitServers(boost::thread_group& threadGroup)
801 {
804  if (!InitHTTPServer())
805  return false;
806  if (!StartRPC())
807  return false;
808  if (!StartHTTPRPC())
809  return false;
810  if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
811  return false;
812  if (!StartHTTPServer())
813  return false;
814  return true;
815 }
816 
817 // Parameter interaction based on rules
819 {
820  // when specifying an explicit binding address, you want to listen on it
821  // even when -connect or -proxy is specified
822  if (mapArgs.count("-bind")) {
823  if (SoftSetBoolArg("-listen", true))
824  LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
825  }
826  if (mapArgs.count("-whitebind")) {
827  if (SoftSetBoolArg("-listen", true))
828  LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
829  }
830 
831  if (GetBoolArg("-masternode", false)) {
832  // masternodes must accept connections from outside
833  if (SoftSetBoolArg("-listen", true))
834  LogPrintf("%s: parameter interaction: -masternode=1 -> setting -listen=1\n", __func__);
835  }
836 
837  if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
838  // when only connecting to trusted nodes, do not seed via DNS, or listen by default
839  if (SoftSetBoolArg("-dnsseed", false))
840  LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
841  if (SoftSetBoolArg("-listen", false))
842  LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
843  }
844 
845  if (mapArgs.count("-proxy")) {
846  // to protect privacy, do not listen by default if a default proxy server is specified
847  if (SoftSetBoolArg("-listen", false))
848  LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
849  // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
850  // to listen locally, so don't rely on this happening through -listen below.
851  if (SoftSetBoolArg("-upnp", false))
852  LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
853  // to protect privacy, do not discover addresses by default
854  if (SoftSetBoolArg("-discover", false))
855  LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
856  }
857 
858  if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
859  // do not map ports or try to retrieve public IP when not listening (pointless)
860  if (SoftSetBoolArg("-upnp", false))
861  LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
862  if (SoftSetBoolArg("-discover", false))
863  LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
864  if (SoftSetBoolArg("-listenonion", false))
865  LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
866  }
867 
868  if (mapArgs.count("-externalip")) {
869  // if an explicit public IP is specified, do not try to find others
870  if (SoftSetBoolArg("-discover", false))
871  LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
872  }
873 
874  if (GetBoolArg("-salvagewallet", false)) {
875  // Rewrite just private keys: rescan to find transactions
876  if (SoftSetBoolArg("-rescan", true))
877  LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
878  }
879 
880  // -zapwallettx implies a rescan
881  if (GetBoolArg("-zapwallettxes", false)) {
882  if (SoftSetBoolArg("-rescan", true))
883  LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
884  }
885 
886  // disable walletbroadcast and whitelistrelay in blocksonly mode
887  if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
888  if (SoftSetBoolArg("-whitelistrelay", false))
889  LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
890 #ifdef ENABLE_WALLET
891  if (SoftSetBoolArg("-walletbroadcast", false))
892  LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
893 #endif
894  }
895 
896  // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
897  if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
898  if (SoftSetBoolArg("-whitelistrelay", true))
899  LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
900  }
901 
902  if(!GetBoolArg("-enableinstantsend", fEnableInstantSend)){
903  if (SoftSetArg("-instantsenddepth", 0))
904  LogPrintf("%s: parameter interaction: -enableinstantsend=false -> setting -nInstantSendDepth=0\n", __func__);
905  }
906 
907  int nLiqProvTmp = GetArg("-liquidityprovider", DEFAULT_PRIVATESEND_LIQUIDITY);
908  if (nLiqProvTmp > 0) {
909  mapArgs["-enableprivatesend"] = "1";
910  LogPrintf("%s: parameter interaction: -liquidityprovider=%d -> setting -enableprivatesend=1\n", __func__, nLiqProvTmp);
911  mapArgs["-privatesendrounds"] = "99999";
912  LogPrintf("%s: parameter interaction: -liquidityprovider=%d -> setting -privatesendrounds=99999\n", __func__, nLiqProvTmp);
913  mapArgs["-privatesendamount"] = "999999";
914  LogPrintf("%s: parameter interaction: -liquidityprovider=%d -> setting -privatesendamount=999999\n", __func__, nLiqProvTmp);
915  mapArgs["-privatesendmultisession"] = "0";
916  LogPrintf("%s: parameter interaction: -liquidityprovider=%d -> setting -privatesendmultisession=0\n", __func__, nLiqProvTmp);
917  }
918 
919  if (mapArgs.count("-hdseed") && IsHex(GetArg("-hdseed", "not hex")) && (mapArgs.count("-mnemonic") || mapArgs.count("-mnemonicpassphrase"))) {
920  mapArgs.erase("-mnemonic");
921  mapArgs.erase("-mnemonicpassphrase");
922  LogPrintf("%s: parameter interaction: can't use -hdseed and -mnemonic/-mnemonicpassphrase together, will prefer -seed\n", __func__);
923  }
924 }
925 
927 {
928  fPrintToConsole = GetBoolArg("-printtoconsole", false);
929  fPrintToDebugLog = GetBoolArg("-printtodebuglog", true) && !fPrintToConsole;
930  fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
931  fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
932  fLogThreadNames = GetBoolArg("-logthreadnames", DEFAULT_LOGTHREADNAMES);
933  fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
934 
935  LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
936  LogPrintf("Dash Core version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
937 }
938 
942 bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
943 {
944  // ********************************************************* Step 1: setup
945 #ifdef _MSC_VER
946  // Turn off Microsoft heap dump noise
947  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
948  _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
949 #endif
950 #if _MSC_VER >= 1400
951  // Disable confusing "helpful" text message on abort, Ctrl-C
952  _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
953 #endif
954 #ifdef WIN32
955  // Enable Data Execution Prevention (DEP)
956  // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
957  // A failure is non-critical and needs no further attention!
958 #ifndef PROCESS_DEP_ENABLE
959  // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
960  // which is not correct. Can be removed, when GCCs winbase.h is fixed!
961 #define PROCESS_DEP_ENABLE 0x00000001
962 #endif
963  typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
964  PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
965  if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
966 #endif
967 
968  if (!SetupNetworking())
969  return InitError("Initializing networking failed");
970 
971 #ifndef WIN32
972  if (GetBoolArg("-sysperms", false)) {
973 #ifdef ENABLE_WALLET
974  if (!GetBoolArg("-disablewallet", false))
975  return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
976 #endif
977  } else {
978  umask(077);
979  }
980 
981  // Clean shutdown on SIGTERM
982  struct sigaction sa;
983  sa.sa_handler = HandleSIGTERM;
984  sigemptyset(&sa.sa_mask);
985  sa.sa_flags = 0;
986  sigaction(SIGTERM, &sa, NULL);
987  sigaction(SIGINT, &sa, NULL);
988 
989  // Reopen debug.log on SIGHUP
990  struct sigaction sa_hup;
991  sa_hup.sa_handler = HandleSIGHUP;
992  sigemptyset(&sa_hup.sa_mask);
993  sa_hup.sa_flags = 0;
994  sigaction(SIGHUP, &sa_hup, NULL);
995 
996  // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
997  signal(SIGPIPE, SIG_IGN);
998 #endif
999 
1000  // ********************************************************* Step 2: parameter interactions
1001  const CChainParams& chainparams = Params();
1002 
1003  // also see: InitParameterInteraction()
1004 
1005  // if using block pruning, then disable txindex
1006  if (GetArg("-prune", 0)) {
1007  if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
1008  return InitError(_("Prune mode is incompatible with -txindex."));
1009 #ifdef ENABLE_WALLET
1010  if (GetBoolArg("-rescan", false)) {
1011  return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
1012  }
1013 #endif
1014  }
1015 
1016  // Make sure enough file descriptors are available
1017  int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
1018  int nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1019  int nMaxConnections = std::max(nUserMaxConnections, 0);
1020 
1021  // Trim requested connection counts, to fit into system limitations
1022  nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
1023  int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
1024  if (nFD < MIN_CORE_FILEDESCRIPTORS)
1025  return InitError(_("Not enough file descriptors available."));
1026  nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS, nMaxConnections);
1027 
1028  if (nMaxConnections < nUserMaxConnections)
1029  InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
1030 
1031  // ********************************************************* Step 3: parameter-to-internal-flags
1032 
1033  fDebug = !mapMultiArgs["-debug"].empty();
1034  // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
1035  const vector<string>& categories = mapMultiArgs["-debug"];
1036  if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
1037  fDebug = false;
1038 
1039  // Check for -debugnet
1040  if (GetBoolArg("-debugnet", false))
1041  InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
1042  // Check for -socks - as this is a privacy risk to continue, exit here
1043  if (mapArgs.count("-socks"))
1044  return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
1045  // Check for -tor - as this is a privacy risk to continue, exit here
1046  if (GetBoolArg("-tor", false))
1047  return InitError(_("Unsupported argument -tor found, use -onion."));
1048 
1049  if (GetBoolArg("-benchmark", false))
1050  InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
1051 
1052  if (GetBoolArg("-whitelistalwaysrelay", false))
1053  InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
1054 
1055  // Checkmempool and checkblockindex default to true in regtest mode
1056  int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
1057  if (ratio != 0) {
1058  mempool.setSanityCheck(1.0 / ratio);
1059  }
1060  fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
1062 
1063  hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
1064  if (!hashAssumeValid.IsNull())
1065  LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
1066  else
1067  LogPrintf("Validating signatures for all blocks.\n");
1068 
1069  // mempool limits
1070  int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1071  int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
1072  if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
1073  return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
1074 
1075  // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
1077  if (nScriptCheckThreads <= 0)
1079  if (nScriptCheckThreads <= 1)
1080  nScriptCheckThreads = 0;
1083 
1084  fServer = GetBoolArg("-server", false);
1085 
1086  // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
1087  int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
1088  if (nSignedPruneTarget < 0) {
1089  return InitError(_("Prune cannot be configured with a negative value."));
1090  }
1091  nPruneTarget = (uint64_t) nSignedPruneTarget;
1092  if (nPruneTarget) {
1094  return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1095  }
1096  LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1097  fPruneMode = true;
1098  }
1099 
1100 #ifdef ENABLE_WALLET
1101  bool fDisableWallet = GetBoolArg("-disablewallet", false);
1102 #endif
1103 
1105  if (nConnectTimeout <= 0)
1107 
1108  // Fee-per-kilobyte amount considered the same as "free"
1109  // If you are mining, be careful setting this:
1110  // if you set it to zero then
1111  // a transaction spammer can cheaply fill blocks using
1112  // 1-satoshi-fee transactions. It should be set above the real
1113  // cost to you of processing a transaction.
1114  if (mapArgs.count("-minrelaytxfee"))
1115  {
1116  CAmount n = 0;
1117  if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
1118  ::minRelayTxFee = CFeeRate(n);
1119  else
1120  return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
1121  }
1122 
1123  fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !Params().RequireStandard());
1124  if (Params().RequireStandard() && !fRequireStandard)
1125  return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1126  nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
1127 
1128 #ifdef ENABLE_WALLET
1129  if (mapArgs.count("-mintxfee"))
1130  {
1131  CAmount n = 0;
1132  if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
1134  else
1135  return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
1136  }
1137  if (mapArgs.count("-fallbackfee"))
1138  {
1139  CAmount nFeePerK = 0;
1140  if (!ParseMoney(mapArgs["-fallbackfee"], nFeePerK))
1141  return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), mapArgs["-fallbackfee"]));
1142  if (nFeePerK > nHighTransactionFeeWarning)
1143  InitWarning(_("-fallbackfee is set very high! This is the transaction fee you may pay when fee estimates are not available."));
1144  CWallet::fallbackFee = CFeeRate(nFeePerK);
1145  }
1146  if (mapArgs.count("-paytxfee"))
1147  {
1148  CAmount nFeePerK = 0;
1149  if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
1150  return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
1151  if (nFeePerK > nHighTransactionFeeWarning)
1152  InitWarning(_("-paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
1153  payTxFee = CFeeRate(nFeePerK, 1000);
1154  if (payTxFee < ::minRelayTxFee)
1155  {
1156  return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
1157  mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
1158  }
1159  }
1160  if (mapArgs.count("-maxtxfee"))
1161  {
1162  CAmount nMaxFee = 0;
1163  if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
1164  return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maxtxfee"]));
1165  if (nMaxFee > nHighTransactionMaxFeeWarning)
1166  InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
1167  maxTxFee = nMaxFee;
1168  if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
1169  {
1170  return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
1171  mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
1172  }
1173  }
1174  nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
1177 
1178  std::string strWalletFile = GetArg("-wallet", "wallet.dat");
1179 #endif // ENABLE_WALLET
1180 
1181  fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1183  nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1184 
1185  fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
1186 
1187  // Option to startup with mocktime set (used for regression testing):
1188  SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1189 
1190  ServiceFlags nLocalServices = NODE_NETWORK;
1191  ServiceFlags nRelevantServices = NODE_NETWORK;
1192 
1193  if (GetBoolArg("-peerbloomfilters", true))
1194  nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1195 
1196  fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1197  if ((!fEnableReplacement) && mapArgs.count("-mempoolreplacement")) {
1198  // Minimal effort at forwards compatibility
1199  std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
1200  std::vector<std::string> vstrReplacementModes;
1201  boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1202  fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1203  }
1204 
1205  // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log, seed insecure_rand()
1206 
1207  // Initialize fast PRNG
1208  seed_insecure_rand(false);
1209 
1210  // Initialize elliptic curve code
1211  ECC_Start();
1212  globalVerifyHandle.reset(new ECCVerifyHandle());
1213 
1214  // Sanity check
1215  if (!InitSanityCheck())
1216  return InitError(_("Initialization sanity check failed. Dash Core is shutting down."));
1217 
1218  std::string strDataDir = GetDataDir().string();
1219 #ifdef ENABLE_WALLET
1220  // Wallet file must be a plain filename without a directory
1221  if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
1222  return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
1223 #endif
1224  // Make sure only a single Dash Core process is using the data directory.
1225  boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
1226  FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
1227  if (file) fclose(file);
1228 
1229  try {
1230  static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1231  // Wait maximum 10 seconds if an old wallet is still running. Avoids lockup during restart
1232  if (!lock.timed_lock(boost::get_system_time() + boost::posix_time::seconds(10)))
1233  return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Dash Core is probably already running."), strDataDir));
1234  } catch(const boost::interprocess::interprocess_exception& e) {
1235  return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Dash Core is probably already running.") + " %s.", strDataDir, e.what()));
1236  }
1237 
1238 #ifndef WIN32
1239  CreatePidFile(GetPidFile(), getpid());
1240 #endif
1241  if (GetBoolArg("-shrinkdebugfile", !fDebug)) {
1242  // Do this first since it both loads a bunch of debug.log into memory,
1243  // and because this needs to happen before any other debug.log printing
1244  ShrinkDebugFile();
1245  }
1246 
1247  if (fPrintToDebugLog)
1248  OpenDebugLog();
1249 
1250 #ifdef ENABLE_WALLET
1251  LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
1252 #endif
1253  if (!fLogTimestamps)
1254  LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1255  LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1256  LogPrintf("Using data directory %s\n", strDataDir);
1257  LogPrintf("Using config file %s\n", GetConfigFile().string());
1258  LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
1259  std::ostringstream strErrors;
1260 
1261  LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1262  if (nScriptCheckThreads) {
1263  for (int i=0; i<nScriptCheckThreads-1; i++)
1264  threadGroup.create_thread(&ThreadScriptCheck);
1265  }
1266 
1267  if (mapArgs.count("-sporkkey")) // spork priv key
1268  {
1269  if (!sporkManager.SetPrivKey(GetArg("-sporkkey", "")))
1270  return InitError(_("Unable to sign spork message, wrong key?"));
1271  }
1272 
1273  // Start the lightweight task scheduler thread
1274  CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1275  threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1276 
1277  /* Start the RPC server already. It will be started in "warmup" mode
1278  * and not really process calls already (but it will signify connections
1279  * that the server is there and will be ready later). Warmup mode will
1280  * be disabled when initialisation is finished.
1281  */
1282  if (fServer)
1283  {
1285  if (!AppInitServers(threadGroup))
1286  return InitError(_("Unable to start HTTP server. See debug log for details."));
1287  }
1288 
1289  int64_t nStart;
1290 
1291  // ********************************************************* Step 5: Backup wallet and verify wallet database integrity
1292 #ifdef ENABLE_WALLET
1293  if (!fDisableWallet) {
1294  std::string strWarning;
1295  std::string strError;
1296 
1297  nWalletBackups = GetArg("-createwalletbackups", 10);
1298  nWalletBackups = std::max(0, std::min(10, nWalletBackups));
1299 
1300  if(!AutoBackupWallet(NULL, strWalletFile, strWarning, strError)) {
1301  if (!strWarning.empty())
1302  InitWarning(strWarning);
1303  if (!strError.empty())
1304  return InitError(strError);
1305  }
1306 
1307  LogPrintf("Using wallet %s\n", strWalletFile);
1308  uiInterface.InitMessage(_("Verifying wallet..."));
1309 
1310  // reset warning string
1311  strWarning = "";
1312 
1313  if (!CWallet::Verify(strWalletFile, strWarning, strError))
1314  return false;
1315 
1316  if (!strWarning.empty())
1317  InitWarning(strWarning);
1318  if (!strError.empty())
1319  return InitError(strError);
1320 
1321 
1322  // Initialize KeePass Integration
1323  keePassInt.init();
1324 
1325  } // (!fDisableWallet)
1326 #endif // ENABLE_WALLET
1327  // ********************************************************* Step 6: network initialization
1328  // Note that we absolutely cannot open any actual connections
1329  // until the very end ("start node") as the UTXO/block state
1330  // is not yet setup and may end up being set up twice if we
1331  // need to reindex later.
1332 
1333  assert(!g_connman);
1334  g_connman = std::unique_ptr<CConnman>(new CConnman());
1335  CConnman& connman = *g_connman;
1336 
1337  peerLogic.reset(new PeerLogicValidation(&connman));
1340 
1341  // sanitize comments per BIP-0014, format user agent and check total size
1342  std::vector<string> uacomments;
1343  BOOST_FOREACH(string cmt, mapMultiArgs["-uacomment"])
1344  {
1345  if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1346  return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1347  uacomments.push_back(SanitizeString(cmt, SAFE_CHARS_UA_COMMENT));
1348  }
1350  if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1351  return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1353  }
1354 
1355  if (mapArgs.count("-onlynet")) {
1356  std::set<enum Network> nets;
1357  BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) {
1358  enum Network net = ParseNetwork(snet);
1359  if (net == NET_UNROUTABLE)
1360  return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1361  nets.insert(net);
1362  }
1363  for (int n = 0; n < NET_MAX; n++) {
1364  enum Network net = (enum Network)n;
1365  if (!nets.count(net))
1366  SetLimited(net);
1367  }
1368  }
1369 
1370  if (mapArgs.count("-whitelist")) {
1371  BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
1372  CSubNet subnet;
1373  LookupSubNet(net.c_str(), subnet);
1374  if (!subnet.IsValid())
1375  return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1376  connman.AddWhitelistedRange(subnet);
1377  }
1378  }
1379 
1380  bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1381  // -proxy sets a proxy for all outgoing network traffic
1382  // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1383  std::string proxyArg = GetArg("-proxy", "");
1385  if (proxyArg != "" && proxyArg != "0") {
1386  CService resolved(LookupNumeric(proxyArg.c_str(), 9050));
1387  proxyType addrProxy = proxyType(resolved, proxyRandomize);
1388  if (!addrProxy.IsValid())
1389  return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
1390 
1391  SetProxy(NET_IPV4, addrProxy);
1392  SetProxy(NET_IPV6, addrProxy);
1393  SetProxy(NET_TOR, addrProxy);
1394  SetNameProxy(addrProxy);
1395  SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1396  }
1397 
1398  // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1399  // -noonion (or -onion=0) disables connecting to .onion entirely
1400  // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1401  std::string onionArg = GetArg("-onion", "");
1402  if (onionArg != "") {
1403  if (onionArg == "0") { // Handle -noonion/-onion=0
1404  SetLimited(NET_TOR); // set onions as unreachable
1405  } else {
1406  CService resolved(LookupNumeric(onionArg.c_str(), 9050));
1407  proxyType addrOnion = proxyType(resolved, proxyRandomize);
1408  if (!addrOnion.IsValid())
1409  return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
1410  SetProxy(NET_TOR, addrOnion);
1411  SetLimited(NET_TOR, false);
1412  }
1413  }
1414 
1415  // see Step 2: parameter interactions for more information about these
1416  fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1417  fDiscover = GetBoolArg("-discover", true);
1419  fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1420 
1421  bool fBound = false;
1422  if (fListen) {
1423  if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
1424  BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
1425  CService addrBind;
1426  if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1427  return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
1428  fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1429  }
1430  BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
1431  CService addrBind;
1432  if (!Lookup(strBind.c_str(), addrBind, 0, false))
1433  return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
1434  if (addrBind.GetPort() == 0)
1435  return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1436  fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1437  }
1438  }
1439  else {
1440  struct in_addr inaddr_any;
1441  inaddr_any.s_addr = INADDR_ANY;
1442  fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
1443  fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1444  }
1445  if (!fBound)
1446  return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1447  }
1448 
1449  if (mapArgs.count("-externalip")) {
1450  BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
1451  CService addrLocal;
1452  if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1453  AddLocal(addrLocal, LOCAL_MANUAL);
1454  else
1455  return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
1456  }
1457  }
1458 
1459  BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
1460  connman.AddOneShot(strDest);
1461 
1462 #if ENABLE_ZMQ
1463  pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
1464 
1465  if (pzmqNotificationInterface) {
1466  RegisterValidationInterface(pzmqNotificationInterface);
1467  }
1468 #endif
1469 
1472 
1473  if (mapArgs.count("-maxuploadtarget")) {
1474  connman.SetMaxOutboundTarget(GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024);
1475  }
1476 
1477  // ********************************************************* Step 7: load block chain
1478 
1479  fReindex = GetBoolArg("-reindex", false);
1480  bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
1481 
1482  // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
1483  boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1484  if (!boost::filesystem::exists(blocksDir))
1485  {
1486  boost::filesystem::create_directories(blocksDir);
1487  bool linked = false;
1488  for (unsigned int i = 1; i < 10000; i++) {
1489  boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1490  if (!boost::filesystem::exists(source)) break;
1491  boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
1492  try {
1493  boost::filesystem::create_hard_link(source, dest);
1494  LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
1495  linked = true;
1496  } catch (const boost::filesystem::filesystem_error& e) {
1497  // Note: hardlink creation failing is not a disaster, it just means
1498  // blocks will get re-downloaded from peers.
1499  LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
1500  break;
1501  }
1502  }
1503  if (linked)
1504  {
1505  fReindex = true;
1506  }
1507  }
1508 
1509  // cache size calculations
1510  int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1511  nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1512  nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache
1513  int64_t nBlockTreeDBCache = nTotalCache / 8;
1514  if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", DEFAULT_TXINDEX))
1515  nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
1516  nTotalCache -= nBlockTreeDBCache;
1517  int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1518  nTotalCache -= nCoinDBCache;
1519  nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1520  LogPrintf("Cache configuration:\n");
1521  LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1522  LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1523  LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
1524 
1525  bool fLoaded = false;
1526  while (!fLoaded) {
1527  bool fReset = fReindex;
1528  std::string strLoadError;
1529 
1530  uiInterface.InitMessage(_("Loading block index..."));
1531 
1532  nStart = GetTimeMillis();
1533  do {
1534  try {
1535  UnloadBlockIndex();
1536  delete pcoinsTip;
1537  delete pcoinsdbview;
1538  delete pcoinscatcher;
1539  delete pblocktree;
1540 
1541  pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1542  pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState);
1545 
1546  if (fReindex) {
1547  pblocktree->WriteReindexing(true);
1548  //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1549  if (fPruneMode)
1551  }
1552 
1553  if (!LoadBlockIndex()) {
1554  strLoadError = _("Error loading block database");
1555  break;
1556  }
1557 
1558  // If the loaded chain has a wrong genesis, bail out immediately
1559  // (we're likely using a testnet datadir, or the other way around).
1560  if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1561  return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1562 
1563  // Initialize the block index (no-op if non-empty database was already loaded)
1564  if (!InitBlockIndex(chainparams)) {
1565  strLoadError = _("Error initializing block database");
1566  break;
1567  }
1568 
1569  // Check for changed -txindex state
1570  if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1571  strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
1572  break;
1573  }
1574 
1575  // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1576  // in the past, but is now trying to run unpruned.
1577  if (fHavePruned && !fPruneMode) {
1578  strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1579  break;
1580  }
1581 
1582  uiInterface.InitMessage(_("Verifying blocks..."));
1583  if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1584  LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
1585  MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", DEFAULT_CHECKBLOCKS));
1586  }
1587 
1588  {
1589  LOCK(cs_main);
1590  CBlockIndex* tip = chainActive.Tip();
1591  if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1592  strLoadError = _("The block database contains a block which appears to be from the future. "
1593  "This may be due to your computer's date and time being set incorrectly. "
1594  "Only rebuild the block database if you are sure that your computer's date and time are correct");
1595  break;
1596  }
1597  }
1598 
1599  if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1600  GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1601  strLoadError = _("Corrupted block database detected");
1602  break;
1603  }
1604  } catch (const std::exception& e) {
1605  if (fDebug) LogPrintf("%s\n", e.what());
1606  strLoadError = _("Error opening block database");
1607  break;
1608  }
1609 
1610  fLoaded = true;
1611  } while(false);
1612 
1613  if (!fLoaded) {
1614  // first suggest a reindex
1615  if (!fReset) {
1616  bool fRet = uiInterface.ThreadSafeQuestion(
1617  strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1618  strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1620  if (fRet) {
1621  fReindex = true;
1622  fRequestShutdown = false;
1623  } else {
1624  LogPrintf("Aborted block database rebuild. Exiting.\n");
1625  return false;
1626  }
1627  } else {
1628  return InitError(strLoadError);
1629  }
1630  }
1631  }
1632 
1633  // As LoadBlockIndex can take several minutes, it's possible the user
1634  // requested to kill the GUI during the last operation. If so, exit.
1635  // As the program has not fully started yet, Shutdown() is possibly overkill.
1636  if (fRequestShutdown)
1637  {
1638  LogPrintf("Shutdown requested. Exiting.\n");
1639  return false;
1640  }
1641  LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1642 
1643  boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1644  CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
1645  // Allowed to fail as this file IS missing on first startup.
1646  if (!est_filein.IsNull())
1647  mempool.ReadFeeEstimates(est_filein);
1648  fFeeEstimatesInitialized = true;
1649 
1650  // ********************************************************* Step 8: load wallet
1651 #ifdef ENABLE_WALLET
1652  if (fDisableWallet) {
1653  pwalletMain = NULL;
1654  LogPrintf("Wallet disabled!\n");
1655  } else {
1656 
1657  // needed to restore wallet transaction meta data after -zapwallettxes
1658  std::vector<CWalletTx> vWtx;
1659 
1660  if (GetBoolArg("-zapwallettxes", false)) {
1661  uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
1662 
1663  pwalletMain = new CWallet(strWalletFile);
1664  DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
1665  if (nZapWalletRet != DB_LOAD_OK) {
1666  uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
1667  return false;
1668  }
1669 
1670  delete pwalletMain;
1671  pwalletMain = NULL;
1672  }
1673 
1674  uiInterface.InitMessage(_("Loading wallet..."));
1675 
1676  nStart = GetTimeMillis();
1677  bool fFirstRun = true;
1678  pwalletMain = new CWallet(strWalletFile);
1679  DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
1680  if (nLoadWalletRet != DB_LOAD_OK)
1681  {
1682  if (nLoadWalletRet == DB_CORRUPT)
1683  strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
1684  else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
1685  {
1686  InitWarning(_("Error reading wallet.dat! All keys read correctly, but transaction data"
1687  " or address book entries might be missing or incorrect."));
1688  }
1689  else if (nLoadWalletRet == DB_TOO_NEW)
1690  strErrors << _("Error loading wallet.dat: Wallet requires newer version of Dash Core") << "\n";
1691  else if (nLoadWalletRet == DB_NEED_REWRITE)
1692  {
1693  strErrors << _("Wallet needed to be rewritten: restart Dash Core to complete") << "\n";
1694  LogPrintf("%s", strErrors.str());
1695  return InitError(strErrors.str());
1696  }
1697  else
1698  strErrors << _("Error loading wallet.dat") << "\n";
1699  }
1700 
1701  if (GetBoolArg("-upgradewallet", fFirstRun))
1702  {
1703  int nMaxVersion = GetArg("-upgradewallet", 0);
1704  if (nMaxVersion == 0) // the -upgradewallet without argument case
1705  {
1706  LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
1707  nMaxVersion = CLIENT_VERSION;
1708  pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
1709  }
1710  else
1711  LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
1712  if (nMaxVersion < pwalletMain->GetVersion())
1713  strErrors << _("Cannot downgrade wallet") << "\n";
1714  pwalletMain->SetMaxVersion(nMaxVersion);
1715  }
1716 
1717  if (fFirstRun)
1718  {
1719  // Create new keyUser and set as default key
1721 
1722  if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !pwalletMain->IsHDEnabled()) {
1723  if (GetArg("-mnemonicpassphrase", "").size() > 256)
1724  return InitError(_("Mnemonic passphrase is too long, must be at most 256 characters"));
1725  // generate a new master key
1727 
1728  // ensure this wallet.dat can only be opened by clients supporting HD
1730  }
1731 
1732  CPubKey newDefaultKey;
1733  if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
1734  pwalletMain->SetDefaultKey(newDefaultKey);
1735  if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
1736  strErrors << _("Cannot write default address") << "\n";
1737  }
1738 
1740 
1741  // Try to create wallet backup right after new wallet was created
1742  std::string strBackupWarning;
1743  std::string strBackupError;
1744  if(!AutoBackupWallet(pwalletMain, "", strBackupWarning, strBackupError)) {
1745  if (!strBackupWarning.empty())
1746  InitWarning(strBackupWarning);
1747  if (!strBackupError.empty())
1748  return InitError(strBackupError);
1749  }
1750 
1751  }
1752  else if (mapArgs.count("-usehd")) {
1753  bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
1754  if (pwalletMain->IsHDEnabled() && !useHD)
1755  return InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), strWalletFile));
1756  if (!pwalletMain->IsHDEnabled() && useHD)
1757  return InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), strWalletFile));
1758  }
1759 
1760  // Warn user every time he starts non-encrypted HD wallet
1761  if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !pwalletMain->IsLocked()) {
1762  InitWarning(_("Make sure to encrypt your wallet and delete all non-encrypted backups after you verified that wallet works!"));
1763  }
1764 
1765  LogPrintf("%s", strErrors.str());
1766  LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
1767 
1769 
1770  CBlockIndex *pindexRescan = chainActive.Tip();
1771  if (GetBoolArg("-rescan", false))
1772  pindexRescan = chainActive.Genesis();
1773  else
1774  {
1775  CWalletDB walletdb(strWalletFile);
1776  CBlockLocator locator;
1777  if (walletdb.ReadBestBlock(locator))
1778  pindexRescan = FindForkInGlobalIndex(chainActive, locator);
1779  else
1780  pindexRescan = chainActive.Genesis();
1781  }
1782  if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
1783  {
1784  //We can't rescan beyond non-pruned blocks, stop and throw an error
1785  //this might happen if a user uses a old wallet within a pruned node
1786  // or if he ran -disablewallet for a longer time, then decided to re-enable
1787  if (fPruneMode)
1788  {
1789  CBlockIndex *block = chainActive.Tip();
1790  while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
1791  block = block->pprev;
1792 
1793  if (pindexRescan != block)
1794  return InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
1795  }
1796 
1797  uiInterface.InitMessage(_("Rescanning..."));
1798  LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
1799  nStart = GetTimeMillis();
1800  pwalletMain->ScanForWalletTransactions(pindexRescan, true);
1801  LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
1803  nWalletDBUpdated++;
1804 
1805  // Restore wallet transaction metadata after -zapwallettxes=1
1806  if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
1807  {
1808  CWalletDB walletdb(strWalletFile);
1809 
1810  BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
1811  {
1812  uint256 hash = wtxOld.GetHash();
1813  std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
1814  if (mi != pwalletMain->mapWallet.end())
1815  {
1816  const CWalletTx* copyFrom = &wtxOld;
1817  CWalletTx* copyTo = &mi->second;
1818  copyTo->mapValue = copyFrom->mapValue;
1819  copyTo->vOrderForm = copyFrom->vOrderForm;
1820  copyTo->nTimeReceived = copyFrom->nTimeReceived;
1821  copyTo->nTimeSmart = copyFrom->nTimeSmart;
1822  copyTo->fFromMe = copyFrom->fFromMe;
1823  copyTo->strFromAccount = copyFrom->strFromAccount;
1824  copyTo->nOrderPos = copyFrom->nOrderPos;
1825  copyTo->WriteToDisk(&walletdb);
1826  }
1827  }
1828  }
1829  }
1831  } // (!fDisableWallet)
1832 #else // ENABLE_WALLET
1833  LogPrintf("No wallet support compiled in!\n");
1834 #endif // !ENABLE_WALLET
1835 
1836  // ********************************************************* Step 9: data directory maintenance
1837 
1838  // if pruning, unset the service bit and perform the initial blockstore prune
1839  // after any wallet rescanning has taken place.
1840  if (fPruneMode) {
1841  LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1842  nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1843  if (!fReindex) {
1844  uiInterface.InitMessage(_("Pruning blockstore..."));
1845  PruneAndFlush();
1846  }
1847  }
1848 
1849  // ********************************************************* Step 10: import blocks
1850 
1851  if (mapArgs.count("-blocknotify"))
1853 
1854  std::vector<boost::filesystem::path> vImportFiles;
1855  if (mapArgs.count("-loadblock"))
1856  {
1857  BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
1858  vImportFiles.push_back(strFile);
1859  }
1860  threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1861  if (chainActive.Tip() == NULL) {
1862  LogPrintf("Waiting for genesis block to be imported...\n");
1863  while (!fRequestShutdown && chainActive.Tip() == NULL)
1864  MilliSleep(10);
1865  }
1866 
1867  // ********************************************************* Step 11a: setup PrivateSend
1868  fMasterNode = GetBoolArg("-masternode", false);
1869 
1870  if((fMasterNode || masternodeConfig.getCount() > -1) && fTxIndex == false) {
1871  return InitError("Enabling Masternode support requires turning on transaction indexing."
1872  "Please add txindex=1 to your configuration and start with -reindex");
1873  }
1874 
1875  if(fMasterNode) {
1876  LogPrintf("MASTERNODE:\n");
1877 
1878  if(!GetArg("-masternodeaddr", "").empty()) {
1879  // Hot masternode (either local or remote) should get its address in
1880  // CActiveMasternode::ManageState() automatically and no longer relies on masternodeaddr.
1881  return InitError(_("masternodeaddr option is deprecated. Please use masternode.conf to manage your remote masternodes."));
1882  }
1883 
1884  std::string strMasterNodePrivKey = GetArg("-masternodeprivkey", "");
1885  if(!strMasterNodePrivKey.empty()) {
1887  return InitError(_("Invalid masternodeprivkey. Please see documenation."));
1888 
1889  LogPrintf(" pubKeyMasternode: %s\n", CBitcoinAddress(activeMasternode.pubKeyMasternode.GetID()).ToString());
1890  } else {
1891  return InitError(_("You must specify a masternodeprivkey in the configuration. Please see documentation for help."));
1892  }
1893  }
1894 
1895  LogPrintf("Using masternode config file %s\n", GetMasternodeConfigFile().string());
1896 
1897  if(GetBoolArg("-mnconflock", true) && pwalletMain && (masternodeConfig.getCount() > 0)) {
1899  LogPrintf("Locking Masternodes:\n");
1900  uint256 mnTxHash;
1901  int outputIndex;
1903  mnTxHash.SetHex(mne.getTxHash());
1904  outputIndex = boost::lexical_cast<unsigned int>(mne.getOutputIndex());
1905  COutPoint outpoint = COutPoint(mnTxHash, outputIndex);
1906  // don't lock non-spendable outpoint (i.e. it's already spent or it's not from this wallet at all)
1907  if(pwalletMain->IsMine(CTxIn(outpoint)) != ISMINE_SPENDABLE) {
1908  LogPrintf(" %s %s - IS NOT SPENDABLE, was not locked\n", mne.getTxHash(), mne.getOutputIndex());
1909  continue;
1910  }
1911  pwalletMain->LockCoin(outpoint);
1912  LogPrintf(" %s %s - locked successfully\n", mne.getTxHash(), mne.getOutputIndex());
1913  }
1914  }
1915 
1916 
1917  privateSendClient.nLiquidityProvider = std::min(std::max((int)GetArg("-liquidityprovider", DEFAULT_PRIVATESEND_LIQUIDITY), 0), 100);
1919  // special case for liquidity providers only, normal clients should use default value
1921  }
1922 
1923  privateSendClient.fEnablePrivateSend = GetBoolArg("-enableprivatesend", false);
1925  privateSendClient.nPrivateSendRounds = std::min(std::max((int)GetArg("-privatesendrounds", DEFAULT_PRIVATESEND_ROUNDS), 2), privateSendClient.nLiquidityProvider ? 99999 : 16);
1926  privateSendClient.nPrivateSendAmount = std::min(std::max((int)GetArg("-privatesendamount", DEFAULT_PRIVATESEND_AMOUNT), 2), 999999);
1927 
1928  fEnableInstantSend = GetBoolArg("-enableinstantsend", 1);
1929  nInstantSendDepth = GetArg("-instantsenddepth", DEFAULT_INSTANTSEND_DEPTH);
1930  nInstantSendDepth = std::min(std::max(nInstantSendDepth, 0), 60);
1931 
1932  //lite mode disables all Masternode and Darksend related functionality
1933  fLiteMode = GetBoolArg("-litemode", false);
1934  if(fMasterNode && fLiteMode){
1935  return InitError("You can not start a masternode in litemode");
1936  }
1937 
1938  LogPrintf("fLiteMode %d\n", fLiteMode);
1939  LogPrintf("nInstantSendDepth %d\n", nInstantSendDepth);
1940  LogPrintf("PrivateSend rounds %d\n", privateSendClient.nPrivateSendRounds);
1941  LogPrintf("PrivateSend amount %d\n", privateSendClient.nPrivateSendAmount);
1942 
1944 
1945  // ********************************************************* Step 11b: Load cache data
1946 
1947  // LOAD SERIALIZED DAT FILES INTO DATA CACHES FOR INTERNAL USE
1948 
1949  boost::filesystem::path pathDB = GetDataDir();
1950  std::string strDBName;
1951 
1952  strDBName = "mncache.dat";
1953  uiInterface.InitMessage(_("Loading masternode cache..."));
1954  CFlatDB<CMasternodeMan> flatdb1(strDBName, "magicMasternodeCache");
1955  if(!flatdb1.Load(mnodeman)) {
1956  return InitError(_("Failed to load masternode cache from") + "\n" + (pathDB / strDBName).string());
1957  }
1958 
1959  if(mnodeman.size()) {
1960  strDBName = "mnpayments.dat";
1961  uiInterface.InitMessage(_("Loading masternode payment cache..."));
1962  CFlatDB<CMasternodePayments> flatdb2(strDBName, "magicMasternodePaymentsCache");
1963  if(!flatdb2.Load(mnpayments)) {
1964  return InitError(_("Failed to load masternode payments cache from") + "\n" + (pathDB / strDBName).string());
1965  }
1966 
1967  strDBName = "governance.dat";
1968  uiInterface.InitMessage(_("Loading governance cache..."));
1969  CFlatDB<CGovernanceManager> flatdb3(strDBName, "magicGovernanceCache");
1970  if(!flatdb3.Load(governance)) {
1971  return InitError(_("Failed to load governance cache from") + "\n" + (pathDB / strDBName).string());
1972  }
1974  } else {
1975  uiInterface.InitMessage(_("Masternode cache is empty, skipping payments and governance cache..."));
1976  }
1977 
1978  strDBName = "netfulfilled.dat";
1979  uiInterface.InitMessage(_("Loading fulfilled requests cache..."));
1980  CFlatDB<CNetFulfilledRequestManager> flatdb4(strDBName, "magicFulfilledCache");
1981  if(!flatdb4.Load(netfulfilledman)) {
1982  return InitError(_("Failed to load fulfilled requests cache from") + "\n" + (pathDB / strDBName).string());
1983  }
1984 
1985  // ********************************************************* Step 11c: update block tip in Dash modules
1986 
1987  // force UpdatedBlockTip to initialize nCachedBlockHeight for DS, MN payments and budgets
1988  // but don't call it directly to prevent triggering of other listeners like zmq etc.
1989  // GetMainSignals().UpdatedBlockTip(chainActive.Tip());
1991 
1992  // ********************************************************* Step 11d: start dash-ps-<smth> threads
1993 
1994  threadGroup.create_thread(boost::bind(&ThreadCheckPrivateSend, boost::ref(*g_connman)));
1995  if (fMasterNode)
1996  threadGroup.create_thread(boost::bind(&ThreadCheckPrivateSendServer, boost::ref(*g_connman)));
1997  else
1998  threadGroup.create_thread(boost::bind(&ThreadCheckPrivateSendClient, boost::ref(*g_connman)));
1999 
2000  // ********************************************************* Step 12: start node
2001 
2002  if (!CheckDiskSpace())
2003  return false;
2004 
2005  if (!strErrors.str().empty())
2006  return InitError(strErrors.str());
2007 
2009 
2011  LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
2012  LogPrintf("chainActive.Height() = %d\n", chainActive.Height());
2013 #ifdef ENABLE_WALLET
2014  if (pwalletMain) {
2016  LogPrintf("setExternalKeyPool.size() = %u\n", pwalletMain->KeypoolCountExternalKeys());
2017  LogPrintf("setInternalKeyPool.size() = %u\n", pwalletMain->KeypoolCountInternalKeys());
2018  LogPrintf("mapWallet.size() = %u\n", pwalletMain->mapWallet.size());
2019  LogPrintf("mapAddressBook.size() = %u\n", pwalletMain->mapAddressBook.size());
2020  } else {
2021  LogPrintf("wallet is NULL\n");
2022  }
2023 #endif
2024 
2025  if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
2026  StartTorControl(threadGroup, scheduler);
2027 
2028  Discover(threadGroup);
2029 
2030  // Map ports with UPnP
2031  MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
2032 
2033  std::string strNodeError;
2034  CConnman::Options connOptions;
2035  connOptions.nLocalServices = nLocalServices;
2036  connOptions.nRelevantServices = nRelevantServices;
2037  connOptions.nMaxConnections = nMaxConnections;
2038  connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
2039  connOptions.nMaxFeeler = 1;
2040  connOptions.nBestHeight = chainActive.Height();
2041  connOptions.uiInterface = &uiInterface;
2042  connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
2043  connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
2044 
2045  if (!connman.Start(scheduler, strNodeError, connOptions))
2046  return InitError(strNodeError);
2047 
2048  // Generate coins in the background
2049  GenerateBitcoins(GetBoolArg("-gen", DEFAULT_GENERATE), GetArg("-genproclimit", DEFAULT_GENERATE_THREADS), chainparams, connman);
2050 
2051  // ********************************************************* Step 13: finished
2052 
2054  uiInterface.InitMessage(_("Done loading"));
2055 
2056 #ifdef ENABLE_WALLET
2057  if (pwalletMain) {
2058  // Add wallet transactions that aren't already in a block to mapTransactions
2060 
2061  // Run a thread to flush wallet periodically
2062  threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
2063  }
2064 #endif
2065 
2066  threadGroup.create_thread(boost::bind(&ThreadSendAlert, boost::ref(connman)));
2067 
2068  return !fRequestShutdown;
2069 }
void CleanupBlockRevFiles()
Definition: init.cpp:683
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:547
unsigned int nWalletDBUpdated
Definition: db.cpp:27
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, const CBlock *pblock)
static const int MAX_OUTBOUND_CONNECTIONS
Definition: net.h:63
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Definition: validation.h:68
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Definition: util.cpp:486
static const int DEFAULT_SCRIPTCHECK_THREADS
Definition: validation.h:85
void ECC_Start()
Definition: key.cpp:304
void AppendParamsHelpMessages(std::string &strUsage, bool debugHelp)
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:66
uint256 defaultAssumeValid
Definition: params.h:84
CNodeSignals & GetNodeSignals()
Definition: net.cpp:92
bool SetupNetworking()
Definition: util.cpp:923
CMasternodeMan mnodeman
int nScriptCheckThreads
Definition: validation.cpp:69
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Definition: validation.h:70
bool fPruneMode
Definition: validation.cpp:77
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:70
void OnRPCPreCommand(const CRPCCommand &cmd)
Definition: init.cpp:375
bool AppInit2(boost::thread_group &threadGroup, CScheduler &scheduler)
Definition: init.cpp:942
void SetBestChain(const CBlockLocator &loc)
Definition: wallet.cpp:521
void ThreadSendAlert(CConnman &connman)
Definition: sendalert.cpp:26
std::vector< CMasternodeEntry > & getEntries()
boost::signals2::signal< void(const std::string &message)> InitMessage
Definition: ui_interface.h:83
ServiceFlags
Definition: protocol.h:253
Definition: coins.h:73
static const bool DEFAULT_PERMIT_BAREMULTISIG
Definition: validation.h:120
bool StartHTTPServer()
Definition: httpserver.cpp:453
void UnloadBlockIndex()
std::string NetworkIDString() const
Definition: chainparams.h:75
void RegisterNodeSignals(CNodeSignals &nodeSignals)
void InitLogging()
Initialize the logging infrastructure.
Definition: init.cpp:926
void setSanityCheck(double dFrequency=1.0)
Definition: txmempool.h:459
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:205
void SetBroadcastTransactions(bool broadcast)
Definition: wallet.h:1029
CMasternodeConfig masternodeConfig
void MilliSleep(int64_t n)
Definition: utiltime.cpp:63
CActiveMasternode activeMasternode
static const int DEFAULT_HTTP_SERVER_TIMEOUT
Definition: httpserver.h:16
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:3683
char fFromMe
Definition: wallet.h:286
#define TRY_LOCK(cs, name)
Definition: sync.h:170
const char *const BITCOIN_CONF_FILENAME
Definition: util.cpp:119
static const unsigned int MAX_OP_RETURN_RELAY
Definition: standard.h:30
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: init.cpp:177
static const unsigned int DEFAULT_KEEPASS_HTTP_PORT
Definition: keepass.h:14
bool IsValid() const
Definition: netbase.h:34
void SetRPCWarmupStatus(const std::string &newStatus)
Definition: server.cpp:457
bool fDebug
Definition: util.cpp:124
HelpMessageMode
Definition: init.h:34
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:15
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
Definition: util.cpp:664
static const CAmount nHighTransactionFeeWarning
-paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB ...
Definition: wallet.h:49
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:85
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Definition: policy.h:29
bool IsHDEnabled()
Definition: wallet.cpp:1485
const char *const BITCOIN_PID_FILENAME
Definition: util.cpp:120
bool ShutdownRequested()
Definition: init.cpp:168
void GenerateNewHDChain()
Definition: wallet.cpp:1392
#define strprintf
Definition: tinyformat.h:1011
void OnPreCommand(boost::function< void(const CRPCCommand &)> slot)
Definition: server.cpp:60
static const int DEFAULT_HTTP_WORKQUEUE
Definition: httpserver.h:15
BindFlags
Definition: init.cpp:122
bool fHavePruned
Definition: validation.cpp:76
CCriticalSection cs_wallet
Definition: wallet.h:672
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Definition: util.cpp:470
bool ReadFeeEstimates(CAutoFile &filein)
Definition: txmempool.cpp:916
bool bSpendZeroConfChange
Definition: wallet.cpp:48
void RandAddSeedPerfmon()
Definition: random.cpp:46
static const int DEFAULT_INSTANTSEND_DEPTH
Definition: instantx.h:29
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:55
const std::string & getOutputIndex() const
CService LookupNumeric(const char *pszName, int portDefault)
Definition: netbase.cpp:228
static const bool DEFAULT_ACCEPT_DATACARRIER
Definition: standard.h:16
static const int DEFAULT_GENERATE_THREADS
Definition: miner.h:22
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:81
static const unsigned int MIN_BLOCKS_TO_KEEP
Definition: validation.h:188
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Definition: validation.h:66
boost::filesystem::path GetPidFile()
Definition: util.cpp:657
const std::string CURRENCY_UNIT
Definition: amount.cpp:10
CAmount maxTxFee
Definition: wallet.cpp:46
static const int DEFAULT_PRIVATESEND_AMOUNT
void StartShutdown()
Definition: init.cpp:164
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:75
void SetMockTime(int64_t nMockTimeIn)
Definition: utiltime.cpp:29
bool StartHTTPRPC()
Definition: httprpc.cpp:224
CCriticalSection cs_main
Definition: validation.cpp:62
bool fReindex
Definition: validation.cpp:71
bool fAcceptDatacarrier
bytes (+1 for OP_RETURN, +2 for the pushdata opcodes)
Definition: standard.cpp:19
void StopTorControl()
Definition: torcontrol.cpp:694
void StopREST()
Definition: rest.cpp:624
void SetLimited(enum Network net, bool fLimited)
Definition: net.cpp:245
static const bool DEFAULT_LISTEN
Definition: net.h:67
static const std::string TESTNET
bool Dump(T &objToSave)
mapValue_t mapValue
Definition: wallet.h:281
const CBaseChainParams & BaseParams()
bool IsValid() const
Definition: netaddress.cpp:186
uint256 hashGenesisBlock
Definition: params.h:44
Definition: net.h:108
void InterruptRPC()
Definition: server.cpp:438
int flags
Definition: dash-tx.cpp:326
bool fDiscover
Definition: net.cpp:76
static const unsigned int DEFAULT_LIMITFREERELAY
Definition: validation.h:116
const std::string & getTxHash() const
void UnregisterAllValidationInterfaces()
CWallet * pwalletMain
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyBlockTip
Definition: ui_interface.h:107
bool IsHex(const string &str)
unsigned short GetListenPort()
Definition: net.cpp:100
static const int64_t nMinDbCache
min. -dbcache in (MiB)
Definition: txdb.h:36
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
void Flush(bool shutdown=false)
Flush wallet (bitdb flush)
Definition: wallet.cpp:589
bool BindListenPort(const CService &bindAddr, std::string &strError, bool fWhitelisted=false)
Definition: net.cpp:1964
static const int DEFAULT_PRIVATESEND_LIQUIDITY
void InterruptHTTPRPC()
Definition: httprpc.cpp:238
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:366
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
Definition: util.cpp:675
CClientUIInterface * uiInterface
Definition: net.h:127
DBErrors
Definition: walletdb.h:34
std::string LicenseInfo()
Definition: init.cpp:637
unsigned int nTx
Definition: chain.h:129
void InterruptHTTPServer()
Definition: httpserver.cpp:465
bool IsNull() const
Definition: streams.h:393
uint64_t nPruneTarget
Definition: validation.cpp:84
bool SetNameProxy(const proxyType &addrProxy)
Definition: netbase.cpp:545
void PrepareShutdown()
Definition: init.cpp:210
static const bool DEFAULT_LOGTIMEMICROS
Definition: util.h:50
static const unsigned int DEFAULT_KEYPOOL_SIZE
Definition: wallet.h:45
void RenameThread(const char *name)
Definition: util.cpp:873
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:144
bool IsNull() const
Definition: uint256.h:33
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Definition: ui_interface.h:77
bool fIsBareMultisigStd
Definition: validation.cpp:78
volatile bool fReopenDebugLog
Definition: util.cpp:134
static const bool DEFAULT_STOPAFTERBLOCKIMPORT
Definition: init.cpp:101
std::map< uint256, CWalletTx > mapWallet
Definition: wallet.h:738
static const bool DEFAULT_ADDRESSINDEX
Definition: validation.h:124
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:139
const std::string strWalletFile
Definition: wallet.h:675
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Definition: validation.h:64
std::string HelpMessage(HelpMessageMode mode)
Definition: init.cpp:384
bool StartREST()
Definition: rest.cpp:613
static const bool DEFAULT_LOGTIMESTAMPS
Definition: util.h:52
unsigned int nTimeReceived
Definition: wallet.h:284
bool fEnableInstantSend
Definition: instantx.cpp:26
void MapPort(bool)
Definition: net.cpp:1511
void OnRPCStopped()
Definition: init.cpp:369
unsigned int nReceiveFloodSize
Definition: net.h:129
unsigned short GetPort() const
Definition: netaddress.cpp:495
int RaiseFileDescriptorLimit(int nMinFD)
Definition: util.cpp:734
static CCoinsViewErrorCatcher * pcoinscatcher
Definition: init.cpp:194
boost::signals2::signal< bool(const std::string &message, const std::string &noninteractive_message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeQuestion
Definition: ui_interface.h:80
bool fMasterNode
Definition: util.cpp:108
int64_t CAmount
Definition: amount.h:14
bool SetMinVersion(enum WalletFeature, CWalletDB *pwalletdbIn=NULL, bool fExplicit=false)
signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVe...
Definition: wallet.cpp:527
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:818
static const bool DEFAULT_DISABLE_SAFEMODE
Definition: init.cpp:100
bool LoadBlockIndex()
void SetRPCWarmupFinished()
Definition: server.cpp:463
bool CheckDiskSpace(uint64_t nAdditionalBytes)
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:86
bool fLiteMode
Definition: util.cpp:109
CCoinsViewCache * pcoinsTip
Definition: validation.cpp:187
static CFeeRate minTxFee
Definition: wallet.h:909
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: wallet.cpp:3657
static bool GetKeysFromSecret(const std::string strSecret, CKey &keyRet, CPubKey &pubkeyRet)
Set the private/public key values, returns true if successful.
bool glibc_sanity_test()
bool InitHTTPServer()
Definition: httpserver.cpp:384
static const bool DEFAULT_LOGIPS
Definition: util.h:51
static bool InitWarning(const std::string &str)
Definition: init.cpp:351
bool fCheckpointsEnabled
Definition: validation.cpp:82
const char * source
Definition: rpcconsole.cpp:63
unsigned int nTxConfirmTarget
Definition: wallet.cpp:47
bool fSendFreeTransactions
Definition: wallet.cpp:49
static const int DEFAULT_PRIVATESEND_ROUNDS
bool fRelayTxes
Definition: net.cpp:78
int nWalletBackups
Definition: util.cpp:117
enum Network ParseNetwork(std::string net)
Definition: netbase.cpp:43
static const bool DEFAULT_ALERTS
Definition: validation.h:51
size_t KeypoolCountInternalKeys()
Definition: wallet.cpp:3773
bool GetKeyFromPool(CPubKey &key, bool fInternal)
Definition: wallet.cpp:3903
static CZMQNotificationInterface * CreateWithArguments(const std::map< std::string, std::string > &args)
bool GetBoolArg(const std::string &strArg, bool fDefault)
Definition: util.cpp:455
#define LogPrintf(...)
Definition: util.h:98
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Definition: util.cpp:462
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
CImportingNow()
Definition: init.cpp:665
static const bool DEFAULT_WHITELISTRELAY
Definition: validation.h:53
const std::string DEFAULT_TOR_CONTROL
Definition: torcontrol.cpp:29
void StopHTTPServer()
Definition: httpserver.cpp:480
void serviceQueue()
Definition: scheduler.cpp:30
static boost::scoped_ptr< ECCVerifyHandle > globalVerifyHandle
Definition: init.cpp:195
CMasternodePayments mnpayments
volatile bool fRequestShutdown
Definition: init.cpp:162
CFeeRate minRelayTxFee
Definition: validation.cpp:94
static int LogPrint(const char *category, const char *format)
Definition: util.h:126
#define LOCK(cs)
Definition: sync.h:168
void Interrupt(boost::thread_group &threadGroup)
Definition: init.cpp:197
void ECC_Stop()
Definition: key.cpp:323
int nMaxOutbound
Definition: net.h:124
void UnregisterNodeSignals(CNodeSignals &nodeSignals)
std::string ToString() const
Definition: amount.cpp:30
bool fLogTimeMicros
Definition: util.cpp:131
static const unsigned int DEFAULT_BYTES_PER_SIGOP
Definition: validation.h:121
bool SetMaxVersion(int nVersion)
change which version we&#39;re allowed to upgrade to (note that this does not immediately imply upgrading...
Definition: wallet.cpp:554
#define COPYRIGHT_YEAR
Definition: clientversion.h:29
uint256 uint256S(const char *str)
Definition: uint256.h:140
bool fRestartRequested
Definition: init.cpp:97
bool fServer
Definition: util.cpp:128
CAmount GetFeePerK() const
Definition: amount.h:47
CClientUIInterface uiInterface
Definition: init.cpp:130
void GenerateBitcoins(bool fGenerate, int nThreads, const CChainParams &chainparams, CConnman &connman)
Definition: miner.cpp:524
static CFeeRate fallbackFee
Definition: wallet.h:910
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Definition: validation.h:72
int Height() const
Definition: chain.h:397
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Definition: validation.h:74
unsigned int nTimeSmart
time received by this node
Definition: wallet.h:285
CBlockIndex * Genesis() const
Definition: chain.h:361
CPubKey vchDefaultKey
Definition: wallet.h:750
void Shutdown()
Definition: init.cpp:315
static const CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: wallet.h:62
bool IsLocked(bool fForMixing=false) const
Definition: crypter.h:166
std::string FormatParagraph(const std::string &in, size_t width, size_t indent)
unsigned int nTime
Definition: chain.h:142
static const int64_t nDefaultDbCache
-dbcache default (MiB)
Definition: txdb.h:32
Network
Definition: netaddress.h:19
static const bool DEFAULT_USE_HD_WALLET
if set, all keys will be derived by using BIP39/BIP44
Definition: wallet.h:78
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:282
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
Definition: net.h:79
int nMaxFeeler
Definition: net.h:125
bool ParseMoney(const string &str, CAmount &nRet)
static const unsigned int DEFAULT_BLOCK_MAX_SIZE
Definition: policy.h:18
static const CAmount DEFAULT_LEGACY_TRANSACTION_MINFEE
-mintxfee default
Definition: wallet.h:59
CChain chainActive
Definition: validation.cpp:65
static const bool DEFAULT_SEND_FREE_TRANSACTIONS
Default for -sendfreetransactions.
Definition: wallet.h:68
static const CAmount DEFAULT_LEGACY_FALLBACK_FEE
-fallbackfee default
Definition: wallet.h:51
BIP-0014 subset.
void ThreadScriptCheck()
bool fEnableReplacement
Definition: validation.cpp:86
static const unsigned int DEFAULT_WALLET_DBLOGSIZE
Definition: db.h:23
const std::string CLIENT_NAME
std::string strSubVersion
Definition: net.cpp:83
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:26
static const bool DEFAULT_LOGTHREADNAMES
Definition: util.h:53
bool fTxIndex
Definition: validation.cpp:72
int size()
Return the number of (unique) Masternodes.
std::string FormatMoney(const CAmount &n)
int nConnectTimeout
Definition: netbase.cpp:36
static bool InitError(const std::string &str)
Definition: init.cpp:345
static const bool DEFAULT_PROXYRANDOMIZE
Definition: init.cpp:98
ServiceFlags nLocalServices
Definition: net.h:121
std::string FormatFullVersion()
DBErrors LoadWallet(bool &fFirstRunRet)
Definition: wallet.cpp:3616
void ThreadImport(std::vector< boost::filesystem::path > vImportFiles)
Definition: init.cpp:719
uint256 hashAssumeValid
Definition: validation.cpp:91
version
Definition: setup.py:3
const std::string CLIENT_DATE
static const unsigned int DEFAULT_BLOCK_MIN_SIZE
Definition: policy.h:19
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:640
void HandleSIGTERM(int)
Definition: init.cpp:335
bool Load(T &objToLoad)
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:527
bool fLogTimestamps
Definition: util.cpp:130
static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE
Definition: policy.h:21
void RegisterValidationInterface(CValidationInterface *pwalletIn)
int64_t nOrderPos
Definition: wallet.h:288
void StopHTTPRPC()
Definition: httprpc.cpp:243
int nInstantSendDepth
Definition: instantx.cpp:27
static bool FlushStateToDisk(CValidationState &state, FlushStateMode mode)
CSporkManager sporkManager
Definition: spork.cpp:14
static const CAmount nHighTransactionMaxFeeWarning
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:72
std::string strFromAccount
Definition: wallet.h:287
size_t KeypoolCountExternalKeys()
Definition: wallet.cpp:3767
bool fLogIPs
Definition: util.cpp:133
void seed_insecure_rand(bool fDeterministic)
Definition: random.cpp:123
CPrivateSendClient privateSendClient
bool glibcxx_sanity_test()
bool fCheckBlockIndex
Definition: validation.cpp:81
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp)
bool IsValid() const
Definition: netaddress.cpp:698
static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
Definition: init.cpp:652
void ThreadFlushWalletDB(const string &strFile)
Definition: walletdb.cpp:842
bool fFeeEstimatesInitialized
Definition: init.cpp:96
bool fAlerts
Definition: validation.cpp:85
int ScanForWalletTransactions(CBlockIndex *pindexStart, bool fUpdate=false)
Definition: wallet.cpp:1687
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:122
CTxMemPool mempool
static const bool DEFAULT_GENERATE
Definition: miner.h:21
static const bool DEFAULT_ENABLE_REPLACEMENT
Definition: validation.h:131
void StopRPC()
Definition: server.cpp:445
bool fPrintToConsole
Definition: util.cpp:125
static const bool DEFAULT_TESTSAFEMODE
Definition: validation.h:129
bool fRequireStandard
Definition: validation.cpp:79
isminetype IsMine(const CTxIn &txin) const
Definition: wallet.cpp:1210
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:87
std::string GetWarnings(const std::string &strFor)
void OpenDebugLog()
Definition: util.cpp:226
static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
Definition: net.h:81
static bool Verify(const std::string &walletFile, std::string &warningString, std::string &errorString)
Verify the wallet database and perform salvage if required.
Definition: wallet.cpp:594
const CChainParams & Params()
void SetMinBlocksToWait(int nMinBlocksToWaitIn)
CKeePassIntegrator keePassInt
Definition: keepass.cpp:35
static const char * FEE_ESTIMATES_FILENAME
Definition: init.cpp:129
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:190
int64_t GetTimeMillis()
Definition: utiltime.cpp:34
const uint256 & GetHash() const
Definition: transaction.h:262
static const unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition: net.h:92
bool fPrintToDebugLog
Definition: util.cpp:126
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:137
void InterruptREST()
Definition: rest.cpp:620
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Definition: validation.cpp:172
int64_t GetAdjustedTime()
Definition: timedata.cpp:33
void runCommand(const std::string &strCommand)
Definition: util.cpp:866
static const bool DEFAULT_FLUSHWALLET
Definition: walletdb.h:20
bool fImporting
Definition: validation.cpp:70
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:24
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:200
uint256 GetBlockHash() const
Definition: chain.h:218
void StartTorControl(boost::thread_group &threadGroup, CScheduler &scheduler)
Definition: torcontrol.cpp:669
static const int64_t nMaxDbCache
max. -dbcache in (MiB)
Definition: txdb.h:34
static const bool DEFAULT_TIMESTAMPINDEX
Definition: validation.h:125
std::string FormatSubVersion(const std::string &name, int nClientVersion, const std::vector< std::string > &comments)
bool AppInitServers(boost::thread_group &threadGroup)
Definition: init.cpp:800
void ReacceptWalletTransactions()
Definition: wallet.cpp:1728
CNetFulfilledRequestManager netfulfilledman
std::string GetHex() const
Definition: uint256.cpp:21
unsigned int nSendBufferMaxSize
Definition: net.h:128
std::exception thrown in command handling
Definition: protocol.h:42
bool fListen
Definition: net.cpp:77
bool WriteFeeEstimates(CAutoFile &fileout) const
Definition: txmempool.cpp:900
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:103
void Discover(boost::thread_group &threadGroup)
Definition: net.cpp:2062
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE)
static const unsigned int MAX_SUBVERSION_LENGTH
Definition: net.h:61
bool InitSanityCheck(void)
Definition: init.cpp:788
int nMaxConnections
Definition: net.h:123
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:748
static CDSNotificationInterface * pdsNotificationInterface
Definition: init.cpp:110
static const bool DEFAULT_UPNP
Definition: net.h:72
CBlockIndex * Tip() const
Definition: chain.h:366
std::unique_ptr< PeerLogicValidation > peerLogic
Definition: init.cpp:104
boost::function< void(void)> Function
Definition: scheduler.h:42
CBlockTreeDB * pblocktree
Definition: validation.cpp:188
static const bool DEFAULT_BLOCKSONLY
Definition: net.h:83
bool SetPrivKey(std::string strPrivKey)
Definition: spork.cpp:204
boost::filesystem::path GetMasternodeConfigFile()
Definition: util.cpp:620
static const std::string MAIN
Definition: pubkey.h:37
static const bool DEFAULT_WALLET_PRIVDB
Definition: db.h:24
ServiceFlags nRelevantServices
Definition: net.h:122
void HandleSIGHUP(int)
Definition: init.cpp:340
static const unsigned int DEFAULT_BANSCORE_THRESHOLD
Definition: validation.h:127
bool WriteToDisk(CWalletDB *pwalletdb)
Definition: wallet.cpp:1677
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Definition: util.cpp:441
void InterruptTorControl()
Definition: torcontrol.cpp:686
static const bool DEFAULT_SPENTINDEX
Definition: validation.h:126
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:107
bool StartRPC()
Definition: server.cpp:430
void ThreadCheckPrivateSendClient(CConnman &connman)
bool okSafeMode
Definition: server.h:122
bool fLogThreadNames
Definition: util.cpp:132
int64_t GetTime()
For unit testing.
Definition: utiltime.cpp:20
unsigned int nBytesPerSigOp
Definition: validation.cpp:80
CGovernanceManager governance
Definition: governance.cpp:17
static void InitStandardDenominations()
int GetNumCores()
Definition: util.cpp:948
bool ECC_InitSanityCheck()
Definition: key.cpp:297
void LockCoin(COutPoint &output)
Definition: wallet.cpp:4193
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:24
void OnStopped(boost::function< void()> slot)
Definition: server.cpp:55
void PruneAndFlush()
static const unsigned int DEFAULT_LEGACY_MIN_RELAY_TX_FEE
Definition: validation.h:61
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
Definition: chain.cpp:25
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:201
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:118
map< string, vector< string > > mapMultiArgs
Definition: util.cpp:123
void SetHex(const char *psz)
Definition: uint256.cpp:30
static const bool DEFAULT_RELAYPRIORITY
Definition: validation.h:117
void ThreadCheckPrivateSend(CConnman &connman)
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:113
static const bool DEFAULT_WHITELISTFORCERELAY
Definition: validation.h:55
static const int CLIENT_VERSION
Definition: clientversion.h:54
static const bool DEFAULT_LISTEN_ONION
Definition: torcontrol.h:14
#define PAIRTYPE(t1, t2)
bool WriteReindexing(bool fReindex)
Definition: txdb.cpp:85
UniValue JSONRPCError(int code, const string &message)
Definition: protocol.cpp:57
std::string HelpMessageGroup(const std::string &message)
Definition: util.cpp:482
static const bool DEFAULT_PRIVATESEND_MULTISESSION
static const bool DEFAULT_TXINDEX
Definition: validation.h:123
BlockMap mapBlockIndex
Definition: validation.cpp:64
static const int DEFAULT_HTTP_THREADS
Definition: httpserver.h:14
static const bool DEFAULT_REST_ENABLE
Definition: init.cpp:99
void ThreadCheckPrivateSendServer(CConnman &connman)
bool AutoBackupWallet(CWallet *wallet, std::string strWalletFile, std::string &strBackupWarning, std::string &strBackupError)
Definition: walletdb.cpp:946
unsigned nMaxDatacarrierBytes
Definition: standard.cpp:20
bool fNameLookup
Definition: netbase.cpp:37
string SanitizeString(const string &str, int rule)
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: coins.cpp:52
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:191
size_t nCoinCacheUsage
Definition: validation.cpp:83
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: init.cpp:176
void ShrinkDebugFile()
Definition: util.cpp:799
bool IsLimited(enum Network net)
Definition: net.cpp:253
bool SetDefaultKey(const CPubKey &vchPubKey)
Definition: wallet.cpp:3728
std::string _(const char *psz)
Definition: util.h:84
int nBestHeight
Definition: net.h:126
int atoi(const std::string &str)
static const int MAX_SCRIPTCHECK_THREADS
Definition: validation.h:83
map< string, string > mapArgs
Definition: util.cpp:122
static bool Bind(CConnman &connman, const CService &addr, unsigned int flags)
Definition: init.cpp:357
CConditionVariable cvBlockChange
Definition: validation.cpp:68
boost::filesystem::path GetDefaultDataDir()
Definition: util.cpp:516
static CCoinsViewDB * pcoinsdbview
Definition: init.cpp:193
bool InitBlockIndex(const CChainParams &chainparams)
boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
boost::filesystem::path GetConfigFile()
Definition: util.cpp:611
bool DefaultConsistencyChecks() const
Definition: chainparams.h:64
~CImportingNow()
Definition: init.cpp:670