PRCYCoin  2.0.0.7rc1
P2P Digital Currency
init.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin developers
3 // Copyright (c) 2014-2015 The Dash developers
4 // Copyright (c) 2015-2018 The PIVX developers
5 // Copyright (c) 2018-2020 The DAPS Project developers
6 // Distributed under the MIT software license, see the accompanying
7 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 
9 #if defined(HAVE_CONFIG_H)
10 #include "config/prcycoin-config.h"
11 #endif
12 
13 #include "init.h"
14 
15 #include "activemasternode.h"
16 #include "addrman.h"
17 #include "amount.h"
18 #include "checkpoints.h"
19 #include "compat/sanity.h"
20 #include "fs.h"
21 #include "httpserver.h"
22 #include "httprpc.h"
23 #include "invalid.h"
24 #include "key.h"
25 #include "main.h"
26 #include "masternode-budget.h"
27 #include "masternode-payments.h"
28 #include "masternodeconfig.h"
29 #include "masternodeman.h"
30 #include "messagesigner.h"
31 #include "miner.h"
32 #include "netbase.h"
33 #include "net.h"
34 #include "rpc/server.h"
35 #include "script/standard.h"
36 #include "script/sigcache.h"
37 #include "scheduler.h"
38 #include "txdb.h"
39 #include "torcontrol.h"
40 #include "guiinterface.h"
41 #include "guiinterfaceutil.h"
42 #include "util.h"
43 #include "utilmoneystr.h"
44 #include "util/threadnames.h"
45 #include "validationinterface.h"
46 #ifdef ENABLE_WALLET
47 #include "wallet/db.h"
48 #include "wallet/wallet.h"
49 #include "wallet/walletdb.h"
50 
51 #endif
52 
53 #include <fstream>
54 #include <stdint.h>
55 #include <stdio.h>
56 
57 #ifndef WIN32
58 #include <signal.h>
59 #endif
60 
61 #include <boost/algorithm/string/predicate.hpp>
62 #include <boost/algorithm/string/replace.hpp>
63 #include <boost/foreach.hpp>
64 #include <boost/interprocess/sync/file_lock.hpp>
65 #include <boost/thread.hpp>
66 #include <openssl/crypto.h>
67 
68 #if ENABLE_ZMQ
70 #endif
71 
72 
73 #ifdef ENABLE_WALLET
74 int nWalletBackups = 10;
75 #endif
76 volatile bool fFeeEstimatesInitialized = false;
77 volatile bool fRestartRequested = false; // true: restart false: shutdown
78 
79 #if ENABLE_ZMQ
80 static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
81 #endif
82 
83 #ifdef WIN32
84 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
85 // accessing block files, don't count towards to fd_set size limit
86 // anyway.
87 #define MIN_CORE_FILEDESCRIPTORS 0
88 #else
89 #define MIN_CORE_FILEDESCRIPTORS 150
90 #endif
91 
93 enum BindFlags {
94  BF_NONE = 0,
95  BF_EXPLICIT = (1U << 0),
96  BF_REPORT_ERROR = (1U << 1),
97  BF_WHITELIST = (1U << 2),
98 };
99 
100 static const char* FEE_ESTIMATES_FILENAME = "fee_estimates.dat";
102 
104 //
105 // Shutdown
106 //
107 
108 //
109 // Thread management and startup/shutdown:
110 //
111 // The network-processing threads are all part of a thread group
112 // created by AppInit() or the Qt main() function.
113 //
114 // A clean exit happens when StartShutdown() or the SIGTERM
115 // signal handler sets fRequestShutdown, which triggers
116 // the DetectShutdownThread(), which interrupts the main thread group.
117 // DetectShutdownThread() then exits, which causes AppInit() to
118 // continue (it .joins the shutdown thread).
119 // Shutdown() is then
120 // called to clean up database connections, and stop other
121 // threads that should only be stopped after the main network-processing
122 // threads have exited.
123 //
124 // Shutdown for Qt is very similar, only it uses a QTimer to detect
125 // fRequestShutdown getting set, and then does the normal Qt
126 // shutdown thing.
127 //
128 
129 volatile bool fRequestShutdown = false;
130 
132 {
133  fRequestShutdown = true;
134 }
136 {
138 }
139 
141 {
142 public:
144  bool GetCoins(const uint256& txid, CCoins& coins) const
145  {
146  try {
147  return CCoinsViewBacked::GetCoins(txid, coins);
148  } catch (const std::runtime_error& e) {
149  uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
150  LogPrintf("Error reading from database: %s\n", e.what());
151  // Starting the shutdown sequence and returning false to the caller would be
152  // interpreted as 'entry not found' (as opposed to unable to read data), and
153  // could lead to invalid interpration. Just exit immediately, as we can't
154  // continue anyway, and all writes should be atomic.
155  abort();
156  }
157  }
158  // Writes do not need similar protection, as failure to write is handled by the caller.
159 };
160 
161 static CCoinsViewDB* pcoinsdbview = NULL;
162 static CCoinsViewErrorCatcher* pcoinscatcher = NULL;
163 
164 static boost::thread_group threadGroup;
165 static CScheduler scheduler;
166 void Interrupt()
167 {
170  InterruptRPC();
171  InterruptREST();
173 }
174 
177 {
178  fRequestShutdown = true; // Needed when we shutdown the wallet
179  fRestartRequested = true; // Needed when we restart the wallet
180  LogPrintf("%s: In progress...\n", __func__);
181  static RecursiveMutex cs_Shutdown;
182  TRY_LOCK(cs_Shutdown, lockShutdown);
183  if (!lockShutdown)
184  return;
185 
190  util::ThreadRename("prcycoin-shutoff");
192  StopHTTPRPC();
193  StopREST();
194  StopRPC();
195  StopHTTPServer();
196 #ifdef ENABLE_WALLET
197  if (pwalletMain)
198  bitdb.Flush(false);
199  GeneratePrcycoins(false, NULL, 0);
200 #endif
201  StopNode();
202 
203  // After everything has been shut down, but before things get flushed, stop the
204  // CScheduler/checkqueue threadGroup
205  threadGroup.interrupt_all();
206  threadGroup.join_all();
207 
208  DumpMasternodes();
209  DumpBudgets();
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  mempool.WriteFeeEstimates(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  {
224  LOCK(cs_main);
225  if (pcoinsTip != NULL) {
227 
228  //record that client took the proper shutdown procedure
229  pblocktree->WriteFlag("shutdown", true);
230  }
231  delete pcoinsTip;
232  pcoinsTip = NULL;
233  delete pcoinscatcher;
234  pcoinscatcher = NULL;
235  delete pcoinsdbview;
236  pcoinsdbview = NULL;
237  delete pblocktree;
238  pblocktree = NULL;
239  }
240 #ifdef ENABLE_WALLET
241  if (pwalletMain)
242  bitdb.Flush(true);
243 #endif
244 
245 #if ENABLE_ZMQ
246  if (pzmqNotificationInterface) {
247  UnregisterValidationInterface(pzmqNotificationInterface);
248  delete pzmqNotificationInterface;
249  pzmqNotificationInterface = NULL;
250  }
251 #endif
252 
253  // Disconnect all slots
255 
256 #ifndef WIN32
257  try {
258  fs::remove(GetPidFile());
259  } catch (const fs::filesystem_error& e) {
260  LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
261  }
262 #endif
263 }
264 
274 void Shutdown()
275 {
276  // Shutdown part 1: prepare shutdown
277  if (!fRestartRequested) {
278  PrepareShutdown();
279  }
280 
281 // Shutdown part 2: Stop TOR thread and delete wallet instance
282  StopTorControl();
283 #ifdef ENABLE_WALLET
284  delete pwalletMain;
285  pwalletMain = NULL;
286 #endif
287  DestroyContext();
288  LogPrintf("%s: done\n", __func__);
289 }
290 
294 void HandleSIGTERM(int)
295 {
296  StartShutdown();
297 }
298 
299 void HandleSIGHUP(int)
300 {
301  g_logger->m_reopen_file = true;
302 }
303 
304 #ifndef WIN32
305 static void registerSignalHandler(int signal, void(*handler)(int))
306 {
307  struct sigaction sa;
308  sa.sa_handler = handler;
309  sigemptyset(&sa.sa_mask);
310  sa.sa_flags = 0;
311  sigaction(signal, &sa, nullptr);
312 }
313 #endif
314 
315 bool static Bind(const CService& addr, unsigned int flags)
316 {
317  if (!(flags & BF_EXPLICIT) && IsLimited(addr))
318  return false;
319  std::string strError;
320  if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
321  if (flags & BF_REPORT_ERROR)
322  return UIError(strError);
323  return false;
324  }
325  return true;
326 }
327 
329 {
331 }
332 
334 {
336  //RPCNotifyBlockChange(0);
337  g_best_block_cv.notify_all();
338  LogPrint(BCLog::RPC, "RPC stopped.\n");
339 }
340 
341 void OnRPCPreCommand(const CRPCCommand& cmd)
342 {
343 #ifdef ENABLE_WALLET
344  if (cmd.reqWallet && !pwalletMain)
345  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
346 #endif
347  // Observe safe mode
348  std::string strWarning = GetWarnings("rpc");
349  if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
350  !cmd.okSafeMode)
351  throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
352 }
353 
354 std::string HelpMessage(HelpMessageMode mode)
355 {
356 
357  // When adding new options to the categories, please keep and ensure alphabetical ordering.
358  std::string strUsage = HelpMessageGroup(_("Options:"));
359  strUsage += HelpMessageOpt("-?", _("This help message"));
360  strUsage += HelpMessageOpt("-version", _("Print version and exit"));
361  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)"));
362  strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
363  strUsage += HelpMessageOpt("-blocksizenotify=<cmd>", _("Execute command when the best block changes and its size is over (%s in cmd is replaced by block hash, %d with the block size)"));
364  strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 500));
365  strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "prcycoin.conf"));
366  if (mode == HMM_BITCOIND) {
367 #if !defined(WIN32)
368  strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
369 #endif
370  }
371  strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
372  strUsage += HelpMessageOpt("-debuglogfile=<file>", strprintf(_("Specify location of debug log file: this can be an absolute path or a path relative to the data directory (default: %s)"), DEFAULT_DEBUGLOGFILE));
373  strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
374  strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup"));
375  strUsage += HelpMessageOpt("-maxreorg=<n>", strprintf(_("Set the Maximum reorg depth (default: %u)"), Params(CBaseChainParams::MAIN).MaxReorganizationDepth()));
376  strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
377  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)"), -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
378 #ifndef WIN32
379  strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "prcycoind.pid"));
380 #endif
381  strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files") + " " + _("on startup"));
382  strUsage += HelpMessageOpt("-reindexmoneysupply",strprintf(_("Reindex the %s money supply statistics"), CURRENCY_UNIT) + " " + _("on startup"));
383  strUsage += HelpMessageOpt("-resync", _("Delete blockchain folders and resync from scratch") + " " + _("on startup"));
384 #if !defined(WIN32)
385  strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
386 #endif
387  strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
388  strUsage += HelpMessageOpt("-forcestart", _("Attempt to force blockchain corruption recovery") + " " + _("on startup"));
389 
390  strUsage += HelpMessageGroup(_("Connection options:"));
391  strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
392  strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100));
393  strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400));
394  strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
395  strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -noconnect or -connect=0 alone to disable automatic connections"));
396  strUsage += HelpMessageOpt("-discover", _("Discover own IP address (default: 1 when listening and no -externalip)"));
397  strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)"));
398  strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect/-noconnect)"));
399  strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
400  strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0));
401  strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect/-noconnect)"));
402  strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
403  strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
404  strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000));
405  strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000));
406  strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
407  strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
408  strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1));
409  strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
410  strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 59682, 59684));
411  strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
412  strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1));
413  strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
414  strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
415  strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
416  strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
417 #ifdef USE_UPNP
418 #if USE_UPNP
419  strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening)"));
420 #else
421  strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
422 #endif
423 #endif
424  strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
425  strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
426  " " + _("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"));
427 
428 
429 #ifdef ENABLE_WALLET
430  strUsage += HelpMessageGroup(_("Wallet options:"));
431  strUsage += HelpMessageOpt("-backuppath=<(dir/file)>", _("Specify custom backup path to add a copy of any wallet backup. If set as dir, every backup generates a timestamped file. If set as file, will rewrite to that file every backup."));
432  strUsage += HelpMessageOpt("-createwalletbackups=<n>", _("Number of automatic wallet backups (default: 10)"));
433  strUsage += HelpMessageOpt("-custombackupthreshold=<n>", strprintf(_("Number of custom location backups to retain (default: %d)"), DEFAULT_CUSTOMBACKUPTHRESHOLD));
434  strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
435  strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100));
436  strUsage += HelpMessageOpt("-deletetx", _("Enable Old Transaction Deletion"));
437  strUsage += HelpMessageOpt("-deleteinterval", strprintf(_("Delete transaction every <n> blocks during inital block download (default: %i)"), DEFAULT_TX_DELETE_INTERVAL));
438  strUsage += HelpMessageOpt("-keeptxnum", strprintf(_("Keep the last <n> transactions (default: %i)"), DEFAULT_TX_RETENTION_LASTTX));
439  strUsage += HelpMessageOpt("-keeptxfornblocks", strprintf(_("Keep transactions for at least <n> blocks (default: %i)"), DEFAULT_TX_RETENTION_BLOCKS));
440  if (GetBoolArg("-help-debug", false))
441  strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/Kb) smaller than this are considered zero fee for transaction creation (default: %s)"),
443  strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"), CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
444  strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
445  strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
446  strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
447  strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1));
448  strUsage += HelpMessageOpt("-disablesystemnotifications", strprintf(_("Disable OS notifications for incoming transactions (default: %u)"), 0));
449  strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), 1));
450  strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees to use in a single wallet transaction, setting too low may abort large transactions (default: %s)"),
452  strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup"));
453  strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
454  strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
455  if (mode == HMM_BITCOIN_QT)
456  strUsage += HelpMessageOpt("-windowtitle=<name>", _("Wallet window title"));
457  strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
458  " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
459 #endif
460 
461 #if ENABLE_ZMQ
462  strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
463  strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
464  strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
465  strUsage += HelpMessageOpt("-zmqpubhashtxlock=<address>", _("Enable publish hash transaction (locked via SwiftX) in <address>"));
466  strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
467  strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
468  strUsage += HelpMessageOpt("-zmqpubrawtxlock=<address>", _("Enable publish raw transaction (locked via SwiftX) in <address>"));
469 #endif
470 
471  strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
472  strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
473  if (GetBoolArg("-help-debug", false)) {
474  strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
475  strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
476  strUsage += HelpMessageOpt("-checkpoints", strprintf(_("Only accept block chain matching built-in checkpoints (default: %u)"), 1));
477  strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf(_("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)"), 100));
478  strUsage += HelpMessageOpt("-disablesafemode", strprintf(_("Disable safemode, override a real safe mode event (default: %u)"), 0));
479  strUsage += HelpMessageOpt("-testsafemode", strprintf(_("Force safe mode (default: %u)"), 0));
480  strUsage += HelpMessageOpt("-dropmessagestest=<n>", _("Randomly drop 1 of every <n> network messages"));
481  strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", _("Randomly fuzz 1 of every <n> network messages"));
482  strUsage += HelpMessageOpt("-flushwallet", strprintf(_("Run a thread to flush wallet periodically (default: %u)"), 1));
483  strUsage += HelpMessageOpt("-maxreorg", strprintf(_("Use a custom max chain reorganization depth (default: %u)"), 100));
484  strUsage += HelpMessageOpt("-stopafterblockimport", strprintf(_("Stop running after importing blocks from disk (default: %u)"), 0));
485  }
486  strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
487  _("If <category> is not supplied, output all debugging information.") + _("<category> can be:") + " " + ListLogCategories() + ".");
488  strUsage += HelpMessageOpt("-debugexclude=<category>", _("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."));
489  if (GetBoolArg("-help-debug", false))
490  strUsage += HelpMessageOpt("-nodebug", "Turn off debugging messages, same as -debug=0");
491 #ifdef ENABLE_WALLET
492  strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0));
493  strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
494 #endif
495  strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
496  strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
497  strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
498  if (GetBoolArg("-help-debug", false)) {
499  strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf(_("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default:%u)"), 15));
500  strUsage += HelpMessageOpt("-relaypriority", strprintf(_("Require high priority for relaying free or low-fee transactions (default:%u)"), 1));
501  strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf(_("Limit size of signature cache to <n> MiB (default: %u)"), DEFAULT_MAX_SIG_CACHE_SIZE));
502  }
503  strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
504  strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/Kb) smaller than this are considered zero fee for relaying (default: %s)"), CURRENCY_UNIT, FormatMoney(::minRelayTxFee.GetFeePerK())));
505  strUsage += HelpMessageOpt("-printtoconsole", strprintf(_("Send trace/debug info to console instead of debug.log file (default: %u)"), 0));
506  if (GetBoolArg("-help-debug", false)) {
507  strUsage += HelpMessageOpt("-printpriority", strprintf(_("Log transaction priority and fee per kB when mining blocks (default: %u)"), 0));
508  strUsage += HelpMessageOpt("-privdb", strprintf(_("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"), 1));
509  strUsage += HelpMessageOpt("-regtest", _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly.") + " " +
510  _("This is intended for regression testing tools and app development.") + " " +
511  _("In this mode -genproclimit controls how many blocks are generated immediately."));
512  }
513  strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
514  strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
515 
516 #ifdef ENABLE_WALLET
517  strUsage += HelpMessageGroup(_("Staking options:"));
518  strUsage += HelpMessageOpt("-staking=<n>", strprintf(_("Enable staking functionality (0-1, default: %u)"), 1));
519  strUsage += HelpMessageOpt("-prcystake=<n>", strprintf(_("Enable or disable staking functionality for PRCY inputs (0-1, default: %u)"), 1));
520  strUsage += HelpMessageOpt("-reservebalance=<amt>", _("Keep the specified amount available for spending at all times (default: 0)"));
521  if (GetBoolArg("-help-debug", false)) {
522  strUsage += HelpMessageOpt("-printstakemodifier", _("Display the stake modifier calculations in the debug.log file."));
523  strUsage += HelpMessageOpt("-printcoinstake", _("Display verbose coin stake messages in the debug.log file."));
524  }
525 #endif
526 
527  strUsage += HelpMessageGroup(_("Masternode options:"));
528  strUsage += HelpMessageOpt("-masternode=<n>", strprintf(_("Enable the client to act as a masternode (0-1, default: %u)"), 0));
529  strUsage += HelpMessageOpt("-mnconf=<file>", strprintf(_("Specify masternode configuration file (default: %s)"), "masternode.conf"));
530  strUsage += HelpMessageOpt("-mnconflock=<n>", strprintf(_("Lock masternodes from masternode configuration file (default: %u)"), 1));
531  strUsage += HelpMessageOpt("-masternodeprivkey=<n>", _("Set the masternode private key"));
532  strUsage += HelpMessageOpt("-masternodeaddr=<n>", strprintf(_("Set external address:port to get to this masternode (example: %s)"), "128.127.106.235:59682"));
533  strUsage += HelpMessageOpt("-budgetvotemode=<mode>", _("Change automatic finalized budget voting behavior. mode=auto: Vote for only exact finalized budget match to my generated budget. (string, default: auto)"));
534 
535  strUsage += HelpMessageGroup(_("SwiftX options:"));
536  strUsage += HelpMessageOpt("-enableswifttx=<n>", strprintf(_("Enable SwiftX, show confirmations for locked transactions (bool, default: %s)"), "true"));
537  strUsage += HelpMessageOpt("-swifttxdepth=<n>", strprintf(_("Show N confirmations for a successfully locked transaction (0-9999, default: %u)"), nSwiftTXDepth));
538 
539  strUsage += HelpMessageGroup(_("Node relay options:"));
540  strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1));
541  strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
542  if (GetBoolArg("-help-debug", false)) {
543  strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
544  }
545 
546  strUsage += HelpMessageGroup(_("Block creation options:"));
547  strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), 0));
548  strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
549  strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
550 
551  strUsage += HelpMessageGroup(_("RPC server options:"));
552  strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
553  strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0));
554  strUsage += HelpMessageOpt("-rpcbind=<addr>", _("Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)"));
555  strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
556  strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
557  strUsage += HelpMessageOpt("-rpcauth=<userpw>", _("Username and hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcuser. This option can be specified multiple times"));
558  strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 59683, 59685));
559  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"));
560  strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
561 
562  if (GetBoolArg("-help-debug", false)) {
563  strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
564  strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
565  }
566 
567  strUsage += HelpMessageOpt("-blockspamfilter=<n>", strprintf(_("Use block spam filter (default: %u)"), DEFAULT_BLOCK_SPAM_FILTER));
568  strUsage += HelpMessageOpt("-blockspamfiltermaxsize=<n>", strprintf(_("Maximum size of the list of indexes in the block spam filter (default: %u)"), DEFAULT_BLOCK_SPAM_FILTER_MAX_SIZE));
569  strUsage += HelpMessageOpt("-blockspamfiltermaxavg=<n>", strprintf(_("Maximum average size of an index occurrence in the block spam filter (default: %u)"), DEFAULT_BLOCK_SPAM_FILTER_MAX_AVG));
570 
571  return strUsage;
572 }
573 
574 std::string LicenseInfo()
575 {
576  return FormatParagraph(strprintf(_("Copyright (C) 2009-%i The Bitcoin Core Developers"), COPYRIGHT_YEAR)) + "\n" +
577  "\n" +
578  FormatParagraph(strprintf(_("Copyright (C) 2014-%i The Dash Core Developers"), COPYRIGHT_YEAR)) + "\n" +
579  "\n" +
580  FormatParagraph(strprintf(_("Copyright (C) 2015-%i The PIVX Core Developers"), COPYRIGHT_YEAR)) + "\n" +
581  "\n" +
582  FormatParagraph(strprintf(_("Copyright (C) 2018-%i The DAPS Project developers"), COPYRIGHT_YEAR)) + "\n" +
583  "\n" +
584  FormatParagraph(strprintf(_("Copyright (C) 2020-%i The PRivaCY Coin Developers"), COPYRIGHT_YEAR)) + "\n" +
585  "\n" +
586  FormatParagraph(_("This is experimental software.")) + "\n" +
587  "\n" +
588  FormatParagraph(_("Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.")) + "\n" +
589  "\n" +
590  FormatParagraph(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.")) +
591  "\n";
592 }
593 
594 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
595 {
596  if (initialSync || !pBlockIndex)
597  return;
598 
599  std::string strCmd = GetArg("-blocknotify", "");
600 
601  if (!strCmd.empty()) {
602  boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
603  std::thread t(runCommand, strCmd);
604  t.detach(); // thread runs free
605  }
606 }
607 
608 static void BlockSizeNotifyCallback(int size, const uint256& hashNewTip)
609 {
610  std::string strCmd = GetArg("-blocksizenotify", "");
611 
612  boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
613  boost::replace_all(strCmd, "%d", std::to_string(size));
614  boost::thread t(runCommand, strCmd); // thread runs free
615 }
616 
618 
619 static bool fHaveGenesis = false;
620 static std::mutex cs_GenesisWait;
621 static std::condition_variable condvar_GenesisWait;
622 
623 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
624 {
625  if (pBlockIndex != nullptr) {
626  {
627  std::unique_lock<std::mutex> lock_GenesisWait(cs_GenesisWait);
628  fHaveGenesis = true;
629  }
630  condvar_GenesisWait.notify_all();
631  }
632 }
633 
635 
636 
639  {
640  assert(fImporting == false);
641  fImporting = true;
642  }
643 
645  {
646  assert(fImporting == true);
647  fImporting = false;
648  }
649 };
650 
651 void ThreadImport(std::vector<fs::path> vImportFiles)
652 {
653  util::ThreadRename("prcycoin-loadblk");
654 
655  // -reindex
656  if (fReindex) {
657  CImportingNow imp;
658  int nFile = 0;
659  while (true) {
660  CDiskBlockPos pos(nFile, 0);
661  if (!fs::exists(GetBlockPosFilename(pos, "blk")))
662  break; // No block files left to reindex
663  FILE* file = OpenBlockFile(pos, true);
664  if (!file)
665  break; // This error is logged in OpenBlockFile
666  LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
667  LoadExternalBlockFile(file, &pos);
668  nFile++;
669  }
670  pblocktree->WriteReindexing(false);
671  fReindex = false;
672  LogPrintf("Reindexing finished\n");
673  // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
674  InitBlockIndex();
675  }
676 
677  // hardcoded $DATADIR/bootstrap.dat
678  fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
679  if (fs::exists(pathBootstrap)) {
680  FILE* file = fsbridge::fopen(pathBootstrap, "rb");
681  if (file) {
682  CImportingNow imp;
683  fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
684  LogPrintf("Importing bootstrap.dat...\n");
685  LoadExternalBlockFile(file);
686  RenameOver(pathBootstrap, pathBootstrapOld);
687  } else {
688  LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
689  }
690  }
691 
692  // -loadblock=
693  for (fs::path& path : vImportFiles) {
694  FILE* file = fsbridge::fopen(path, "rb");
695  if (file) {
696  CImportingNow imp;
697  LogPrintf("Importing blocks file %s...\n", path.string());
698  LoadExternalBlockFile(file);
699  } else {
700  LogPrintf("Warning: Could not open blocks file %s\n", path.string());
701  }
702  }
703 
704  if (GetBoolArg("-stopafterblockimport", false)) {
705  LogPrintf("Stopping after block import\n");
706  StartShutdown();
707  }
708 }
709 
714 bool InitSanityCheck(void)
715 {
716  if (!ECC_InitSanityCheck()) {
717  UIError("OpenSSL appears to lack support for elliptic curve cryptography. For more "
718  "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries");
719  return false;
720  }
721 
723  return false;
724 
725  if (!Random_SanityCheck()) {
726  UIError("OS cryptographic RNG sanity check failure. Aborting.");
727  return false;
728  }
729 
730  return true;
731 }
732 
734 {
738  if (!InitHTTPServer())
739  return false;
740  if (!StartRPC())
741  return false;
742  if (!StartHTTPRPC())
743  return false;
744  if (GetBoolArg("-rest", false) && !StartREST())
745  return false;
746  if (!StartHTTPServer())
747  return false;
748  return true;
749 }
750 
751 [[noreturn]] static void new_handler_terminate()
752 {
753  // Rather than throwing std::bad-alloc if allocation fails, terminate
754  // immediately to (try to) avoid chain corruption.
755  // Since LogPrintf may itself allocate memory, set the handler directly
756  // to terminate first.
757  std::set_new_handler(std::terminate);
758  LogPrintf("Error: Out of memory. Terminating.\n");
759 
760  // The log was successful, terminate now.
761  std::terminate();
762 };
763 
765 {
766 // ********************************************************* Step 1: setup
767 #ifdef _MSC_VER
768  // Turn off Microsoft heap dump noise
769  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
770  _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
771 #endif
772 #if _MSC_VER >= 1400
773  // Disable confusing "helpful" text message on abort, Ctrl-C
774  _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
775 #endif
776 #ifdef WIN32
777 // Enable Data Execution Prevention (DEP)
778  SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
779 #endif
780 
781  if (!SetupNetworking())
782  return UIError("Error: Initializing networking failed");
783 
784 #ifndef WIN32
785  if (GetBoolArg("-sysperms", false)) {
786 #ifdef ENABLE_WALLET
787  if (!GetBoolArg("-disablewallet", false))
788  return UIError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
789 #endif
790  } else {
791  umask(077);
792  }
793 
794  // Clean shutdown on SIGTERMx
795  registerSignalHandler(SIGTERM, HandleSIGTERM);
796  registerSignalHandler(SIGINT, HandleSIGTERM);
797 
798  // Reopen debug.log on SIGHUP
799  registerSignalHandler(SIGHUP, HandleSIGHUP);
800 
801 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
802  signal(SIGPIPE, SIG_IGN);
803 #endif
804 
805  std::set_new_handler(new_handler_terminate);
806 
807  return true;
808 }
809 
810 // Parameter interaction based on rules
812 {
813  if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
814  // when specifying an explicit binding address, you want to listen on it
815  // even when -connect or -proxy is specified
816  if (SoftSetBoolArg("-listen", true))
817  LogPrintf("%s : parameter interaction: -bind or -whitebind set -> setting -listen=1\n", __func__);
818  }
819 
820  if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
821  // when only connecting to trusted nodes, do not seed via DNS, or listen by default
822  if (SoftSetBoolArg("-dnsseed", false))
823  LogPrintf("%s : parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
824  if (SoftSetBoolArg("-listen", false))
825  LogPrintf("%s : parameter interaction: -connect set -> setting -listen=0\n", __func__);
826  }
827 
828  if (mapArgs.count("-proxy")) {
829  // to protect privacy, do not listen by default if a default proxy server is specified
830  if (SoftSetBoolArg("-listen", false))
831  LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
832  // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
833  // to listen locally, so don't rely on this happening through -listen below.
834  if (SoftSetBoolArg("-upnp", false))
835  LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
836  // to protect privacy, do not discover addresses by default
837  if (SoftSetBoolArg("-discover", false))
838  LogPrintf("%s : parameter interaction: -proxy set -> setting -discover=0\n", __func__);
839  }
840 
841  if (!GetBoolArg("-listen", true)) {
842  // do not map ports or try to retrieve public IP when not listening (pointless)
843  if (SoftSetBoolArg("-upnp", false))
844  LogPrintf("%s : parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
845  if (SoftSetBoolArg("-discover", false))
846  LogPrintf("%s : parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
847  if (SoftSetBoolArg("-listenonion", false))
848  LogPrintf("%s : parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
849  }
850 
851  if (mapArgs.count("-externalip")) {
852  // if an explicit public IP is specified, do not try to find others
853  if (SoftSetBoolArg("-discover", false))
854  LogPrintf("%s : parameter interaction: -externalip set -> setting -discover=0\n", __func__);
855  }
856 
857  if (GetBoolArg("-salvagewallet", false)) {
858  // Rewrite just private keys: rescan to find transactions
859  if (SoftSetBoolArg("-rescan", true))
860  LogPrintf("%s : parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
861  }
862 
863  // -zapwallettx implies a rescan
864  if (GetBoolArg("-zapwallettxes", false)) {
865  if (SoftSetBoolArg("-rescan", true))
866  LogPrintf("%s : parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
867  }
868 
869  if (!GetBoolArg("-enableswifttx", fEnableSwiftTX)) {
870  if (SoftSetArg("-swifttxdepth", "0"))
871  LogPrintf("%s : parameter interaction: -enableswifttx=false -> setting -nSwiftTXDepth=0\n", __func__);
872  }
873 }
874 
875 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
876 {
877  return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
878 }
879 
881 {
882  //g_logger->m_print_to_file = !IsArgNegated("-debuglogfile");
883  g_logger->m_print_to_file = true;
885 
886  // Add newlines to the logfile to distinguish this execution from the last
887  // one; called before console logging is set up, so this is only sent to
888  // debug.log.
889  LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
890 
891  g_logger->m_print_to_console = GetBoolArg("-printtoconsole", !GetBoolArg("-daemon", false));
892  g_logger->m_log_timestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
893  g_logger->m_log_time_micros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
894 
895  fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
896 
897  std::string version_string = FormatFullVersion();
898 #ifdef DEBUG
899  version_string += " (debug build)";
900 #else
901  version_string += " (release build)";
902 #endif
903  LogPrintf("PRCY version %s\n", version_string);
904 }
905 
909 bool AppInit2(bool isDaemon)
910 {
911  // ********************************************************* Step 1: setup
912  if (!AppInitBasicSetup())
913  return false;
914 
915  // ********************************************************* Step 2: parameter interactions
916 #ifdef ENABLE_WALLET
917  if (mapArgs.count("-reservebalance")) {
918  if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) {
919  UIError(_("Invalid amount for -reservebalance=<amount>"));
920  return false;
921  }
922  }
923 #endif
924 
925  // Make sure enough file descriptors are available
926  int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
927  nMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
928  nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
930  if (nFD < MIN_CORE_FILEDESCRIPTORS)
931  return UIError(_("Not enough file descriptors available."));
934 
935  // ********************************************************* Step 3: parameter-to-internal-flags
936 
937  // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
938  const std::vector<std::string>& categories = mapMultiArgs["-debug"];
939 
940  if (!(GetBoolArg("-nodebug", false) ||
941  find(categories.begin(), categories.end(), std::string("0")) != categories.end())) {
942  for (const auto& cat : categories) {
943  if (!g_logger->EnableCategory(cat)) {
944  UIWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
945  }
946  }
947  }
948 
949  // Now remove the logging categories which were explicitly excluded
950  if (mapMultiArgs.count("-debugexclude") > 0) {
951  const std::vector<std::string>& excludedCategories = mapMultiArgs.at("-debugexclude");
952  for (const auto& cat : excludedCategories) {
953  if (!g_logger->DisableCategory(cat)) {
954  UIWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
955  }
956  }
957  }
958 
959  // Check for -debugnet
960  if (GetBoolArg("-debugnet", false))
961  UIWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
962  // Check for -socks - as this is a privacy risk to continue, exit here
963  if (mapArgs.count("-socks"))
964  return UIError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
965  // Check for -tor - as this is a privacy risk to continue, exit here
966  if (GetBoolArg("-tor", false))
967  return UIError(_("Error: Unsupported argument -tor found, use -onion."));
968  // Exit early if -masternode=1 and -listen=0
969  if (GetBoolArg("-masternode", false) && !GetBoolArg("-listen", true))
970  return UIError(_("Error: -listen must be true if -masternode is set."));
971  // Exit early if -masternode=1 and -port is not the default port
972  if (GetBoolArg("-masternode", false) && GetListenPort() != Params().GetDefaultPort())
973  return UIError(strprintf(_("Error: Invalid port %d for running a masternode."), GetListenPort()) + "\n\n" +
974  strprintf(_("Masternodes are required to run on port %d for %s-net"), Params().GetDefaultPort(), Params().NetworkIDString()));
975 
976  if (GetBoolArg("-benchmark", false))
977  UIWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
978 
979  // Checkmempool and checkblockindex default to true in regtest mode
980  mempool.setSanityCheck(GetBoolArg("-checkmempool", Params().DefaultConsistencyChecks()));
981  fCheckBlockIndex = GetBoolArg("-checkblockindex", Params().DefaultConsistencyChecks());
982  Checkpoints::fEnabled = GetBoolArg("-checkpoints", true);
983 
984  // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
985  nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
986  if (nScriptCheckThreads <= 0)
987  nScriptCheckThreads += boost::thread::hardware_concurrency();
988  if (nScriptCheckThreads <= 1)
990  else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
991  nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
992 
993  setvbuf(stdout, NULL, _IOLBF, 0);
994 
995  // Staking needs a CWallet instance, so make sure wallet is enabled
996 #ifdef ENABLE_WALLET
997  bool fDisableWallet = GetBoolArg("-disablewallet", false);
998  if (fDisableWallet) {
999  if (SoftSetBoolArg("-staking", false))
1000  LogPrintf("%s : parameter interaction: wallet functionality not enabled -> setting -staking=0\n", __func__);
1001  }
1002 #endif
1003 
1004  nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1005  if (nConnectTimeout <= 0)
1006  nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1007 
1008  // Fee-per-kilobyte amount considered the same as "free"
1009  // If you are mining, be careful setting this:
1010  // if you set it to zero then
1011  // a transaction spammer can cheaply fill blocks using
1012  // 1-satoshi-fee transactions. It should be set above the real
1013  // cost to you of processing a transaction.
1014  if (mapArgs.count("-minrelaytxfee")) {
1015  CAmount n = 0;
1016  if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
1018  else
1019  return UIError(strprintf(_("Invalid amount for -%s=<amount>: '%s'"), "minrelaytxfee", mapArgs["-minrelaytxfee"]));
1020  }
1021 
1022 #ifdef ENABLE_WALLET
1023  std::string strWalletFile = GetArg("-wallet", "wallet.dat");
1025  return false;
1026 #endif // ENABLE_WALLET
1027 
1028  fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true) != 0;
1029  nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1030 
1031 
1032  if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1034 
1035  nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1036 
1037  // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
1038 
1039  RandomInit();
1040 
1041  // Sanity check
1042  if (!InitSanityCheck())
1043  return UIError(_("Initialization sanity check failed. PRCY is shutting down."));
1044 
1045  std::string strDataDir = GetDataDir().string();
1046 #ifdef ENABLE_WALLET
1047  // Wallet file must be a plain filename without a directory
1048  fs::path wallet_file_path(strWalletFile);
1049  if (strWalletFile != wallet_file_path.filename().string())
1050  return UIError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
1051 #endif
1052  // Make sure only a single PRCY process is using the data directory.
1053  fs::path pathLockFile = GetDataDir() / ".lock";
1054  FILE* file = fsbridge::fopen(pathLockFile, "a"); // empty lock file; created if it doesn't exist.
1055  if (file) fclose(file);
1056  static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1057 
1058  // Wait maximum 10 seconds if an old wallet is still running. Avoids lockup during restart
1059  if (!lock.timed_lock(boost::get_system_time() + boost::posix_time::seconds(10)))
1060  return UIError(strprintf(_("Cannot obtain a lock on data directory %s. PRCY is probably already running."), strDataDir));
1061 
1062 #ifndef WIN32
1063  CreatePidFile(GetPidFile(), getpid());
1064 #endif
1065  if (g_logger->m_print_to_file) {
1066  if (GetBoolArg("-shrinkdebugfile", g_logger->DefaultShrinkDebugFile()))
1068  if (!g_logger->OpenDebugLog())
1069  return UIError(strprintf("Could not open debug log file %s", g_logger->m_file_path.string()));
1070  }
1071  LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
1072 #ifdef ENABLE_WALLET
1073  LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
1074 #endif
1075  if (!g_logger->m_log_timestamps)
1076  LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1077  LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1078  LogPrintf("Using data directory %s\n", strDataDir);
1079  LogPrintf("Using config file %s\n", GetConfigFile().string());
1080  LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
1081  std::ostringstream strErrors;
1082 
1084 
1085  LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1086  if (nScriptCheckThreads) {
1087  for (int i = 0; i < nScriptCheckThreads - 1; i++)
1088  threadGroup.create_thread(&ThreadScriptCheck);
1089  }
1090 
1091  // Start the lightweight task scheduler thread
1092  CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1093  threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1094 
1095  /* Start the RPC server already. It will be started in "warmup" mode
1096  * and not really process calls already (but it will signify connections
1097  * that the server is there and will be ready later). Warmup mode will
1098  * be disabled when initialisation is finished.
1099  */
1100  if (GetBoolArg("-server", false)) {
1102  if (!AppInitServers())
1103  return UIError(_("Unable to start HTTP server. See debug log for details."));
1104  }
1105 
1106 // ********************************************************* Step 5: Backup wallet and verify wallet database integrity
1107 #ifdef ENABLE_WALLET
1108  if (!fDisableWallet) {
1109  fs::path backupDir = GetDataDir() / "backups";
1110  if (!fs::exists(backupDir)) {
1111  // Always create backup folder to not confuse the operating system's file browser
1112  fs::create_directories(backupDir);
1113  }
1114  nWalletBackups = GetArg("-createwalletbackups", 10);
1115  nWalletBackups = std::max(0, std::min(10, nWalletBackups));
1116  if (nWalletBackups > 0) {
1117  if (fs::exists(backupDir)) {
1118  // Create backup of the wallet
1119  std::string dateTimeStr = DateTimeStrFormat(".%Y-%m-%d-%H-%M", GetTime());
1120  std::string backupPathStr = backupDir.string();
1121  backupPathStr += "/" + strWalletFile;
1122  std::string sourcePathStr = GetDataDir().string();
1123  sourcePathStr += "/" + strWalletFile;
1124  fs::path sourceFile = sourcePathStr;
1125  fs::path backupFile = backupPathStr + dateTimeStr;
1126  sourceFile.make_preferred();
1127  backupFile.make_preferred();
1128  if (fs::exists(sourceFile)) {
1129 #if BOOST_VERSION >= 105800
1130  try {
1131  fs::copy_file(sourceFile, backupFile);
1132  LogPrintf("Creating backup of %s -> %s\n", sourceFile, backupFile);
1133  } catch (const fs::filesystem_error& error) {
1134  LogPrintf("Failed to create backup %s\n", error.what());
1135  }
1136 #else
1137  std::ifstream src(sourceFile.string(), std::ios::binary);
1138  std::ofstream dst(backupFile.string(), std::ios::binary);
1139  dst << src.rdbuf();
1140 #endif
1141  }
1142  // Keep only the last 10 backups, including the new one of course
1143  typedef std::multimap<std::time_t, fs::path> folder_set_t;
1144  folder_set_t folder_set;
1145  fs::directory_iterator end_iter;
1146  fs::path backupFolder = backupDir.string();
1147  backupFolder.make_preferred();
1148  // Build map of backup files for current(!) wallet sorted by last write time
1149  fs::path currentFile;
1150  for (fs::directory_iterator dir_iter(backupFolder); dir_iter != end_iter; ++dir_iter) {
1151  // Only check regular files
1152  if (fs::is_regular_file(dir_iter->status())) {
1153  currentFile = dir_iter->path().filename();
1154  // Only add the backups for the current wallet, e.g. wallet.dat.*
1155  if (dir_iter->path().stem().string() == strWalletFile) {
1156  folder_set.insert(folder_set_t::value_type(fs::last_write_time(dir_iter->path()), *dir_iter));
1157  }
1158  }
1159  }
1160  // Loop backward through backup files and keep the N newest ones (1 <= N <= 10)
1161  int counter = 0;
1162  BOOST_REVERSE_FOREACH (PAIRTYPE(const std::time_t, fs::path) file, folder_set) {
1163  counter++;
1164  if (counter > nWalletBackups) {
1165  // More than nWalletBackups backups: delete oldest one(s)
1166  try {
1167  fs::remove(file.second);
1168  LogPrintf("Old backup deleted: %s\n", file.second);
1169  } catch (const fs::filesystem_error& error) {
1170  LogPrintf("Failed to delete backup %s\n", error.what());
1171  }
1172  }
1173  }
1174  }
1175  }
1176 
1177  if (GetBoolArg("-resync", false)) {
1178  uiInterface.InitMessage(_("Preparing for resync..."));
1179  // Delete the local blockchain folders to force a resync from scratch to get a consitent blockchain-state
1180  fs::path blocksDir = GetDataDir() / "blocks";
1181  fs::path chainstateDir = GetDataDir() / "chainstate";
1182 
1183  // We delete in 4 individual steps in case one of the folder is missing already
1184  try {
1185  if (fs::exists(blocksDir)){
1186  fs::remove_all(blocksDir);
1187  LogPrintf("-resync: folder deleted: %s\n", blocksDir.string().c_str());
1188  }
1189 
1190  if (fs::exists(chainstateDir)){
1191  fs::remove_all(chainstateDir);
1192  LogPrintf("-resync: folder deleted: %s\n", chainstateDir.string().c_str());
1193  }
1194  } catch (const fs::filesystem_error& error) {
1195  LogPrintf("Failed to delete blockchain folders %s\n", error.what());
1196  }
1197  }
1198 
1199  LogPrintf("Using wallet %s\n", strWalletFile);
1200  uiInterface.InitMessage(_("Verifying wallet..."));
1201 
1202  if (!bitdb.Open(GetDataDir())) {
1203  // try moving the database env out of the way
1204  fs::path pathDatabase = GetDataDir() / "database";
1205  fs::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
1206  try {
1207  fs::rename(pathDatabase, pathDatabaseBak);
1208  LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
1209  } catch (const fs::filesystem_error& error) {
1210  // failure is ok (well, not really, but it's not worse than what we started with)
1211  }
1212 
1213  // try again
1214  if (!bitdb.Open(GetDataDir())) {
1215  // if it still fails, it probably means we can't even create the database env
1216  std::string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir);
1217  return UIError(msg);
1218  }
1219  }
1220 
1221  if (GetBoolArg("-salvagewallet", false)) {
1222  // Recover readable keypairs:
1223  if (!CWalletDB::Recover(bitdb, strWalletFile, true))
1224  return false;
1225  }
1226 
1227  if (fs::exists(GetDataDir() / strWalletFile)) {
1229  if (r == CDBEnv::RECOVER_OK) {
1230  std::string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
1231  " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
1232  " your balance or transactions are incorrect you should"
1233  " restore from a backup."),
1234  strDataDir);
1235  UIWarning(msg);
1236  }
1237  if (r == CDBEnv::RECOVER_FAIL)
1238  return UIError(_("wallet.dat corrupt, salvage failed"));
1239  }
1240 
1241  } // (!fDisableWallet)
1242 #endif // ENABLE_WALLET
1243  // ********************************************************* Step 6: network initialization
1245 
1246  // sanitize comments per BIP-0014, format user agent and check total size
1247  std::vector<std::string> uacomments;
1248  for (const std::string& cmt : mapMultiArgs["-uacomment"]) {
1249  if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1250  return UIError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1251  uacomments.push_back(cmt);
1252  }
1253 
1254  // format user agent, check total size
1255  strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1256  if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1257  return UIError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1258  strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1259  }
1260 
1261  if (mapArgs.count("-onlynet")) {
1262  std::set<enum Network> nets;
1263  for (std::string snet : mapMultiArgs["-onlynet"]) {
1264  enum Network net = ParseNetwork(snet);
1265  if (net == NET_UNROUTABLE)
1266  return UIError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1267  nets.insert(net);
1268  }
1269  for (int n = 0; n < NET_MAX; n++) {
1270  enum Network net = (enum Network)n;
1271  if (!nets.count(net))
1272  SetLimited(net);
1273  }
1274  }
1275 
1276  if (mapArgs.count("-whitelist")) {
1277  for (const std::string& net : mapMultiArgs["-whitelist"]) {
1278  CSubNet subnet;
1279  LookupSubNet(net.c_str(), subnet);
1280  if (!subnet.IsValid())
1281  return UIError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1283  }
1284  }
1285 
1286  // Check for host lookup allowed before parsing any network related parameters
1287  fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1288 
1289  bool proxyRandomize = GetBoolArg("-proxyrandomize", true);
1290  // -proxy sets a proxy for all outgoing network traffic
1291  // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1292  std::string proxyArg = GetArg("-proxy", "");
1294  if (proxyArg != "" && proxyArg != "0") {
1295  CService proxyAddr;
1296  if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1297  return UIError(strprintf(_("Lookup(): Invalid -proxy address or hostname: '%s'"), proxyArg));
1298  }
1299 
1300  proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1301  if (!addrProxy.IsValid())
1302  return UIError(strprintf(_("isValid(): Invalid -proxy address or hostname: '%s'"), proxyArg));
1303 
1304  SetProxy(NET_IPV4, addrProxy);
1305  SetProxy(NET_IPV6, addrProxy);
1306  SetProxy(NET_TOR, addrProxy);
1307  SetNameProxy(addrProxy);
1308  SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1309  }
1310 
1311  // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1312  // -noonion (or -onion=0) disables connecting to .onion entirely
1313  // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1314  std::string onionArg = GetArg("-onion", "");
1315  if (onionArg != "") {
1316  if (onionArg == "0") { // Handle -noonion/-onion=0
1317  SetLimited(NET_TOR); // set onions as unreachable
1318  } else {
1319  CService onionProxy;
1320  if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1321  return UIError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1322  }
1323  proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1324  if (!addrOnion.IsValid())
1325  return UIError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1326  SetProxy(NET_TOR, addrOnion);
1327  SetLimited(NET_TOR, false);
1328  }
1329  }
1330 
1331  // see Step 2: parameter interactions for more information about these
1332  fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1333  fDiscover = GetBoolArg("-discover", true);
1334 
1335  bool fBound = false;
1336  if (fListen) {
1337  if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
1338  for (std::string strBind : mapMultiArgs["-bind"]) {
1339  CService addrBind;
1340  if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1341  return UIError(ResolveErrMsg("bind", strBind));
1342  fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1343  }
1344  for (std::string strBind : mapMultiArgs["-whitebind"]) {
1345  CService addrBind;
1346  if (!Lookup(strBind.c_str(), addrBind, 0, false))
1347  return UIError(ResolveErrMsg("whitebind", strBind));
1348  if (addrBind.GetPort() == 0)
1349  return UIError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1350  fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1351  }
1352  } else {
1353  struct in_addr inaddr_any;
1354  inaddr_any.s_addr = INADDR_ANY;
1355  fBound |= Bind(CService((in6_addr)IN6ADDR_ANY_INIT, GetListenPort()), BF_NONE);
1356  fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1357  }
1358  if (!fBound)
1359  return UIError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1360  }
1361 
1362  if (mapArgs.count("-externalip")) {
1363  for (std::string strAddr : mapMultiArgs["-externalip"]) {
1364  CService addrLocal;
1365  if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1366  AddLocal(addrLocal,LOCAL_MANUAL);
1367  else
1368  return UIError(ResolveErrMsg("externalip", strAddr));
1369  }
1370  }
1371 
1372  for (std::string strDest : mapMultiArgs["-seednode"])
1373  AddOneShot(strDest);
1374 
1375 #if ENABLE_ZMQ
1376  pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
1377 
1378  if (pzmqNotificationInterface) {
1379  RegisterValidationInterface(pzmqNotificationInterface);
1380  }
1381 #endif
1382 
1383  // ********************************************************* Step 7: load block chain
1384 
1385  fReindex = GetBoolArg("-reindex", false);
1386 
1387  // Create blocks directory if it doesn't already exist
1388  fs::create_directories(GetDataDir() / "blocks");
1389 
1390  // cache size calculations
1391  int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1392  nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1393  nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1394  int64_t nBlockTreeDBCache = nTotalCache / 8;
1395  if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", true))
1396  nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
1397  nTotalCache -= nBlockTreeDBCache;
1398  int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1399  nTotalCache -= nCoinDBCache;
1400  nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1401  LogPrintf("Cache configuration:\n");
1402  LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1403  LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1404  LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
1405 
1406  bool fLoaded = false;
1407  while (!fLoaded && !ShutdownRequested()) {
1408  bool fReset = fReindex;
1409  std::string strLoadError;
1410 
1411  uiInterface.InitMessage(_("Loading block index..."));
1412 
1413  do {
1414  const int64_t load_block_index_start_time = GetTimeMillis();
1415 
1416  try {
1417  UnloadBlockIndex();
1418  delete pcoinsTip;
1419  delete pcoinsdbview;
1420  delete pcoinscatcher;
1421  delete pblocktree;
1422 
1423  pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1424  pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
1425  pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1426  pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1427 
1428  if (fReindex)
1429  pblocktree->WriteReindexing(true);
1430 
1431  // End loop if shutdown was requested
1432  if (ShutdownRequested()) break;
1433 
1434  uiInterface.InitMessage(_("Loading block index..."));
1435  std::string strBlockIndexError = "";
1436  if (!LoadBlockIndex(strBlockIndexError)) {
1437  if (ShutdownRequested()) break;
1438  strLoadError = _("Error loading block database");
1439  strLoadError = strprintf("%s : %s", strLoadError, strBlockIndexError);
1440  break;
1441  }
1442 
1443  // If the loaded chain has a wrong genesis, bail out immediately
1444  // (we're likely using a testnet datadir, or the other way around).
1445  if (!mapBlockIndex.empty() && mapBlockIndex.count(Params().HashGenesisBlock()) == 0)
1446  return UIError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1447 
1448  // Initialize the block index (no-op if non-empty database was already loaded)
1449  if (!InitBlockIndex()) {
1450  strLoadError = _("Error initializing block database");
1451  break;
1452  }
1453 
1454  // Check for changed -txindex state
1455  if (fTxIndex != GetBoolArg("-txindex", true)) {
1456  strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
1457  break;
1458  }
1459 
1460  // Populate list of invalid/fraudulent outpoints that are banned from the chain
1462 
1463  // Recalculate money supply for blocks
1464  if (GetBoolArg("-reindexmoneysupply", false)) {
1466  }
1467 
1468  if (!fReindex) {
1469  uiInterface.InitMessage(_("Verifying blocks..."));
1470 
1471  // Flag sent to validation code to let it know it can skip certain checks
1472  fVerifyingBlocks = true;
1473 
1474  {
1475  LOCK(cs_main);
1477  RPCNotifyBlockChange(true, tip);
1478  if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1479  strLoadError = _("The block database contains a block which appears to be from the future. "
1480  "This may be due to your computer's date and time being set incorrectly. "
1481  "Only rebuild the block database if you are sure that your computer's date and time are correct");
1482  break;
1483  }
1484  }
1485 
1486  //Must check at level 4
1487  if (!CVerifyDB().VerifyDB(pcoinsdbview, 4, GetArg("-checkblocks", 100))) {
1488  strLoadError = _("Corrupted block database detected");
1489  fVerifyingBlocks = false;
1490  break;
1491  }
1492  }
1493  } catch (const std::exception& e) {
1494  LogPrintf("%s\n", e.what());
1495  strLoadError = _("Error opening block database");
1496  fVerifyingBlocks = false;
1497  break;
1498  }
1499 
1500  fVerifyingBlocks = false;
1501  fLoaded = true;
1502  LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time);
1503  } while (false);
1504 
1505  if (!fLoaded && !ShutdownRequested()) {
1506  // first suggest a reindex
1507  if (!fReset) {
1508  bool fRet = uiInterface.ThreadSafeMessageBox(
1509  strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1511  if (fRet) {
1512  fReindex = true;
1513  fRequestShutdown = false;
1514 
1515  fs::path blocksDir = GetDataDir() / "blocks";
1516  fs::path chainstateDir = GetDataDir() / "chainstate";
1517 
1518  // We delete in 4 individual steps in case one of the folder is missing already
1519  try {
1520  if (fs::exists(blocksDir)){
1521  fs::remove_all(blocksDir);
1522  LogPrintf("-resync: folder deleted: %s\n", blocksDir.string().c_str());
1523  }
1524 
1525  if (fs::exists(chainstateDir)){
1526  fs::remove_all(chainstateDir);
1527  LogPrintf("-resync: folder deleted: %s\n", chainstateDir.string().c_str());
1528  }
1529 
1530  fs::create_directories(blocksDir);
1531  fs::create_directories(chainstateDir);
1532  } catch (const fs::filesystem_error& error) {
1533  LogPrintf("Failed to delete blockchain folders %s\n", error.what());
1534  }
1535 
1536  } else {
1537  LogPrintf("Aborted block database rebuild. Exiting.\n");
1538  return false;
1539  }
1540  } else {
1541  return UIError(strLoadError);
1542  }
1543  }
1544  }
1545 
1546  // As LoadBlockIndex can take several minutes, it's possible the user
1547  // requested to kill the GUI during the last operation. If so, exit.
1548  // As the program has not fully started yet, Shutdown() is possibly overkill.
1549  if (ShutdownRequested()) {
1550  LogPrintf("Shutdown requested. Exiting.\n");
1551  return false;
1552  }
1553 
1554  fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1555  CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
1556  // Allowed to fail as this file IS missing on first startup.
1557  if (!est_filein.IsNull())
1558  mempool.ReadFeeEstimates(est_filein);
1559  fFeeEstimatesInitialized = true;
1560 
1561 // ********************************************************* Step 8: load wallet
1562 #ifdef ENABLE_WALLET
1563  if (fDisableWallet) {
1564  pwalletMain = NULL;
1565  LogPrintf("Wallet disabled!\n");
1566  } else {
1567  // needed to restore wallet transaction meta data after -zapwallettxes
1568  std::vector<CWalletTx> vWtx;
1569 
1570  if (GetBoolArg("-zapwallettxes", false)) {
1571  uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
1572 
1573  pwalletMain = new CWallet(strWalletFile);
1574  DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
1575  if (nZapWalletRet != DB_LOAD_OK) {
1576  uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
1577  return false;
1578  }
1579 
1580  delete pwalletMain;
1581  pwalletMain = NULL;
1582  }
1583 
1584  uiInterface.InitMessage(_("Loading... Please do not interrupt this process as it could lead to a corrupt wallet."));
1585  fVerifyingBlocks = true;
1586 
1587  const int64_t nWalletStartTime = GetTimeMillis();
1588  bool fFirstRun = true;
1589  pwalletMain = new CWallet(strWalletFile);
1590  DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
1591  if (nLoadWalletRet != DB_LOAD_OK) {
1592  if (nLoadWalletRet == DB_CORRUPT)
1593  strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
1594  else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) {
1595  std::string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
1596  " or address book entries might be missing or incorrect."));
1597  UIWarning(msg);
1598  } else if (nLoadWalletRet == DB_TOO_NEW)
1599  strErrors << _("Error loading wallet.dat: Wallet requires newer version of PRCYcoin") << "\n";
1600  else if (nLoadWalletRet == DB_NEED_REWRITE) {
1601  strErrors << _("Wallet needed to be rewritten: restart PRCY to complete") << "\n";
1602  LogPrintf("%s", strErrors.str());
1603  return UIError(strErrors.str());
1604  } else
1605  strErrors << _("Error loading wallet.dat") << "\n";
1606  }
1607 
1608  if (GetBoolArg("-upgradewallet", fFirstRun)) {
1609  int nMaxVersion = GetArg("-upgradewallet", 0);
1610  if (nMaxVersion == 0) // the -upgradewallet without argument case
1611  {
1612  LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
1613  nMaxVersion = CLIENT_VERSION;
1614  pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
1615  } else
1616  LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
1617  if (nMaxVersion < pwalletMain->GetVersion())
1618  strErrors << _("Cannot downgrade wallet") << "\n";
1619  pwalletMain->SetMaxVersion(nMaxVersion);
1620  }
1621 
1622  //Set Transaction Deletion Options
1623  fTxDeleteEnabled = GetBoolArg("-deletetx", false);
1624  fTxConflictDeleteEnabled = GetBoolArg("-deleteconflicttx", true);
1625 
1626  fDeleteInterval = GetArg("-deleteinterval", DEFAULT_TX_DELETE_INTERVAL);
1627  if (fDeleteInterval < 1)
1628  return UIError("deleteinterval must be greater than 0");
1629 
1630  fKeepLastNTransactions = GetArg("-keeptxnum", DEFAULT_TX_RETENTION_LASTTX);
1631  if (fKeepLastNTransactions < 1)
1632  return UIError("keeptxnum must be greater than 0");
1633 
1634  fDeleteTransactionsAfterNBlocks = GetArg("-keeptxfornblocks", DEFAULT_TX_RETENTION_BLOCKS);
1636  return UIError("keeptxfornblocks must be greater than 0");
1637 
1638  if (fDeleteTransactionsAfterNBlocks < Params().COINBASE_MATURITY() + 1 ) {
1639  LogPrintf("keeptxfornblock is less than Params().COINBASE_MATURITY(), Setting to %i\n", Params().COINBASE_MATURITY() + 1);
1641  }
1642 
1643  if (fFirstRun) {
1644  // Create new keyUser and set as default key
1645  if (!pwalletMain->IsHDEnabled()) {
1646  if (!isDaemon) {
1648  }
1649 
1650  if (!pwalletMain->IsHDEnabled()) {
1651  // generate a new master key
1653  }
1654  }
1655 
1656  CPubKey newDefaultKey;
1657  if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
1658  pwalletMain->SetDefaultKey(newDefaultKey);
1659  if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
1660  strErrors << _("Cannot write default address") << "\n";
1661  }
1662 
1664  }
1665 
1666  LogPrintf("%s", strErrors.str());
1667  LogPrintf("Wallet completed loading in %15dms\n", GetTimeMillis() - nWalletStartTime);
1668 
1670  int height = -1;
1671  CBlockIndex* pindexRescan = chainActive.Tip();
1672 
1673  {
1674  //Sort Transactions by block and block index, then reorder
1676  if (chainActive.Tip()) {
1677  LogPrintf("Running transaction reorder\n");
1678  int64_t maxOrderPos = 0;
1679  std::map<std::pair<int,int>, CWalletTx*> mapSorted;
1680  pwalletMain->ReorderWalletTransactions(mapSorted, maxOrderPos);
1681  pwalletMain->UpdateWalletTransactionOrder(mapSorted, true);
1682  }
1683  }
1684 
1685  if (GetBoolArg("-rescan", false)) {
1686  pindexRescan = chainActive.Genesis();
1687  } else {
1688  CWalletDB walletdb(strWalletFile);
1689  CBlockLocator locator;
1690  if (walletdb.ReadBestBlock(locator)) {
1691  pindexRescan = FindForkInGlobalIndex(chainActive, locator);
1692  } else {
1693  if (!walletdb.ReadScannedBlockHeight(height)) {
1694  if (height > chainActive.Height()) {
1695  pindexRescan = chainActive.Genesis();
1696  } else {
1697  pindexRescan = chainActive[height];
1698  }
1699  } else
1700  pindexRescan = chainActive.Genesis();
1701  }
1702  }
1703  if (chainActive.Tip() && chainActive.Tip() != pindexRescan) {
1704  uiInterface.InitMessage(_("Rescanning..."));
1705  LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
1706  const int64_t nWalletRescanTime = GetTimeMillis();
1707  if (pwalletMain->ScanForWalletTransactions(pindexRescan, true, true) == -1) {
1708  return error("Shutdown requested over the txs scan. Exiting.");
1709  }
1710  LogPrintf("Rescan completed in %15dms\n", GetTimeMillis() - nWalletRescanTime);
1713 
1714  // Restore wallet transaction metadata after -zapwallettxes=1
1715  if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2") {
1716  CWalletDB walletdb(strWalletFile);
1717  for (const CWalletTx& wtxOld : vWtx) {
1718  uint256 hash = wtxOld.GetHash();
1719  std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
1720  if (mi != pwalletMain->mapWallet.end()) {
1721  const CWalletTx* copyFrom = &wtxOld;
1722  CWalletTx* copyTo = &mi->second;
1723  copyTo->mapValue = copyFrom->mapValue;
1724  copyTo->vOrderForm = copyFrom->vOrderForm;
1725  copyTo->nTimeReceived = copyFrom->nTimeReceived;
1726  copyTo->nTimeSmart = copyFrom->nTimeSmart;
1727  copyTo->fFromMe = copyFrom->fFromMe;
1728  copyTo->strFromAccount = copyFrom->strFromAccount;
1729  copyTo->nOrderPos = copyFrom->nOrderPos;
1730  copyTo->WriteToDisk(&walletdb);
1731  }
1732  }
1733  }
1734  }
1735  fVerifyingBlocks = false;
1736 
1737  } // (!fDisableWallet)
1738 #else // ENABLE_WALLET
1739  LogPrintf("No wallet compiled in!\n");
1740 #endif // !ENABLE_WALLET
1741  // ********************************************************* Step 9: import blocks
1742 
1743  if (!CheckDiskSpace())
1744  return false;
1745 
1746  // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1747  // No locking, as this happens before any background thread is started.
1748  if (chainActive.Tip() == nullptr) {
1749  uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1750  } else {
1751  fHaveGenesis = true;
1752  }
1753 
1754  if (mapArgs.count("-blocknotify"))
1755  uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1756 
1757  if (mapArgs.count("-blocksizenotify"))
1758  uiInterface.NotifyBlockSize.connect(BlockSizeNotifyCallback);
1759 
1760  // scan for better chains in the block chain database, that are not yet connected in the active best chain
1761  CValidationState state;
1762  if (!ActivateBestChain(state)) {
1763  strErrors << "Failed to connect best block";
1764  StartShutdown();
1765  return false;
1766  }
1767  // update g_best_block if needed
1768  {
1770  if (g_best_block.IsNull() && chainActive.Tip()) {
1772  g_best_block_cv.notify_all();
1773  }
1774  }
1775 
1776  std::vector<fs::path> vImportFiles;
1777  if (mapArgs.count("-loadblock")) {
1778  for (std::string strFile : mapMultiArgs["-loadblock"])
1779  vImportFiles.push_back(strFile);
1780  }
1781  threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1782 
1783  // Wait for genesis block to be processed
1784  LogPrintf("Waiting for genesis block to be imported...\n");
1785  {
1786  std::unique_lock<std::mutex> lockG(cs_GenesisWait);
1787  while (!fHaveGenesis) {
1788  condvar_GenesisWait.wait(lockG);
1789  }
1790  uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1791  }
1792 
1793  // ********************************************************* Step 10: setup layer 2 data
1794 
1795  uiInterface.InitMessage(_("Loading masternode cache..."));
1796 
1797  CMasternodeDB mndb;
1798  CMasternodeDB::ReadResult readResult = mndb.Read(mnodeman);
1799  if (readResult == CMasternodeDB::FileError)
1800  LogPrintf("Missing masternode cache file - mncache.dat, will try to recreate\n");
1801  else if (readResult != CMasternodeDB::Ok) {
1802  LogPrintf("Error reading mncache.dat: ");
1803  if (readResult == CMasternodeDB::IncorrectFormat)
1804  LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
1805  else
1806  LogPrintf("file format is unknown or invalid, please fix it manually\n");
1807  }
1808 
1809  uiInterface.InitMessage(_("Loading budget cache..."));
1810 
1811  CBudgetDB budgetdb;
1812  CBudgetDB::ReadResult readResult2 = budgetdb.Read(budget);
1813 
1814  if (readResult2 == CBudgetDB::FileError)
1815  LogPrintf("Missing budget cache - budget.dat, will try to recreate\n");
1816  else if (readResult2 != CBudgetDB::Ok) {
1817  LogPrintf("Error reading budget.dat: ");
1818  if (readResult2 == CBudgetDB::IncorrectFormat)
1819  LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
1820  else
1821  LogPrintf("file format is unknown or invalid, please fix it manually\n");
1822  }
1823 
1824  //flag our cached items so we send them to our peers
1825  budget.ResetSync();
1826  budget.ClearSeen();
1827 
1828 
1829  uiInterface.InitMessage(_("Loading masternode payment cache..."));
1830 
1831  CMasternodePaymentDB mnpayments;
1832  CMasternodePaymentDB::ReadResult readResult3 = mnpayments.Read(masternodePayments);
1833 
1834  if (readResult3 == CMasternodePaymentDB::FileError)
1835  LogPrintf("Missing masternode payment cache - mnpayments.dat, will try to recreate\n");
1836  else if (readResult3 != CMasternodePaymentDB::Ok) {
1837  LogPrintf("Error reading mnpayments.dat: ");
1838  if (readResult3 == CMasternodePaymentDB::IncorrectFormat)
1839  LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
1840  else
1841  LogPrintf("file format is unknown or invalid, please fix it manually\n");
1842  }
1843 
1844  fMasterNode = GetBoolArg("-masternode", false);
1845 
1846  if ((fMasterNode || masternodeConfig.getCount() > -1) && fTxIndex == false) {
1847  return UIError("Enabling Masternode support requires turning on transaction indexing."
1848  "Please add txindex=1 to your configuration and start with -reindex");
1849  }
1850 
1851  if (fMasterNode) {
1852  LogPrintf("IS MASTER NODE\n");
1853  strMasterNodeAddr = GetArg("-masternodeaddr", "");
1854 
1855  LogPrintf(" addr %s\n", strMasterNodeAddr.c_str());
1856 
1857  if (!strMasterNodeAddr.empty()) {
1858  int nPort;
1859  int nDefaultPort = Params().GetDefaultPort();
1860  std::string strHost;
1861  SplitHostPort(strMasterNodeAddr, nPort, strHost);
1862 
1863  // Allow for the port number to be omitted here and just double check
1864  // that if a port is supplied, it matches the required default port.
1865  if (nPort == 0) nPort = nDefaultPort;
1866  if (nPort != nDefaultPort) {
1867  return UIError(strprintf(_("Invalid -masternodeaddr port %d, only %d is supported on %s-net."),
1868  nPort, nDefaultPort, Params().NetworkIDString()));
1869  }
1870  CService addrTest(LookupNumeric(strHost.c_str(), nPort));
1871  if (!addrTest.IsValid()) {
1872  return UIError(strprintf(_("Invalid -masternodeaddr address: %s"), strMasterNodeAddr));
1873  }
1874  }
1875 
1876  strMasterNodePrivKey = GetArg("-masternodeprivkey", "");
1877  if (!strMasterNodePrivKey.empty()) {
1878  std::string errorMessage;
1879 
1880  CKey key;
1881  CPubKey pubkey;
1882 
1884  return UIError(_("Invalid masternodeprivkey. Please see documenation."));
1885  }
1886 
1888 
1889  } else {
1890  return UIError(_("You must specify a masternodeprivkey in the configuration. Please see documentation for help."));
1891  }
1892  }
1893 
1894  //get the mode of budget voting for this masternode
1895  strBudgetMode = GetArg("-budgetvotemode", "auto");
1896 
1897 #ifdef ENABLE_WALLET
1898  if (GetBoolArg("-mnconflock", true) && pwalletMain) {
1900  LogPrintf("Locking Masternodes collateral utxo:\n");
1901  uint256 mnTxHash;
1902  for (const auto& mne : masternodeConfig.getEntries()) {
1903  mnTxHash.SetHex(mne.getTxHash());
1904  COutPoint outpoint = COutPoint(mnTxHash, (unsigned int) std::stoul(mne.getOutputIndex().c_str()));
1905  pwalletMain->LockCoin(outpoint);
1906  LogPrintf("Locked collateral, MN: %s, tx hash: %s, output index: %s\n",
1907  mne.getAlias(), mne.getTxHash(), mne.getOutputIndex());
1908  }
1909  }
1910 #endif
1911 
1912  fEnableSwiftTX = GetBoolArg("-enableswifttx", fEnableSwiftTX);
1913  nSwiftTXDepth = GetArg("-swifttxdepth", nSwiftTXDepth);
1914  nSwiftTXDepth = std::min(std::max(nSwiftTXDepth, 0), 60);
1915 
1916  // lite mode disables all Masternode related functionality
1917  fLiteMode = GetBoolArg("-litemode", false);
1918  if (fMasterNode && fLiteMode) {
1919  return UIError("You can not start a masternode in litemode");
1920  }
1921 
1922  LogPrintf("fLiteMode %d\n", fLiteMode);
1923  LogPrintf("nSwiftTXDepth %d\n", nSwiftTXDepth);
1924  LogPrintf("Budget Mode %s\n", strBudgetMode.c_str());
1925 
1926  threadGroup.create_thread(boost::bind(&ThreadCheckMasternodes));
1927 
1928  if (ShutdownRequested()) {
1929  LogPrintf("Shutdown requested. Exiting.\n");
1930  return false;
1931  }
1932 
1933  // ********************************************************* Step 11: start node
1934 
1935  if (!strErrors.str().empty())
1936  return UIError(strErrors.str());
1937 
1939  LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1940  LogPrintf("chainActive.Height() = %d\n", chainActive.Height());
1941 #ifdef ENABLE_WALLET
1942  LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
1943  LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
1944  LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
1945 #endif
1946 
1947  if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1948  StartTorControl(threadGroup);
1949 
1950  StartNode(threadGroup, scheduler);
1951 
1952 #ifdef ENABLE_WALLET
1953  // Generate coins in the background
1954  if (pwalletMain)
1955  GeneratePrcycoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 1));
1956 #endif
1957 
1958  // ********************************************************* Step 12: finished
1959 
1961  uiInterface.InitMessage(_("Done loading"));
1962 
1963 #ifdef ENABLE_WALLET
1964  bool storedStakingStatus = false;
1965 
1966  if (pwalletMain) {
1967  // Add wallet transactions that aren't already in a block to mapTransactions
1969  // Run a thread to flush wallet periodically
1970  threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
1971 
1972  // Check if there is a combinedust setting in the .conf file
1973  pwalletMain->fCombineDust = GetBoolArg("-combinedust", true);
1974  if (pwalletMain->fCombineDust){
1975  LogPrintf("Autocombinedust is enabled\n");
1976  } else {
1977  LogPrintf("Autocombinedust is disabled\n");
1978  }
1979 
1980  storedStakingStatus = pwalletMain->ReadStakingStatus();
1981  if (GetBoolArg("-staking", false) || storedStakingStatus) {
1982  fGeneratePrcycoins = true;
1984  LogPrintf("Starting staking\n");
1985  threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "stakemint", &ThreadStakeMinter));
1986  // combineMode should be OFF on first launch or keep previous setting when available
1987  // This changes that setting only if staking is on
1988  if (GetBoolArg("-autoconsolidate", false)){
1989  LogPrintf("Autoconsolidate is enabled and we are setting CombineMode::ON now\n");
1991  } else {
1993  LogPrintf("Autoconsolidate is disabled\n");
1994  }
1995  } else {
1996  LogPrintf("Staking is disabled\n");
1997  }
1998  //read decoy confirmation min
1999  pwalletMain->DecoyConfirmationMinimum = GetArg("-decoyconfirm", 15);
2000  CWalletDB walletdb(strWalletFile);
2001  double reserveBalance;
2002  if (walletdb.ReadReserveAmount(reserveBalance))
2003  nReserveBalance = reserveBalance * COIN;
2004  }
2005 #endif
2006 
2007  return !fRequestShutdown;
2008 }
RPC_METHOD_NOT_FOUND
@ RPC_METHOD_NOT_FOUND
Definition: protocol.h:34
StartHTTPRPC
bool StartHTTPRPC()
Start HTTP RPC subsystem.
Definition: httprpc.cpp:228
DB_TOO_NEW
@ DB_TOO_NEW
Definition: walletdb.h:40
CWalletDB::ReadReserveAmount
bool ReadReserveAmount(double &amount)
Definition: walletdb.cpp:167
CWallet::LockCoin
void LockCoin(COutPoint &output)
Definition: wallet.cpp:5057
InitLogging
void InitLogging()
Initialize the logging infrastructure.
Definition: init.cpp:880
OpenBlockFile
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
Definition: main.cpp:5150
LOCK2
#define LOCK2(cs1, cs2)
Definition: sync.h:183
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:133
fImporting
std::atomic< bool > fImporting
Definition: main.cpp:80
CTxMemPool::AddTransactionsUpdated
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:395
CScheduler
Definition: scheduler.h:37
fLogIPs
bool fLogIPs
Definition: logging.cpp:30
CMasternodeDB::FileError
@ FileError
Definition: masternodeman.h:43
BCLog::Logger::m_print_to_file
bool m_print_to_file
Definition: logging.h:92
CCoinsViewDB
CCoinsView backed by the LevelDB coin database (chainstate/)
Definition: txdb.h:58
CWallet::minTxFee
static CFeeRate minTxFee
Fees smaller than this (in duffs) are considered zero fee (for transaction creation) We are ~100 time...
Definition: wallet.h:536
g_best_block_mutex
Mutex g_best_block_mutex
Definition: main.cpp:75
LookupSubNet
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:667
NET_TOR
@ NET_TOR
Definition: netaddress.h:24
CClientUIInterface::BTN_ABORT
@ BTN_ABORT
Definition: guiinterface.h:46
minRelayTxFee
CFeeRate minRelayTxFee
Fees smaller than this (in duffs) are considered zero fee (for relaying and mining) We are ~100 times...
Definition: main.cpp:100
proxyType::IsValid
bool IsValid() const
Definition: netbase.h:34
NET_UNROUTABLE
@ NET_UNROUTABLE
Definition: netaddress.h:21
SplitHostPort
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
Definition: netbase.cpp:74
CDBEnv::VerifyResult
VerifyResult
Verify that database file strFile is OK.
Definition: db.h:58
InitBlockIndex
bool InitBlockIndex()
Initialize a new block tree database + block data on disk.
Definition: main.cpp:5425
fDeleteTransactionsAfterNBlocks
unsigned int fDeleteTransactionsAfterNBlocks
Definition: wallet.cpp:63
ShutdownRequested
bool ShutdownRequested()
Definition: init.cpp:135
CBudgetManager::ResetSync
void ResetSync()
Definition: masternode-budget.cpp:1176
OnRPCStarted
void OnRPCStarted()
Definition: init.cpp:328
GetTime
int64_t GetTime()
For unit testing.
Definition: utiltime.cpp:19
CWallet::mapWallet
std::map< uint256, CWalletTx > mapWallet
Definition: wallet.h:344
fCheckBlockIndex
bool fCheckBlockIndex
Definition: main.cpp:84
NET_IPV4
@ NET_IPV4
Definition: netaddress.h:22
activeMasternode
CActiveMasternode activeMasternode
Keep track of the active Masternode.
Definition: masternodeman.cpp:24
CImportingNow::~CImportingNow
~CImportingNow()
Definition: init.cpp:644
CWallet::ReadStakingStatus
bool ReadStakingStatus()
Definition: wallet.cpp:370
CClientUIInterface
Signals for UI communication.
Definition: guiinterface.h:28
SoftSetBoolArg
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: util.cpp:270
CBudgetDB::ReadResult
ReadResult
Definition: masternode-budget.h:153
CWallet::ScanForWalletTransactions
int ScanForWalletTransactions(CBlockIndex *pindexStart, bool fUpdate=false, bool fromStartup=false, int height=-1)
Scan the block chain (starting in pindexStart) for transactions from or to us.
Definition: wallet.cpp:2062
COPYRIGHT_YEAR
#define COPYRIGHT_YEAR
Definition: prcycoin-config.h:27
fs.h
SetupNetworking
bool SetupNetworking()
Definition: util.cpp:636
glibc_sanity_test
bool glibc_sanity_test()
Definition: glibc_sanity.cpp:62
CMasternodePaymentDB::Read
ReadResult Read(CMasternodePayments &objToLoad, bool fDryRun=false)
Definition: masternode-payments.cpp:66
FlushStateToDisk
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
Definition: main.cpp:3467
HelpMessageGroup
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: util.cpp:282
StartShutdown
void StartShutdown()
Definition: init.cpp:131
fsbridge::fopen
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:13
AppInitServers
bool AppInitServers()
Definition: init.cpp:733
BCLog::Logger::OpenDebugLog
bool OpenDebugLog()
Definition: logging.cpp:38
base_uint::GetHex
std::string GetHex() const
Definition: arith_uint256.cpp:155
ThreadImport
void ThreadImport(std::vector< fs::path > vImportFiles)
Definition: init.cpp:651
AppInit2
bool AppInit2(bool isDaemon)
Initialize prcy.
Definition: init.cpp:909
ThreadScriptCheck
void ThreadScriptCheck()
Run an instance of the script checking thread.
Definition: main.cpp:2996
DestroyContext
void DestroyContext()
Definition: main.cpp:369
chainActive
CChain chainActive
The currently-connected chain of blocks.
Definition: main.cpp:70
CBudgetDB::IncorrectFormat
@ IncorrectFormat
Definition: masternode-budget.h:160
Interrupt
void Interrupt()
Interrupt threads.
Definition: init.cpp:166
CWallet::GetKeyFromPool
bool GetKeyFromPool(CPubKey &key)
Definition: wallet.cpp:4829
CWalletTx::mapValue
mapValue_t mapValue
Definition: wallet.h:798
LoadBlockIndex
bool LoadBlockIndex(std::string &strError)
Load the block tree and coins database from disk.
Definition: main.cpp:5416
InterruptRPC
void InterruptRPC()
Definition: server.cpp:476
fTxConflictDeleteEnabled
bool fTxConflictDeleteEnabled
Definition: wallet.cpp:61
DumpMasternodePayments
void DumpMasternodePayments()
Definition: masternode-payments.cpp:148
NET_MAX
@ NET_MAX
Definition: netaddress.h:26
mapArgs
std::map< std::string, std::string > mapArgs
Definition: util.cpp:111
FEATURE_LATEST
@ FEATURE_LATEST
Definition: wallet.h:106
FormatSubVersion
std::string FormatSubVersion(const std::string &name, int nClientVersion, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip...
Definition: clientversion.cpp:88
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:181
CTxMemPool::ReadFeeEstimates
bool ReadFeeEstimates(CAutoFile &filein)
Definition: txmempool.cpp:658
HelpMessageOpt
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:286
validationinterface.h
CMasternodeDB::Ok
@ Ok
Definition: masternodeman.h:42
wallet.h
nConnectTimeout
int nConnectTimeout
Definition: netbase.cpp:45
CWallet::SetMaxVersion
bool SetMaxVersion(int nVersion)
change which version we're allowed to upgrade to (note that this does not immediately imply upgrading...
Definition: wallet.cpp:742
RegisterValidationInterface
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
Definition: validationinterface.cpp:15
flags
int flags
Definition: prcycoin-tx.cpp:297
InterruptTorControl
void InterruptTorControl()
Definition: torcontrol.cpp:762
DB_LOAD_OK
@ DB_LOAD_OK
Definition: walletdb.h:37
RaiseFileDescriptorLimit
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: util.cpp:507
ECC_InitSanityCheck
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:239
g_logger
BCLog::Logger *const g_logger
NOTE: the logger instances is leaked on exit.
Definition: logging.cpp:28
FindForkInGlobalIndex
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: main.cpp:1115
BindFlags
BindFlags
Used to pass flags to the Bind() function.
Definition: init.cpp:93
AppInitBasicSetup
bool AppInitBasicSetup()
Initialize PRCY: Basic context setup.
Definition: init.cpp:764
glibcxx_sanity_test
bool glibcxx_sanity_test()
Definition: glibcxx_sanity.cpp:58
AnnotatedMixin< std::recursive_mutex >
StopNode
bool StopNode()
Definition: net.cpp:1972
LicenseInfo
std::string LicenseInfo()
Returns licensing information (for -version)
Definition: init.cpp:574
RPC_FORBIDDEN_BY_SAFE_MODE
@ RPC_FORBIDDEN_BY_SAFE_MODE
std::exception thrown in command handling
Definition: protocol.h:41
ServiceFlags
ServiceFlags
nServices flags
Definition: protocol.h:296
CClientUIInterface::NotifyBlockSize
boost::signals2::signal< void(int size, const uint256 &hash)> NotifyBlockSize
New block has been accepted and is over a certain size.
Definition: guiinterface.h:107
StopREST
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:612
InterruptHTTPRPC
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:242
CMasternodePaymentDB
Save Masternode Payment Data (mnpayments.dat)
Definition: masternode-payments.h:38
TRY_LOCK
#define TRY_LOCK(cs, name)
Definition: sync.h:186
fDiscover
bool fDiscover
Definition: net.cpp:71
StartTorControl
void StartTorControl(boost::thread_group &threadGroup)
Definition: torcontrol.cpp:745
CDBEnv::Verify
VerifyResult Verify(std::string strFile, bool(*recoverFunc)(CDBEnv &dbenv, std::string strFile))
Definition: db.cpp:148
CDBEnv::Open
bool Open(const fs::path &path)
Definition: db.cpp:69
SoftSetArg
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
Definition: util.cpp:262
DateTimeStrFormat
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:50
SanitizeString
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
Definition: utilstrencodings.cpp:32
CWalletDB::ReadScannedBlockHeight
bool ReadScannedBlockHeight(int &height)
Definition: walletdb.cpp:308
CMasternodePaymentDB::IncorrectFormat
@ IncorrectFormat
Definition: masternode-payments.h:52
guiinterfaceutil.h
guiinterface.h
FormatMoney
std::string FormatMoney(const CAmount &n, bool fPlus)
Money parsing/formatting utilities.
Definition: utilmoneystr.cpp:13
sanity.h
masternodeman.h
Network
Network
Definition: netaddress.h:19
nSwiftTXDepth
int nSwiftTXDepth
Definition: util.cpp:103
StartREST
bool StartREST()
Start HTTP REST subsystem.
Definition: rest.cpp:601
CCoinsViewErrorCatcher::CCoinsViewErrorCatcher
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: init.cpp:143
payTxFee
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE)
Transaction fee set by the user.
proxyType
Definition: netbase.h:28
CFeeRate
Fee rate in PRCY per kilobyte: CAmount / kB.
Definition: amount.h:39
fMasterNode
bool fMasterNode
Definition: util.cpp:97
GetPidFile
fs::path GetPidFile()
Definition: util.cpp:432
db.h
scheduler.h
CWallet::DecoyConfirmationMinimum
int64_t DecoyConfirmationMinimum
Definition: wallet.h:366
DB_NEED_REWRITE
@ DB_NEED_REWRITE
Definition: walletdb.h:42
nCoinCacheUsage
size_t nCoinCacheUsage
Definition: main.cpp:86
CWalletTx::nTimeSmart
unsigned int nTimeSmart
time received by this node
Definition: wallet.h:802
fIsBareMultisigStd
bool fIsBareMultisigStd
Definition: main.cpp:83
CWallet::UpdateWalletTransactionOrder
void UpdateWalletTransactionOrder(std::map< std::pair< int, int >, CWalletTx * > &mapSorted, bool resetOrder)
Update the nOrderPos with passed in ordered map.
Definition: wallet.cpp:1825
CCoinsView
Abstract view on the open txout dataset.
Definition: coins.h:346
r
void const uint64_t uint64_t * r
Definition: field_5x52_asm_impl.h:10
nScriptCheckThreads
int nScriptCheckThreads
Definition: main.cpp:79
CActiveMasternode::pubKeyMasternode
CPubKey pubKeyMasternode
Definition: activemasternode.h:41
CWallet::SetAddressBook
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:4589
ThreadCheckMasternodes
void ThreadCheckMasternodes()
Definition: masternodeman.cpp:847
g_best_block
uint256 g_best_block
Definition: main.cpp:77
CBlockIndex::nTime
unsigned int nTime
Definition: chain.h:228
CScheduler::serviceQueue
void serviceQueue()
Definition: scheduler.cpp:21
ActivateBestChain
bool ActivateBestChain(CValidationState &state, CBlock *pblock, bool fAlreadyChecked)
Make the best chain active, in multiple steps.
Definition: main.cpp:3892
CAutoFile
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:303
CWallet::SetBestChain
void SetBestChain(const CBlockLocator &loc)
Definition: wallet.cpp:710
strMasterNodePrivKey
std::string strMasterNodePrivKey
Definition: util.cpp:98
BCLog::RPC
@ RPC
Definition: logging.h:47
BCLog::Logger::m_log_timestamps
bool m_log_timestamps
Definition: logging.h:94
AddOneShot
void AddOneShot(std::string strDest)
Definition: net.cpp:109
cs_main
RecursiveMutex cs_main
Global state.
Definition: main.cpp:65
CClientUIInterface::InitMessage
boost::signals2::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
Definition: guiinterface.h:83
PrepareShutdown
void PrepareShutdown()
Preparing steps before shutting down or restarting the wallet.
Definition: init.cpp:176
pblocktree
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: main.cpp:1131
SetRPCWarmupFinished
void SetRPCWarmupFinished()
Definition: server.cpp:496
SetRPCWarmupStatus
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:491
strBudgetMode
std::string strBudgetMode
Definition: util.cpp:109
ThreadFlushWalletDB
void ThreadFlushWalletDB(const std::string &strFile)
Definition: walletdb.cpp:984
CZMQNotificationInterface::CreateWithArguments
static CZMQNotificationInterface * CreateWithArguments(const std::map< std::string, std::string > &args)
Definition: zmqnotificationinterface.cpp:32
CWallet::SetMinVersion
bool SetMinVersion(enum WalletFeature, CWalletDB *pwalletdbIn=NULL, bool fExplicit=false)
signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVe...
Definition: wallet.cpp:716
CWalletTx::nTimeReceived
unsigned int nTimeReceived
Definition: wallet.h:801
fDeleteInterval
int fDeleteInterval
Definition: wallet.cpp:62
mnodeman
CMasternodeMan mnodeman
Masternode manager.
Definition: masternodeman.cpp:22
fRequestShutdown
volatile bool fRequestShutdown
Definition: init.cpp:129
strMasterNodeAddr
std::string strMasterNodeAddr
Definition: util.cpp:99
CChainParams::COINBASE_MATURITY
int COINBASE_MATURITY() const
Definition: chainparams.h:85
DB_NONCRITICAL_ERROR
@ DB_NONCRITICAL_ERROR
Definition: walletdb.h:39
CMasternodePaymentDB::ReadResult
ReadResult
Definition: masternode-payments.h:45
fEnableSwiftTX
bool fEnableSwiftTX
Definition: util.cpp:102
BindListenPort
bool BindListenPort(const CService &addrBind, std::string &strError, bool fWhitelisted)
Definition: net.cpp:1757
UnloadBlockIndex
void UnloadBlockIndex()
Unload database information.
Definition: main.cpp:5386
RegisterNodeSignals
void RegisterNodeSignals(CNodeSignals &nodeSignals)
Register with a network node to receive its signals.
Definition: main.cpp:1097
CWallet::GenerateNewHDChain
void GenerateNewHDChain(std::string *phrase=NULL)
Definition: wallet.cpp:317
CWalletTx::nOrderPos
int64_t nOrderPos
Definition: wallet.h:805
DEFAULT_TOR_CONTROL
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:35
prcycoin-config.h
CImportingNow::CImportingNow
CImportingNow()
Definition: init.cpp:638
_
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
Definition: guiinterface.h:119
GetWarnings
std::string GetWarnings(std::string strFor)
Format a string that describes several potential problems detected by the core.
Definition: main.cpp:5739
CRPCCommand
Definition: server.h:118
fTxDeleteEnabled
bool fTxDeleteEnabled
Definition: wallet.cpp:60
CWallet::vchDefaultKey
CPubKey vchDefaultKey
Definition: wallet.h:358
nReserveBalance
int64_t nReserveBalance
Definition: wallet.cpp:59
CLIENT_NAME
const std::string CLIENT_NAME
init.h
CClientUIInterface::ThreadSafeMessageBox
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: guiinterface.h:80
RPCServer::OnStopped
void OnStopped(boost::function< void()> slot)
Definition: server.cpp:58
RecalculatePRCYSupply
bool RecalculatePRCYSupply(int nHeightStart)
Definition: main.cpp:3002
BCLog::Logger::ShrinkDebugFile
void ShrinkDebugFile()
Definition: logging.cpp:231
fLiteMode
bool fLiteMode
Definition: util.cpp:100
AbsPathForConfigVal
fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific)
Definition: util.cpp:423
CMasternodePaymentDB::Ok
@ Ok
Definition: masternode-payments.h:46
g_best_block_cv
std::condition_variable g_best_block_cv
Definition: main.cpp:76
util::ThreadRename
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
Definition: threadnames.cpp:57
CImportingNow
Definition: init.cpp:637
miner.h
StopHTTPRPC
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:247
CMasternodePaymentDB::FileError
@ FileError
Definition: masternode-payments.h:47
BF_WHITELIST
@ BF_WHITELIST
Definition: init.cpp:97
CWallet::IsHDEnabled
bool IsHDEnabled()
Definition: wallet.cpp:345
HelpMessage
std::string HelpMessage(HelpMessageMode mode)
Help for options shared between UI and daemon (for -help)
Definition: init.cpp:354
GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:255
PAIRTYPE
#define PAIRTYPE(t1, t2)
This is needed because the foreach macro can't get over the comma in pair<t1, t2>
Definition: utilstrencodings.h:24
CTxMemPool::setSanityCheck
void setSanityCheck(bool _fSanityCheck)
Definition: txmempool.h:150
CWalletDB
Access to the wallet database (wallet.dat)
Definition: walletdb.h:80
CBaseChainParams::MAIN
@ MAIN
Definition: chainparamsbase.h:19
Checkpoints::fEnabled
bool fEnabled
Definition: checkpoints.cpp:29
CBlockTreeDB
Access to the block database (blocks/index/)
Definition: txdb.h:74
CDiskBlockPos
Definition: chain.h:76
CRPCCommand::okSafeMode
bool okSafeMode
Definition: server.h:124
CMasternodeDB::ReadResult
ReadResult
Definition: masternodeman.h:41
JSONRPCError
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:60
CWallet::LoadWallet
DBErrors LoadWallet(bool &fFirstRunRet)
Definition: wallet.cpp:4540
CDBEnv::RECOVER_OK
@ RECOVER_OK
Definition: db.h:59
NODE_BLOOM
@ NODE_BLOOM
Definition: protocol.h:307
CAmount
int64_t CAmount
Amount in PRCY (Can be negative)
Definition: amount.h:17
LogPrintf
#define LogPrintf(...)
Definition: logging.h:147
standard.h
pcoinsTip
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: main.cpp:1130
BF_NONE
@ BF_NONE
Definition: init.cpp:94
GetNodeSignals
CNodeSignals & GetNodeSignals()
Definition: net.cpp:107
BCLog::Logger::EnableCategory
void EnableCategory(LogFlags flag)
Definition: logging.cpp:58
masternodePayments
CMasternodePayments masternodePayments
Object for who's going to get paid on which blocks.
Definition: masternode-payments.cpp:19
fRestartRequested
volatile bool fRestartRequested
Definition: init.cpp:77
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:188
fNameLookup
bool fNameLookup
Definition: netbase.cpp:46
OnRPCStopped
void OnRPCStopped()
Definition: init.cpp:333
BCLog::Logger::m_reopen_file
std::atomic< bool > m_reopen_file
Definition: logging.h:98
mempool
CTxMemPool mempool(::minRelayTxFee)
StartHTTPServer
bool StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:476
CMasternodeConfig::getCount
int getCount()
Definition: masternodeconfig.h:108
CSubNet
Definition: netaddress.h:95
SER_DISK
@ SER_DISK
Definition: serialize.h:160
CWallet::ReorderWalletTransactions
void ReorderWalletTransactions(std::map< std::pair< int, int >, CWalletTx * > &mapSorted, int64_t &maxOrderPos)
Reorder the transactions based on block hieght and block index.
Definition: wallet.cpp:1792
CAutoFile::IsNull
bool IsNull() const
Return true if the wrapped FILE* is NULL, false otherwise.
Definition: streams.h:355
CNode::AddWhitelistedRange
static void AddWhitelistedRange(const CSubNet &subnet)
Definition: net.cpp:633
InitParameterInteraction
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:811
masternode-payments.h
GetListenPort
unsigned short GetListenPort()
Definition: net.cpp:114
CWalletTx::vOrderForm
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:799
CMasternodeDB::IncorrectFormat
@ IncorrectFormat
Definition: masternodeman.h:48
uint256
256-bit unsigned big integer.
Definition: uint256.h:38
nMaxDatacarrierBytes
unsigned nMaxDatacarrierBytes
Definition: standard.cpp:16
CWalletDB::IncrementUpdateCounter
static void IncrementUpdateCounter()
Definition: walletdb.cpp:1326
uint256::GetHash
uint64_t GetHash(const uint256 &salt) const
Definition: uint256.cpp:99
base_uint::SetHex
void SetHex(const char *psz)
Definition: arith_uint256.cpp:164
CCoinsViewErrorCatcher::GetCoins
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: init.cpp:144
CDBEnv::Flush
void Flush(bool fShutdown)
Definition: db.cpp:473
CService::GetPort
unsigned short GetPort() const
Definition: netaddress.cpp:494
LogPrint
#define LogPrint(category,...)
Definition: logging.h:162
zmqnotificationinterface.h
fGeneratePrcycoins
bool fGeneratePrcycoins
base_uint::IsNull
bool IsNull() const
Definition: arith_uint256.h:312
CWalletTx::strFromAccount
std::string strFromAccount
Definition: wallet.h:804
RandomInit
void RandomInit()
Initialize the RNG.
Definition: random.cpp:478
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:359
CWalletDB::ReadBestBlock
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:179
maxTxFee
CAmount maxTxFee
Definition: wallet.cpp:52
fKeepLastNTransactions
unsigned int fKeepLastNTransactions
Definition: wallet.cpp:64
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:641
checkpoints.h
CScheduler::Function
boost::function< void(void)> Function
Definition: scheduler.h:43
fVerifyingBlocks
bool fVerifyingBlocks
Definition: main.cpp:85
CMessageSigner::GetKeysFromSecret
static bool GetKeysFromSecret(const std::string &strSecret, CKey &keyRet, CPubKey &pubkeyRet)
Set the private/public key values, returns true if successful.
Definition: messagesigner.cpp:13
activemasternode.h
CVerifyDB
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: main.h:421
BCLog::Logger::m_file_path
fs::path m_file_path
Definition: logging.h:97
CChainParams::GetDefaultPort
int GetDefaultPort() const
Definition: chainparams.h:56
RPCNotifyBlockChange
void RPCNotifyBlockChange(bool fInitialDownload, const CBlockIndex *pindex)
Definition: blockchain.cpp:224
GetBlockPosFilename
fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
Definition: main.cpp:5160
masternodeConfig
CMasternodeConfig masternodeConfig
Definition: masternodeconfig.cpp:13
CCoinsViewBacked::GetCoins
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: coins.cpp:74
ListLogCategories
std::string ListLogCategories()
Returns a string with the supported log categories.
Definition: logging.cpp:149
RPCServer::OnStarted
void OnStarted(boost::function< void()> slot)
Definition: server.cpp:54
GetTimeMillis
int64_t GetTimeMillis()
Definition: utiltime.cpp:31
StartRPC
bool StartRPC()
Definition: server.cpp:469
messagesigner.h
CBlockTreeDB::WriteReindexing
bool WriteReindexing(bool fReindex)
Definition: txdb.cpp:92
UnregisterAllValidationInterfaces
void UnregisterAllValidationInterfaces()
Unregister all wallets from core.
Definition: validationinterface.cpp:41
InitSignatureCache
void InitSignatureCache()
Definition: sigcache.cpp:74
invalid.h
fTxIndex
bool fTxIndex
Definition: main.cpp:82
ParseNetwork
enum Network ParseNetwork(std::string net)
Definition: netbase.cpp:51
SetProxy
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:548
FormatParagraph
std::string FormatParagraph(const std::string in, size_t width, size_t indent)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line.
Definition: utilstrencodings.cpp:527
GetConfigFile
fs::path GetConfigFile()
Definition: util.cpp:383
strprintf
#define strprintf
Definition: tinyformat.h:1056
CClientUIInterface::MSG_ERROR
@ MSG_ERROR
Definition: guiinterface.h:76
CWallet::fCombineDust
bool fCombineDust
Definition: wallet.h:331
key.h
CBlockTreeDB::WriteFlag
bool WriteFlag(const std::string &name, bool fValue)
Definition: txdb.cpp:214
DBErrors
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:36
CTxMemPool::WriteFeeEstimates
bool WriteFeeEstimates(CAutoFile &fileout) const
Write/Read estimates to disk.
Definition: txmempool.cpp:644
CreatePidFile
void CreatePidFile(const fs::path &path, pid_t pid)
Definition: util.cpp:438
httprpc.h
GetDefaultDataDir
fs::path GetDefaultDataDir()
Definition: util.cpp:317
strSubVersion
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:83
CPubKey
An encapsulated public key.
Definition: pubkey.h:37
GetAdjustedTime
int64_t GetAdjustedTime()
Definition: timedata.cpp:30
CBudgetManager::ClearSeen
void ClearSeen()
Definition: masternode-budget.h:200
BCLog::Logger::DefaultShrinkDebugFile
bool DefaultShrinkDebugFile() const
Definition: logging.cpp:89
LOCAL_MANUAL
@ LOCAL_MANUAL
Definition: net.h:127
uiInterface
CClientUIInterface uiInterface
Definition: init.cpp:101
BF_EXPLICIT
@ BF_EXPLICIT
Definition: init.cpp:95
SetNameProxy
bool SetNameProxy(const proxyType &addrProxy)
Definition: netbase.cpp:568
CChain::GetLocator
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:25
CWallet::SetDefaultKey
bool SetDefaultKey(const CPubKey &vchPubKey)
Definition: wallet.cpp:4632
HandleSIGTERM
void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do, so:
Definition: init.cpp:294
Shutdown
void Shutdown()
Shutdown is split into 2 parts: Part 1: shut down everything but the main wallet instance (done in Pr...
Definition: init.cpp:274
CKey
An encapsulated private key.
Definition: key.h:39
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:414
LoadExternalBlockFile
bool LoadExternalBlockFile(FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
Definition: main.cpp:5467
torcontrol.h
CCoinsViewBacked
CCoinsView backed by another CCoinsView.
Definition: coins.h:372
ON
@ ON
Definition: wallet.h:236
utilmoneystr.h
fReindex
std::atomic< bool > fReindex
Definition: main.cpp:81
CheckDiskSpace
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
Definition: main.cpp:5116
main.h
CWallet::setKeyPool
std::set< int64_t > setKeyPool
Definition: wallet.h:307
BCLog::Logger::m_print_to_console
bool m_print_to_console
Definition: logging.h:91
SAFE_CHARS_UA_COMMENT
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
Definition: utilstrencodings.h:30
LOCK
#define LOCK(cs)
Definition: sync.h:182
HelpMessageMode
HelpMessageMode
The help message mode determines what help message to show.
Definition: init.h:38
CWalletTx::WriteToDisk
bool WriteToDisk(CWalletDB *pwalletdb)
Definition: wallet.cpp:1761
key
CKey key
Definition: bip38tooldialog.cpp:173
nLocalServices
ServiceFlags nLocalServices
Definition: net.cpp:73
InitSanityCheck
bool InitSanityCheck(void)
Sanity checks Ensure that PRCY is running in a usable environment with all necessary library support.
Definition: init.cpp:714
CBudgetDB::Ok
@ Ok
Definition: masternode-budget.h:154
SetLimited
void SetLimited(enum Network net, bool fLimited)
Make a particular network entirely off-limits (no automatic connects to it)
Definition: net.cpp:245
CWallet
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,...
Definition: wallet.h:243
MIN_CORE_FILEDESCRIPTORS
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:89
InterruptHTTPServer
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:492
CWalletTx
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:792
IsLimited
bool IsLimited(enum Network net)
Definition: net.cpp:252
RenameOver
bool RenameOver(fs::path src, fs::path dest)
Definition: util.cpp:448
Random_SanityCheck
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:411
HandleSIGHUP
void HandleSIGHUP(int)
Definition: init.cpp:299
CCoinsViewErrorCatcher
Definition: init.cpp:140
CWallet::ZapWalletTx
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: wallet.cpp:4567
LookupNumeric
CService LookupNumeric(const char *pszName, int portDefault)
Definition: netbase.cpp:234
CBudgetDB::FileError
@ FileError
Definition: masternode-budget.h:155
GetDataDir
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:349
BCLog::Logger::m_log_time_micros
bool m_log_time_micros
Definition: logging.h:95
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:463
masternode-budget.h
BF_REPORT_ERROR
@ BF_REPORT_ERROR
Definition: init.cpp:96
CSubNet::IsValid
bool IsValid() const
Definition: netaddress.cpp:698
DEFAULT_DEBUGLOGFILE
const char *const DEFAULT_DEBUGLOGFILE
Server/client environment: argument handling, config file parsing, thread wrappers.
Definition: logging.cpp:12
TraceThread
void TraceThread(const char *name, Callable func)
Definition: util.h:169
StartNode
void StartNode(boost::thread_group &threadGroup, CScheduler &scheduler)
Definition: net.cpp:1891
CClientUIInterface::ShowRecoveryDialog
boost::signals2::signal< void()> ShowRecoveryDialog
Show recovery dialog.
Definition: guiinterface.h:86
CWallet::cs_wallet
RecursiveMutex cs_wallet
Definition: wallet.h:301
InterruptREST
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:608
CWalletDB::Recover
static bool Recover(CDBEnv &dbenv, std::string filename, bool fOnlyKeys)
Definition: walletdb.cpp:1189
UnregisterNodeSignals
void UnregisterNodeSignals(CNodeSignals &nodeSignals)
Unregister a network node.
Definition: main.cpp:1106
NET_IPV6
@ NET_IPV6
Definition: netaddress.h:23
addrman.h
CCoins
Definition: coins.h:77
CWallet::combineMode
CombineMode combineMode
Definition: wallet.h:365
runCommand
void runCommand(std::string strCommand)
Definition: util.cpp:593
GUIUtil::dateTimeStr
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:70
OFF
@ OFF
Definition: wallet.h:235
StopTorControl
void StopTorControl()
Definition: torcontrol.cpp:770
netbase.h
DumpMasternodes
void DumpMasternodes()
Definition: masternodeman.cpp:174
walletdb.h
RPCServer::OnPreCommand
void OnPreCommand(boost::function< void(const CRPCCommand &)> slot)
Definition: server.cpp:62
CURRENCY_UNIT
const std::string CURRENCY_UNIT
Definition: amount.cpp:10
HMM_BITCOIND
@ HMM_BITCOIND
Definition: init.h:39
CBudgetDB::Read
ReadResult Read(CBudgetManager &objToLoad, bool fDryRun=false)
Definition: masternode-budget.cpp:287
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
handler
bool(* handler)(HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:589
CChain::Tip
CBlockIndex * Tip(bool fProofOfStake=false) const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: chain.h:596
DumpBudgets
void DumpBudgets()
Definition: masternode-budget.cpp:372
httpserver.h
sigcache.h
CWallet::ReacceptWalletTransactions
void ReacceptWalletTransactions()
Definition: wallet.cpp:2132
FormatFullVersion
std::string FormatFullVersion()
Definition: clientversion.cpp:80
invalid_out::LoadOutpoints
bool LoadOutpoints()
Definition: invalid.cpp:24
CClientUIInterface::NotifyBlockTip
boost::signals2::signal< void(bool fInitialDownload, const CBlockIndex *newTip)> NotifyBlockTip
New block has been accepted.
Definition: guiinterface.h:104
budget
CBudgetManager budget
Definition: masternode-budget.cpp:19
UnregisterValidationInterface
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
Definition: validationinterface.cpp:28
CWallet::WriteStakingStatus
bool WriteStakingStatus(bool status)
Definition: wallet.cpp:366
BCLog::Logger::DisableCategory
void DisableCategory(LogFlags flag)
Definition: logging.cpp:71
CBlockLocator
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:249
fListen
bool fListen
Definition: net.cpp:72
CRPCCommand::reqWallet
bool reqWallet
Definition: server.h:126
server.h
mapMultiArgs
std::map< std::string, std::vector< std::string > > mapMultiArgs
Definition: util.cpp:112
net.h
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:162
StopHTTPServer
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:505
CFeeRate::GetFeePerK
CAmount GetFeePerK() const
Definition: amount.h:50
GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:241
OnRPCPreCommand
void OnRPCPreCommand(const CRPCCommand &cmd)
Definition: init.cpp:341
CWalletTx::fFromMe
char fFromMe
Definition: wallet.h:803
CWallet::strWalletFile
std::string strWalletFile
Definition: wallet.h:305
pwalletMain
CWallet * pwalletMain
Definition: wallet.cpp:49
StopRPC
void StopRPC()
Definition: server.cpp:482
threadnames.h
amount.h
bitdb
CDBEnv bitdb
Definition: db.cpp:29
CValidationState
Capture information about block/transaction validation.
Definition: validation.h:23
util.h
nMaxConnections
int nMaxConnections
Definition: net.cpp:81
DB_CORRUPT
@ DB_CORRUPT
Definition: walletdb.h:38
masternodeconfig.h
zxcvbn::time_t
double time_t
Definition: time_estimates.hpp:10
CZMQNotificationInterface
Definition: zmqnotificationinterface.h:15
CDBEnv::RECOVER_FAIL
@ RECOVER_FAIL
Definition: db.h:60
fFeeEstimatesInitialized
volatile bool fFeeEstimatesInitialized
Definition: init.cpp:76
CBudgetDB
Save Budget Manager (budget.dat)
Definition: masternode-budget.h:146
CChain::Genesis
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or NULL if none.
Definition: chain.h:590
CMasternodeDB::Read
ReadResult Read(CMasternodeMan &mnodemanToLoad, bool fDryRun=false)
Definition: masternodeman.cpp:93
txdb.h
CWallet::mapAddressBook
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:354
CWallet::ParameterInteraction
static bool ParameterInteraction()
Definition: wallet.cpp:812
HMM_BITCOIN_QT
@ HMM_BITCOIN_QT
Definition: init.h:40
InitHTTPServer
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:393
error
bool error(const char *fmt, const Args &... args)
Definition: util.h:61
CPubKey::GetID
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:143
nMaxTipAge
int64_t nMaxTipAge
Definition: main.cpp:89
ParseMoney
bool ParseMoney(const std::string &str, CAmount &nRet)
Definition: utilmoneystr.cpp:37
CMasternodeDB
Access to the MN database (mncache.dat)
Definition: masternodeman.h:34
mapBlockIndex
BlockMap mapBlockIndex
Definition: main.cpp:67
Lookup
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:206
CMasternodeConfig::getEntries
std::vector< CMasternodeEntry > & getEntries()
Definition: masternodeconfig.h:103
AddLocal
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:208