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