Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

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-2020 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 <base58.h>
16 #include <chain.h>
17 #include <chainparams.h>
18 #include <checkpoints.h>
19 #include <compat/sanity.h>
20 #include <consensus/validation.h>
21 #include <fs.h>
22 #include <httpserver.h>
23 #include <httprpc.h>
24 #include <key.h>
25 #include <validation.h>
26 #include <miner.h>
27 #include <netbase.h>
28 #include <net.h>
29 #include <net_processing.h>
30 #include <policy/feerate.h>
31 #include <policy/fees.h>
32 #include <policy/policy.h>
33 #include <rpc/server.h>
34 #include <rpc/register.h>
35 #include <rpc/safemode.h>
36 #include <rpc/blockchain.h>
37 #include <script/standard.h>
38 #include <script/sigcache.h>
39 #include <scheduler.h>
40 #include <timedata.h>
41 #include <txdb.h>
42 #include <txmempool.h>
43 #include <torcontrol.h>
44 #include <ui_interface.h>
45 #include <util.h>
46 #include <utilmoneystr.h>
47 #include <validationinterface.h>
48 
51 #include <flat-database.h>
52 #include <governance/governance.h>
57 #include <messagesigner.h>
58 #include <netfulfilledman.h>
60 #include <spork.h>
61 #include <warnings.h>
62 #include <walletinitinterface.h>
63 
64 #include <evo/deterministicmns.h>
65 #include <llmq/quorums_init.h>
66 
67 #include <llmq/quorums_init.h>
68 
69 #include <stdint.h>
70 #include <stdio.h>
71 #include <memory>
72 
73 #include <bls/bls.h>
74 
75 #ifndef WIN32
76 #include <signal.h>
77 #endif
78 
79 #include <boost/algorithm/string/classification.hpp>
80 #include <boost/algorithm/string/replace.hpp>
81 #include <boost/algorithm/string/split.hpp>
82 #include <boost/bind.hpp>
83 #include <boost/interprocess/sync/file_lock.hpp>
84 #include <boost/thread.hpp>
85 #include <openssl/crypto.h>
86 
87 #if ENABLE_ZMQ
89 #endif
90 
92 static const bool DEFAULT_PROXYRANDOMIZE = true;
93 static const bool DEFAULT_REST_ENABLE = false;
94 static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
95 
96 
97 std::unique_ptr<CConnman> g_connman;
98 std::unique_ptr<PeerLogicValidation> peerLogic;
99 
100 #if !(ENABLE_WALLET)
102 public:
103 
104  std::string GetHelpString(bool showDebug) override {return std::string{};}
105  bool ParameterInteraction() override {return true;}
106  void RegisterRPC(CRPCTable &) override {}
107  bool Verify() override {return true;}
108  bool Open() override {return true;}
109  void Start(CScheduler& scheduler) override {}
110  void Flush() override {}
111  void Stop() override {}
112  void Close() override {}
113 
114  // Dash Specific WalletInitInterface InitPrivateSendSettings
115  void AutoLockMasternodeCollaterals() override {}
116  void InitPrivateSendSettings() override {}
117  void InitKeePass() override {}
118  bool InitAutoBackup() override {return true;}
119 };
120 
123 #endif
124 
125 #if ENABLE_ZMQ
126 static CZMQNotificationInterface* pzmqNotificationInterface = nullptr;
127 #endif
128 
130 
131 #ifdef WIN32
132 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
133 // accessing block files don't count towards the fd_set size limit
134 // anyway.
135 #define MIN_CORE_FILEDESCRIPTORS 0
136 #else
137 #define MIN_CORE_FILEDESCRIPTORS 150
138 #endif
139 
140 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
141 
143 //
144 // Shutdown
145 //
146 
147 //
148 // Thread management and startup/shutdown:
149 //
150 // The network-processing threads are all part of a thread group
151 // created by AppInit() or the Qt main() function.
152 //
153 // A clean exit happens when StartShutdown() or the SIGTERM
154 // signal handler sets fRequestShutdown, which makes main thread's
155 // WaitForShutdown() interrupts the thread group.
156 // And then, WaitForShutdown() makes all other on-going threads
157 // in the thread group join the main thread.
158 // Shutdown() is then called to clean up database connections, and stop other
159 // threads that should only be stopped after the main network-processing
160 // threads have exited.
161 //
162 // Shutdown for Qt is very similar, only it uses a QTimer to detect
163 // fRequestShutdown getting set, and then does the normal Qt
164 // shutdown thing.
165 //
166 
167 std::atomic<bool> fRequestShutdown(false);
168 std::atomic<bool> fRequestRestart(false);
169 std::atomic<bool> fDumpMempoolLater(false);
170 
172 {
173  fRequestShutdown = true;
174 }
176 {
178 }
180 {
181  return fRequestShutdown;
182 }
183 
190 {
191 public:
193  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override {
194  try {
195  return CCoinsViewBacked::GetCoin(outpoint, coin);
196  } catch(const std::runtime_error& e) {
197  uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
198  LogPrintf("Error reading from database: %s\n", e.what());
199  // Starting the shutdown sequence and returning false to the caller would be
200  // interpreted as 'entry not found' (as opposed to unable to read data), and
201  // could lead to invalid interpretation. Just exit immediately, as we can't
202  // continue anyway, and all writes should be atomic.
203  abort();
204  }
205  }
206  // Writes do not need similar protection, as failure to write is handled by the caller.
207 };
208 
209 static std::unique_ptr<CCoinsViewErrorCatcher> pcoinscatcher;
210 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
211 
212 static boost::thread_group threadGroup;
214 
215 void Interrupt()
216 {
219  InterruptRPC();
220  InterruptREST();
223  if (g_connman)
224  g_connman->Interrupt();
225 }
226 
229 {
230  LogPrintf("%s: In progress...\n", __func__);
231  static CCriticalSection cs_Shutdown;
232  TRY_LOCK(cs_Shutdown, lockShutdown);
233  if (!lockShutdown)
234  return;
235 
240  RenameThread("dash-shutoff");
242  StopHTTPRPC();
243  StopREST();
244  StopRPC();
245  StopHTTPServer();
247 
248  // fRPCInWarmup should be `false` if we completed the loading sequence
249  // before a shutdown request was received
250  std::string statusmessage;
251  bool fRPCInWarmup = RPCIsInWarmup(&statusmessage);
252 
254  MapPort(false);
255 
256  // Because these depend on each-other, we make sure that neither can be
257  // using the other before destroying them.
259  if (g_connman) g_connman->Stop();
260  // if (g_txindex) g_txindex->Stop(); //TODO watch out when backporting bitcoin#13033 (don't accidently put the reset here, as we've already backported bitcoin#13894)
261 
262  // After everything has been shut down, but before things get flushed, stop the
263  // CScheduler/checkqueue threadGroup
264  threadGroup.interrupt_all();
265  threadGroup.join_all();
266 
267  // After there are no more peers/RPC left to give us new data which may generate
268  // CValidationInterface callbacks, flush them...
270 
271  if (!fRPCInWarmup) {
272  // STORE DATA CACHES INTO SERIALIZED DAT FILES
273  CFlatDB<CMasternodeMetaMan> flatdb1("mncache.dat", "magicMasternodeCache");
274  flatdb1.Dump(mmetaman);
275  CFlatDB<CNetFulfilledRequestManager> flatdb4("netfulfilled.dat", "magicFulfilledCache");
276  flatdb4.Dump(netfulfilledman);
277  CFlatDB<CSporkManager> flatdb6("sporks.dat", "magicSporkCache");
278  flatdb6.Dump(sporkManager);
279  if (!fDisableGovernance) {
280  CFlatDB<CGovernanceManager> flatdb3("governance.dat", "magicGovernanceCache");
281  flatdb3.Dump(governance);
282  }
283  }
284 
285  // After the threads that potentially access these pointers have been stopped,
286  // destruct and reset all to nullptr.
287  peerLogic.reset();
288  g_connman.reset();
289  //g_txindex.reset(); //TODO watch out when backporting bitcoin#13033 (re-enable this, was backported via bitcoin#13894)
290 
291  if (fDumpMempoolLater && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
292  DumpMempool();
293  }
294 
296  {
298  fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
299  CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
300  if (!est_fileout.IsNull())
301  ::feeEstimator.Write(est_fileout);
302  else
303  LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
304  fFeeEstimatesInitialized = false;
305  }
306 
307  // FlushStateToDisk generates a SetBestChain callback, which we should avoid missing
308  if (pcoinsTip != nullptr) {
310  }
311 
312  // Any future callbacks will be dropped. This should absolutely be safe - if
313  // missing a callback results in an unrecoverable situation, unclean shutdown
314  // would too. The only reason to do the above flushes is to let the wallet catch
315  // up with our current chain to avoid any strange pruning edge cases and make
316  // next startup faster by avoiding rescan.
317 
318  {
319  LOCK(cs_main);
320  if (pcoinsTip != nullptr) {
322  }
323  pcoinsTip.reset();
324  pcoinscatcher.reset();
325  pcoinsdbview.reset();
326  pblocktree.reset();
328  deterministicMNManager.reset();
329  evoDb.reset();
330  }
332 
333 #if ENABLE_ZMQ
334  if (pzmqNotificationInterface) {
335  UnregisterValidationInterface(pzmqNotificationInterface);
336  delete pzmqNotificationInterface;
337  pzmqNotificationInterface = nullptr;
338  }
339 #endif
340 
344  pdsNotificationInterface = nullptr;
345  }
346  if (fMasternodeMode) {
348  }
349 
350  // make sure to clean up BLS keys before global destructors are called (they have allocated from the secure memory pool)
353 
354 #ifndef WIN32
355  try {
356  fs::remove(GetPidFile());
357  } catch (const fs::filesystem_error& e) {
358  LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
359  }
360 #endif
364 }
365 
375 void Shutdown()
376 {
377  // Shutdown part 1: prepare shutdown
378  if(!fRequestRestart) {
379  PrepareShutdown();
380  }
381  // Shutdown part 2: Stop TOR thread and delete wallet instance
382  StopTorControl();
384  globalVerifyHandle.reset();
385  ECC_Stop();
386  LogPrintf("%s: done\n", __func__);
387 }
388 
394 #ifndef WIN32
395 static void HandleSIGTERM(int)
396 {
397  fRequestShutdown = true;
398 }
399 
400 static void HandleSIGHUP(int)
401 {
402  fReopenDebugLog = true;
403 }
404 #else
405 static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
406 {
407  fRequestShutdown = true;
408  Sleep(INFINITE);
409  return true;
410 }
411 #endif
412 
413 #ifndef WIN32
414 static void registerSignalHandler(int signal, void(*handler)(int))
415 {
416  struct sigaction sa;
417  sa.sa_handler = handler;
418  sigemptyset(&sa.sa_mask);
419  sa.sa_flags = 0;
420  sigaction(signal, &sa, nullptr);
421 }
422 #endif
423 
425 {
427 }
428 
430 {
432  RPCNotifyBlockChange(false, nullptr);
433  g_best_block_cv.notify_all();
434  LogPrint(BCLog::RPC, "RPC stopped.\n");
435 }
436 
438 {
439  std::string strSupportedModes = "'select'";
440 #ifdef USE_POLL
441  strSupportedModes += ", 'poll'";
442 #endif
443 #ifdef USE_EPOLL
444  strSupportedModes += ", 'epoll'";
445 #endif
446  return strSupportedModes;
447 }
448 
449 std::string HelpMessage(HelpMessageMode mode)
450 {
451  const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
452  const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
453  const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
454  const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET);
455  const bool showDebug = gArgs.GetBoolArg("-help-debug", false);
456 
457  // When adding new options to the categories, please keep and ensure alphabetical ordering.
458  // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
459  std::string strUsage = HelpMessageGroup(_("Options:"));
460  strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
461  strUsage += HelpMessageOpt("-version", _("Print version and exit"));
462  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)"));
463  strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
464  if (showDebug)
465  strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
466  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)"), defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()));
467  strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file. Relative paths will be prefixed by datadir location. (default: %s)"), BITCOIN_CONF_FILENAME));
468  if (mode == HMM_BITCOIND)
469  {
470 #if HAVE_DECL_DAEMON
471  strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
472 #endif
473  }
474  strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
475  if (showDebug) {
476  strUsage += HelpMessageOpt("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize));
477  }
478  strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
479  strUsage += HelpMessageOpt("-debuglogfile=<file>", strprintf(_("Specify location of debug log file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)"), DEFAULT_DEBUGLOGFILE));
480  strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
481  strUsage += HelpMessageOpt("-maxorphantxsize=<n>", strprintf(_("Maximum total size of all orphan transactions in megabytes (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS_SIZE));
482  strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
483  strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
484  if (showDebug) {
485  strUsage += HelpMessageOpt("-minimumchainwork=<hex>", strprintf("Minimum work assumed to exist on a valid chain in hex (default: %s, testnet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()));
486  }
487  strUsage += HelpMessageOpt("-persistmempool", strprintf(_("Whether to save the mempool on shutdown and load on restart (default: %u)"), DEFAULT_PERSIST_MEMPOOL));
488  strUsage += HelpMessageOpt("-syncmempool", strprintf(_("Sync mempool from other nodes on start (default: %u)"), DEFAULT_SYNC_MEMPOOL));
489  strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
490  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)"),
492 #ifndef WIN32
493  strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)"), BITCOIN_PID_FILENAME));
494 #endif
495  strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex, -rescan and -disablegovernance=false. "
496  "Warning: Reverting this setting requires re-downloading the entire blockchain. "
497  "(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >%u = automatically prune block files to stay under the specified target size in MiB)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
498  strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
499  strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
500 #ifndef WIN32
501  strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
502 #endif
503  strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
504 
505  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));
506  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));
507  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));
508 
509  strUsage += HelpMessageGroup(_("Connection options:"));
510  strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open (see the `addnode` RPC command help for more info)"));
511  strUsage += HelpMessageOpt("-allowprivatenet", strprintf(_("Allow RFC1918 addresses to be relayed and connected to (default: %u)"), DEFAULT_ALLOWPRIVATENET));
512  strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
513  strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
514  strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
515  strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -connect=0 disables automatic connections (the rules for this peer are the same as for -addnode)"));
516  strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
517  strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
518  strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)"));
519  strUsage += HelpMessageOpt("-enablebip61", strprintf(_("Send reject messages per BIP61 (default: %u)"), DEFAULT_ENABLE_BIP61));
520  strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
521  strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
522  strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
523  strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
524  strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (temporary service connections excluded) (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
525  strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
526  strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
527  strUsage += HelpMessageOpt("-maxtimeadjustment", strprintf(_("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)"), DEFAULT_MAX_TIME_ADJUSTMENT));
528  strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
529  strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
530  strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
531  strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
532  strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort()));
533  strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
534  strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
535  strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
536  strUsage += HelpMessageOpt("-socketevents=<mode>", strprintf(_("Socket events mode, which must be one of: %s (default: %s)"), GetSupportedSocketEventsStr(), DEFAULT_SOCKETEVENTS));
537  strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
538  strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
539  strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
540 #ifdef USE_UPNP
541 #if USE_UPNP
542  strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
543 #else
544  strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
545 #endif
546 #endif
547  strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
548  strUsage += HelpMessageOpt("-whitelist=<IP address or network>", _("Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR notated network (e.g. 1.2.3.0/24). Can be specified multiple times.") +
549  " " + _("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"));
550  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));
551 
552  strUsage += g_wallet_init_interface->GetHelpString(showDebug);
553  if (mode == HMM_BITCOIN_QT)
554  strUsage += HelpMessageOpt("-windowtitle=<name>", _("Sets a window title which is appended to \"Dash Core - \""));
555 
556 #if ENABLE_ZMQ
557  strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
558  strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
559  strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
560  strUsage += HelpMessageOpt("-zmqpubhashtxlock=<address>", _("Enable publish hash transaction (locked via InstantSend) in <address>"));
561  strUsage += HelpMessageOpt("-zmqpubhashgovernancevote=<address>", _("Enable publish hash of governance votes in <address>"));
562  strUsage += HelpMessageOpt("-zmqpubhashgovernanceobject=<address>", _("Enable publish hash of governance objects (like proposals) in <address>"));
563  strUsage += HelpMessageOpt("-zmqpubhashinstantsenddoublespend=<address>", _("Enable publish transaction hashes of attempted InstantSend double spend in <address>"));
564  strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
565  strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
566  strUsage += HelpMessageOpt("-zmqpubrawtxlock=<address>", _("Enable publish raw transaction (locked via InstantSend) in <address>"));
567  strUsage += HelpMessageOpt("-zmqpubrawinstantsenddoublespend=<address>", _("Enable publish raw transactions of attempted InstantSend double spend in <address>"));
568 #endif
569 
570  strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
571  strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
572  if (showDebug)
573  {
574  strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
575  strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
576  strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
577  strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
578  strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
579  strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
580  strUsage += HelpMessageOpt("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used");
581  strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
582  strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
583  strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
584  strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
585  strUsage += HelpMessageOpt("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT));
586 
587  strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
588  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));
589  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));
590  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));
591  strUsage += HelpMessageOpt("-vbparams=<deployment>:<start>:<end>(:<window>:<threshold>)", "Use given start/end times for specified version bits deployment (regtest-only). Specifying window and threshold is optional.");
592  strUsage += HelpMessageOpt("-watchquorums=<n>", strprintf("Watch and validate quorum communication (default: %u)", llmq::DEFAULT_WATCH_QUORUMS));
593  strUsage += HelpMessageOpt("-addrmantest", "Allows to test address relay on localhost");
594  }
595  strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
596  _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + ListLogCategories() + ".");
597  strUsage += HelpMessageOpt("-debugexclude=<category>", strprintf(_("Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except one or more specified categories.")));
598  strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
599  strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
600  strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
601  if (showDebug)
602  {
603  strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
604  strUsage += HelpMessageOpt("-logthreadnames", strprintf("Add thread names to debug messages (default: %u)", DEFAULT_LOGTHREADNAMES));
605  strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
606  strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
607  strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
608  }
609  strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)"),
611  strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
612  strUsage += HelpMessageOpt("-printtodebuglog", strprintf(_("Send trace/debug info to debug.log file (default: %u)"), 1));
613  if (showDebug)
614  {
615  strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
616  }
617  strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
618  AppendParamsHelpMessages(strUsage, showDebug);
619  strUsage += HelpMessageOpt("-disablegovernance", strprintf(_("Disable governance validation (0-1, default: %u)"), 0));
620  strUsage += HelpMessageOpt("-sporkaddr=<dashaddress>", strprintf(_("Override spork address. Only useful for regtest and devnet. Using this on mainnet or testnet will ban you.")));
621  strUsage += HelpMessageOpt("-minsporkkeys=<n>", strprintf(_("Overrides minimum spork signers to change spork value. Only useful for regtest and devnet. Using this on mainnet or testnet will ban you.")));
622 
623  strUsage += HelpMessageGroup(_("Masternode options:"));
624  strUsage += HelpMessageOpt("-masternodeblsprivkey=<hex>", _("Set the masternode BLS private key and enable the client to act as a masternode"));
625 
626  strUsage += HelpMessageGroup(_("InstantSend options:"));
627  strUsage += HelpMessageOpt("-instantsendnotify=<cmd>", _("Execute command when a wallet InstantSend transaction is successfully locked (%s in cmd is replaced by TxID)"));
628 
629 
630  strUsage += HelpMessageGroup(_("Node relay options:"));
631  if (showDebug) {
632  strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()));
633  strUsage += HelpMessageOpt("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)));
634  strUsage += HelpMessageOpt("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to defined dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)));
635  }
636  strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Minimum bytes per sigop in transactions we relay and mine (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
637  strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
638  strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
639  strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
641  strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
642  strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
643 
644  strUsage += HelpMessageGroup(_("Block creation options:"));
645  strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
646  strUsage += HelpMessageOpt("-blockmintxfee=<amt>", strprintf(_("Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)"), CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)));
647  if (showDebug)
648  strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
649 
650  strUsage += HelpMessageGroup(_("RPC server options:"));
651  strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
652  strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
653  strUsage += HelpMessageOpt("-rpcbind=<addr>[:port]", _("Bind to given address to listen for JSON-RPC connections. This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost, or if -rpcallowip has been specified, 0.0.0.0 and :: i.e., all addresses)"));
654  strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)"));
655  strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
656  strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
657  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. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times"));
658  strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
659  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"));
660  strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
661  if (showDebug) {
662  strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
663  strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
664  }
665 
666  return strUsage;
667 }
668 
669 std::string LicenseInfo()
670 {
671  const std::string URL_SOURCE_CODE = "<https://github.com/dashpay/dash>";
672  const std::string URL_WEBSITE = "<https://dash.org>";
673 
674  return CopyrightHolders(_("Copyright (C)"), 2014, COPYRIGHT_YEAR) + "\n" +
675  "\n" +
676  strprintf(_("Please contribute if you find %s useful. "
677  "Visit %s for further information about the software."),
678  PACKAGE_NAME, URL_WEBSITE) +
679  "\n" +
680  strprintf(_("The source code is available from %s."),
681  URL_SOURCE_CODE) +
682  "\n" +
683  "\n" +
684  _("This is experimental software.") + "\n" +
685  strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
686  "\n" +
687  strprintf(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard."), "<https://www.openssl.org>") +
688  "\n";
689 }
690 
691 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
692 {
693  if (initialSync || !pBlockIndex)
694  return;
695 
696  std::string strCmd = gArgs.GetArg("-blocknotify", "");
697  if (!strCmd.empty()) {
698  boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
699  boost::thread t(runCommand, strCmd); // thread runs free
700  }
701 }
702 
703 static bool fHaveGenesis = false;
706 
707 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
708 {
709  if (pBlockIndex != nullptr) {
710  {
711  WaitableLock lock_GenesisWait(cs_GenesisWait);
712  fHaveGenesis = true;
713  }
714  condvar_GenesisWait.notify_all();
715  }
716 }
717 
719 {
721  assert(fImporting == false);
722  fImporting = true;
723  }
724 
726  assert(fImporting == true);
727  fImporting = false;
728  }
729 };
730 
731 
732 // If we're using -prune with -reindex, then delete block files that will be ignored by the
733 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
734 // is missing, do the same here to delete any later block files after a gap. Also delete all
735 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
736 // is in sync with what's actually on disk by the time we start downloading, so that pruning
737 // works correctly.
739 {
740  std::map<std::string, fs::path> mapBlockFiles;
741 
742  // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
743  // Remove the rev files immediately and insert the blk file paths into an
744  // ordered map keyed by block file index.
745  LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
746  fs::path blocksdir = GetDataDir() / "blocks";
747  for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
748  if (fs::is_regular_file(*it) &&
749  it->path().filename().string().length() == 12 &&
750  it->path().filename().string().substr(8,4) == ".dat")
751  {
752  if (it->path().filename().string().substr(0,3) == "blk")
753  mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
754  else if (it->path().filename().string().substr(0,3) == "rev")
755  remove(it->path());
756  }
757  }
758 
759  // Remove all block files that aren't part of a contiguous set starting at
760  // zero by walking the ordered map (keys are block file indices) by
761  // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
762  // start removing block files.
763  int nContigCounter = 0;
764  for (const std::pair<std::string, fs::path>& item : mapBlockFiles) {
765  if (atoi(item.first) == nContigCounter) {
766  nContigCounter++;
767  continue;
768  }
769  remove(item.second);
770  }
771 }
772 
773 void ThreadImport(std::vector<fs::path> vImportFiles)
774 {
775  const CChainParams& chainparams = Params();
776  RenameThread("dash-loadblk");
777 
778  {
779  CImportingNow imp;
780 
781  // -reindex
782  if (fReindex) {
783  int nFile = 0;
784  while (true) {
785  CDiskBlockPos pos(nFile, 0);
786  if (!fs::exists(GetBlockPosFilename(pos, "blk")))
787  break; // No block files left to reindex
788  FILE *file = OpenBlockFile(pos, true);
789  if (!file)
790  break; // This error is logged in OpenBlockFile
791  LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
792  LoadExternalBlockFile(chainparams, file, &pos);
793  nFile++;
794  }
795  pblocktree->WriteReindexing(false);
796  fReindex = false;
797  LogPrintf("Reindexing finished\n");
798  // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
799  LoadGenesisBlock(chainparams);
800  }
801 
802  // hardcoded $DATADIR/bootstrap.dat
803  fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
804  if (fs::exists(pathBootstrap)) {
805  FILE *file = fsbridge::fopen(pathBootstrap, "rb");
806  if (file) {
807  fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
808  LogPrintf("Importing bootstrap.dat...\n");
809  LoadExternalBlockFile(chainparams, file);
810  RenameOver(pathBootstrap, pathBootstrapOld);
811  } else {
812  LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
813  }
814  }
815 
816  // -loadblock=
817  for (const fs::path& path : vImportFiles) {
818  FILE *file = fsbridge::fopen(path, "rb");
819  if (file) {
820  LogPrintf("Importing blocks file %s...\n", path.string());
821  LoadExternalBlockFile(chainparams, file);
822  } else {
823  LogPrintf("Warning: Could not open blocks file %s\n", path.string());
824  }
825  }
826 
827  // scan for better chains in the block chain database, that are not yet connected in the active best chain
828  CValidationState state;
829  if (!ActivateBestChain(state, chainparams)) {
830  LogPrintf("Failed to connect best block (%s)\n", FormatStateMessage(state));
831  StartShutdown();
832  return;
833  }
834 
835  if (gArgs.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
836  LogPrintf("Stopping after block import\n");
837  StartShutdown();
838  return;
839  }
840  } // End scope of CImportingNow
841 
842  // force UpdatedBlockTip to initialize nCachedBlockHeight for DS, MN payments and budgets
843  // but don't call it directly to prevent triggering of other listeners like zmq etc.
844  // GetMainSignals().UpdatedBlockTip(chainActive.Tip());
846 
847  {
848  // Get all UTXOs for each MN collateral in one go so that we can fill coin cache early
849  // and reduce further locking overhead for cs_main in other parts of code inclluding GUI
850  LogPrintf("Filling coin cache with masternode UTXOs...\n");
851  LOCK(cs_main);
852  int64_t nStart = GetTimeMillis();
853  auto mnList = deterministicMNManager->GetListAtChainTip();
854  mnList.ForEachMN(false, [&](const CDeterministicMNCPtr& dmn) {
855  Coin coin;
856  GetUTXOCoin(dmn->collateralOutpoint, coin);
857  });
858  LogPrintf("Filling coin cache with masternode UTXOs: done in %dms\n", GetTimeMillis() - nStart);
859  }
860 
861  if (fMasternodeMode) {
862  assert(activeMasternodeManager);
863  const CBlockIndex* pindexTip;
864  {
865  LOCK(cs_main);
866  pindexTip = chainActive.Tip();
867  }
868  activeMasternodeManager->Init(pindexTip);
869  }
870 
872 
873  if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
874  LoadMempool();
876  }
877 }
878 
883 bool InitSanityCheck(void)
884 {
885  if(!ECC_InitSanityCheck()) {
886  InitError("Elliptic curve cryptography sanity check failure. Aborting.");
887  return false;
888  }
889 
891  return false;
892 
893  if (!BLSInit()) {
894  return false;
895  }
896 
897  if (!Random_SanityCheck()) {
898  InitError("OS cryptographic RNG sanity check failure. Aborting.");
899  return false;
900  }
901 
902  return true;
903 }
904 
906 {
909  if (!InitHTTPServer())
910  return false;
911  if (!StartRPC())
912  return false;
913  if (!StartHTTPRPC())
914  return false;
915  if (gArgs.GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
916  return false;
917  if (!StartHTTPServer())
918  return false;
919  return true;
920 }
921 
922 // Parameter interaction based on rules
924 {
925  // when specifying an explicit binding address, you want to listen on it
926  // even when -connect or -proxy is specified
927  if (gArgs.IsArgSet("-bind")) {
928  if (gArgs.SoftSetBoolArg("-listen", true))
929  LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
930  }
931  if (gArgs.IsArgSet("-whitebind")) {
932  if (gArgs.SoftSetBoolArg("-listen", true))
933  LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
934  }
935 
936  if (gArgs.IsArgSet("-connect")) {
937  // when only connecting to trusted nodes, do not seed via DNS, or listen by default
938  if (gArgs.SoftSetBoolArg("-dnsseed", false))
939  LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
940  if (gArgs.SoftSetBoolArg("-listen", false))
941  LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
942  }
943 
944  if (gArgs.IsArgSet("-proxy")) {
945  // to protect privacy, do not listen by default if a default proxy server is specified
946  if (gArgs.SoftSetBoolArg("-listen", false))
947  LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
948  // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
949  // to listen locally, so don't rely on this happening through -listen below.
950  if (gArgs.SoftSetBoolArg("-upnp", false))
951  LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
952  // to protect privacy, do not discover addresses by default
953  if (gArgs.SoftSetBoolArg("-discover", false))
954  LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
955  }
956 
957  if (!gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
958  // do not map ports or try to retrieve public IP when not listening (pointless)
959  if (gArgs.SoftSetBoolArg("-upnp", false))
960  LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
961  if (gArgs.SoftSetBoolArg("-discover", false))
962  LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
963  if (gArgs.SoftSetBoolArg("-listenonion", false))
964  LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
965  }
966 
967  if (gArgs.IsArgSet("-externalip")) {
968  // if an explicit public IP is specified, do not try to find others
969  if (gArgs.SoftSetBoolArg("-discover", false))
970  LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
971  }
972 
973  // disable whitelistrelay in blocksonly mode
974  if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
975  if (gArgs.SoftSetBoolArg("-whitelistrelay", false))
976  LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
977  }
978 
979  // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
980  if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
981  if (gArgs.SoftSetBoolArg("-whitelistrelay", true))
982  LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
983  }
984 
985  if (gArgs.GetBoolArg("-litemode", false)) {
986  if (gArgs.SoftSetBoolArg("-disablegovernance", true)) {
987  LogPrintf("%s: parameter interaction: -litemode=true -> setting -disablegovernance=true\n", __func__);
988  }
989  }
990 
991  int64_t nPruneArg = gArgs.GetArg("-prune", 0);
992  if (nPruneArg > 0) {
993  if (gArgs.SoftSetBoolArg("-disablegovernance", true)) {
994  LogPrintf("%s: parameter interaction: -prune=%d -> setting -disablegovernance=true\n", __func__, nPruneArg);
995  }
996  if (gArgs.SoftSetBoolArg("-txindex", false)) {
997  LogPrintf("%s: parameter interaction: -prune=%d -> setting -txindex=false\n", __func__, nPruneArg);
998  }
999  }
1000 
1001  // Make sure additional indexes are recalculated correctly in VerifyDB
1002  // (we must reconnect blocks whenever we disconnect them for these indexes to work)
1003  bool fAdditionalIndexes =
1004  gArgs.GetBoolArg("-addressindex", DEFAULT_ADDRESSINDEX) ||
1005  gArgs.GetBoolArg("-spentindex", DEFAULT_SPENTINDEX) ||
1006  gArgs.GetBoolArg("-timestampindex", DEFAULT_TIMESTAMPINDEX);
1007 
1008  if (fAdditionalIndexes && gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL) < 4) {
1009  gArgs.ForceSetArg("-checklevel", "4");
1010  LogPrintf("%s: parameter interaction: additional indexes -> setting -checklevel=4\n", __func__);
1011  }
1012 
1013  // Warn if network-specific options (-addnode, -connect, etc) are
1014  // specified in default section of config file, but not overridden
1015  // on the command line or in this network's section of the config file.
1017 }
1018 
1019 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
1020 {
1021  return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
1022 }
1023 
1025 {
1026  fPrintToConsole = gArgs.GetBoolArg("-printtoconsole", false);
1027  fPrintToDebugLog = gArgs.GetBoolArg("-printtodebuglog", true) && !fPrintToConsole;
1031  fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS);
1032 
1033  LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
1034  LogPrintf("Dash Core version %s\n", FormatFullVersion());
1035 }
1036 
1037 namespace { // Variables internal to initialization process only
1038 
1039 int nMaxConnections;
1040 int nUserMaxConnections;
1041 int nFD;
1043 
1044 } // namespace
1045 
1046 [[noreturn]] static void new_handler_terminate()
1047 {
1048  // Rather than throwing std::bad-alloc if allocation fails, terminate
1049  // immediately to (try to) avoid chain corruption.
1050  // Since LogPrintf may itself allocate memory, set the handler directly
1051  // to terminate first.
1052  std::set_new_handler(std::terminate);
1053  LogPrintf("Error: Out of memory. Terminating.\n");
1054 
1055  // The log was successful, terminate now.
1056  std::terminate();
1057 };
1058 
1060 {
1061  // ********************************************************* Step 1: setup
1062 #ifdef _MSC_VER
1063  // Turn off Microsoft heap dump noise
1064  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1065  _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
1066  // Disable confusing "helpful" text message on abort, Ctrl-C
1067  _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1068 #endif
1069 #ifdef WIN32
1070  // Enable Data Execution Prevention (DEP)
1071  // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
1072  // A failure is non-critical and needs no further attention!
1073 #ifndef PROCESS_DEP_ENABLE
1074  // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
1075  // which is not correct. Can be removed, when GCCs winbase.h is fixed!
1076 #define PROCESS_DEP_ENABLE 0x00000001
1077 #endif
1078  typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
1079  PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
1080  if (setProcDEPPol != nullptr) setProcDEPPol(PROCESS_DEP_ENABLE);
1081 #endif
1082 
1083  if (!SetupNetworking())
1084  return InitError("Initializing networking failed");
1085 
1086 #ifndef WIN32
1087  if (!gArgs.GetBoolArg("-sysperms", false)) {
1088  umask(077);
1089  }
1090 
1091  // Clean shutdown on SIGTERM
1094 
1095  // Reopen debug.log on SIGHUP
1097 
1098  // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
1099  signal(SIGPIPE, SIG_IGN);
1100 #else
1101  SetConsoleCtrlHandler(consoleCtrlHandler, true);
1102 #endif
1103 
1104  std::set_new_handler(new_handler_terminate);
1105 
1106  return true;
1107 }
1108 
1110 {
1111  const CChainParams& chainparams = Params();
1112  // ********************************************************* Step 2: parameter interactions
1113 
1114  // also see: InitParameterInteraction()
1115 
1116  // if using block pruning, then disallow txindex and require disabling governance validation
1117  if (gArgs.GetArg("-prune", 0)) {
1118  if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX))
1119  return InitError(_("Prune mode is incompatible with -txindex."));
1120  if (!gArgs.GetBoolArg("-disablegovernance", false)) {
1121  return InitError(_("Prune mode is incompatible with -disablegovernance=false."));
1122  }
1123  }
1124 
1125  if (gArgs.IsArgSet("-devnet")) {
1126  // Require setting of ports when running devnet
1127  if (gArgs.GetArg("-listen", DEFAULT_LISTEN) && !gArgs.IsArgSet("-port")) {
1128  return InitError(_("-port must be specified when -devnet and -listen are specified"));
1129  }
1130  if (gArgs.GetArg("-server", false) && !gArgs.IsArgSet("-rpcport")) {
1131  return InitError(_("-rpcport must be specified when -devnet and -server are specified"));
1132  }
1133  if (gArgs.GetArgs("-devnet").size() > 1) {
1134  return InitError(_("-devnet can only be specified once"));
1135  }
1136  }
1137 
1139 
1140  // -bind and -whitebind can't be set when not listening
1141  size_t nUserBind = gArgs.GetArgs("-bind").size() + gArgs.GetArgs("-whitebind").size();
1142  if (nUserBind != 0 && !gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1143  return InitError("Cannot set -bind or -whitebind together with -listen=0");
1144  }
1145 
1146  // Make sure enough file descriptors are available
1147  int nBind = std::max(nUserBind, size_t(1));
1148  nUserMaxConnections = gArgs.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1149  nMaxConnections = std::max(nUserMaxConnections, 0);
1150 
1151  // Trim requested connection counts, to fit into system limitations
1152  // <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695
1154 #ifdef USE_POLL
1155  int fd_max = nFD;
1156 #else
1157  int fd_max = FD_SETSIZE;
1158 #endif
1159  nMaxConnections = std::max(std::min<int>(nMaxConnections, fd_max - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS), 0);
1160  if (nFD < MIN_CORE_FILEDESCRIPTORS)
1161  return InitError(_("Not enough file descriptors available."));
1162  nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
1163 
1164  if (nMaxConnections < nUserMaxConnections)
1165  InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
1166 
1167  // ********************************************************* Step 3: parameter-to-internal-flags
1168  if (gArgs.IsArgSet("-debug")) {
1169  // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
1170  const std::vector<std::string> categories = gArgs.GetArgs("-debug");
1171 
1172  if (std::none_of(categories.begin(), categories.end(),
1173  [](std::string cat){return cat == "0" || cat == "none";})) {
1174  for (const auto& cat : categories) {
1175  uint64_t flag;
1176  if (!GetLogCategory(&flag, &cat)) {
1177  InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
1178  }
1179  logCategories |= flag;
1180  }
1181  }
1182  }
1183 
1184  // Now remove the logging categories which were explicitly excluded
1185  for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
1186  uint64_t flag;
1187  if (!GetLogCategory(&flag, &cat)) {
1188  InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
1189  }
1190  logCategories &= ~flag;
1191  }
1192 
1193  // Check for -debugnet
1194  if (gArgs.GetBoolArg("-debugnet", false))
1195  InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
1196  // Check for -socks - as this is a privacy risk to continue, exit here
1197  if (gArgs.IsArgSet("-socks"))
1198  return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
1199  // Check for -tor - as this is a privacy risk to continue, exit here
1200  if (gArgs.GetBoolArg("-tor", false))
1201  return InitError(_("Unsupported argument -tor found, use -onion."));
1202 
1203  if (gArgs.GetBoolArg("-benchmark", false))
1204  InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
1205 
1206  if (gArgs.GetBoolArg("-whitelistalwaysrelay", false))
1207  InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
1208 
1209  if (gArgs.IsArgSet("-blockminsize"))
1210  InitWarning("Unsupported argument -blockminsize ignored.");
1211 
1212  // Checkmempool and checkblockindex default to true in regtest mode
1213  int ratio = std::min<int>(std::max<int>(gArgs.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
1214  if (ratio != 0) {
1215  mempool.setSanityCheck(1.0 / ratio);
1216  }
1217  fCheckBlockIndex = gArgs.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
1219 
1220  hashAssumeValid = uint256S(gArgs.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
1221  if (!hashAssumeValid.IsNull())
1222  LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
1223  else
1224  LogPrintf("Validating signatures for all blocks.\n");
1225 
1226  if (gArgs.IsArgSet("-minimumchainwork")) {
1227  const std::string minChainWorkStr = gArgs.GetArg("-minimumchainwork", "");
1228  if (!IsHexNumber(minChainWorkStr)) {
1229  return InitError(strprintf("Invalid non-hex (%s) minimum chain work value specified", minChainWorkStr));
1230  }
1231  nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
1232  } else {
1234  }
1235  LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
1237  LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex());
1238  }
1239 
1240  // mempool limits
1241  int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1242  int64_t nMempoolSizeMin = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
1243  if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
1244  return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
1245  // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
1246  // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
1247  if (gArgs.IsArgSet("-incrementalrelayfee"))
1248  {
1249  CAmount n = 0;
1250  if (!ParseMoney(gArgs.GetArg("-incrementalrelayfee", ""), n))
1251  return InitError(AmountErrMsg("incrementalrelayfee", gArgs.GetArg("-incrementalrelayfee", "")));
1253  }
1254 
1255  // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
1257  if (nScriptCheckThreads <= 0)
1259  if (nScriptCheckThreads <= 1)
1260  nScriptCheckThreads = 0;
1263 
1264  // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
1265  int64_t nPruneArg = gArgs.GetArg("-prune", 0);
1266  if (nPruneArg < 0) {
1267  return InitError(_("Prune cannot be configured with a negative value."));
1268  }
1269  nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
1270  if (nPruneArg == 1) { // manual pruning: -prune=1
1271  LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1272  nPruneTarget = std::numeric_limits<uint64_t>::max();
1273  fPruneMode = true;
1274  } else if (nPruneTarget) {
1275  if (gArgs.GetBoolArg("-regtest", false)) {
1276  // we use 1MB blocks to test this on regtest
1277  if (nPruneTarget < 550 * 1024 * 1024) {
1278  return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), 550));
1279  }
1280  } else {
1282  return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1283  }
1284  }
1285  LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1286  fPruneMode = true;
1287  }
1288 
1290  if (nConnectTimeout <= 0)
1292 
1293  if (gArgs.IsArgSet("-minrelaytxfee")) {
1294  CAmount n = 0;
1295  if (!ParseMoney(gArgs.GetArg("-minrelaytxfee", ""), n)) {
1296  return InitError(AmountErrMsg("minrelaytxfee", gArgs.GetArg("-minrelaytxfee", "")));
1297  }
1298  // High fee check is done afterward in WalletParameterInteraction()
1300  } else if (incrementalRelayFee > ::minRelayTxFee) {
1301  // Allow only setting incrementalRelayFee to control both
1303  LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1304  }
1305 
1306  // Sanity check argument for min fee for including tx in block
1307  // TODO: Harmonize which arguments need sanity checking and where that happens
1308  if (gArgs.IsArgSet("-blockmintxfee"))
1309  {
1310  CAmount n = 0;
1311  if (!ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n))
1312  return InitError(AmountErrMsg("blockmintxfee", gArgs.GetArg("-blockmintxfee", "")));
1313  }
1314 
1315  // Feerate used to define dust. Shouldn't be changed lightly as old
1316  // implementations may inadvertently create non-standard transactions
1317  if (gArgs.IsArgSet("-dustrelayfee"))
1318  {
1319  CAmount n = 0;
1320  if (!ParseMoney(gArgs.GetArg("-dustrelayfee", ""), n) || 0 == n)
1321  return InitError(AmountErrMsg("dustrelayfee", gArgs.GetArg("-dustrelayfee", "")));
1322  dustRelayFee = CFeeRate(n);
1323  }
1324 
1325  fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1326  if (chainparams.RequireStandard() && !fRequireStandard)
1327  return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1328  nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp);
1329 
1330  if (!g_wallet_init_interface->ParameterInteraction()) return false;
1331 
1334  nMaxDatacarrierBytes = gArgs.GetArg("-datacarriersize", nMaxDatacarrierBytes);
1335 
1336  // Option to startup with mocktime set (used for regression testing):
1337  SetMockTime(gArgs.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1338 
1339  if (gArgs.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1340  nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1341 
1343 
1344  nMaxTipAge = gArgs.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1345 
1346  if (gArgs.IsArgSet("-vbparams")) {
1347  // Allow overriding version bits parameters for testing
1348  if (!chainparams.MineBlocksOnDemand()) {
1349  return InitError("Version bits parameters may only be overridden on regtest.");
1350  }
1351  for (const std::string& strDeployment : gArgs.GetArgs("-vbparams")) {
1352  std::vector<std::string> vDeploymentParams;
1353  boost::split(vDeploymentParams, strDeployment, boost::is_any_of(":"));
1354  if (vDeploymentParams.size() != 3 && vDeploymentParams.size() != 5 && vDeploymentParams.size() != 7) {
1355  return InitError("Version bits parameters malformed, expecting deployment:start:end or deployment:start:end:window:threshold or deployment:start:end:window:thresholdstart:thresholdmin:falloffcoeff");
1356  }
1357  int64_t nStartTime, nTimeout, nWindowSize = -1, nThresholdStart = -1, nThresholdMin = -1, nFalloffCoeff = -1;
1358  if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1359  return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1360  }
1361  if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1362  return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1363  }
1364  if (vDeploymentParams.size() == 5) {
1365  if (!ParseInt64(vDeploymentParams[3], &nWindowSize)) {
1366  return InitError(strprintf("Invalid nWindowSize (%s)", vDeploymentParams[3]));
1367  }
1368  if (!ParseInt64(vDeploymentParams[4], &nThresholdStart)) {
1369  return InitError(strprintf("Invalid nThresholdStart (%s)", vDeploymentParams[4]));
1370  }
1371  }
1372  if (vDeploymentParams.size() == 7) {
1373  if (!ParseInt64(vDeploymentParams[5], &nThresholdMin)) {
1374  return InitError(strprintf("Invalid nThresholdMin (%s)", vDeploymentParams[5]));
1375  }
1376  if (!ParseInt64(vDeploymentParams[6], &nFalloffCoeff)) {
1377  return InitError(strprintf("Invalid nFalloffCoeff (%s)", vDeploymentParams[6]));
1378  }
1379  }
1380  bool found = false;
1381  for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1382  {
1383  if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1384  UpdateVersionBitsParameters(Consensus::DeploymentPos(j), nStartTime, nTimeout, nWindowSize, nThresholdStart, nThresholdMin, nFalloffCoeff);
1385  found = true;
1386  LogPrintf("Setting version bits activation parameters for %s to start=%ld, timeout=%ld, window=%ld, thresholdstart=%ld, thresholdmin=%ld, falloffcoeff=%ld\n",
1387  vDeploymentParams[0], nStartTime, nTimeout, nWindowSize, nThresholdStart, nThresholdMin, nFalloffCoeff);
1388  break;
1389  }
1390  }
1391  if (!found) {
1392  return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1393  }
1394  }
1395  }
1396 
1397  if (gArgs.IsArgSet("-dip3params")) {
1398  // Allow overriding budget parameters for testing
1399  if (!chainparams.MineBlocksOnDemand()) {
1400  return InitError("DIP3 parameters may only be overridden on regtest.");
1401  }
1402  std::string strDIP3Params = gArgs.GetArg("-dip3params", "");
1403  std::vector<std::string> vDIP3Params;
1404  boost::split(vDIP3Params, strDIP3Params, boost::is_any_of(":"));
1405  if (vDIP3Params.size() != 2) {
1406  return InitError("DIP3 parameters malformed, expecting DIP3ActivationHeight:DIP3EnforcementHeight");
1407  }
1408  int nDIP3ActivationHeight, nDIP3EnforcementHeight;
1409  if (!ParseInt32(vDIP3Params[0], &nDIP3ActivationHeight)) {
1410  return InitError(strprintf("Invalid nDIP3ActivationHeight (%s)", vDIP3Params[0]));
1411  }
1412  if (!ParseInt32(vDIP3Params[1], &nDIP3EnforcementHeight)) {
1413  return InitError(strprintf("Invalid nDIP3EnforcementHeight (%s)", vDIP3Params[1]));
1414  }
1415  UpdateDIP3Parameters(nDIP3ActivationHeight, nDIP3EnforcementHeight);
1416  }
1417 
1418  if (gArgs.IsArgSet("-budgetparams")) {
1419  // Allow overriding budget parameters for testing
1420  if (!chainparams.MineBlocksOnDemand()) {
1421  return InitError("Budget parameters may only be overridden on regtest.");
1422  }
1423 
1424  std::string strBudgetParams = gArgs.GetArg("-budgetparams", "");
1425  std::vector<std::string> vBudgetParams;
1426  boost::split(vBudgetParams, strBudgetParams, boost::is_any_of(":"));
1427  if (vBudgetParams.size() != 3) {
1428  return InitError("Budget parameters malformed, expecting masternodePaymentsStartBlock:budgetPaymentsStartBlock:superblockStartBlock");
1429  }
1430  int nMasternodePaymentsStartBlock, nBudgetPaymentsStartBlock, nSuperblockStartBlock;
1431  if (!ParseInt32(vBudgetParams[0], &nMasternodePaymentsStartBlock)) {
1432  return InitError(strprintf("Invalid nMasternodePaymentsStartBlock (%s)", vBudgetParams[0]));
1433  }
1434  if (!ParseInt32(vBudgetParams[1], &nBudgetPaymentsStartBlock)) {
1435  return InitError(strprintf("Invalid nBudgetPaymentsStartBlock (%s)", vBudgetParams[1]));
1436  }
1437  if (!ParseInt32(vBudgetParams[2], &nSuperblockStartBlock)) {
1438  return InitError(strprintf("Invalid nSuperblockStartBlock (%s)", vBudgetParams[2]));
1439  }
1440  UpdateBudgetParameters(nMasternodePaymentsStartBlock, nBudgetPaymentsStartBlock, nSuperblockStartBlock);
1441  }
1442 
1443  if (chainparams.NetworkIDString() == CBaseChainParams::DEVNET) {
1444  int nMinimumDifficultyBlocks = gArgs.GetArg("-minimumdifficultyblocks", chainparams.GetConsensus().nMinimumDifficultyBlocks);
1445  int nHighSubsidyBlocks = gArgs.GetArg("-highsubsidyblocks", chainparams.GetConsensus().nHighSubsidyBlocks);
1446  int nHighSubsidyFactor = gArgs.GetArg("-highsubsidyfactor", chainparams.GetConsensus().nHighSubsidyFactor);
1447  UpdateDevnetSubsidyAndDiffParams(nMinimumDifficultyBlocks, nHighSubsidyBlocks, nHighSubsidyFactor);
1448  } else if (gArgs.IsArgSet("-minimumdifficultyblocks") || gArgs.IsArgSet("-highsubsidyblocks") || gArgs.IsArgSet("-highsubsidyfactor")) {
1449  return InitError("Difficulty and subsidy parameters may only be overridden on devnet.");
1450  }
1451 
1452  if (chainparams.NetworkIDString() == CBaseChainParams::DEVNET) {
1453  std::string llmqTypeChainLocks = gArgs.GetArg("-llmqchainlocks", Params().GetConsensus().llmqs.at(Params().GetConsensus().llmqTypeChainLocks).name);
1455  for (const auto& p : Params().GetConsensus().llmqs) {
1456  if (p.second.name == llmqTypeChainLocks) {
1457  llmqType = p.first;
1458  break;
1459  }
1460  }
1461  if (llmqType == Consensus::LLMQ_NONE) {
1462  return InitError("Invalid LLMQ type specified for -llmqchainlocks.");
1463  }
1464  UpdateDevnetLLMQChainLocks(llmqType);
1465  } else if (gArgs.IsArgSet("-llmqchainlocks")) {
1466  return InitError("LLMQ type for ChainLocks can only be overridden on devnet.");
1467  }
1468 
1469  if (chainparams.NetworkIDString() == CBaseChainParams::DEVNET) {
1470  if (gArgs.IsArgSet("-llmqdevnetparams")) {
1471  std::string s = gArgs.GetArg("-llmqdevnetparams", "");
1472  std::vector<std::string> v;
1473  boost::split(v, s, boost::is_any_of(":"));
1474  int size, threshold;
1475  if (v.size() != 2 || !ParseInt32(v[0], &size) || !ParseInt32(v[1], &threshold)) {
1476  return InitError("Invalid -llmqdevnetparams specified");
1477  }
1478  UpdateLLMQDevnetParams(size, threshold);
1479  }
1480  } else if (gArgs.IsArgSet("-llmqdevnetparams")) {
1481  return InitError("LLMQ devnet params can only be overridden on devnet.");
1482  }
1483 
1484  if (chainparams.NetworkIDString() == CBaseChainParams::REGTEST) {
1485  if (gArgs.IsArgSet("-llmqtestparams")) {
1486  std::string s = gArgs.GetArg("-llmqtestparams", "");
1487  std::vector<std::string> v;
1488  boost::split(v, s, boost::is_any_of(":"));
1489  int size, threshold;
1490  if (v.size() != 2 || !ParseInt32(v[0], &size) || !ParseInt32(v[1], &threshold)) {
1491  return InitError("Invalid -llmqtestparams specified");
1492  }
1493  UpdateLLMQTestParams(size, threshold);
1494  }
1495  } else if (gArgs.IsArgSet("-llmqtestparams")) {
1496  return InitError("LLMQ test params can only be overridden on regtest.");
1497  }
1498 
1499  if (gArgs.IsArgSet("-maxorphantx")) {
1500  InitWarning("-maxorphantx is not supported anymore. Use -maxorphantxsize instead.");
1501  }
1502 
1503  if (gArgs.IsArgSet("-masternode")) {
1504  InitWarning(_("-masternode option is deprecated and ignored, specifying -masternodeblsprivkey is enough to start this node as a masternode."));
1505  }
1506 
1507  if (gArgs.IsArgSet("-masternodeblsprivkey")) {
1509  return InitError("Masternode must accept connections from outside, set -listen=1");
1510  }
1511  if (!gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1512  return InitError("Masternode must have transaction index enabled, set -txindex=1");
1513  }
1514  if (!gArgs.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) {
1515  return InitError("Masternode must have bloom filters enabled, set -peerbloomfilters=1");
1516  }
1517  if (gArgs.GetArg("-prune", 0) > 0) {
1518  return InitError("Masternode must have no pruning enabled, set -prune=0");
1519  }
1521  return InitError(strprintf("Masternode must be able to handle at least %d connections, set -maxconnections=%d", DEFAULT_MAX_PEER_CONNECTIONS, DEFAULT_MAX_PEER_CONNECTIONS));
1522  }
1523  if (gArgs.GetBoolArg("-disablegovernance", false)) {
1524  return InitError(_("You can not disable governance validation on a masternode."));
1525  }
1526  }
1527 
1528  if (gArgs.IsArgSet("-litemode")) {
1529  InitWarning(_("-litemode is deprecated.") + (gArgs.GetBoolArg("-litemode", false) ? (" " + _("Its replacement -disablegovernance has been forced instead.")) : ( " " + _("It has been replaced by -disablegovernance."))));
1530  gArgs.ForceRemoveArg("-litemode");
1531  }
1532 
1533  fDisableGovernance = gArgs.GetBoolArg("-disablegovernance", false);
1534  LogPrintf("fDisableGovernance %d\n", fDisableGovernance);
1535 
1536  if (fDisableGovernance) {
1537  InitWarning(_("You are starting with governance validation disabled.") + (fPruneMode ? " " + _("This is expected because you are running a pruned node.") : ""));
1538  }
1539 
1540  return true;
1541 }
1542 
1543 static bool LockDataDirectory(bool probeOnly)
1544 {
1545  // Make sure only a single Dash Core process is using the data directory.
1546  fs::path datadir = GetDataDir();
1547  if (!LockDirectory(datadir, ".lock", probeOnly)) {
1548  return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), datadir.string(), _(PACKAGE_NAME)));
1549  }
1550  return true;
1551 }
1552 
1554 {
1555  // ********************************************************* Step 4: sanity checks
1556 
1557  // Initialize elliptic curve code
1558  std::string sha256_algo = SHA256AutoDetect();
1559  LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
1560  RandomInit();
1561  ECC_Start();
1562  globalVerifyHandle.reset(new ECCVerifyHandle());
1563 
1564  // Sanity check
1565  if (!InitSanityCheck())
1566  return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1567 
1568  // Probe the data directory lock to give an early error message, if possible
1569  // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened,
1570  // and a fork will cause weird behavior to it.
1571  return LockDataDirectory(true);
1572 }
1573 
1575 {
1576  // After daemonization get the data directory lock again and hold on to it until exit
1577  // This creates a slight window for a race condition to happen, however this condition is harmless: it
1578  // will at most make us exit without printing a message to console.
1579  if (!LockDataDirectory(false)) {
1580  // Detailed error printed inside LockDataDirectory
1581  return false;
1582  }
1583  return true;
1584 }
1585 
1587 {
1588  const CChainParams& chainparams = Params();
1589  // ********************************************************* Step 4a: application initialization
1590 #ifndef WIN32
1591  CreatePidFile(GetPidFile(), getpid());
1592 #endif
1593  if (gArgs.GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
1594  // Do this first since it both loads a bunch of debug.log into memory,
1595  // and because this needs to happen before any other debug.log printing
1596  ShrinkDebugFile();
1597  }
1598 
1599  if (fPrintToDebugLog) {
1600  if (!OpenDebugLog()) {
1601  return InitError(strprintf("Could not open debug log file %s", GetDebugLogPath().string()));
1602  }
1603  }
1604 
1605  if (!fLogTimestamps)
1606  LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1607  LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1608  LogPrintf("Using data directory %s\n", GetDataDir().string());
1609  LogPrintf("Using config file %s\n", GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1610  LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1611 
1612  // Warn about relative -datadir path.
1613  if (gArgs.IsArgSet("-datadir") && !fs::path(gArgs.GetArg("-datadir", "")).is_absolute()) {
1614  LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the "
1615  "current working directory '%s'. This is fragile, because if Dash Core is started in the future "
1616  "from a different location, it will be unable to locate the current data files. There could "
1617  "also be data loss if Dash Core is started while in a temporary directory.\n",
1618  gArgs.GetArg("-datadir", ""), fs::current_path().string());
1619  }
1620 
1623 
1624  LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1625  if (nScriptCheckThreads) {
1626  for (int i=0; i<nScriptCheckThreads-1; i++)
1627  threadGroup.create_thread(&ThreadScriptCheck);
1628  }
1629 
1630  std::vector<std::string> vSporkAddresses;
1631  if (gArgs.IsArgSet("-sporkaddr")) {
1632  vSporkAddresses = gArgs.GetArgs("-sporkaddr");
1633  } else {
1634  vSporkAddresses = Params().SporkAddresses();
1635  }
1636  for (const auto& address: vSporkAddresses) {
1637  if (!sporkManager.SetSporkAddress(address)) {
1638  return InitError(_("Invalid spork address specified with -sporkaddr"));
1639  }
1640  }
1641 
1642  int minsporkkeys = gArgs.GetArg("-minsporkkeys", Params().MinSporkKeys());
1643  if (!sporkManager.SetMinSporkKeys(minsporkkeys)) {
1644  return InitError(_("Invalid minimum number of spork signers specified with -minsporkkeys"));
1645  }
1646 
1647 
1648  if (gArgs.IsArgSet("-sporkkey")) { // spork priv key
1649  if (!sporkManager.SetPrivKey(gArgs.GetArg("-sporkkey", ""))) {
1650  return InitError(_("Unable to sign spork message, wrong key?"));
1651  }
1652  }
1653 
1654  // Start the lightweight task scheduler thread
1655  CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1656  threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1657 
1660 
1661  /* Register RPC commands regardless of -server setting so they will be
1662  * available in the GUI RPC console even if external calls are disabled.
1663  */
1666 
1667  /* Start the RPC server already. It will be started in "warmup" mode
1668  * and not really process calls already (but it will signify connections
1669  * that the server is there and will be ready later). Warmup mode will
1670  * be disabled when initialisation is finished.
1671  */
1672  if (gArgs.GetBoolArg("-server", false))
1673  {
1675  if (!AppInitServers())
1676  return InitError(_("Unable to start HTTP server. See debug log for details."));
1677  }
1678 
1679  // ********************************************************* Step 5: verify wallet database integrity
1680 
1681  if(!g_wallet_init_interface->InitAutoBackup()) return false;
1682  if (!g_wallet_init_interface->Verify()) return false;
1683 
1684  // Initialize KeePass Integration
1686  // ********************************************************* Step 6: network initialization
1687  // Note that we absolutely cannot open any actual connections
1688  // until the very end ("start node") as the UTXO/block state
1689  // is not yet setup and may end up being set up twice if we
1690  // need to reindex later.
1691 
1692  assert(!g_connman);
1693  g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1694  CConnman& connman = *g_connman;
1695 
1696  peerLogic.reset(new PeerLogicValidation(&connman, scheduler));
1698 
1699  // sanitize comments per BIP-0014, format user agent and check total size
1700  std::vector<std::string> uacomments;
1701 
1702  if (chainparams.NetworkIDString() == CBaseChainParams::DEVNET) {
1703  // Add devnet name to user agent. This allows to disconnect nodes immediately if they don't belong to our own devnet
1704  uacomments.push_back(strprintf("devnet=%s", gArgs.GetDevNetName()));
1705  }
1706 
1707  for (const std::string& cmt : gArgs.GetArgs("-uacomment")) {
1708  if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1709  return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1710  uacomments.push_back(cmt);
1711  }
1713  if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1714  return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1716  }
1717 
1718  if (gArgs.IsArgSet("-onlynet")) {
1719  std::set<enum Network> nets;
1720  for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
1721  enum Network net = ParseNetwork(snet);
1722  if (net == NET_UNROUTABLE)
1723  return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1724  nets.insert(net);
1725  }
1726  for (int n = 0; n < NET_MAX; n++) {
1727  enum Network net = (enum Network)n;
1728  if (!nets.count(net))
1729  SetLimited(net);
1730  }
1731  }
1732 
1733  // Check for host lookup allowed before parsing any network related parameters
1735 
1736  bool proxyRandomize = gArgs.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1737  // -proxy sets a proxy for all outgoing network traffic
1738  // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1739  std::string proxyArg = gArgs.GetArg("-proxy", "");
1741  if (proxyArg != "" && proxyArg != "0") {
1742  CService proxyAddr;
1743  if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1744  return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1745  }
1746 
1747  proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1748  if (!addrProxy.IsValid())
1749  return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1750 
1751  SetProxy(NET_IPV4, addrProxy);
1752  SetProxy(NET_IPV6, addrProxy);
1753  SetProxy(NET_TOR, addrProxy);
1754  SetNameProxy(addrProxy);
1755  SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1756  }
1757 
1758  // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1759  // -noonion (or -onion=0) disables connecting to .onion entirely
1760  // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1761  std::string onionArg = gArgs.GetArg("-onion", "");
1762  if (onionArg != "") {
1763  if (onionArg == "0") { // Handle -noonion/-onion=0
1764  SetLimited(NET_TOR); // set onions as unreachable
1765  } else {
1766  CService onionProxy;
1767  if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1768  return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1769  }
1770  proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1771  if (!addrOnion.IsValid())
1772  return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1773  SetProxy(NET_TOR, addrOnion);
1774  SetLimited(NET_TOR, false);
1775  }
1776  }
1777 
1778  // see Step 2: parameter interactions for more information about these
1779  fListen = gArgs.GetBoolArg("-listen", DEFAULT_LISTEN);
1780  fDiscover = gArgs.GetBoolArg("-discover", true);
1781  fRelayTxes = !gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1782 
1783  for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
1784  CService addrLocal;
1785  if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1786  AddLocal(addrLocal, LOCAL_MANUAL);
1787  else
1788  return InitError(ResolveErrMsg("externalip", strAddr));
1789  }
1790 
1791 #if ENABLE_ZMQ
1792  pzmqNotificationInterface = CZMQNotificationInterface::Create();
1793 
1794  if (pzmqNotificationInterface) {
1795  RegisterValidationInterface(pzmqNotificationInterface);
1796  }
1797 #endif
1798 
1801 
1802  uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1803  uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1804 
1805  if (gArgs.IsArgSet("-maxuploadtarget")) {
1806  nMaxOutboundLimit = gArgs.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1807  }
1808 
1809  // ********************************************************* Step 7a: Load sporks
1810 
1811  uiInterface.InitMessage(_("Loading sporks cache..."));
1812  CFlatDB<CSporkManager> flatdb6("sporks.dat", "magicSporkCache");
1813  if (!flatdb6.Load(sporkManager)) {
1814  return InitError(_("Failed to load sporks cache from") + "\n" + (GetDataDir() / "sporks.dat").string());
1815  }
1816 
1817  // ********************************************************* Step 7b: load block chain
1818 
1819  fReindex = gArgs.GetBoolArg("-reindex", false);
1820  bool fReindexChainState = gArgs.GetBoolArg("-reindex-chainstate", false);
1821 
1822  // cache size calculations
1823  int64_t nTotalCache = (gArgs.GetArg("-dbcache", nDefaultDbCache) << 20);
1824  nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1825  nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1826  int64_t nBlockTreeDBCache = nTotalCache / 8;
1827  nBlockTreeDBCache = std::min(nBlockTreeDBCache, (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1828  nTotalCache -= nBlockTreeDBCache;
1829  int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1830  nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1831  nTotalCache -= nCoinDBCache;
1832  nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1833  int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1834  int64_t nEvoDbCache = 1024 * 1024 * 16; // TODO
1835  LogPrintf("Cache configuration:\n");
1836  LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1837  LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1838  LogPrintf("* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
1839 
1840  bool fLoaded = false;
1841  int64_t nStart = GetTimeMillis();
1842 
1843  while (!fLoaded && !fRequestShutdown) {
1844  bool fReset = fReindex;
1845  std::string strLoadError;
1846 
1847  uiInterface.InitMessage(_("Loading block index..."));
1848 
1849  nStart = GetTimeMillis();
1850  do {
1851  try {
1852  UnloadBlockIndex();
1853  pcoinsTip.reset();
1854  pcoinsdbview.reset();
1855  pcoinscatcher.reset();
1856  // new CBlockTreeDB tries to delete the existing file, which
1857  // fails if it's still open from the previous loop. Close it first:
1858  pblocktree.reset();
1859  pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
1861  // Same logic as above with pblocktree
1862  evoDb.reset();
1863  evoDb.reset(new CEvoDB(nEvoDbCache, false, fReset || fReindexChainState));
1864  deterministicMNManager.reset();
1866 
1867  llmq::InitLLMQSystem(*evoDb, false, fReset || fReindexChainState);
1868 
1869  if (fReset) {
1870  pblocktree->WriteReindexing(true);
1871  //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1872  if (fPruneMode)
1874  }
1875 
1876  if (fRequestShutdown) break;
1877 
1878  // LoadBlockIndex will load fTxIndex from the db, or set it if
1879  // we're reindexing. It will also load fHavePruned if we've
1880  // ever removed a block file from disk.
1881  // Note that it also sets fReindex based on the disk flag!
1882  // From here on out fReindex and fReset mean something different!
1883  if (!LoadBlockIndex(chainparams)) {
1884  strLoadError = _("Error loading block database");
1885  break;
1886  }
1887 
1888  if (!fDisableGovernance && !fTxIndex
1889  && chainparams.NetworkIDString() != CBaseChainParams::REGTEST) { // TODO remove this when pruning is fixed. See https://github.com/dashpay/dash/pull/1817 and https://github.com/dashpay/dash/pull/1743
1890  return InitError(_("Transaction index can't be disabled with governance validation enabled. Either start with -disablegovernance command line switch or enable transaction index."));
1891  }
1892 
1893  // If the loaded chain has a wrong genesis, bail out immediately
1894  // (we're likely using a testnet datadir, or the other way around).
1895  if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1896  return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1897 
1898  if (!chainparams.GetConsensus().hashDevnetGenesisBlock.IsNull() && !mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashDevnetGenesisBlock) == 0)
1899  return InitError(_("Incorrect or no devnet genesis block found. Wrong datadir for devnet specified?"));
1900 
1901  // Check for changed -txindex state
1902  if (fTxIndex != gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1903  strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1904  break;
1905  }
1906 
1907  // Check for changed -addressindex state
1908  if (fAddressIndex != gArgs.GetBoolArg("-addressindex", DEFAULT_ADDRESSINDEX)) {
1909  strLoadError = _("You need to rebuild the database using -reindex to change -addressindex");
1910  break;
1911  }
1912 
1913  // Check for changed -timestampindex state
1914  if (fTimestampIndex != gArgs.GetBoolArg("-timestampindex", DEFAULT_TIMESTAMPINDEX)) {
1915  strLoadError = _("You need to rebuild the database using -reindex to change -timestampindex");
1916  break;
1917  }
1918 
1919  // Check for changed -spentindex state
1920  if (fSpentIndex != gArgs.GetBoolArg("-spentindex", DEFAULT_SPENTINDEX)) {
1921  strLoadError = _("You need to rebuild the database using -reindex to change -spentindex");
1922  break;
1923  }
1924 
1925  // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1926  // in the past, but is now trying to run unpruned.
1927  if (fHavePruned && !fPruneMode) {
1928  strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1929  break;
1930  }
1931 
1932  // At this point blocktree args are consistent with what's on disk.
1933  // If we're not mid-reindex (based on disk + args), add a genesis block on disk
1934  // (otherwise we use the one already on disk).
1935  // This is called again in ThreadImport after the reindex completes.
1936  if (!fReindex && !LoadGenesisBlock(chainparams)) {
1937  strLoadError = _("Error initializing block database");
1938  break;
1939  }
1940 
1941  // At this point we're either in reindex or we've loaded a useful
1942  // block tree into mapBlockIndex!
1943 
1944  pcoinsdbview.reset(new CCoinsViewDB(nCoinDBCache, false, fReset || fReindexChainState));
1946 
1947  // If necessary, upgrade from older database format.
1948  // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1949  if (!pcoinsdbview->Upgrade()) {
1950  strLoadError = _("Error upgrading chainstate database");
1951  break;
1952  }
1953 
1954  // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1955  if (!ReplayBlocks(chainparams, pcoinsdbview.get())) {
1956  strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1957  break;
1958  }
1959 
1960  // The on-disk coinsdb is now in a good state, create the cache
1961  pcoinsTip.reset(new CCoinsViewCache(pcoinscatcher.get()));
1962 
1963  // flush evodb
1964  if (!evoDb->CommitRootTransaction()) {
1965  strLoadError = _("Failed to commit EvoDB");
1966  break;
1967  }
1968 
1969  bool is_coinsview_empty = fReset || fReindexChainState || pcoinsTip->GetBestBlock().IsNull();
1970  if (!is_coinsview_empty) {
1971  // LoadChainTip sets chainActive based on pcoinsTip's best block
1972  if (!LoadChainTip(chainparams)) {
1973  strLoadError = _("Error initializing block database");
1974  break;
1975  }
1976  assert(chainActive.Tip() != NULL);
1977  }
1978 
1979  if (!deterministicMNManager->UpgradeDBIfNeeded()) {
1980  strLoadError = _("Error upgrading evo database");
1981  break;
1982  }
1983 
1984  if (!is_coinsview_empty) {
1985  uiInterface.InitMessage(_("Verifying blocks..."));
1986  if (fHavePruned && gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1987  LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
1989  }
1990 
1991  {
1992  LOCK(cs_main);
1993  CBlockIndex* tip = chainActive.Tip();
1994  RPCNotifyBlockChange(true, tip);
1995  if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1996  strLoadError = _("The block database contains a block which appears to be from the future. "
1997  "This may be due to your computer's date and time being set incorrectly. "
1998  "Only rebuild the block database if you are sure that your computer's date and time are correct");
1999  break;
2000  }
2001  }
2002 
2003  if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview.get(), gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
2004  gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
2005  strLoadError = _("Corrupted block database detected");
2006  break;
2007  }
2008  }
2009  } catch (const std::exception& e) {
2010  LogPrintf("%s\n", e.what());
2011  strLoadError = _("Error opening block database");
2012  break;
2013  }
2014 
2015  fLoaded = true;
2016  } while(false);
2017 
2018  if (!fLoaded && !fRequestShutdown) {
2019  // first suggest a reindex
2020  if (!fReset) {
2021  bool fRet = uiInterface.ThreadSafeQuestion(
2022  strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
2023  strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
2025  if (fRet) {
2026  fReindex = true;
2027  fRequestShutdown = false;
2028  } else {
2029  LogPrintf("Aborted block database rebuild. Exiting.\n");
2030  return false;
2031  }
2032  } else {
2033  return InitError(strLoadError);
2034  }
2035  }
2036  }
2037 
2038  // As LoadBlockIndex can take several minutes, it's possible the user
2039  // requested to kill the GUI during the last operation. If so, exit.
2040  // As the program has not fully started yet, Shutdown() is possibly overkill.
2041  if (fRequestShutdown)
2042  {
2043  LogPrintf("Shutdown requested. Exiting.\n");
2044  return false;
2045  }
2046  if (fLoaded) {
2047  LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
2048  }
2049 
2050  fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
2051  CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
2052  // Allowed to fail as this file IS missing on first startup.
2053  if (!est_filein.IsNull())
2054  ::feeEstimator.Read(est_filein);
2055  fFeeEstimatesInitialized = true;
2056 
2057  // ********************************************************* Step 8: load wallet
2058  if (!g_wallet_init_interface->Open()) return false;
2059 
2060  // As InitLoadWallet can take several minutes, it's possible the user
2061  // requested to kill the GUI during the last operation. If so, exit.
2062  if (fRequestShutdown)
2063  {
2064  LogPrintf("Shutdown requested. Exiting.\n");
2065  return false;
2066  }
2067 
2068  // ********************************************************* Step 9: data directory maintenance
2069 
2070  // if pruning, unset the service bit and perform the initial blockstore prune
2071  // after any wallet rescanning has taken place.
2072  if (fPruneMode) {
2073  LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
2074  nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
2075  if (!fReindex) {
2076  uiInterface.InitMessage(_("Pruning blockstore..."));
2077  PruneAndFlush();
2078  }
2079  }
2080 
2081  // As PruneAndFlush can take several minutes, it's possible the user
2082  // requested to kill the GUI during the last operation. If so, exit.
2083  if (fRequestShutdown)
2084  {
2085  LogPrintf("Shutdown requested. Exiting.\n");
2086  return false;
2087  }
2088 
2089  // ********************************************************* Step 10a: Prepare Masternode related stuff
2090  fMasternodeMode = false;
2091  std::string strMasterNodeBLSPrivKey = gArgs.GetArg("-masternodeblsprivkey", "");
2092  if (!strMasterNodeBLSPrivKey.empty()) {
2093  auto binKey = ParseHex(strMasterNodeBLSPrivKey);
2094  CBLSSecretKey keyOperator;
2095  keyOperator.SetBuf(binKey);
2096  if (!keyOperator.IsValid()) {
2097  return InitError(_("Invalid masternodeblsprivkey. Please see documentation."));
2098  }
2099  fMasternodeMode = true;
2100  activeMasternodeInfo.blsKeyOperator = std::make_unique<CBLSSecretKey>(keyOperator);
2101  activeMasternodeInfo.blsPubKeyOperator = std::make_unique<CBLSPublicKey>(activeMasternodeInfo.blsKeyOperator->GetPublicKey());
2102  LogPrintf("MASTERNODE:\n");
2103  LogPrintf(" blsPubKeyOperator: %s\n", keyOperator.GetPublicKey().ToString());
2104  }
2105 
2106  if(fMasternodeMode) {
2107  // Create and register activeMasternodeManager, will init later in ThreadImport
2110  }
2111 
2112  if (activeMasternodeInfo.blsKeyOperator == nullptr) {
2113  activeMasternodeInfo.blsKeyOperator = std::make_unique<CBLSSecretKey>();
2114  }
2115  if (activeMasternodeInfo.blsPubKeyOperator == nullptr) {
2116  activeMasternodeInfo.blsPubKeyOperator = std::make_unique<CBLSPublicKey>();
2117  }
2118 
2119  // ********************************************************* Step 10b: setup PrivateSend
2120 
2123 
2124  // ********************************************************* Step 10b: Load cache data
2125 
2126  // LOAD SERIALIZED DAT FILES INTO DATA CACHES FOR INTERNAL USE
2127 
2128  bool fLoadCacheFiles = !(fReindex || fReindexChainState);
2129  {
2130  LOCK(cs_main);
2131  // was blocks/chainstate deleted?
2132  if (chainActive.Tip() == nullptr) {
2133  fLoadCacheFiles = false;
2134  }
2135  }
2136  fs::path pathDB = GetDataDir();
2137  std::string strDBName;
2138 
2139  strDBName = "mncache.dat";
2140  uiInterface.InitMessage(_("Loading masternode cache..."));
2141  CFlatDB<CMasternodeMetaMan> flatdb1(strDBName, "magicMasternodeCache");
2142  if (fLoadCacheFiles) {
2143  if(!flatdb1.Load(mmetaman)) {
2144  return InitError(_("Failed to load masternode cache from") + "\n" + (pathDB / strDBName).string());
2145  }
2146  } else {
2147  CMasternodeMetaMan mmetamanTmp;
2148  if(!flatdb1.Dump(mmetamanTmp)) {
2149  return InitError(_("Failed to clear masternode cache at") + "\n" + (pathDB / strDBName).string());
2150  }
2151  }
2152 
2153  strDBName = "governance.dat";
2154  uiInterface.InitMessage(_("Loading governance cache..."));
2155  CFlatDB<CGovernanceManager> flatdb3(strDBName, "magicGovernanceCache");
2156  if (fLoadCacheFiles && !fDisableGovernance) {
2157  if(!flatdb3.Load(governance)) {
2158  return InitError(_("Failed to load governance cache from") + "\n" + (pathDB / strDBName).string());
2159  }
2161  } else {
2162  CGovernanceManager governanceTmp;
2163  if(!flatdb3.Dump(governanceTmp)) {
2164  return InitError(_("Failed to clear governance cache at") + "\n" + (pathDB / strDBName).string());
2165  }
2166  }
2167 
2168  strDBName = "netfulfilled.dat";
2169  uiInterface.InitMessage(_("Loading fulfilled requests cache..."));
2170  CFlatDB<CNetFulfilledRequestManager> flatdb4(strDBName, "magicFulfilledCache");
2171  if (fLoadCacheFiles) {
2172  if(!flatdb4.Load(netfulfilledman)) {
2173  return InitError(_("Failed to load fulfilled requests cache from") + "\n" + (pathDB / strDBName).string());
2174  }
2175  } else {
2176  CNetFulfilledRequestManager netfulfilledmanTmp;
2177  if(!flatdb4.Dump(netfulfilledmanTmp)) {
2178  return InitError(_("Failed to clear fulfilled requests cache at") + "\n" + (pathDB / strDBName).string());
2179  }
2180  }
2181 
2182  // ********************************************************* Step 10c: schedule Dash-specific tasks
2183 
2185  scheduler.scheduleEvery(boost::bind(&CMasternodeSync::DoMaintenance, boost::ref(masternodeSync), boost::ref(*g_connman)), 1 * 1000);
2186  scheduler.scheduleEvery(boost::bind(&CMasternodeUtils::DoMaintenance, boost::ref(*g_connman)), 1 * 1000);
2187 
2188  if (!fDisableGovernance) {
2189  scheduler.scheduleEvery(boost::bind(&CGovernanceManager::DoMaintenance, boost::ref(governance), boost::ref(*g_connman)), 60 * 5 * 1000);
2190  }
2191 
2192  if (fMasternodeMode) {
2193  scheduler.scheduleEvery(boost::bind(&CPrivateSendServer::DoMaintenance, boost::ref(privateSendServer), boost::ref(*g_connman)), 1 * 1000);
2194  }
2195 
2197 
2198  // ********************************************************* Step 11: import blocks
2199 
2200  if (!CheckDiskSpace())
2201  return false;
2202 
2203  // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
2204  // No locking, as this happens before any background thread is started.
2205  if (chainActive.Tip() == nullptr) {
2207  } else {
2208  fHaveGenesis = true;
2209  }
2210 
2211  if (gArgs.IsArgSet("-blocknotify"))
2213 
2214  std::vector<fs::path> vImportFiles;
2215  for (const std::string& strFile : gArgs.GetArgs("-loadblock")) {
2216  vImportFiles.push_back(strFile);
2217  }
2218 
2219  threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
2220 
2221  // Wait for genesis block to be processed
2222  {
2224  // We previously could hang here if StartShutdown() is called prior to
2225  // ThreadImport getting started, so instead we just wait on a timer to
2226  // check ShutdownRequested() regularly.
2227  while (!fHaveGenesis && !ShutdownRequested()) {
2228  condvar_GenesisWait.wait_for(lock, std::chrono::milliseconds(500));
2229  }
2231  }
2232 
2233  // As importing blocks can take several minutes, it's possible the user
2234  // requested to kill the GUI during one of the last operations. If so, exit.
2235  if (ShutdownRequested()) {
2236  LogPrintf("Shutdown requested. Exiting.\n");
2237  return false;
2238  }
2239 
2240  // ********************************************************* Step 12: start node
2241 
2242  int chain_active_height;
2243 
2245  {
2246  LOCK(cs_main);
2247  LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
2248  chain_active_height = chainActive.Height();
2249  }
2250  LogPrintf("chainActive.Height() = %d\n", chain_active_height);
2251  if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
2253 
2255 
2256  // Map ports with UPnP
2257  MapPort(gArgs.GetBoolArg("-upnp", DEFAULT_UPNP));
2258 
2259  CConnman::Options connOptions;
2260  connOptions.nLocalServices = nLocalServices;
2261  connOptions.nMaxConnections = nMaxConnections;
2262  connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
2263  connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
2264  connOptions.nMaxFeeler = 1;
2265  connOptions.nBestHeight = chain_active_height;
2266  connOptions.uiInterface = &uiInterface;
2267  connOptions.m_msgproc = peerLogic.get();
2268  connOptions.nSendBufferMaxSize = 1000*gArgs.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
2269  connOptions.nReceiveFloodSize = 1000*gArgs.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
2270  connOptions.m_added_nodes = gArgs.GetArgs("-addnode");
2271 
2272  connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
2273  connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
2274 
2275  for (const std::string& strBind : gArgs.GetArgs("-bind")) {
2276  CService addrBind;
2277  if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) {
2278  return InitError(ResolveErrMsg("bind", strBind));
2279  }
2280  connOptions.vBinds.push_back(addrBind);
2281  }
2282  for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
2283  CService addrBind;
2284  if (!Lookup(strBind.c_str(), addrBind, 0, false)) {
2285  return InitError(ResolveErrMsg("whitebind", strBind));
2286  }
2287  if (addrBind.GetPort() == 0) {
2288  return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
2289  }
2290  connOptions.vWhiteBinds.push_back(addrBind);
2291  }
2292 
2293  for (const auto& net : gArgs.GetArgs("-whitelist")) {
2294  CSubNet subnet;
2295  LookupSubNet(net.c_str(), subnet);
2296  if (!subnet.IsValid())
2297  return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
2298  connOptions.vWhitelistedRange.push_back(subnet);
2299  }
2300 
2301  connOptions.vSeedNodes = gArgs.GetArgs("-seednode");
2302 
2303  // Initiate outbound connections unless connect=0
2304  connOptions.m_use_addrman_outgoing = !gArgs.IsArgSet("-connect");
2305  if (!connOptions.m_use_addrman_outgoing) {
2306  const auto connect = gArgs.GetArgs("-connect");
2307  if (connect.size() != 1 || connect[0] != "0") {
2308  connOptions.m_specified_outgoing = connect;
2309  }
2310  }
2311 
2312  std::string strSocketEventsMode = gArgs.GetArg("-socketevents", DEFAULT_SOCKETEVENTS);
2313  if (strSocketEventsMode == "select") {
2314  connOptions.socketEventsMode = CConnman::SOCKETEVENTS_SELECT;
2315 #ifdef USE_POLL
2316  } else if (strSocketEventsMode == "poll") {
2317  connOptions.socketEventsMode = CConnman::SOCKETEVENTS_POLL;
2318 #endif
2319 #ifdef USE_EPOLL
2320  } else if (strSocketEventsMode == "epoll") {
2321  connOptions.socketEventsMode = CConnman::SOCKETEVENTS_EPOLL;
2322 #endif
2323  } else {
2324  return InitError(strprintf(_("Invalid -socketevents ('%s') specified. Only these modes are supported: %s"), strSocketEventsMode, GetSupportedSocketEventsStr()));
2325  }
2326 
2327  if (!connman.Start(scheduler, connOptions)) {
2328  return false;
2329  }
2330 
2331  // ********************************************************* Step 13: finished
2332 
2334  uiInterface.InitMessage(_("Done loading"));
2335 
2337 
2338  return true;
2339 }
void Stop() override
Stop Wallets.
Definition: init.cpp:111
CConditionVariable g_best_block_cv
Definition: validation.cpp:220
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: init.cpp:193
void CleanupBlockRevFiles()
Definition: init.cpp:738
void RandomInit()
Initialize the RNG.
Definition: random.cpp:487
static const int MAX_OUTBOUND_CONNECTIONS
Maximum number of automatic outgoing nodes.
Definition: net.h:70
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:66
CTxMemPool mempool
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
Definition: util.cpp:884
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:85
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:76
bool(* handler)(HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:575
void ECC_Start()
Initialize the elliptic curve support.
Definition: key.cpp:323
unsigned short GetPort() const
Definition: netaddress.cpp:512
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Creates and returns a std::unique_ptr<CBaseChainParams> of the chosen chain.
void AppendParamsHelpMessages(std::string &strUsage, bool debugHelp)
Append the help messages for the chainparams options to the parameter string.
std::string ListLogCategories()
Returns a string with the log categories.
Definition: util.cpp:322
bool IsHexNumber(const std::string &str)
Return true if the string is a hex number, optionally prefixed with "0x".
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: util.cpp:784
bool SetupNetworking()
Definition: util.cpp:1343
int nScriptCheckThreads
Definition: validation.cpp:222
static bool FlushStateToDisk(const CChainParams &chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Update the on-disk chain state.
CMasternodeSync masternodeSync
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:68
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:230
CPrivateSendServer privateSendServer
virtual void RegisterRPC(CRPCTable &)=0
Register wallet RPC.
std::condition_variable CConditionVariable
Just a typedef for std::condition_variable, can be wrapped later if desired.
Definition: sync.h:106
bool DumpMempool(void)
Dump the mempool to disk.
ServiceFlags
nServices flags
Definition: protocol.h:280
static const uint64_t MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
Definition: net.h:90
static const bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
Definition: validation.h:119
bool StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:430
void UnloadBlockIndex()
Unload database information.
bool fAddressIndex
Definition: validation.cpp:226
void RegisterRPC(CRPCTable &) override
Register wallet RPC.
Definition: init.cpp:106
void UpdateLLMQTestParams(int size, int threshold)
Allows modifying parameters of the test LLMQ.
Dash RPC command dispatcher.
Definition: server.h:140
void InitLogging()
Initialize the logging infrastructure.
Definition: init.cpp:1024
static CConditionVariable condvar_GenesisWait
Definition: init.cpp:705
Definition: evodb.h:32
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:236
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:5
static const int DEFAULT_HTTP_SERVER_TIMEOUT
Definition: httpserver.h:14
#define TRY_LOCK(cs, name)
Definition: sync.h:180
const char *const BITCOIN_CONF_FILENAME
Definition: util.cpp:104
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
Definition: standard.h:34
static constexpr bool DEFAULT_ENABLE_BIP61
Default for BIP61 (sending reject messages)
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: util.cpp:840
static const std::string REGTEST
A UTXO entry.
Definition: coins.h:29
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:395
bool AppInitMain()
Dash Core main initialization.
Definition: init.cpp:1586
HelpMessageMode
The help message mode determines what help message to show.
Definition: init.h:66
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:16
void StartLLMQSystem()
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:94
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:30
const char *const BITCOIN_PID_FILENAME
Definition: util.cpp:105
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
static const CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: validation.h:58
bool ShutdownRequested()
Definition: init.cpp:179
#define strprintf
Definition: tinyformat.h:1066
void SetBuf(const void *buf, size_t size)
Definition: bls.h:99
static const int DEFAULT_HTTP_WORKQUEUE
Definition: httpserver.h:13
static void RegisterAllCoreRPCCommands(CRPCTable &t)
Definition: register.h:33
WalletInitInterface *const g_wallet_init_interface
Definition: init.cpp:122
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:229
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:114
~CImportingNow()
Definition: init.cpp:725
std::atomic< bool > fRequestShutdown(false)
bool ParameterInteraction() override
Check wallet parameter interaction.
Definition: init.cpp:105
BlockMap & mapBlockIndex
Definition: validation.cpp:215
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
Definition: init.cpp:395
static const bool DEFAULT_ACCEPT_DATACARRIER
Definition: standard.h:16
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:93
bool Write(CAutoFile &fileout) const
Write estimation data to a file.
Definition: fees.cpp:898
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be prun...
Definition: validation.h:207
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:64
void UpdateLLMQDevnetParams(int size, int threshold)
Allows modifying parameters of the devnet LLMQ.
std::string GetHelpString(bool showDebug) override
Get wallet help string.
Definition: init.cpp:104
static const bool DEFAULT_DISABLE_SAFEMODE
Definition: safemode.h:8
void WarnForSectionOnlyArgs()
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition: util.cpp:697
int Height() const
Return the maximal height in the chain.
Definition: chain.h:484
void StartShutdown()
Definition: init.cpp:171
void SetMockTime(int64_t nMockTimeIn)
For testing.
Definition: utiltime.cpp:46
bool StartHTTPRPC()
Start HTTP RPC subsystem.
Definition: httprpc.cpp:231
CCriticalSection cs_main
Definition: validation.cpp:213
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
Definition: standard.cpp:16
void StopTorControl()
Definition: torcontrol.cpp:768
bool Verify() override
Verify wallets.
Definition: init.cpp:107
bool fAllowPrivateNet
Definition: netaddress.cpp:18
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:598
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
Definition: versionbits.cpp:8
bool fTimestampIndex
Definition: validation.cpp:227
void OnStopped(std::function< void()> slot)
Definition: server.cpp:49
static const unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or BIP...
Definition: policy.h:32
void SetLimited(enum Network net, bool fLimited)
Make a particular network entirely off-limits (no automatic connects to it)
Definition: net.cpp:276
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:76
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:72
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
void Interrupt()
Interrupt threads.
Definition: init.cpp:215
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:244
static const int64_t nMaxBlockDBAndTxIndexCache
Max memory allocated to block tree DB specific cache, if -txindex (MiB)
Definition: txdb.h:41
std::unique_ptr< CEvoDB > evoDb
Definition: evodb.cpp:7
void InterruptRPC()
Definition: server.cpp:375
void OnRPCStarted()
Definition: init.cpp:424
bool fDiscover
Definition: net.cpp:112
virtual void Close()=0
Close wallets.
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
Definition: chainparams.h:61
void InitLLMQSystem(CEvoDB &evoDb, bool unitTests, bool fWipe)
void scheduleEvery(Function f, int64_t deltaMilliSeconds)
Definition: scheduler.cpp:126
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
static std::unique_ptr< ECCVerifyHandle > globalVerifyHandle
Definition: init.cpp:210
CChainParams defines various tweakable parameters of a given instance of the Dash system...
Definition: chainparams.h:41
void UnregisterAllValidationInterfaces()
Unregister all wallets from core.
uint32_t nTime
Definition: chain.h:212
std::shared_ptr< const CDeterministicMN > CDeterministicMNCPtr
static std::string ResolveErrMsg(const char *const optname, const std::string &strBind)
Definition: init.cpp:1019
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:824
unsigned short GetListenPort()
Definition: net.cpp:126
static const int64_t nMinDbCache
min. -dbcache (MiB)
Definition: txdb.h:35
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
Definition: sha256.cpp:573
static void DoMaintenance(CConnman &connman)
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:248
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: util.cpp:848
static void HandleSIGHUP(int)
Definition: init.cpp:400
bool AppInitServers()
Definition: init.cpp:905
bool AppInitBasicSetup()
Initialize Dash Core: Basic context setup.
Definition: init.cpp:1059
static boost::thread_group threadGroup
Definition: init.cpp:212
virtual void Flush()=0
Flush Wallets.
static CScheduler scheduler
Definition: init.cpp:213
void ThreadImport(std::vector< fs::path > vImportFiles)
Definition: init.cpp:773
void Start(CScheduler &scheduler) override
Start wallets.
Definition: init.cpp:109
std::string LicenseInfo()
Returns licensing information (for -version)
Definition: init.cpp:669
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:443
uint64_t nPruneTarget
Number of MiB of block files that we&#39;re trying to stay below.
Definition: validation.cpp:237
bool SetNameProxy(const proxyType &addrProxy)
Definition: netbase.cpp:565
void PrepareShutdown()
Preparing steps before shutting down or restarting the wallet.
Definition: init.cpp:228
static const bool DEFAULT_LOGTIMEMICROS
Definition: util.h:59
std::unique_ptr< CDeterministicMNManager > deterministicMNManager
void RenameThread(const char *name)
Definition: util.cpp:1244
int nHighSubsidyFactor
Definition: params.h:187
bool InitAutoBackup() override
Definition: init.cpp:118
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: util.cpp:477
bool IsNull() const
Definition: uint256.h:33
const std::vector< std::string > & SporkAddresses() const
Definition: chainparams.h:96
bool fIsBareMultisigStd
Definition: validation.cpp:231
static const bool DEFAULT_STOPAFTERBLOCKIMPORT
Definition: init.cpp:94
static const bool DEFAULT_ADDRESSINDEX
Definition: validation.h:123
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Find the best known block, and make it the tip of the block chain.
std::string HelpMessage(HelpMessageMode mode)
Help for options shared between UI and daemon (for -help)
Definition: init.cpp:449
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:455
bool StartREST()
Start HTTP REST subsystem.
Definition: rest.cpp:587
static const bool DEFAULT_LOGTIMESTAMPS
Definition: util.h:61
arith_uint256 UintToArith256(const uint256 &a)
void MapPort(bool)
Definition: net.cpp:2065
void OnRPCStopped()
Definition: init.cpp:429
static CWaitableCriticalSection cs_GenesisWait
Definition: init.cpp:704
std::string CopyrightHolders(const std::string &strPrefix, unsigned int nStartYear, unsigned int nEndYear)
Definition: util.cpp:1364
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: init.cpp:192
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
void Flush() override
Flush Wallets.
Definition: init.cpp:110
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: util.cpp:1128
bool IsValid() const
Definition: netaddress.cpp:191
bool SetSporkAddress(const std::string &strAddress)
SetSporkAddress is used to set a public key ID which will be used to verify spork signatures...
Definition: spork.cpp:269
CMasternodeMetaMan mmetaman
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:300
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
bool fSpentIndex
Definition: validation.cpp:228
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:923
uint256 GetBlockHash() const
Definition: chain.h:292
void SetRPCWarmupFinished()
Definition: server.cpp:401
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyBlockTip
New block has been accepted.
Definition: ui_interface.h:105
CGovernanceManager governance
Definition: governance.cpp:23
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:249
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:95
bool ParseInt64(const std::string &str, int64_t *out)
Convert string to signed 64-bit integer with strict parse error feedback.
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: utiltime.cpp:22
bool fMasternodeMode
Definition: util.cpp:93
LLMQType
Definition: params.h:48
bool GetUTXOCoin(const COutPoint &outpoint, Coin &coin)
Definition: validation.cpp:439
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:128
int nMinimumDifficultyBlocks
these parameters are only used on devnet and can be configured from the outside
Definition: params.h:185
bool glibc_sanity_test()
CRPCTable tableRPC
Definition: server.cpp:616
void setSanityCheck(double dFrequency=1.0)
Definition: txmempool.h:552
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:355
static const bool DEFAULT_LOGIPS
Definition: util.h:60
Users of this module must hold an ECCVerifyHandle.
Definition: pubkey.h:248
bool fCheckpointsEnabled
Definition: validation.cpp:235
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:138
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1553
bool ReplayBlocks(const CChainParams &params, CCoinsView *view)
Replay blocks that aren&#39;t fully applied to the database.
bool fRelayTxes
Definition: net.cpp:114
enum Network ParseNetwork(std::string net)
Definition: netbase.cpp:42
#define LogPrintf(...)
Definition: util.h:203
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
static CZMQNotificationInterface * Create()
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: validation.h:52
static void InitStandardDenominations()
CActiveMasternodeInfo activeMasternodeInfo
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:31
static const bool DEFAULT_ALLOWPRIVATENET
Definition: netbase.h:27
bool MineBlocksOnDemand() const
Make miner stop after a block is found.
Definition: chainparams.h:68
Access to the block database (blocks/index/)
Definition: txdb.h:114
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:454
Abstract view on the open txout dataset.
Definition: coins.h:145
bool ParseInt32(const std::string &str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:246
std::unique_ptr< CChainParams > CreateChainParams(const std::string &chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
DeploymentPos
Definition: params.h:15
bool GetLogCategory(uint64_t *f, const std::string *str)
Return true if str parses as a log category and set the flags in f.
Definition: util.cpp:291
std::string ToString() const
Definition: bls.h:210
std::atomic< uint64_t > logCategories
#define LOCK(cs)
Definition: sync.h:178
virtual void InitKeePass()=0
const char * name
Definition: rest.cpp:36
fs::path GetPidFile()
Definition: util.cpp:1053
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition: key.cpp:340
std::unique_ptr< CCoinsViewDB > pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
Definition: validation.cpp:299
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
If possible, ask the user a question.
Definition: ui_interface.h:79
bool fLogTimeMicros
Definition: util.cpp:113
CImportingNow()
Definition: init.cpp:720
static const unsigned int DEFAULT_BYTES_PER_SIGOP
Definition: validation.h:120
static const unsigned int DEFAULT_BLOCK_MIN_TX_FEE
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
Definition: policy.h:22
void FlushUnconfirmed(CTxMemPool &pool)
Empty mempool transactions on shutdown to record failure to confirm for txs still in mempool...
Definition: fees.cpp:983
static const bool DEFAULT_TESTSAFEMODE
Definition: warnings.h:25
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:143
uint256 uint256S(const char *str)
Definition: uint256.h:143
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:426
bool Load(T &objToLoad)
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:56
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:70
void RegisterWithMempoolSignals(CTxMemPool &pool)
Register with mempool to call TransactionRemovedFromMempool callbacks.
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:72
std::function< void(void)> Function
Definition: scheduler.h:43
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:141
void InitSignatureCache()
Definition: sigcache.cpp:73
void Shutdown()
Shutdown is split into 2 parts: Part 1: shut down everything but the main wallet instance (done in Pr...
Definition: init.cpp:375
CMainSignals & GetMainSignals()
static const int64_t nDefaultDbCache
-dbcache default (MiB)
Definition: txdb.h:29
Network
Definition: netaddress.h:21
void serviceQueue()
Definition: scheduler.cpp:33
void UnregisterWithMempoolSignals(CTxMemPool &pool)
Unregister with mempool.
bool ParseMoney(const std::string &str, CAmount &nRet)
void AutoLockMasternodeCollaterals() override
Definition: init.cpp:115
Definition: net.h:136
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:86
static const unsigned int DEFAULT_BLOCK_MAX_SIZE
Default for -blockmaxsize, which controls the maximum size of block the mining code will create...
Definition: policy.h:20
virtual void Start(CScheduler &scheduler)=0
Start wallets.
std::atomic_bool fImporting
static const int64_t nDefaultDbBatchSize
-dbbatchsize default (bytes)
Definition: txdb.h:31
BIP-0014 subset.
static const std::string DEVNET
void ThreadScriptCheck()
Run an instance of the script checking thread.
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
static const bool DEFAULT_SYNC_MEMPOOL
Default for -syncmempool.
Definition: validation.h:130
bool RequireRoutableExternalIP() const
Require addresses specified with "-externalip" parameter to be routable.
Definition: chainparams.h:65
const std::string CLIENT_NAME
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:118
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:26
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:356
static const bool DEFAULT_LOGTHREADNAMES
Definition: util.h:62
void DoMaintenance(CConnman &connman)
bool fTxIndex
Definition: validation.cpp:225
bool RenameOver(fs::path src, fs::path dest)
Definition: util.cpp:1069
std::string GetSupportedSocketEventsStr()
Definition: init.cpp:437
void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout, int64_t nWindowSize, int64_t nThresholdStart, int64_t nThresholdMin, int64_t nFalloffCoeff)
Allows modifying the Version Bits regtest parameters.
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
int nConnectTimeout
Definition: netbase.cpp:35
std::map< LLMQType, LLMQParams > llmqs
Definition: params.h:189
static const bool DEFAULT_PROXYRANDOMIZE
Definition: init.cpp:92
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download...
Definition: validation.cpp:238
void ForceRemoveArg(const std::string &strArg)
Definition: util.cpp:854
std::string FormatFullVersion()
#define DEFAULT_SOCKETEVENTS
Definition: net.h:106
fs::path GetDefaultDataDir()
Definition: util.cpp:898
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:243
static const int64_t nMaxBlockDBCache
Max memory allocated to block tree DB specific cache, if no -txindex (MiB)
Definition: txdb.h:37
void DoMaintenance(CConnman &connman)
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:618
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:547
bool fLogTimestamps
Definition: util.cpp:112
std::atomic< bool > fDumpMempoolLater(false)
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
bool LoadBlockIndex(const CChainParams &chainparams)
Load the block tree and coins database from disk, initializing state if we&#39;re running with -reindex...
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:253
void InitKeePass() override
Definition: init.cpp:117
bool AppInitParameterInteraction()
Initialization: parameter interaction.
Definition: init.cpp:1109
CSporkManager sporkManager
Definition: spork.cpp:29
#define LogPrint(category,...)
Definition: util.h:214
std::atomic_bool fReindex
bool fLogIPs
Definition: util.cpp:115
bool IsValid() const
Definition: netaddress.cpp:711
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once) ...
Capture information about block/transaction validation.
Definition: validation.h:22
bool glibcxx_sanity_test()
bool fCheckBlockIndex
Definition: validation.cpp:234
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
Definition: init.cpp:691
std::string GetDevNetName() const
Looks for -devnet and returns either "devnet-<name>" or simply "devnet" if no name was specified...
Definition: util.cpp:1045
bool fFeeEstimatesInitialized
Definition: init.cpp:91
ArgsManager gArgs
Definition: util.cpp:108
uint256 nMinimumChainWork
Definition: params.h:181
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
Definition: chainparams.h:63
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:121
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:513
void StopRPC()
Definition: server.cpp:382
bool InitError(const std::string &str)
Show error message.
bool IsValid() const
Definition: netbase.h:35
bool fPrintToConsole
Definition: util.cpp:109
std::atomic< bool > fReopenDebugLog
uint256 defaultAssumeValid
Definition: params.h:182
bool fRequireStandard
Definition: validation.cpp:232
Template mixin that adds -Wthread-safety locking annotations to a subset of the mutex API...
Definition: sync.h:54
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:96
void UpdateDevnetLLMQChainLocks(Consensus::LLMQType llmqType)
Allows modifying the LLMQ type for ChainLocks.
void UpdateBudgetParameters(int nMasternodePaymentsStartBlock, int nBudgetPaymentsStartBlock, int nSuperblockStartBlock)
Allows modifying the budget regtest parameters.
static void new_handler_terminate()
Definition: init.cpp:1046
static const uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:88
void StopLLMQSystem()
Generic Dumping and Loading
Definition: flat-database.h:21
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
const CChainParams & Params()
Return the currently selected parameters.
fs::path GetConfigFile(const std::string &confPath)
Definition: util.cpp:976
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
void UpdateDIP3Parameters(int nActivationHeight, int nEnforcementHeight)
Allows modifying the DIP3 activation and enforcement height.
static const char * FEE_ESTIMATES_FILENAME
Definition: init.cpp:140
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:211
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:71
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: utiltime.cpp:56
static const int64_t nMaxCoinsDBCache
Max memory allocated to coin DB specific cache (MiB)
Definition: txdb.h:43
void InitScriptExecutionCache()
Initializes the script-execution cache.
virtual std::string GetHelpString(bool showDebug)=0
Get wallet help string.
static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of orphan+recently-replaced txn to keep around for block reconstruction.
static const unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition: net.h:99
static const unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
Definition: policy.h:38
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:808
virtual bool Verify()=0
Verify wallets.
bool fPrintToDebugLog
Definition: util.cpp:110
bool Dump(T &objToSave)
bool Open() override
Open wallets.
Definition: init.cpp:108
bool Read(CAutoFile &filein)
Read estimation data from a file.
Definition: fees.cpp:923
ServiceFlags nLocalServices
Definition: net.h:156
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:594
void StartRestart()
Definition: init.cpp:175
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
void runCommand(const std::string &strCommand)
Definition: util.cpp:1236
bool LoadMempool(void)
Load the mempool from disk.
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:140
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:23
void StartTorControl(boost::thread_group &threadGroup, CScheduler &scheduler)
Definition: torcontrol.cpp:743
static const int64_t nMaxDbCache
max. -dbcache (MiB)
Definition: txdb.h:33
static const bool DEFAULT_TIMESTAMPINDEX
Definition: validation.h:124
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:453
std::string FormatSubVersion(const std::string &name, int nClientVersion, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip...
CNetFulfilledRequestManager netfulfilledman
std::string GetHex() const
Definition: uint256.cpp:21
CBLSPublicKey GetPublicKey() const
Definition: bls.cpp:147
const char *const DEFAULT_DEBUGLOGFILE
Definition: util.cpp:106
static const bool DEFAULT_WATCH_QUORUMS
Definition: quorums_init.h:15
bool fListen
Definition: net.cpp:113
bool RPCIsInWarmup(std::string *outStatus)
Definition: server.cpp:408
void InterruptLLMQSystem()
void Close() override
Close wallets.
Definition: init.cpp:112
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:97
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:301
void Discover(boost::thread_group &threadGroup)
Definition: net.cpp:2835
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of strSubVer in version message.
Definition: net.h:68
bool InitSanityCheck(void)
Sanity checks Ensure that Dash Core is running in a usable environment with all necessary library sup...
Definition: init.cpp:883
static CDSNotificationInterface * pdsNotificationInterface
Definition: init.cpp:129
static const bool DEFAULT_UPNP
-upnp default
Definition: net.h:81
std::unique_ptr< PeerLogicValidation > peerLogic
Definition: init.cpp:98
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: ui_interface.h:76
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:92
static const std::string TESTNET
virtual bool ParameterInteraction()=0
Check wallet parameter interaction.
void RPCNotifyBlockChange(bool ibd, const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:252
std::unique_ptr< CBLSPublicKey > blsPubKeyOperator
static const unsigned int DEFAULT_BANSCORE_THRESHOLD
Definition: validation.h:126
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:928
void CreatePidFile(const fs::path &path, pid_t pid)
Definition: util.cpp:1058
virtual void InitPrivateSendSettings()=0
void InterruptTorControl()
Definition: torcontrol.cpp:760
static const bool DEFAULT_SPENTINDEX
Definition: validation.h:125
virtual bool InitAutoBackup()=0
static DummyWalletInit g_dummy_wallet_init
Definition: init.cpp:121
bool StartRPC()
Definition: server.cpp:367
void OnStarted(std::function< void()> slot)
Definition: server.cpp:44
std::string GetHex() const
bool AppInitLockDataDirectory()
Lock Dash Core data directory.
Definition: init.cpp:1574
bool fLogThreadNames
Definition: util.cpp:114
std::string ToString() const
Definition: feerate.cpp:40
void InitWarning(const std::string &str)
Show warning message.
uint256 hashDevnetGenesisBlock
Definition: params.h:132
CClientUIInterface uiInterface
Definition: ui_interface.cpp:8
static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
Definition: init.cpp:707
unsigned int nBytesPerSigOp
Definition: validation.cpp:233
virtual void AutoLockMasternodeCollaterals()=0
CCoinsView backed by another CCoinsView.
Definition: coins.h:182
int GetNumCores()
Return the number of physical cores available on the current system.
Definition: util.cpp:1355
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:316
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:54
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:24
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:201
void PruneAndFlush()
Prune block files and flush state to disk.
static void registerSignalHandler(int signal, void(*handler)(int))
Definition: init.cpp:414
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:222
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: util.cpp:765
bool OpenDebugLog()
Definition: util.cpp:214
bool fDisableGovernance
Definition: util.cpp:94
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:217
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:137
std::unique_lock< std::mutex > WaitableLock
Just a typedef for std::unique_lock, can be wrapped later if desired.
Definition: sync.h:109
std::string AmountErrMsg(const char *const optname, const std::string &strValue)
fs::path GetDebugLogPath()
Definition: util.cpp:208
bool SetMinSporkKeys(int minSporkKeys)
SetMinSporkKeys is used to set the required spork signer threshold, for a spork to be considered acti...
Definition: spork.cpp:281
bool SetPrivKey(const std::string &strPrivKey)
SetPrivKey is used to set a spork key to enable setting / signing of spork values.
Definition: spork.cpp:292
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: validation.h:54
void Init(const CBlockIndex *pindex)
static const int CLIENT_VERSION
dashd-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
static const bool DEFAULT_LISTEN_ONION
Definition: torcontrol.h:14
fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
Definition: init.cpp:189
void UpdateDevnetSubsidyAndDiffParams(int nMinimumDifficultyBlocks, int nHighSubsidyBlocks, int nHighSubsidyFactor)
Allows modifying the subsidy and difficulty devnet parameters.
std::unique_ptr< CBLSSecretKey > blsKeyOperator
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:434
CFeeRate incrementalRelayFee
Definition: policy.cpp:176
std::atomic< bool > fRequestRestart(false)
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: util.cpp:880
static const bool DEFAULT_TXINDEX
Definition: validation.h:122
bool IsValid() const
Definition: bls.h:94
static const int DEFAULT_HTTP_THREADS
Definition: httpserver.h:12
static const bool DEFAULT_REST_ENABLE
Definition: init.cpp:93
bool g_enable_bip61
Enable BIP61 (sending reject messages)
unsigned nMaxDatacarrierBytes
Maximum size of TX_NULL_DATA scripts that this node considers standard.
Definition: standard.cpp:17
static std::unique_ptr< CCoinsViewErrorCatcher > pcoinscatcher
Definition: init.cpp:209
bool fNameLookup
Definition: netbase.cpp:36
bool LoadChainTip(const CChainParams &chainparams)
Update the chain tip based on database information.
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS_SIZE
Default for -maxorphantxsize, maximum size in megabytes the orphan map can grow before entries are re...
uint256 hashGenesisBlock
Definition: params.h:131
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
Definition: timedata.h:13
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:212
int nHighSubsidyBlocks
Definition: params.h:186
size_t nCoinCacheUsage
Definition: validation.cpp:236
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:410
void ShrinkDebugFile()
Definition: util.cpp:1193
static bool fRPCInWarmup
Definition: server.cpp:29
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: util.h:92
Wrapped mutex: supports recursive locking, but no waiting TODO: We should move away from using the re...
Definition: sync.h:94
int atoi(const std::string &str)
boost::signals2::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
Definition: ui_interface.h:82
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of script-checking threads allowed.
Definition: validation.h:83
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:354
static bool LockDataDirectory(bool probeOnly)
Definition: init.cpp:1543
static bool fHaveGenesis
Definition: init.cpp:703
void DestroyLLMQSystem()
CActiveMasternodeManager * activeMasternodeManager
void InitPrivateSendSettings() override
Definition: init.cpp:116
std::vector< unsigned char > ParseHex(const char *psz)
virtual void Stop()=0
Stop Wallets.
void DoMaintenance(CConnman &connman)
Definition: governance.cpp:547
CFeeRate dustRelayFee
Definition: policy.cpp:177
virtual bool Open()=0
Open wallets.
bool BLSInit()
Definition: bls.cpp:466
Released under the MIT license