Raven Core  3.0.0
P2P Digital Currency
init.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Raven 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/raven-config.h"
9 #endif
10 
11 #include "init.h"
12 
13 #include "addrman.h"
14 #include "amount.h"
15 #include "chain.h"
16 #include "chainparams.h"
17 #include "checkpoints.h"
18 #include "compat/sanity.h"
19 #include "consensus/validation.h"
20 #include "fs.h"
21 #include "httpserver.h"
22 #include "httprpc.h"
23 #include "key.h"
24 #include "validation.h"
25 #include "miner.h"
26 #include "netbase.h"
27 #include "net.h"
28 #include "net_processing.h"
29 #include "policy/feerate.h"
30 #include "policy/fees.h"
31 #include "policy/policy.h"
32 #include "rpc/server.h"
33 #include "rpc/register.h"
34 #include "rpc/safemode.h"
35 #include "rpc/blockchain.h"
36 #include "rpc/mining.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 #include "assets/assets.h"
49 #include "assets/assetdb.h"
50 #ifdef ENABLE_WALLET
51 #include "wallet/init.h"
52 #include <wallet/wallet.h>
53 #endif
54 #include "warnings.h"
55 #include "tinyformat.h"
56 #include <stdint.h>
57 #include <stdio.h>
58 #include <memory>
59 
60 #ifndef WIN32
61 #include <signal.h>
62 #endif
63 
64 #include <boost/algorithm/string/classification.hpp>
65 #include <boost/algorithm/string/replace.hpp>
66 #include <boost/algorithm/string/split.hpp>
67 #include <boost/bind.hpp>
68 #include <boost/interprocess/sync/file_lock.hpp>
69 #include <boost/thread.hpp>
70 #include <openssl/crypto.h>
71 
72 #if ENABLE_ZMQ
74 #endif
75 
77 static const bool DEFAULT_PROXYRANDOMIZE = true;
78 static const bool DEFAULT_REST_ENABLE = false;
79 static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
80 
81 std::unique_ptr<CConnman> g_connman;
82 std::unique_ptr<PeerLogicValidation> peerLogic;
83 
84 #if ENABLE_ZMQ
85 static CZMQNotificationInterface* pzmqNotificationInterface = nullptr;
86 #endif
87 
88 #ifdef WIN32
89 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
90 // accessing block files don't count towards the fd_set size limit
91 // anyway.
92 #define MIN_CORE_FILEDESCRIPTORS 0
93 #else
94 #define MIN_CORE_FILEDESCRIPTORS 150
95 #endif
96 
97 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
98 
100 //
101 // Shutdown
102 //
103 
104 //
105 // Thread management and startup/shutdown:
106 //
107 // The network-processing threads are all part of a thread group
108 // created by AppInit() or the Qt main() function.
109 //
110 // A clean exit happens when StartShutdown() or the SIGTERM
111 // signal handler sets fRequestShutdown, which makes main thread's
112 // WaitForShutdown() interrupts the thread group.
113 // And then, WaitForShutdown() makes all other on-going threads
114 // in the thread group join the main thread.
115 // Shutdown() is then called to clean up database connections, and stop other
116 // threads that should only be stopped after the main network-processing
117 // threads have exited.
118 //
119 // Shutdown for Qt is very similar, only it uses a QTimer to detect
120 // fRequestShutdown getting set, and then does the normal Qt
121 // shutdown thing.
122 //
123 
124 std::atomic<bool> fRequestShutdown(false);
125 std::atomic<bool> fRequestRestart(false);
126 std::atomic<bool> fDumpMempoolLater(false);
127 
129 {
130  fRequestShutdown = true;
131 }
133 {
135 }
137 {
138  return fRequestShutdown;
139 }
140 
147 {
148 public:
150  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override {
151  try {
152  return CCoinsViewBacked::GetCoin(outpoint, coin);
153  } catch(const std::runtime_error& e) {
154  uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
155  LogPrintf("Error reading from database: %s\n", e.what());
156  // Starting the shutdown sequence and returning false to the caller would be
157  // interpreted as 'entry not found' (as opposed to unable to read data), and
158  // could lead to invalid interpretation. Just exit immediately, as we can't
159  // continue anyway, and all writes should be atomic.
160  abort();
161  }
162  }
163  // Writes do not need similar protection, as failure to write is handled by the caller.
164 };
165 
166 static CCoinsViewErrorCatcher *pcoinscatcher = nullptr;
167 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
168 
169 void Interrupt(boost::thread_group& threadGroup)
170 {
173  InterruptRPC();
174  InterruptREST();
176  if (g_connman)
177  g_connman->Interrupt();
178  threadGroup.interrupt_all();
179 }
180 
183 {
184  LogPrintf("%s: In progress...\n", __func__);
185  static CCriticalSection cs_Shutdown;
186  TRY_LOCK(cs_Shutdown, lockShutdown);
187  if (!lockShutdown)
188  return;
189 
194  RenameThread("raven-shutoff");
196 
197  StopHTTPRPC();
198  StopREST();
199  StopRPC();
200  StopHTTPServer();
201 #ifdef ENABLE_WALLET
202  FlushWallets();
203 #endif
204  GenerateRavens(false, 0, Params());
205 
206  MapPort(false);
207 
208  // Because these depend on each-other, we make sure that neither can be
209  // using the other before destroying them.
211  if(g_connman) g_connman->Stop();
212  peerLogic.reset();
213  g_connman.reset();
214 
215  if (fDumpMempoolLater && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
216  DumpMempool();
217  }
218 
220  {
222  fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
223  CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
224  if (!est_fileout.IsNull())
225  ::feeEstimator.Write(est_fileout);
226  else
227  LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
228  fFeeEstimatesInitialized = false;
229  }
230 
231  // FlushStateToDisk generates a SetBestChain callback, which we should avoid missing
232  if (pcoinsTip != nullptr) {
234  }
235 
236  // After there are no more peers/RPC left to give us new data which may generate
237  // CValidationInterface callbacks, flush them...
239 
240  // Any future callbacks will be dropped. This should absolutely be safe - if
241  // missing a callback results in an unrecoverable situation, unclean shutdown
242  // would too. The only reason to do the above flushes is to let the wallet catch
243  // up with our current chain to avoid any strange pruning edge cases and make
244  // next startup faster by avoiding rescan.
245 
246  {
247  LOCK(cs_main);
248  if (pcoinsTip != nullptr) {
250  }
251  delete pcoinsTip;
252  pcoinsTip = nullptr;
253 
254  delete pcoinscatcher;
255  pcoinscatcher = nullptr;
256 
257  delete pcoinsdbview;
258  pcoinsdbview = nullptr;
259 
260  delete pblocktree;
261  pblocktree = nullptr;
262 
264  delete passets;
265  passets = nullptr;
266 
267  delete passetsdb;
268  passetsdb = nullptr;
269 
270  delete passetsCache;
271  passetsCache = nullptr;
272 
273  delete pMessagesCache;
274  pMessagesCache = nullptr;
275 
278 
280  pMessagesSeenAddressCache = nullptr;
281 
282  delete pmessagechanneldb;
283  pmessagechanneldb = nullptr;
284 
285  delete pmessagedb;
286  pmessagedb = nullptr;
287 
288  delete passetsVerifierCache;
289  passetsVerifierCache = nullptr;
290 
291  delete passetsQualifierCache;
292  passetsQualifierCache = nullptr;
293 
295  passetsRestrictionCache = nullptr;
296 
299 
300  delete prestricteddb;
301  prestricteddb = nullptr;
303  }
304 #ifdef ENABLE_WALLET
305  StopWallets();
306 #endif
307 
308 #if ENABLE_ZMQ
309  if (pzmqNotificationInterface) {
310  UnregisterValidationInterface(pzmqNotificationInterface);
311  delete pzmqNotificationInterface;
312  pzmqNotificationInterface = nullptr;
313  }
314 #endif
315 
316 #ifndef WIN32
317  try {
318  fs::remove(GetPidFile());
319  } catch (const fs::filesystem_error& e) {
320  LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
321  }
322 #endif
325 }
326 
336 void Shutdown()
337 {
338  // Shutdown part 1: prepare shutdown
339  if(!fRequestRestart) {
340  PrepareShutdown();
341  }
342  // Shutdown part 2: Stop TOR thread and close wallets
343  StopTorControl();
344  #ifdef ENABLE_WALLET
345  CloseWallets();
346  #endif
347  globalVerifyHandle.reset();
348  ECC_Stop();
349  LogPrintf("%s: done\n", __func__);
350 }
351 
357 static void HandleSIGTERM(int)
358 {
359  fRequestShutdown = true;
360 }
361 
362 static void HandleSIGHUP(int)
363 {
364  fReopenDebugLog = true;
365 }
366 
367 #ifndef WIN32
368 static void registerSignalHandler(int signal, void(*handler)(int))
369 {
370  struct sigaction sa;
371  sa.sa_handler = handler;
372  sigemptyset(&sa.sa_mask);
373  sa.sa_flags = 0;
374  sigaction(signal, &sa, nullptr);
375 }
376 #endif
377 
379 {
381 }
382 
384 {
386  RPCNotifyBlockChange(false, nullptr);
387  cvBlockChange.notify_all();
388  LogPrint(BCLog::RPC, "RPC stopped.\n");
389 }
390 
391 std::string HelpMessage(HelpMessageMode mode)
392 {
393  const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
394  const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
395  const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
396  const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET);
397  const bool showDebug = gArgs.GetBoolArg("-help-debug", false);
398 
399  // When adding new options to the categories, please keep and ensure alphabetical ordering.
400  // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
401  std::string strUsage = HelpMessageGroup(_("Options:"));
402  strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
403  strUsage += HelpMessageOpt("-version", _("Print version and exit"));
404  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)"));
405  strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
406  if (showDebug)
407  strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
408  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()));
409  strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), RAVEN_CONF_FILENAME));
410  if (mode == HMM_RAVEND)
411  {
412 #if HAVE_DECL_DAEMON
413  strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
414 #endif
415  }
416  strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
417  if (showDebug) {
418  strUsage += HelpMessageOpt("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize));
419  }
420  strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
421  strUsage += HelpMessageOpt("-disablemessaging", strprintf(_("Turn off the databasing the messages sent with assets (default: %u)"), false));
422  if (showDebug)
423  strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
424  strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
425  strUsage += HelpMessageOpt("-maxreorg=<n>", strprintf(_("Set the Maximum reorg depth (default: %u)"), defaultChainParams->MaxReorganizationDepth()));
426  strUsage += HelpMessageOpt("-minreorgpeers=<n>", strprintf(_("Set the Minimum amount of peers required to disallow reorg of chains of depth >= maxreorg. Peers must be greater than. (default: %u)"), defaultChainParams->MinReorganizationPeers()));
427  strUsage += HelpMessageOpt("-minreorgage=<n>", strprintf(_("Set the Minimum tip age (in seconds) required to allow reorg of a chain of depth >= maxreorg on a node with more than minreorgpeers peers. (default: %u)"), defaultChainParams->MinReorganizationAge()));
428  strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
429  strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
430  strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
431  if (showDebug) {
432  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()));
433  }
434  strUsage += HelpMessageOpt("-persistmempool", strprintf(_("Whether to save the mempool on shutdown and load on restart (default: %u)"), DEFAULT_PERSIST_MEMPOOL));
435  strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
436  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)"),
437  -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
438 #ifndef WIN32
439  strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), RAVEN_PID_FILENAME));
440 #endif
441  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 and -rescan. "
442  "Warning: Reverting this setting requires re-downloading the entire blockchain. "
443  "(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));
444  strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
445  strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
446 #ifndef WIN32
447  strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
448 #endif
449  strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
450 
451  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));
452  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));
453  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));
454 
455  strUsage += HelpMessageGroup(_("Connection options:"));
456  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)"));
457  strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
458  strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
459  strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
460  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)"));
461  strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
462  strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
463  strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)"));
464  strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
465  strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
466  strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
467  strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
468  strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
469  strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
470  strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
471  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));
472  strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
473  strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
474  strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
475  strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
476  strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort()));
477  strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
478  strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
479  strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
480  strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
481  strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
482  strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
483 #ifdef USE_UPNP
484 #if USE_UPNP
485  strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
486 #else
487  strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
488 #endif
489 #endif
490  strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
491  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.") +
492  " " + _("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"));
493  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));
494 
495 #ifdef ENABLE_WALLET
496  strUsage += GetWalletHelpString(showDebug);
497 #endif
498 
499 #if ENABLE_ZMQ
500  strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
501  strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
502  strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
503  strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
504  strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
505  strUsage += HelpMessageOpt("-zmqpubrawmessage=<address>", _("Enable publish raw asset messages in <address>"));
506 #endif
507 
508  strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
509  strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
510  if (showDebug)
511  {
512  strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
513  strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
514  strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
515  strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", defaultChainParams->DefaultConsistencyChecks()));
516  strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
517  strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
518  strUsage += HelpMessageOpt("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used");
519  strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
520  strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
521  strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
522  strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
523  strUsage += HelpMessageOpt("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT));
524 
525  strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
526  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));
527  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));
528  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));
529  strUsage += HelpMessageOpt("-vbparams=deployment:start:end", "Use given start/end times for specified version bits deployment (regtest-only)");
530  }
531  strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
532  _("If <category> is not supplied or if <category> = 1, output all debugging information.") + " " + _("<category> can be:") + " " + ListLogCategories() + ".");
533  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.")));
534  strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
535  strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
536  strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
537  if (showDebug)
538  {
539  strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
540  strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
541  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));
542  strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
543  }
544  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)"),
545  CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
546  strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
547  if (showDebug)
548  {
549  strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
550  }
551  strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
552 
553  AppendParamsHelpMessages(strUsage, showDebug);
554 
555  strUsage += HelpMessageGroup(_("Node relay options:"));
556  if (showDebug) {
557  strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()));
558  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)));
559  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)));
560  }
561  strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
562  strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
563  strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
564  strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
565  strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
566  CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
567  strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
568  strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
569 
570  strUsage += HelpMessageGroup(_("Block creation options:"));
571  strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), MAX_BLOCK_WEIGHT - 4000));
572  strUsage += HelpMessageOpt("-blockmaxsize=<n>", _("Set maximum BIP141 block weight to this * 4. Deprecated, use blockmaxweight"));
573  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)));
574  if (showDebug)
575  strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
576 
577  strUsage += HelpMessageGroup(_("RPC server options:"));
578  strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
579  strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
580  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)"));
581  strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
582  strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
583  strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
584  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"));
585  strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
586  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"));
587  strUsage += HelpMessageOpt("-rpcserialversion", strprintf(_("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)"), DEFAULT_RPC_SERIALIZE_VERSION));
588  strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
589  if (showDebug) {
590  strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
591  strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
592  }
593 
594  return strUsage;
595 }
596 
597 std::string LicenseInfo()
598 {
599  const std::string URL_SOURCE_CODE = "<https://github.com/RavenProject/Ravencoin>";
600  const std::string URL_WEBSITE = "<https://ravencoin.org>";
601 
602  return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" +
603  "\n" +
604  strprintf(_("Please contribute if you find %s useful. "
605  "Visit %s for further information about the software."),
606  PACKAGE_NAME, URL_WEBSITE) +
607  "\n" +
608  strprintf(_("The source code is available from %s."),
609  URL_SOURCE_CODE) +
610  "\n" +
611  "\n" +
612  _("This is experimental software.") + "\n" +
613  strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
614  "\n" +
615  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>") +
616  "\n";
617 }
618 
619 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
620 {
621  if (initialSync || !pBlockIndex)
622  return;
623 
624  std::string strCmd = gArgs.GetArg("-blocknotify", "");
625  if (!strCmd.empty()) {
626  boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
627  boost::thread t(runCommand, strCmd); // thread runs free
628  }
629 }
630 
631 static bool fHaveGenesis = false;
632 static boost::mutex cs_GenesisWait;
633 static CConditionVariable condvar_GenesisWait;
634 
635 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
636 {
637  if (pBlockIndex != nullptr) {
638  {
639  boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
640  fHaveGenesis = true;
641  }
642  condvar_GenesisWait.notify_all();
643  }
644 }
645 
647 {
649  assert(fImporting == false);
650  fImporting = true;
651  }
652 
654  assert(fImporting == true);
655  fImporting = false;
656  }
657 };
658 
659 
660 // If we're using -prune with -reindex, then delete block files that will be ignored by the
661 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
662 // is missing, do the same here to delete any later block files after a gap. Also delete all
663 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
664 // is in sync with what's actually on disk by the time we start downloading, so that pruning
665 // works correctly.
667 {
668  std::map<std::string, fs::path> mapBlockFiles;
669 
670  // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
671  // Remove the rev files immediately and insert the blk file paths into an
672  // ordered map keyed by block file index.
673  LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
674  fs::path blocksdir = GetDataDir() / "blocks";
675  for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
676  if (fs::is_regular_file(*it) &&
677  it->path().filename().string().length() == 12 &&
678  it->path().filename().string().substr(8,4) == ".dat")
679  {
680  if (it->path().filename().string().substr(0,3) == "blk")
681  mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
682  else if (it->path().filename().string().substr(0,3) == "rev")
683  remove(it->path());
684  }
685  }
686 
687  // Remove all block files that aren't part of a contiguous set starting at
688  // zero by walking the ordered map (keys are block file indices) by
689  // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
690  // start removing block files.
691  int nContigCounter = 0;
692  for (const std::pair<std::string, fs::path>& item : mapBlockFiles) {
693  if (atoi(item.first) == nContigCounter) {
694  nContigCounter++;
695  continue;
696  }
697  remove(item.second);
698  }
699 }
700 
701 void ThreadImport(std::vector<fs::path> vImportFiles)
702 {
703  const CChainParams& chainparams = Params();
704  RenameThread("raven-loadblk");
705 
706  {
707  CImportingNow imp;
708 
709  // -reindex
710  if (fReindex) {
711  int nFile = 0;
712  while (true) {
713  CDiskBlockPos pos(nFile, 0);
714  if (!fs::exists(GetBlockPosFilename(pos, "blk")))
715  break; // No block files left to reindex
716  FILE *file = OpenBlockFile(pos, true);
717  if (!file)
718  break; // This error is logged in OpenBlockFile
719  LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
720  LoadExternalBlockFile(chainparams, file, &pos);
721  nFile++;
722  }
723  pblocktree->WriteReindexing(false);
724  fReindex = false;
725  LogPrintf("Reindexing finished\n");
726  // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
727  LoadGenesisBlock(chainparams);
728  }
729 
730  // hardcoded $DATADIR/bootstrap.dat
731  fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
732  if (fs::exists(pathBootstrap)) {
733  FILE *file = fsbridge::fopen(pathBootstrap, "rb");
734  if (file) {
735  fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
736  LogPrintf("Importing bootstrap.dat...\n");
737  LoadExternalBlockFile(chainparams, file);
738  RenameOver(pathBootstrap, pathBootstrapOld);
739  } else {
740  LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
741  }
742  }
743 
744  // -loadblock=
745  for (const fs::path& path : vImportFiles) {
746  FILE *file = fsbridge::fopen(path, "rb");
747  if (file) {
748  LogPrintf("Importing blocks file %s...\n", path.string());
749  LoadExternalBlockFile(chainparams, file);
750  } else {
751  LogPrintf("Warning: Could not open blocks file %s\n", path.string());
752  }
753  }
754 
755  // scan for better chains in the block chain database, that are not yet connected in the active best chain
756  CValidationState state;
757  if (!ActivateBestChain(state, chainparams)) {
758  LogPrintf("Failed to connect best block");
759  StartShutdown();
760  }
761 
762  if (gArgs.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
763  LogPrintf("Stopping after block import\n");
764  StartShutdown();
765  }
766  } // End scope of CImportingNow
767  if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
768  LoadMempool();
770  }
771 }
772 
777 bool InitSanityCheck(void)
778 {
779  if(!ECC_InitSanityCheck()) {
780  InitError("Elliptic curve cryptography sanity check failure. Aborting.");
781  return false;
782  }
783 
785  return false;
786 
787  if (!Random_SanityCheck()) {
788  InitError("OS cryptographic RNG sanity check failure. Aborting.");
789  return false;
790  }
791 
792  return true;
793 }
794 
795 bool AppInitServers(boost::thread_group& threadGroup)
796 {
799  if (!InitHTTPServer())
800  return false;
801  if (!StartRPC())
802  return false;
803  if (!StartHTTPRPC())
804  return false;
805  if (gArgs.GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
806  return false;
807  if (!StartHTTPServer())
808  return false;
809  return true;
810 }
811 
812 // Parameter interaction based on rules
814 {
815  // when specifying an explicit binding address, you want to listen on it
816  // even when -connect or -proxy is specified
817  if (gArgs.IsArgSet("-bind")) {
818  if (gArgs.SoftSetBoolArg("-listen", true))
819  LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
820  }
821  if (gArgs.IsArgSet("-whitebind")) {
822  if (gArgs.SoftSetBoolArg("-listen", true))
823  LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
824  }
825 
826  if (gArgs.IsArgSet("-connect")) {
827  // when only connecting to trusted nodes, do not seed via DNS, or listen by default
828  if (gArgs.SoftSetBoolArg("-dnsseed", false))
829  LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
830  if (gArgs.SoftSetBoolArg("-listen", false))
831  LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
832  }
833 
834  if (gArgs.IsArgSet("-proxy")) {
835  // to protect privacy, do not listen by default if a default proxy server is specified
836  if (gArgs.SoftSetBoolArg("-listen", false))
837  LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
838  // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
839  // to listen locally, so don't rely on this happening through -listen below.
840  if (gArgs.SoftSetBoolArg("-upnp", false))
841  LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
842  // to protect privacy, do not discover addresses by default
843  if (gArgs.SoftSetBoolArg("-discover", false))
844  LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
845  }
846 
847  if (!gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
848  // do not map ports or try to retrieve public IP when not listening (pointless)
849  if (gArgs.SoftSetBoolArg("-upnp", false))
850  LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
851  if (gArgs.SoftSetBoolArg("-discover", false))
852  LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
853  if (gArgs.SoftSetBoolArg("-listenonion", false))
854  LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
855  }
856 
857  if (gArgs.IsArgSet("-externalip")) {
858  // if an explicit public IP is specified, do not try to find others
859  if (gArgs.SoftSetBoolArg("-discover", false))
860  LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
861  }
862 
863  // disable whitelistrelay in blocksonly mode
864  if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
865  if (gArgs.SoftSetBoolArg("-whitelistrelay", false))
866  LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
867  }
868 
869  // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
870  if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
871  if (gArgs.SoftSetBoolArg("-whitelistrelay", true))
872  LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
873  }
874 
875  if (gArgs.IsArgSet("-blockmaxsize")) {
876  unsigned int max_size = gArgs.GetArg("-blockmaxsize", 0);
877  if (gArgs.SoftSetArg("blockmaxweight", strprintf("%d", max_size * WITNESS_SCALE_FACTOR))) {
878  LogPrintf("%s: parameter interaction: -blockmaxsize=%d -> setting -blockmaxweight=%d (-blockmaxsize is deprecated!)\n", __func__, max_size, max_size * WITNESS_SCALE_FACTOR);
879  } else {
880  LogPrintf("%s: Ignoring blockmaxsize setting which is overridden by blockmaxweight", __func__);
881  }
882  }
883 }
884 
885 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
886 {
887  return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
888 }
889 
891 {
892  fPrintToConsole = gArgs.GetBoolArg("-printtoconsole", false);
893  fLogTimestamps = gArgs.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
894  fLogTimeMicros = gArgs.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
895  fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS);
896 
897  LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
898  LogPrintf("Raven version %s\n", FormatFullVersion());
899 }
900 
901 namespace { // Variables internal to initialization process only
902 
903 int nMaxConnections;
904 int nUserMaxConnections;
905 int nFD;
906 ServiceFlags nLocalServices = NODE_NETWORK;
907 
908 } // namespace
909 
910 [[noreturn]] static void new_handler_terminate()
911 {
912  // Rather than throwing std::bad-alloc if allocation fails, terminate
913  // immediately to (try to) avoid chain corruption.
914  // Since LogPrintf may itself allocate memory, set the handler directly
915  // to terminate first.
916  std::set_new_handler(std::terminate);
917  LogPrintf("Error: Out of memory. Terminating.\n");
918 
919  // The log was successful, terminate now.
920  std::terminate();
921 };
922 
924 {
925  // ********************************************************* Step 1: setup
926 #ifdef _MSC_VER
927  // Turn off Microsoft heap dump noise
928  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
929  _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
930  // Disable confusing "helpful" text message on abort, Ctrl-C
931  _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
932 #endif
933 #ifdef WIN32
934  // Enable Data Execution Prevention (DEP)
935  // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
936  // A failure is non-critical and needs no further attention!
937 #ifndef PROCESS_DEP_ENABLE
938  // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
939  // which is not correct. Can be removed, when GCCs winbase.h is fixed!
940 #define PROCESS_DEP_ENABLE 0x00000001
941 #endif
942  typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
943  PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
944  if (setProcDEPPol != nullptr) setProcDEPPol(PROCESS_DEP_ENABLE);
945 #endif
946 
947  if (!SetupNetworking())
948  return InitError("Initializing networking failed");
949 
950 #ifndef WIN32
951  if (!gArgs.GetBoolArg("-sysperms", false)) {
952  umask(077);
953  }
954 
955  // Clean shutdown on SIGTERM
956  registerSignalHandler(SIGTERM, HandleSIGTERM);
957  registerSignalHandler(SIGINT, HandleSIGTERM);
958 
959  // Reopen debug.log on SIGHUP
960  registerSignalHandler(SIGHUP, HandleSIGHUP);
961 
962  // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
963  signal(SIGPIPE, SIG_IGN);
964 #endif
965 
966  std::set_new_handler(new_handler_terminate);
967 
968  return true;
969 }
970 
972 {
973  const CChainParams& chainparams = Params();
974  // ********************************************************* Step 2: parameter interactions
975 
976  // also see: InitParameterInteraction()
977 
978  // if using block pruning, then disallow txindex
979  if (gArgs.GetArg("-prune", 0)) {
980  if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX))
981  return InitError(_("Prune mode is incompatible with -txindex."));
982  }
983 
984  // -bind and -whitebind can't be set when not listening
985  size_t nUserBind = gArgs.GetArgs("-bind").size() + gArgs.GetArgs("-whitebind").size();
986  if (nUserBind != 0 && !gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
987  return InitError("Cannot set -bind or -whitebind together with -listen=0");
988  }
989 
990  // Make sure enough file descriptors are available
991  int nBind = std::max(nUserBind, size_t(1));
992  nUserMaxConnections = gArgs.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
993  nMaxConnections = std::max(nUserMaxConnections, 0);
994 
995  // Trim requested connection counts, to fit into system limitations
996  nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
997  nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
998  if (nFD < MIN_CORE_FILEDESCRIPTORS)
999  return InitError(_("Not enough file descriptors available."));
1000  nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
1001 
1002  if (nMaxConnections < nUserMaxConnections)
1003  InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
1004 
1005  // ********************************************************* Step 3: parameter-to-internal-flags
1006  if (gArgs.IsArgSet("-debug")) {
1007  // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
1008  const std::vector<std::string> categories = gArgs.GetArgs("-debug");
1009 
1010  if (find(categories.begin(), categories.end(), std::string("0")) == categories.end()) {
1011  for (const auto& cat : categories) {
1012  uint32_t flag = 0;
1013  if (!GetLogCategory(&flag, &cat)) {
1014  InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
1015  continue;
1016  }
1017  logCategories |= flag;
1018  }
1019  }
1020  }
1021 
1022  // Now remove the logging categories which were explicitly excluded
1023  for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
1024  uint32_t flag = 0;
1025  if (!GetLogCategory(&flag, &cat)) {
1026  InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
1027  continue;
1028  }
1029  logCategories &= ~flag;
1030  }
1031 
1032  // Check for -debugnet
1033  if (gArgs.GetBoolArg("-debugnet", false))
1034  InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
1035  // Check for -socks - as this is a privacy risk to continue, exit here
1036  if (gArgs.IsArgSet("-socks"))
1037  return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
1038  // Check for -tor - as this is a privacy risk to continue, exit here
1039  if (gArgs.GetBoolArg("-tor", false))
1040  return InitError(_("Unsupported argument -tor found, use -onion."));
1041 
1042  if (gArgs.GetBoolArg("-benchmark", false))
1043  InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
1044 
1045  if (gArgs.GetBoolArg("-whitelistalwaysrelay", false))
1046  InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
1047 
1048  if (gArgs.IsArgSet("-blockminsize"))
1049  InitWarning("Unsupported argument -blockminsize ignored.");
1050 
1051  // Checkmempool and checkblockindex default to true in regtest mode
1052  int ratio = std::min<int>(std::max<int>(gArgs.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
1053  if (ratio != 0) {
1054  mempool.setSanityCheck(1.0 / ratio);
1055  }
1056  fCheckBlockIndex = gArgs.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
1057  fCheckpointsEnabled = gArgs.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
1058 
1059  hashAssumeValid = uint256S(gArgs.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
1060  if (!hashAssumeValid.IsNull())
1061  LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
1062  else
1063  LogPrintf("Validating signatures for all blocks.\n");
1064 
1065  if (gArgs.IsArgSet("-minimumchainwork")) {
1066  const std::string minChainWorkStr = gArgs.GetArg("-minimumchainwork", "");
1067  if (!IsHexNumber(minChainWorkStr)) {
1068  return InitError(strprintf("Invalid non-hex (%s) minimum chain work value specified", minChainWorkStr));
1069  }
1070  nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
1071  } else {
1073  }
1074  LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
1076  LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex());
1077  }
1078 
1079  // mempool limits
1080  int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1081  int64_t nMempoolSizeMin = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
1082  if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
1083  return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
1084  // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
1085  // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
1086  if (gArgs.IsArgSet("-incrementalrelayfee"))
1087  {
1088  CAmount n = 0;
1089  if (!ParseMoney(gArgs.GetArg("-incrementalrelayfee", ""), n))
1090  return InitError(AmountErrMsg("incrementalrelayfee", gArgs.GetArg("-incrementalrelayfee", "")));
1092  }
1093 
1094  // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
1095  nScriptCheckThreads = gArgs.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
1096  if (nScriptCheckThreads <= 0)
1098  if (nScriptCheckThreads <= 1)
1099  nScriptCheckThreads = 0;
1100  else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
1101  nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
1102 
1103  // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
1104  int64_t nPruneArg = gArgs.GetArg("-prune", 0);
1105  if (nPruneArg < 0) {
1106  return InitError(_("Prune cannot be configured with a negative value."));
1107  }
1108  nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
1109  if (nPruneArg == 1) { // manual pruning: -prune=1
1110  LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1111  nPruneTarget = std::numeric_limits<uint64_t>::max();
1112  fPruneMode = true;
1113  } else if (nPruneTarget) {
1114  if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
1115  return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1116  }
1117  LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1118  fPruneMode = true;
1119  }
1120 
1121  RegisterAllCoreRPCCommands(tableRPC);
1122 #ifdef ENABLE_WALLET
1124 #endif
1125 
1126  nConnectTimeout = gArgs.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1127  if (nConnectTimeout <= 0)
1128  nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1129 
1130  if (gArgs.IsArgSet("-minrelaytxfee")) {
1131  CAmount n = 0;
1132  if (!ParseMoney(gArgs.GetArg("-minrelaytxfee", ""), n)) {
1133  return InitError(AmountErrMsg("minrelaytxfee", gArgs.GetArg("-minrelaytxfee", "")));
1134  }
1135  // High fee check is done afterward in WalletParameterInteraction()
1137  } else if (incrementalRelayFee > ::minRelayTxFee) {
1138  // Allow only setting incrementalRelayFee to control both
1140  LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1141  }
1142 
1143  // Sanity check argument for min fee for including tx in block
1144  // TODO: Harmonize which arguments need sanity checking and where that happens
1145  if (gArgs.IsArgSet("-blockmintxfee"))
1146  {
1147  CAmount n = 0;
1148  if (!ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n))
1149  return InitError(AmountErrMsg("blockmintxfee", gArgs.GetArg("-blockmintxfee", "")));
1150  }
1151 
1152  // Feerate used to define dust. Shouldn't be changed lightly as old
1153  // implementations may inadvertently create non-standard transactions
1154  if (gArgs.IsArgSet("-dustrelayfee"))
1155  {
1156  CAmount n = 0;
1157  if (!ParseMoney(gArgs.GetArg("-dustrelayfee", ""), n) || 0 == n)
1158  return InitError(AmountErrMsg("dustrelayfee", gArgs.GetArg("-dustrelayfee", "")));
1159  dustRelayFee = CFeeRate(n);
1160  }
1161 
1162  fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1163  if (chainparams.RequireStandard() && !fRequireStandard)
1164  return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1165  nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp);
1166 
1167 #ifdef ENABLE_WALLET
1169  return false;
1170 #endif
1171 
1172  fIsBareMultisigStd = gArgs.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1173  fAcceptDatacarrier = gArgs.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1174  nMaxDatacarrierBytes = gArgs.GetArg("-datacarriersize", nMaxDatacarrierBytes);
1175 
1176  // Option to startup with mocktime set (used for regression testing):
1177  SetMockTime(gArgs.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1178 
1179  if (gArgs.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1180  nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1181 
1182  if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1183  return InitError("rpcserialversion must be non-negative.");
1184 
1185  if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1186  return InitError("unknown rpcserialversion requested.");
1187 
1188  nMaxTipAge = gArgs.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1189 
1190  fEnableReplacement = gArgs.GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1191  if ((!fEnableReplacement) && gArgs.IsArgSet("-mempoolreplacement")) {
1192  // Minimal effort at forwards compatibility
1193  std::string strReplacementModeList = gArgs.GetArg("-mempoolreplacement", ""); // default is impossible
1194  std::vector<std::string> vstrReplacementModes;
1195  boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1196  fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1197  }
1198 
1199  if (gArgs.IsArgSet("-vbparams")) {
1200  // Allow overriding version bits parameters for testing
1201  if (!chainparams.MineBlocksOnDemand()) {
1202  return InitError("Version bits parameters may only be overridden on regtest.");
1203  }
1204  for (const std::string& strDeployment : gArgs.GetArgs("-vbparams")) {
1205  std::vector<std::string> vDeploymentParams;
1206  boost::split(vDeploymentParams, strDeployment, boost::is_any_of(":"));
1207  if (vDeploymentParams.size() != 3) {
1208  return InitError("Version bits parameters malformed, expecting deployment:start:end");
1209  }
1210  int64_t nStartTime, nTimeout;
1211  if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1212  return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1213  }
1214  if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1215  return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1216  }
1217  bool found = false;
1218  for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1219  {
1220  if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1221  UpdateVersionBitsParameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1222  found = true;
1223  LogPrintf("Setting version bits activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1224  break;
1225  }
1226  }
1227  if (!found) {
1228  return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1229  }
1230  }
1231  }
1232  return true;
1233 }
1234 
1235 static bool LockDataDirectory(bool probeOnly)
1236 {
1237  std::string strDataDir = GetDataDir().string();
1238 
1239  // Make sure only a single Raven process is using the data directory.
1240  fs::path pathLockFile = GetDataDir() / ".lock";
1241  FILE* file = fsbridge::fopen(pathLockFile, "a"); // empty lock file; created if it doesn't exist.
1242  if (file) fclose(file);
1243 
1244  try {
1245  static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1246  if (!lock.try_lock()) {
1247  return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1248  }
1249  if (probeOnly) {
1250  lock.unlock();
1251  }
1252  } catch(const boost::interprocess::interprocess_exception& e) {
1253  return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1254  }
1255  return true;
1256 }
1257 
1259 {
1260  // ********************************************************* Step 4: sanity checks
1261 
1262  // Initialize elliptic curve code
1263  std::string sha256_algo = SHA256AutoDetect();
1264  LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
1265  RandomInit();
1266  ECC_Start();
1267  globalVerifyHandle.reset(new ECCVerifyHandle());
1268 
1269  // Sanity check
1270  if (!InitSanityCheck())
1271  return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1272 
1273  // Probe the data directory lock to give an early error message, if possible
1274  // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened,
1275  // and a fork will cause weird behavior to it.
1276  return LockDataDirectory(true);
1277 }
1278 
1280 {
1281  // After daemonization get the data directory lock again and hold on to it until exit
1282  // This creates a slight window for a race condition to happen, however this condition is harmless: it
1283  // will at most make us exit without printing a message to console.
1284  if (!LockDataDirectory(false)) {
1285  // Detailed error printed inside LockDataDirectory
1286  return false;
1287  }
1288  return true;
1289 }
1290 
1291 bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
1292 {
1293  const CChainParams& chainparams = Params();
1294  // ********************************************************* Step 4a: application initialization
1295 #ifndef WIN32
1296  CreatePidFile(GetPidFile(), getpid());
1297 #endif
1298  if (gArgs.GetBoolArg("-shrinkdebugfile", logCategories == BCLog::NONE)) {
1299  // Do this first since it both loads a bunch of debug.log into memory,
1300  // and because this needs to happen before any other debug.log printing
1301  ShrinkDebugFile();
1302  }
1303 
1304  if (fPrintToDebugLog)
1305  OpenDebugLog();
1306 
1307  if (!fLogTimestamps)
1308  LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1309  LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1310  LogPrintf("Using data directory %s\n", GetDataDir().string());
1311  LogPrintf("Using config file %s\n", GetConfigFile(gArgs.GetArg("-conf", RAVEN_CONF_FILENAME)).string());
1312  LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1313 
1316 
1317  LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1318  if (nScriptCheckThreads) {
1319  for (int i=0; i<nScriptCheckThreads-1; i++)
1320  threadGroup.create_thread(&ThreadScriptCheck);
1321  }
1322 
1323  // Start the lightweight task scheduler thread
1324  CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1325  threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1326 
1328 
1329  /* Start the RPC server already. It will be started in "warmup" mode
1330  * and not really process calls already (but it will signify connections
1331  * that the server is there and will be ready later). Warmup mode will
1332  * be disabled when initialisation is finished.
1333  */
1334  if (gArgs.GetBoolArg("-server", false))
1335  {
1337  if (!AppInitServers(threadGroup))
1338  return InitError(_("Unable to start HTTP server. See debug log for details."));
1339  }
1340 
1341  int64_t nStart;
1342 
1343  // ********************************************************* Step 5: verify wallet database integrity
1344 #ifdef ENABLE_WALLET
1345  if (!VerifyWallets())
1346  return false;
1347 #endif
1348 
1349  bool fGenerate = gArgs.GetBoolArg("-regtest", false) ? false : DEFAULT_GENERATE;
1350  // Generate coins in the background
1351  GenerateRavens(fGenerate, gArgs.GetArg("-genproclimit", DEFAULT_GENERATE_THREADS), chainparams);
1352 
1353  // ********************************************************* Step 6: network initialization
1354  // Note that we absolutely cannot open any actual connections
1355  // until the very end ("start node") as the UTXO/block state
1356  // is not yet setup and may end up being set up twice if we
1357  // need to reindex later.
1358 
1359  assert(!g_connman);
1360  g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1361  CConnman& connman = *g_connman;
1362 
1363  peerLogic.reset(new PeerLogicValidation(&connman, scheduler));
1365 
1366  // sanitize comments per BIP-0014, format user agent and check total size
1367  std::vector<std::string> uacomments;
1368  for (const std::string& cmt : gArgs.GetArgs("-uacomment")) {
1369  if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1370  return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1371  uacomments.push_back(cmt);
1372  }
1373  strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1374  if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1375  return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1376  strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1377  }
1378 
1379  if (gArgs.IsArgSet("-onlynet")) {
1380  std::set<enum Network> nets;
1381  for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
1382  enum Network net = ParseNetwork(snet);
1383  if (net == NET_UNROUTABLE)
1384  return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1385  nets.insert(net);
1386  }
1387  for (int n = 0; n < NET_MAX; n++) {
1388  enum Network net = (enum Network)n;
1389  if (!nets.count(net))
1390  SetLimited(net);
1391  }
1392  }
1393 
1394  // Check for host lookup allowed before parsing any network related parameters
1395  fNameLookup = gArgs.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1396 
1397  bool proxyRandomize = gArgs.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1398  // -proxy sets a proxy for all outgoing network traffic
1399  // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1400  std::string proxyArg = gArgs.GetArg("-proxy", "");
1402  if (proxyArg != "" && proxyArg != "0") {
1403  CService proxyAddr;
1404  if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1405  return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1406  }
1407 
1408  proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1409  if (!addrProxy.IsValid())
1410  return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1411 
1412  SetProxy(NET_IPV4, addrProxy);
1413  SetProxy(NET_IPV6, addrProxy);
1414  SetProxy(NET_TOR, addrProxy);
1415  SetNameProxy(addrProxy);
1416  SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1417  }
1418 
1419  // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1420  // -noonion (or -onion=0) disables connecting to .onion entirely
1421  // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1422  std::string onionArg = gArgs.GetArg("-onion", "");
1423  if (onionArg != "") {
1424  if (onionArg == "0") { // Handle -noonion/-onion=0
1425  SetLimited(NET_TOR); // set onions as unreachable
1426  } else {
1427  CService onionProxy;
1428  if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1429  return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1430  }
1431  proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1432  if (!addrOnion.IsValid())
1433  return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1434  SetProxy(NET_TOR, addrOnion);
1435  SetLimited(NET_TOR, false);
1436  }
1437  }
1438 
1439  // see Step 2: parameter interactions for more information about these
1440  fListen = gArgs.GetBoolArg("-listen", DEFAULT_LISTEN);
1441  fDiscover = gArgs.GetBoolArg("-discover", true);
1442  fRelayTxes = !gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1443 
1444  for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
1445  CService addrLocal;
1446  if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1447  AddLocal(addrLocal, LOCAL_MANUAL);
1448  else
1449  return InitError(ResolveErrMsg("externalip", strAddr));
1450  }
1451 
1452 #if ENABLE_ZMQ
1453  pzmqNotificationInterface = CZMQNotificationInterface::Create();
1454 
1455  if (pzmqNotificationInterface) {
1456  RegisterValidationInterface(pzmqNotificationInterface);
1457  }
1458 #endif
1459  uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1460  uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1461 
1462  if (gArgs.IsArgSet("-maxuploadtarget")) {
1463  nMaxOutboundLimit = gArgs.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1464  }
1465 
1466  // ********************************************************* Step 7: load block chain
1467 
1468  fReindex = gArgs.GetBoolArg("-reindex", false);
1469  bool fReindexChainState = gArgs.GetBoolArg("-reindex-chainstate", false);
1470 
1471  // block tree db settings
1472  size_t dbMaxFileSize = gArgs.GetArg("-dbmaxfilesize", DEFAULT_DB_MAX_FILE_SIZE) << 20;
1473 
1474  LogPrintf("Block index database configuration:\n");
1475  LogPrintf("* Using %d MB files\n", (dbMaxFileSize / 1024 / 1024));
1476 
1477  // cache size calculations
1478  int64_t nTotalCache = (gArgs.GetArg("-dbcache", nDefaultDbCache) << 20);
1479  nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1480  nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1481  int64_t nBlockTreeDBCache = nTotalCache / 8;
1482  nBlockTreeDBCache = std::min(nBlockTreeDBCache, (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1483  nTotalCache -= nBlockTreeDBCache;
1484  int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1485  nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1486  nTotalCache -= nCoinDBCache;
1487  nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1488  int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1489  LogPrintf("Cache configuration:\n");
1490  LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1491  LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1492  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));
1493 
1494  bool fLoaded = false;
1495  while (!fLoaded && !fRequestShutdown) {
1496  bool fReset = fReindex;
1497  std::string strLoadError;
1498 
1499  uiInterface.InitMessage(_("Loading block index..."));
1500 
1501  nStart = GetTimeMillis();
1502  do {
1503  try {
1504  UnloadBlockIndex();
1505  delete pcoinsTip;
1506  delete pcoinsdbview;
1507  delete pcoinscatcher;
1508  delete pblocktree;
1509  pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReset, dbMaxFileSize);
1510 
1512  {
1513  // Basic assets
1514  delete passets;
1515  delete passetsdb;
1516  delete passetsCache;
1517 
1518  // Messaging assets
1519  delete pmessagedb;
1520  delete pmessagechanneldb;
1521  delete pMessagesCache;
1524 
1525  // Restricted assets
1526  delete prestricteddb;
1527  delete passetsVerifierCache;
1528  delete passetsQualifierCache;
1529  delete passetsRestrictionCache;
1531 
1532  // Basic assets
1533  passetsdb = new CAssetsDB(nBlockTreeDBCache, false, fReset);
1534  passets = new CAssetsCache();
1536 
1537  // Messaging assets
1541  pmessagedb = new CMessageDB(nBlockTreeDBCache, false, false);
1542  pmessagechanneldb = new CMessageChannelDB(nBlockTreeDBCache, false, false);
1543 
1544  // Restricted assets
1545  prestricteddb = new CRestrictedDB(nBlockTreeDBCache, false, fReset);
1551 
1552 
1553  // Read for fAssetIndex to make sure that we only load asset address balances if it if true
1554  pblocktree->ReadFlag("assetindex", fAssetIndex);
1555  // Need to load assets before we verify the database
1556  if (!passetsdb->LoadAssets()) {
1557  strLoadError = _("Failed to load Assets Database");
1558  break;
1559  }
1560 
1562  LogPrintf(
1563  "Database failed to load last Reissued Mempool State. Will have to start from empty state");
1564 
1565  LogPrintf("Loaded Assets from database without error\nCache of assets size: %d\n",
1566  passetsCache->Size());
1567 
1568  // Check for changed -disablemessaging state
1569  if (gArgs.GetArg("-disablemessaging", false)) {
1570  LogPrintf("Messaging is disabled\n");
1571  fMessaging = false;
1572  } else {
1573  LogPrintf("Messaging is enabled\n");
1574  }
1575  }
1578  if (fReset) {
1579  pblocktree->WriteReindexing(true);
1580  //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1581  if (fPruneMode)
1583  }
1584 
1585  if (fRequestShutdown) break;
1586 
1587  // LoadBlockIndex will load fTxIndex from the db, or set it if
1588  // we're reindexing. It will also load fHavePruned if we've
1589  // ever removed a block file from disk.
1590  // Note that it also sets fReindex based on the disk flag!
1591  // From here on out fReindex and fReset mean something different!
1592  if (!LoadBlockIndex(chainparams)) {
1593  strLoadError = _("Error loading block database");
1594  break;
1595  }
1596 
1597  // If the loaded chain has a wrong genesis, bail out immediately
1598  // (we're likely using a testnet datadir, or the other way around).
1599  if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
1600  return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1601 
1602  // Check for changed -txindex state
1603  if (fTxIndex != gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1604  strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1605  break;
1606  }
1607 
1608  // Check for changed -assetindex state
1609  if (fAssetIndex != gArgs.GetBoolArg("-assetindex", DEFAULT_ASSETINDEX)) {
1610  strLoadError = _("You need to rebuild the database using -reindex to change -assetIndex");
1611  break;
1612  }
1613 
1614  // Check for changed -addressindex state
1615  if (fAddressIndex != gArgs.GetBoolArg("-addressindex", DEFAULT_ADDRESSINDEX)) {
1616  strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -addressindex");
1617  break;
1618  }
1619 
1620  // Check for changed -spentindex state
1621  if (fSpentIndex != gArgs.GetBoolArg("-spentindex", DEFAULT_SPENTINDEX)) {
1622  strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -spentindex");
1623  break;
1624  }
1625 
1626  // Check for changed -timestampindex state
1627  if (fTimestampIndex != gArgs.GetBoolArg("-timestampindex", DEFAULT_TIMESTAMPINDEX)) {
1628  strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -timestampindex");
1629  break;
1630  }
1631 
1632  // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1633  // in the past, but is now trying to run unpruned.
1634  if (fHavePruned && !fPruneMode) {
1635  strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1636  break;
1637  }
1638 
1639  // At this point blocktree args are consistent with what's on disk.
1640  // If we're not mid-reindex (based on disk + args), add a genesis block on disk
1641  // (otherwise we use the one already on disk).
1642  // This is called again in ThreadImport after the reindex completes.
1643  if (!fReindex && !LoadGenesisBlock(chainparams)) {
1644  strLoadError = _("Error initializing block database");
1645  break;
1646  }
1647 
1648  // At this point we're either in reindex or we've loaded a useful
1649  // block tree into mapBlockIndex!
1650 
1651  pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReset || fReindexChainState);
1652  pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1653 
1654  // If necessary, upgrade from older database format.
1655  // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1656  if (!pcoinsdbview->Upgrade()) {
1657  strLoadError = _("Error upgrading chainstate database");
1658  break;
1659  }
1660 
1661  // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1662  if (!ReplayBlocks(chainparams, pcoinsdbview)) {
1663  strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1664  break;
1665  }
1666 
1667  // The on-disk coinsdb is now in a good state, create the cache
1668  pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1669 
1670  bool is_coinsview_empty = fReset || fReindexChainState || pcoinsTip->GetBestBlock().IsNull();
1671  if (!is_coinsview_empty) {
1672  // LoadChainTip sets chainActive based on pcoinsTip's best block
1673  if (!LoadChainTip(chainparams)) {
1674  strLoadError = _("Error initializing block database");
1675  break;
1676  }
1677  assert(chainActive.Tip() != nullptr);
1678  }
1679 
1680  if (!fReset) {
1681  // Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate.
1682  // It both disconnects blocks based on chainActive, and drops block data in
1683  // mapBlockIndex based on lack of available witness data.
1684  uiInterface.InitMessage(_("Rewinding blocks..."));
1685  if (!RewindBlockIndex(chainparams)) {
1686  strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1687  break;
1688  }
1689  }
1690 
1691  if (!is_coinsview_empty) {
1692  uiInterface.InitMessage(_("Verifying blocks..."));
1693  if (fHavePruned && gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1694  LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
1695  MIN_BLOCKS_TO_KEEP);
1696  }
1697 
1698  {
1699  LOCK(cs_main);
1700  CBlockIndex* tip = chainActive.Tip();
1701  RPCNotifyBlockChange(true, tip);
1702  if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1703  strLoadError = _("The block database contains a block which appears to be from the future. "
1704  "This may be due to your computer's date and time being set incorrectly. "
1705  "Only rebuild the block database if you are sure that your computer's date and time are correct");
1706  break;
1707  }
1708  }
1709 
1710  if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1711  gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1712  strLoadError = _("Corrupted block database detected");
1713  break;
1714  }
1715  }
1716  } catch (const std::exception& e) {
1717  LogPrintf("%s\n", e.what());
1718  strLoadError = _("Error opening block database");
1719  break;
1720  }
1721 
1722  fLoaded = true;
1723  } while(false);
1724 
1725  if (!fLoaded && !fRequestShutdown) {
1726  // first suggest a reindex
1727  if (!fReset) {
1728  bool fRet = uiInterface.ThreadSafeQuestion(
1729  strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1730  strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1732  if (fRet) {
1733  fReindex = true;
1734  fRequestShutdown = false;
1735  } else {
1736  LogPrintf("Aborted block database rebuild. Exiting.\n");
1737  return false;
1738  }
1739  } else {
1740  return InitError(strLoadError);
1741  }
1742  }
1743  }
1744 
1745  // As LoadBlockIndex can take several minutes, it's possible the user
1746  // requested to kill the GUI during the last operation. If so, exit.
1747  // As the program has not fully started yet, Shutdown() is possibly overkill.
1748  if (fRequestShutdown)
1749  {
1750  LogPrintf("Shutdown requested. Exiting.\n");
1751  return false;
1752  }
1753  if (fLoaded) {
1754  LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1755  }
1756 
1757  fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1758  CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
1759  // Allowed to fail as this file IS missing on first startup.
1760  if (!est_filein.IsNull())
1761  ::feeEstimator.Read(est_filein);
1762  fFeeEstimatesInitialized = true;
1763 
1764  // ********************************************************* Step 8: load wallet
1765 #ifdef ENABLE_WALLET
1766  if (!OpenWallets())
1767  return false;
1768 #else
1769  LogPrintf("No wallet support compiled in!\n");
1770 #endif
1771 
1772  // ********************************************************* Step 9: data directory maintenance
1773 
1774  // if pruning, unset the service bit and perform the initial blockstore prune
1775  // after any wallet rescanning has taken place.
1776  if (fPruneMode) {
1777  LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1778  nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1779  if (!fReindex) {
1780  uiInterface.InitMessage(_("Pruning blockstore..."));
1781  PruneAndFlush();
1782  }
1783  }
1784 
1785  if(chainparams.GetConsensus().nSegwitEnabled) {
1786  nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1787  }
1788  // ********************************************************* Step 10: import blocks
1789 
1790  if (!CheckDiskSpace())
1791  return false;
1792 
1793  // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1794  // No locking, as this happens before any background thread is started.
1795  if (chainActive.Tip() == nullptr) {
1796  uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1797  } else {
1798  fHaveGenesis = true;
1799  }
1800 
1801  if (gArgs.IsArgSet("-blocknotify"))
1802  uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1803 
1804  std::vector<fs::path> vImportFiles;
1805  for (const std::string& strFile : gArgs.GetArgs("-loadblock")) {
1806  vImportFiles.push_back(strFile);
1807  }
1808 
1809  threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1810 
1811  // Wait for genesis block to be processed
1812  {
1813  boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
1814  while (!fHaveGenesis) {
1815  condvar_GenesisWait.wait(lock);
1816  }
1817  uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1818  }
1819 
1820  // ********************************************************* Step 11: start node
1821 
1822  int chain_active_height;
1823 
1825  {
1826  LOCK(cs_main);
1827  LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1828  chain_active_height = chainActive.Height();
1829  }
1830  LogPrintf("nBestHeight = %d\n", chain_active_height);
1831 
1832  if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1833  StartTorControl(threadGroup, scheduler);
1834 
1835  Discover(threadGroup);
1836 
1837  // Map ports with UPnP
1838  MapPort(gArgs.GetBoolArg("-upnp", DEFAULT_UPNP));
1839 
1840  CConnman::Options connOptions;
1841  connOptions.nLocalServices = nLocalServices;
1842  connOptions.nMaxConnections = nMaxConnections;
1843  connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1844  connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1845  connOptions.nMaxFeeler = 1;
1846  connOptions.nBestHeight = chain_active_height;
1847  connOptions.uiInterface = &uiInterface;
1848  connOptions.m_msgproc = peerLogic.get();
1849  connOptions.nSendBufferMaxSize = 1000*gArgs.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1850  connOptions.nReceiveFloodSize = 1000*gArgs.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1851  connOptions.m_added_nodes = gArgs.GetArgs("-addnode");
1852 
1853  connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1854  connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1855 
1856  for (const std::string& strBind : gArgs.GetArgs("-bind")) {
1857  CService addrBind;
1858  if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) {
1859  return InitError(ResolveErrMsg("bind", strBind));
1860  }
1861  connOptions.vBinds.push_back(addrBind);
1862  }
1863  for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
1864  CService addrBind;
1865  if (!Lookup(strBind.c_str(), addrBind, 0, false)) {
1866  return InitError(ResolveErrMsg("whitebind", strBind));
1867  }
1868  if (addrBind.GetPort() == 0) {
1869  return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1870  }
1871  connOptions.vWhiteBinds.push_back(addrBind);
1872  }
1873 
1874  for (const auto& net : gArgs.GetArgs("-whitelist")) {
1875  CSubNet subnet;
1876  LookupSubNet(net.c_str(), subnet);
1877  if (!subnet.IsValid())
1878  return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1879  connOptions.vWhitelistedRange.push_back(subnet);
1880  }
1881 
1882  connOptions.vSeedNodes = gArgs.GetArgs("-seednode");
1883 
1884  // Initiate outbound connections unless connect=0
1885  connOptions.m_use_addrman_outgoing = !gArgs.IsArgSet("-connect");
1886  if (!connOptions.m_use_addrman_outgoing) {
1887  const auto connect = gArgs.GetArgs("-connect");
1888  if (connect.size() != 1 || connect[0] != "0") {
1889  connOptions.m_specified_outgoing = connect;
1890  }
1891  }
1892  if (!connman.Start(scheduler, connOptions)) {
1893  return false;
1894  }
1895 
1896 
1897 
1898 
1899 
1900 
1902 
1903 #ifdef ENABLE_WALLET
1904  StartWallets(scheduler);
1905 #endif
1906 
1907  // ********************************************************* Step 12: Init Msg Channel list
1908  if (!fReindex && fLoaded && fMessaging && pmessagechanneldb && !gArgs.GetBoolArg("-disablewallet", false)) {
1909  bool found;
1910  if (!pmessagechanneldb->ReadFlag("init", found)) {
1911  uiInterface.InitMessage(_("Init Message Channels - Scanning Asset Transactions"));
1912  std::string strLoadError;
1913  if (!ScanForMessageChannels(strLoadError))
1914  return InitError(strLoadError);
1915  pmessagechanneldb->WriteFlag("init", true);
1916  }
1917  }
1918 
1919  // ********************************************************* Step 13: finished
1920  uiInterface.InitMessage(_("Done Loading"));
1921 
1922  return !fRequestShutdown;
1923 }
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: init.cpp:150
void CleanupBlockRevFiles()
Definition: init.cpp:666
void RandomInit()
Initialize the RNG.
Definition: random.cpp:465
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:511
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:75
bool(* handler)(HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:569
void ECC_Start()
Initialize the elliptic curve support.
Definition: key.cpp:292
unsigned short GetPort() const
Definition: netaddress.cpp:523
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:277
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:448
bool SetupNetworking()
Definition: util.cpp:896
int nScriptCheckThreads
Definition: validation.cpp:79
const char *const RAVEN_CONF_FILENAME
Definition: util.cpp:91
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:89
boost::condition_variable CConditionVariable
Just a typedef for boost::condition_variable, can be wrapped later if desired.
Definition: sync.h:104
bool DumpMempool(void)
Dump the mempool to disk.
ServiceFlags
nServices flags
Definition: protocol.h:271
bool StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:443
void UnloadBlockIndex()
Unload database information.
bool fAddressIndex
Definition: validation.cpp:85
bool Upgrade()
Attempt to update from an older database format. Returns whether an error occurred.
Definition: txdb.cpp:562
void InitLogging()
Initialize the logging infrastructure.
Definition: init.cpp:890
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:210
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:5
#define TRY_LOCK(cs, name)
Definition: sync.h:178
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: util.cpp:486
A UTXO entry.
Definition: coins.h:32
CLRUCache< std::string, int8_t > * passetsQualifierCache
Global variable that points to the asset address qualifier LRU Cache (protected by cs_main) ...
Definition: validation.cpp:236
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:341
HelpMessageMode
The help message mode determines what help message to show.
Definition: init.h:72
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
bool ShutdownRequested()
Definition: init.cpp:136
#define strprintf
Definition: tinyformat.h:1054
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:88
CRestrictedDB * prestricteddb
Global variable that points to the active restricted asset database (protected by cs_main) ...
Definition: validation.cpp:239
~CImportingNow()
Definition: init.cpp:653
std::atomic< bool > fRequestShutdown(false)
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:79
bool Write(CAutoFile &fileout) const
Write estimation data to a file.
Definition: fees.cpp:914
bool ReadFlag(const std::string &name, bool &fValue)
Definition: messagedb.cpp:197
int Height() const
Return the maximal height in the chain.
Definition: chain.h:479
void StartShutdown()
Definition: init.cpp:128
void SetMockTime(int64_t nMockTimeIn)
Definition: utiltime.cpp:30
CMessageChannelDB * pmessagechanneldb
Global variable that points to the message channel database (protected by cs_main) ...
Definition: validation.cpp:233
bool StartHTTPRPC()
Start HTTP RPC subsystem.
Definition: httprpc.cpp:230
CCriticalSection cs_main
Global state.
Definition: validation.cpp:72
bool OpenWallets()
Load wallet databases.
Definition: init.cpp:239
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
Definition: standard.cpp:19
void StopTorControl()
Definition: torcontrol.cpp:769
void CloseWallets()
Close all wallets.
Definition: init.cpp:275
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:592
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
Definition: versionbits.cpp:9
bool fTimestampIndex
Definition: validation.cpp:86
void OnStopped(std::function< void()> slot)
Definition: server.cpp:53
void SetLimited(enum Network net, bool fLimited)
Make a particular network entirely off-limits (no automatic connects to it)
Definition: net.cpp:250
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:102
void InterruptRPC()
Definition: server.cpp:321
void OnRPCStarted()
Definition: init.cpp:378
bool fDiscover
Definition: net.cpp:87
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
Definition: chainparams.h:68
const std::string CURRENCY_UNIT
Definition: feerate.cpp:11
CChainParams defines various tweakable parameters of a given instance of the Raven system...
Definition: chainparams.h:48
void UnregisterAllValidationInterfaces()
Unregister all wallets from core.
std::string GetWalletHelpString(bool showDebug)
Return the wallets help message.
Definition: init.cpp:16
uint32_t nTime
Definition: chain.h:214
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:470
unsigned short GetListenPort()
Definition: net.cpp:103
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
Definition: sha256.cpp:180
std::atomic< uint32_t > logCategories
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:247
bool AppInitBasicSetup()
Initialize raven core: Basic context setup.
Definition: init.cpp:923
#define PACKAGE_NAME
Definition: raven-config.h:350
void StopWallets()
Stop all wallets. Wallets will be flushed first.
Definition: init.cpp:269
CAssetsDB * passetsdb
RVN START.
Definition: validation.cpp:226
void ThreadImport(std::vector< fs::path > vImportFiles)
Definition: init.cpp:701
unsigned int nBytesPerSigOp
Definition: policy.cpp:264
std::string LicenseInfo()
Returns licensing information (for -version)
Definition: init.cpp:597
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:459
uint64_t nPruneTarget
Number of MiB of block files that we&#39;re trying to stay below.
Definition: validation.cpp:95
bool SetNameProxy(const proxyType &addrProxy)
Definition: netbase.cpp:561
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn&#39;t already have a value.
Definition: util.cpp:478
void PrepareShutdown()
Preparing steps before shutting down or restarting the wallet.
Definition: init.cpp:182
bool fAssetIndex
Definition: validation.cpp:84
void RenameThread(const char *name)
Definition: util.cpp:849
CLRUCache< std::string, int > * pMessageSubscribedChannelsCache
Global variable that points to the subscribed channel LRU Cache (protected by cs_main) ...
Definition: validation.cpp:230
bool IsNull() const
Definition: uint256.h:33
bool WriteReindexing(bool fReindexing)
Definition: txdb.cpp:164
bool fIsBareMultisigStd
Definition: validation.cpp:90
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Make the best chain active, in multiple steps.
std::string HelpMessage(HelpMessageMode mode)
Help for options shared between UI and daemon (for -help)
Definition: init.cpp:391
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:501
bool StartREST()
Start HTTP REST subsystem.
Definition: rest.cpp:581
bool LoadAssets()
Definition: assetdb.cpp:119
int GenerateRavens(bool fGenerate, int nThreads, const CChainParams &chainparams)
Definition: miner.cpp:668
arith_uint256 UintToArith256(const uint256 &a)
void MapPort(bool)
Definition: net.cpp:1572
void OnRPCStopped()
Definition: init.cpp:383
CLRUCache< std::string, int8_t > * passetsRestrictionCache
Global variable that points to the asset address restriction LRU Cache (protected by cs_main) ...
Definition: validation.cpp:237
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: init.cpp:149
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: util.cpp:729
bool IsValid() const
Definition: netaddress.cpp:198
bool nSegwitEnabled
Definition: params.h:76
int64_t CAmount
Amount in corbies (Can be negative)
Definition: amount.h:13
bool fSpentIndex
Definition: validation.cpp:87
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:813
uint256 GetBlockHash() const
Definition: chain.h:294
void SetRPCWarmupFinished()
Definition: server.cpp:347
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyBlockTip
New block has been accepted.
Definition: ui_interface.h:105
CLRUCache< std::string, CMessage > * pMessagesCache
Global variable that points to the subscribed channel LRU Cache (protected by cs_main) ...
Definition: validation.cpp:229
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:109
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
bool ParseInt64(const std::string &str, int64_t *out)
Convert string to signed 64-bit integer with strict parse error feedback.
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:223
bool glibc_sanity_test()
CRPCTable tableRPC
Definition: server.cpp:567
void setSanityCheck(double dFrequency=1.0)
Definition: txmempool.h:546
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:368
Users of this module must hold an ECCVerifyHandle.
Definition: pubkey.h:242
bool fCheckpointsEnabled
Definition: validation.cpp:93
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1258
bool ReplayBlocks(const CChainParams &params, CCoinsView *view)
Replay blocks that aren&#39;t fully applied to the database.
bool fRelayTxes
Definition: net.cpp:89
enum Network ParseNetwork(std::string net)
Definition: netbase.cpp:44
#define LogPrintf(...)
Definition: util.h:149
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
static CZMQNotificationInterface * Create()
CLRUCache< std::string, CNullAssetTxVerifierString > * passetsVerifierCache
Global variable that points to the asset verifier LRU Cache (protected by cs_main) ...
Definition: validation.cpp:235
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:32
#define COPYRIGHT_YEAR
Definition: raven-config.h:36
bool MineBlocksOnDemand() const
Make miner stop after a block is found.
Definition: chainparams.h:73
Access to the block database (blocks/index/)
Definition: txdb.h:113
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:474
Abstract view on the open txout dataset.
Definition: coins.h:152
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:104
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:16
void RegisterWalletRPC(CRPCTable &t)
Register wallet RPCs.
Definition: init.cpp:175
#define LOCK(cs)
Definition: sync.h:176
fs::path GetPidFile()
Definition: util.cpp:649
void Interrupt(boost::thread_group &threadGroup)
Interrupt threads.
Definition: init.cpp:169
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition: key.cpp:309
CMessageDB * pmessagedb
Global variable that points to the messages database (protected by cs_main)
Definition: validation.cpp:232
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:99
CImportingNow()
Definition: init.cpp:648
void FlushUnconfirmed(CTxMemPool &pool)
Empty mempool transactions on shutdown to record failure to confirm for txs still in mempool...
Definition: fees.cpp:1025
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:141
bool WriteFlag(const std::string &name, bool fValue)
Definition: messagedb.cpp:192
uint256 uint256S(const char *str)
Definition: uint256.h:150
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:471
std::function< void(void)> Function
Definition: scheduler.h:44
void InitSignatureCache()
Definition: sigcache.cpp:74
void Shutdown()
Shutdown is split into 2 parts: Part 1: shut down everything but the main wallet instance (done in Pr...
Definition: init.cpp:336
CMainSignals & GetMainSignals()
Network
Definition: netaddress.h:20
void serviceQueue()
Definition: scheduler.cpp:34
bool ParseMoney(const std::string &str, CAmount &nRet)
Definition: net.h:120
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:75
std::atomic_bool fImporting
bool WalletParameterInteraction()
Wallets parameter interaction.
Definition: init.cpp:55
BIP-0014 subset.
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:22
bool fEnableReplacement
Definition: validation.cpp:97
const std::string CLIENT_NAME
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:93
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:356
bool fTxIndex
Definition: validation.cpp:83
bool RenameOver(fs::path src, fs::path dest)
Definition: util.cpp:668
CLRUCache< std::string, int8_t > * passetsGlobalRestrictionCache
Global variable that points to the global asset restriction LRU Cache (protected by cs_main) ...
Definition: validation.cpp:238
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
int nConnectTimeout
Definition: netbase.cpp:37
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:96
std::string FormatFullVersion()
std::string CopyrightHolders(const std::string &strPrefix)
Definition: util.cpp:917
fs::path GetDefaultDataDir()
Definition: util.cpp:542
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
bool ReadFlag(const std::string &name, bool &fValue)
Definition: txdb.cpp:452
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:101
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:615
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:543
bool fLogTimestamps
Definition: util.cpp:98
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:252
bool AppInitParameterInteraction()
Initialization: parameter interaction.
Definition: init.cpp:971
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:409
#define MAX_CACHE_ASSETS_SIZE
Definition: assets.h:65
#define LogPrint(category,...)
Definition: util.h:160
std::atomic_bool fReindex
bool fLogIPs
Definition: util.cpp:100
bool IsValid() const
Definition: netaddress.cpp:722
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once) ...
RVN END.
Definition: validation.h:30
bool glibcxx_sanity_test()
bool fCheckBlockIndex
Definition: validation.cpp:92
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
CAssetsCache * passets
Global variable that point to the active assets (protected by cs_main)
Definition: validation.cpp:227
bool fFeeEstimatesInitialized
Definition: init.cpp:76
ArgsManager gArgs
Definition: util.cpp:94
uint256 nMinimumChainWork
Definition: params.h:74
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
Definition: chainparams.h:70
void StopRPC()
Definition: server.cpp:328
bool InitError(const std::string &str)
Show error message.
bool IsValid() const
Definition: netbase.h:35
bool fPrintToConsole
Definition: util.cpp:95
std::atomic< bool > fReopenDebugLog
uint256 defaultAssumeValid
Definition: params.h:75
bool fRequireStandard
Definition: validation.cpp:91
bool ScanForMessageChannels(std::string &strError)
Definition: messages.cpp:189
void OpenDebugLog()
Definition: util.cpp:198
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:172
const CChainParams & Params()
Return the currently selected parameters.
fs::path GetConfigFile(const std::string &confPath)
Definition: util.cpp:612
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
bool fMessaging
Definition: validation.cpp:82
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:71
int64_t GetTimeMillis()
Definition: utiltime.cpp:40
void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
Allows modifying the Version Bits regtest parameters.
void InitScriptExecutionCache()
Initializes the script-execution cache.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:454
bool fPrintToDebugLog
Definition: util.cpp:96
bool Read(CAutoFile &filein)
Read estimation data from a file.
Definition: fees.cpp:939
ServiceFlags nLocalServices
Definition: net.h:133
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:588
void StartRestart()
Definition: init.cpp:132
int64_t GetAdjustedTime()
Definition: timedata.cpp:36
void runCommand(const std::string &strCommand)
Definition: util.cpp:841
bool LoadMempool(void)
Load the mempool from disk.
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:142
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:33
void StartTorControl(boost::thread_group &threadGroup, CScheduler &scheduler)
Definition: torcontrol.cpp:744
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:448
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/raven/bips/blob/master/bip-0...
bool AppInitServers(boost::thread_group &threadGroup)
Definition: init.cpp:795
std::string GetHex() const
Definition: uint256.cpp:22
bool ReadReissuedMempoolState()
Definition: assetdb.cpp:106
bool fListen
Definition: net.cpp:88
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:20
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:81
void FlushWallets()
Flush all wallets in preparation for shutdown.
Definition: init.cpp:263
void Discover(boost::thread_group &threadGroup)
Definition: net.cpp:2177
bool InitSanityCheck(void)
Sanity checks Ensure that Raven is running in a usable environment with all necessary library support...
Definition: init.cpp:777
std::unique_ptr< PeerLogicValidation > peerLogic
Definition: init.cpp:82
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:224
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 std::string TESTNET
void RPCNotifyBlockChange(bool ibd, const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:297
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:572
void CreatePidFile(const fs::path &path, pid_t pid)
Definition: util.cpp:656
const char *const RAVEN_PID_FILENAME
Definition: util.cpp:92
void InterruptTorControl()
Definition: torcontrol.cpp:761
bool StartRPC()
Definition: server.cpp:313
void OnStarted(std::function< void()> slot)
Definition: server.cpp:48
void StartWallets(CScheduler &scheduler)
Complete startup of wallets.
Definition: init.cpp:257
std::string GetHex() const
bool AppInitLockDataDirectory()
Lock raven core data directory.
Definition: init.cpp:1279
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:20
std::string ToString() const
Definition: feerate.cpp:41
void InitWarning(const std::string &str)
Show warning message.
CClientUIInterface uiInterface
Definition: ui_interface.cpp:9
bool AppInitMain(boost::thread_group &threadGroup, CScheduler &scheduler)
Raven core main initialization.
Definition: init.cpp:1291
CLRUCache< std::string, CDatabasedAssetData > * passetsCache
Global variable that point to the assets metadata LRU Cache (protected by cs_main) ...
Definition: validation.cpp:228
CCoinsView backed by another CCoinsView.
Definition: coins.h:189
int GetNumCores()
Return the number of physical cores available on the current system.
Definition: util.cpp:908
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:285
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:61
bool VerifyWallets()
Responsible for reading and validating the -wallet arguments and verifying the wallet database...
Definition: init.cpp:182
CCoinsViewDB * pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
Definition: validation.cpp:222
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:208
void PruneAndFlush()
Prune block files and flush state to disk.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: util.cpp:440
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:94
bool GetLogCategory(uint32_t *f, const std::string *str)
Return true if str parses as a log category and set the flags in f.
Definition: util.cpp:256
std::string AmountErrMsg(const char *const optname, const std::string &strValue)
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
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:146
bool RewindBlockIndex(const CChainParams &params)
When there are blocks in the active chain with missing data, rewind the chainstate and remove them fr...
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:412
CFeeRate incrementalRelayFee
Definition: policy.cpp:262
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:506
BlockMap mapBlockIndex
Definition: validation.cpp:74
Access to the block database (blocks/index/)
Definition: assetdb.h:60
unsigned nMaxDatacarrierBytes
Maximum size of TX_NULL_DATA scripts that this node considers standard.
Definition: standard.cpp:20
bool fNameLookup
Definition: netbase.cpp:38
bool LoadChainTip(const CChainParams &chainparams)
Update the chain tip based on database information.
uint256 hashGenesisBlock
Definition: params.h:48
size_t nCoinCacheUsage
Definition: validation.cpp:94
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:456
void ShrinkDebugFile()
Definition: util.cpp:799
CLRUCache< std::string, int > * pMessagesSeenAddressCache
Global variable that points to the address seen LRU Cache (protected by cs_main)
Definition: validation.cpp:231
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: util.h:66
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
Definition: sync.h:92
int atoi(const std::string &str)
boost::signals2::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
Definition: ui_interface.h:82
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:353
CConditionVariable cvBlockChange
Definition: validation.cpp:78
CFeeRate dustRelayFee
Definition: policy.cpp:263