Dogecoin Core  1.14.2
P2P Digital Currency
init.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #if defined(HAVE_CONFIG_H)
7 #include "config/bitcoin-config.h"
8 #endif
9 
10 #include "init.h"
11 
12 #include "addrman.h"
13 #include "amount.h"
14 #include "chain.h"
15 #include "chainparams.h"
16 #include "checkpoints.h"
17 #include "compat/sanity.h"
18 #include "consensus/validation.h"
19 #include "httpserver.h"
20 #include "httprpc.h"
21 #include "key.h"
22 #include "validation.h"
23 #include "miner.h"
24 #include "netbase.h"
25 #include "net.h"
26 #include "net_processing.h"
27 #include "policy/policy.h"
28 #include "rpc/server.h"
29 #include "rpc/register.h"
30 #include "script/standard.h"
31 #include "script/sigcache.h"
32 #include "scheduler.h"
33 #include "timedata.h"
34 #include "txdb.h"
35 #include "txmempool.h"
36 #include "torcontrol.h"
37 #include "ui_interface.h"
38 #include "util.h"
39 #include "utilmoneystr.h"
40 #include "validationinterface.h"
41 #ifdef ENABLE_WALLET
42 #include "wallet/wallet.h"
43 #endif
44 #include "warnings.h"
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <memory>
48 
49 #ifndef WIN32
50 #include <signal.h>
51 #endif
52 
53 #include <boost/algorithm/string/classification.hpp>
54 #include <boost/algorithm/string/predicate.hpp>
55 #include <boost/algorithm/string/replace.hpp>
56 #include <boost/algorithm/string/split.hpp>
57 #include <boost/bind/bind.hpp>
58 #include <boost/filesystem.hpp>
59 #include <boost/function.hpp>
60 #include <boost/interprocess/sync/file_lock.hpp>
61 #include <boost/lexical_cast.hpp>
62 #include <boost/thread.hpp>
63 #include <openssl/crypto.h>
64 
65 #if ENABLE_ZMQ
67 #endif
68 
70 static const bool DEFAULT_PROXYRANDOMIZE = true;
71 static const bool DEFAULT_REST_ENABLE = false;
72 static const bool DEFAULT_DISABLE_SAFEMODE = false;
73 static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
74 
75 std::unique_ptr<CConnman> g_connman;
76 std::unique_ptr<PeerLogicValidation> peerLogic;
77 
78 #if ENABLE_ZMQ
79 static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
80 #endif
81 
82 #ifdef WIN32
83 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
84 // accessing block files don't count towards the fd_set size limit
85 // anyway.
86 #define MIN_CORE_FILEDESCRIPTORS 0
87 #else
88 #define MIN_CORE_FILEDESCRIPTORS 150
89 #endif
90 
92 enum BindFlags {
93  BF_NONE = 0,
94  BF_EXPLICIT = (1U << 0),
95  BF_REPORT_ERROR = (1U << 1),
96  BF_WHITELIST = (1U << 2),
97 };
98 
99 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
100 
102 //
103 // Shutdown
104 //
105 
106 //
107 // Thread management and startup/shutdown:
108 //
109 // The network-processing threads are all part of a thread group
110 // created by AppInit() or the Qt main() function.
111 //
112 // A clean exit happens when StartShutdown() or the SIGTERM
113 // signal handler sets fRequestShutdown, which triggers
114 // the DetectShutdownThread(), which interrupts the main thread group.
115 // DetectShutdownThread() then exits, which causes AppInit() to
116 // continue (it .joins the shutdown thread).
117 // Shutdown() is then
118 // called to clean up database connections, and stop other
119 // threads that should only be stopped after the main network-processing
120 // threads have exited.
121 //
122 // Note that if running -daemon the parent process returns from AppInit2
123 // before adding any threads to the threadGroup, so .join_all() returns
124 // immediately and the parent exits from main().
125 //
126 // Shutdown for Qt is very similar, only it uses a QTimer to detect
127 // fRequestShutdown getting set, and then does the normal Qt
128 // shutdown thing.
129 //
130 
131 std::atomic<bool> fRequestShutdown(false);
132 std::atomic<bool> fDumpMempoolLater(false);
133 
135 {
136  fRequestShutdown = true;
137 }
139 {
140  return fRequestShutdown;
141 }
142 
149 {
150 public:
152  bool GetCoins(const uint256 &txid, CCoins &coins) const {
153  try {
154  return CCoinsViewBacked::GetCoins(txid, coins);
155  } catch(const std::runtime_error& e) {
156  uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
157  LogPrintf("Error reading from database: %s\n", e.what());
158  // Starting the shutdown sequence and returning false to the caller would be
159  // interpreted as 'entry not found' (as opposed to unable to read data), and
160  // could lead to invalid interpretation. Just exit immediately, as we can't
161  // continue anyway, and all writes should be atomic.
162  abort();
163  }
164  }
165  // Writes do not need similar protection, as failure to write is handled by the caller.
166 };
167 
168 static CCoinsViewDB *pcoinsdbview = NULL;
169 static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
170 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
171 
172 void Interrupt(boost::thread_group& threadGroup)
173 {
176  InterruptRPC();
177  InterruptREST();
179  if (g_connman)
180  g_connman->Interrupt();
181  threadGroup.interrupt_all();
182 }
183 
184 void Shutdown()
185 {
186  LogPrintf("%s: In progress...\n", __func__);
187  static CCriticalSection cs_Shutdown;
188  TRY_LOCK(cs_Shutdown, lockShutdown);
189  if (!lockShutdown)
190  return;
191 
196  RenameThread("dogecoin-shutoff");
198 
199  StopHTTPRPC();
200  StopREST();
201  StopRPC();
202  StopHTTPServer();
203 #ifdef ENABLE_WALLET
204  // Dogecoin 1.14 TODO: ShutdownRPCMining();
205  if (pwalletMain)
206  pwalletMain->Flush(false);
207 #endif
208  MapPort(false);
210  peerLogic.reset();
211  g_connman.reset();
212 
213  StopTorControl();
215  if (fDumpMempoolLater)
216  DumpMempool();
217 
219  {
220  boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
221  CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
222  if (!est_fileout.IsNull())
223  mempool.WriteFeeEstimates(est_fileout);
224  else
225  LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
226  fFeeEstimatesInitialized = false;
227  }
228 
229  {
230  LOCK(cs_main);
231  if (pcoinsTip != NULL) {
233  }
234  delete pcoinsTip;
235  pcoinsTip = NULL;
236  delete pcoinscatcher;
237  pcoinscatcher = NULL;
238  delete pcoinsdbview;
239  pcoinsdbview = NULL;
240  delete pblocktree;
241  pblocktree = NULL;
242  }
243 #ifdef ENABLE_WALLET
244  if (pwalletMain)
245  pwalletMain->Flush(true);
246 #endif
247 
248 #if ENABLE_ZMQ
249  if (pzmqNotificationInterface) {
250  UnregisterValidationInterface(pzmqNotificationInterface);
251  delete pzmqNotificationInterface;
252  pzmqNotificationInterface = NULL;
253  }
254 #endif
255 
256 #ifndef WIN32
257  try {
258  boost::filesystem::remove(GetPidFile());
259  } catch (const boost::filesystem::filesystem_error& e) {
260  LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
261  }
262 #endif
264 #ifdef ENABLE_WALLET
265  delete pwalletMain;
266  pwalletMain = NULL;
267 #endif
268  globalVerifyHandle.reset();
269  ECC_Stop();
270  LogPrintf("%s: done\n", __func__);
271 }
272 
276 void HandleSIGTERM(int)
277 {
278  fRequestShutdown = true;
279 }
280 
281 void HandleSIGHUP(int)
282 {
283  fReopenDebugLog = true;
284 }
285 
286 bool static Bind(CConnman& connman, const CService &addr, unsigned int flags) {
287  if (!(flags & BF_EXPLICIT) && IsLimited(addr))
288  return false;
289  std::string strError;
290  if (!connman.BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
291  if (flags & BF_REPORT_ERROR)
292  return InitError(strError);
293  return false;
294  }
295  return true;
296 }
298 {
300 }
301 
303 {
305  RPCNotifyBlockChange(false, nullptr);
306  cvBlockChange.notify_all();
307  LogPrint("rpc", "RPC stopped.\n");
308 }
309 
310 void OnRPCPreCommand(const CRPCCommand& cmd)
311 {
312  // Observe safe mode
313  std::string strWarning = GetWarnings("rpc");
314  if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
315  !cmd.okSafeMode)
316  throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
317 }
318 
319 std::string HelpMessage(HelpMessageMode mode)
320 {
321  const bool showDebug = GetBoolArg("-help-debug", false);
322 
323  // When adding new options to the categories, please keep and ensure alphabetical ordering.
324  // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
325  std::string strUsage = HelpMessageGroup(_("Options:"));
326  strUsage += HelpMessageOpt("-?", _("Print this help message and exit"));
327  strUsage += HelpMessageOpt("-version", _("Print version and exit"));
328  strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
329  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)"));
330  strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash, %i is replaced by block number)"));
331  if (showDebug)
332  strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
333  strUsage +=HelpMessageOpt("-assumevalid=<hex>", strprintf(_("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s)"), Params(CBaseChainParams::MAIN).GetConsensus(0).defaultAssumeValid.GetHex(), Params(CBaseChainParams::TESTNET).GetConsensus(0).defaultAssumeValid.GetHex()));
334  strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
335  if (mode == HMM_BITCOIND)
336  {
337 #if HAVE_DECL_DAEMON
338  strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
339 #endif
340  }
341  strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
342  strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
343  if (showDebug)
344  strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER));
345  strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
346  strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
347  strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
348  strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
349  strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN));
350  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)"),
351  -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
352 #ifndef WIN32
353  strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
354 #endif
355  strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex and -rescan. "
356  "Warning: Reverting this setting requires re-downloading the entire blockchain. "
357  "(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >%u = automatically prune block files to stay under the specified target size in MiB)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
358  strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks"));
359  strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk"));
360 #ifndef WIN32
361  strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
362 #endif
363  strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
364 
365  strUsage += HelpMessageGroup(_("Connection options:"));
366  strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
367  strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
368  strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
369  strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
370  strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -noconnect or -connect=0 alone to disable automatic connections"));
371  strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
372  strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
373  strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect/-noconnect)"));
374  strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
375  strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
376  strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect/-noconnect)"));
377  strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
378  strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
379  strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
380  strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
381  strUsage += HelpMessageOpt("-maxtimeadjustment", strprintf(_("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)"), DEFAULT_MAX_TIME_ADJUSTMENT));
382  strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
383  strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
384  strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
385  strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
386  strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), Params(CBaseChainParams::MAIN).GetDefaultPort(), Params(CBaseChainParams::TESTNET).GetDefaultPort()));
387  strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
388  strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
389  strUsage += HelpMessageOpt("-rpcserialversion", strprintf(_("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)"), DEFAULT_RPC_SERIALIZE_VERSION));
390  strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
391  strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
392  strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
393  strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
394 #ifdef USE_UPNP
395 #if USE_UPNP
396  strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
397 #else
398  strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
399 #endif
400 #endif
401  strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
402  strUsage += HelpMessageOpt("-whitelist=<IP address or network>", _("Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR notated network (e.g. 1.2.3.0/24). Can be specified multiple times.") +
403  " " + _("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"));
404  strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
405  strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
406  strUsage += HelpMessageOpt("-maxuploadtarget=<n>", strprintf(_("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)"), DEFAULT_MAX_UPLOAD_TARGET));
407 
408 #ifdef ENABLE_WALLET
409  strUsage += CWallet::GetWalletHelpString(showDebug);
410 #endif
411 
412 #if ENABLE_ZMQ
413  strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
414  strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
415  strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
416  strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
417  strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
418 #endif
419 
420  strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
421  strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
422  if (showDebug)
423  {
424  strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
425  strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
426  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()));
427  strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
428  strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
429  strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
430  strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
431  strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
432  strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
433  strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
434  strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
435  strUsage += HelpMessageOpt("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT));
436  strUsage += HelpMessageOpt("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT));
437  strUsage += HelpMessageOpt("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT));
438  strUsage += HelpMessageOpt("-bip9params=deployment:start:end", "Use given start/end times for specified BIP9 deployment (regtest-only)");
439  }
440  std::string debugCategories = "addrman, alert, bench, cmpctblock, coindb, db, http, libevent, lock, mempool, mempoolrej, net, proxy, prune, rand, reindex, rpc, selectcoins, tor, zmq"; // Don't translate these and qt below
441  if (mode == HMM_BITCOIN_QT)
442  debugCategories += ", qt";
443  strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
444  _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
445  if (showDebug)
446  strUsage += HelpMessageOpt("-nodebug", "Turn off debugging messages, same as -debug=0");
447  strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
448  strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
449  strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
450  if (showDebug)
451  {
452  strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
453  strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
454  strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", DEFAULT_LIMITFREERELAY));
455  strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", DEFAULT_RELAYPRIORITY));
456  strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
457  strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
458  }
459  strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
460  CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
461  strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)"),
462  CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
463  strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
464  if (showDebug)
465  {
466  strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
467  }
468  strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
469 
470  AppendParamsHelpMessages(strUsage, showDebug);
471 
472  strUsage += HelpMessageGroup(_("Node relay options:"));
473  if (showDebug) {
474  strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
475  strUsage += HelpMessageOpt("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)));
476  strUsage += HelpMessageOpt("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to defined dust, the value of an output such that it will cost about 1/3 of its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)));
477  }
478  strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
479  strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
480  strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
481  strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
482 
483  strUsage += HelpMessageGroup(_("Block creation options:"));
484  strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT));
485  strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
486  strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
487  strUsage += HelpMessageOpt("-blockmintxfee=<amt>", strprintf(_("Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)"), CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)));
488  if (showDebug)
489  strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
490 
491  strUsage += HelpMessageGroup(_("RPC server options:"));
492  strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
493  strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
494  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)"));
495  strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
496  strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
497  strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
498  strUsage += HelpMessageOpt("-rpcauth=<userpw>", _("Username and hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcuser. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times"));
499  strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort()));
500  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"));
501  strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
502  if (showDebug) {
503  strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
504  strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
505  }
506 
507  return strUsage;
508 }
509 
510 std::string LicenseInfo()
511 {
512  const std::string URL_SOURCE_CODE = "<https://github.com/dogecoin/dogecoin>";
513  const std::string URL_WEBSITE = "<https://dogecoin.com>";
514 
515  return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2013, COPYRIGHT_YEAR) + " ") + "\n" +
516  "\n" +
517  strprintf(_("Please contribute if you find %s useful. "
518  "Visit %s for further information about the software."),
519  PACKAGE_NAME, URL_WEBSITE) +
520  "\n" +
521  strprintf(_("The source code is available from %s."),
522  URL_SOURCE_CODE) +
523  "\n" +
524  "\n" +
525  _("This is experimental software.") + "\n" +
526  strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
527  "\n" +
528  strprintf(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard. Paper wallet art provided by Anacoluthia."), "<https://www.openssl.org>") +
529  "\n";
530 }
531 
532 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
533 {
534  if (initialSync || !pBlockIndex)
535  return;
536 
537  std::string strCmd = GetArg("-blocknotify", "");
538 
539  boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
540  boost::replace_all(strCmd, "%i", boost::lexical_cast<std::string>(pBlockIndex->nHeight));
541  boost::thread t(runCommand, strCmd); // thread runs free
542 }
543 
544 static bool fHaveGenesis = false;
545 static boost::mutex cs_GenesisWait;
546 static CConditionVariable condvar_GenesisWait;
547 
548 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
549 {
550  if (pBlockIndex != NULL) {
551  {
552  boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait);
553  fHaveGenesis = true;
554  }
555  condvar_GenesisWait.notify_all();
556  }
557 }
558 
560 {
562  assert(fImporting == false);
563  fImporting = true;
564  }
565 
567  assert(fImporting == true);
568  fImporting = false;
569  }
570 };
571 
572 
573 // If we're using -prune with -reindex, then delete block files that will be ignored by the
574 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
575 // is missing, do the same here to delete any later block files after a gap. Also delete all
576 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
577 // is in sync with what's actually on disk by the time we start downloading, so that pruning
578 // works correctly.
580 {
581  std::map<std::string, boost::filesystem::path> mapBlockFiles;
582 
583  // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
584  // Remove the rev files immediately and insert the blk file paths into an
585  // ordered map keyed by block file index.
586  LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
587  boost::filesystem::path blocksdir = GetDataDir() / "blocks";
588  for (boost::filesystem::directory_iterator it(blocksdir); it != boost::filesystem::directory_iterator(); it++) {
589  if (is_regular_file(*it) &&
590  it->path().filename().string().length() == 12 &&
591  it->path().filename().string().substr(8,4) == ".dat")
592  {
593  if (it->path().filename().string().substr(0,3) == "blk")
594  mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
595  else if (it->path().filename().string().substr(0,3) == "rev")
596  remove(it->path());
597  }
598  }
599 
600  // Remove all block files that aren't part of a contiguous set starting at
601  // zero by walking the ordered map (keys are block file indices) by
602  // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
603  // start removing block files.
604  int nContigCounter = 0;
605  BOOST_FOREACH(const PAIRTYPE(std::string, boost::filesystem::path)& item, mapBlockFiles) {
606  if (atoi(item.first) == nContigCounter) {
607  nContigCounter++;
608  continue;
609  }
610  remove(item.second);
611  }
612 }
613 
614 void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
615 {
616  const CChainParams& chainparams = Params();
617  RenameThread("dogecoin-loadblk");
618 
619  {
620  CImportingNow imp;
621 
622  // -reindex
623  if (fReindex) {
624  int nFile = 0;
625  while (true) {
626  CDiskBlockPos pos(nFile, 0);
627  if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
628  break; // No block files left to reindex
629  FILE *file = OpenBlockFile(pos, true);
630  if (!file)
631  break; // This error is logged in OpenBlockFile
632  LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
633  LoadExternalBlockFile(chainparams, file, &pos);
634  nFile++;
635  }
636  pblocktree->WriteReindexing(false);
637  fReindex = false;
638  LogPrintf("Reindexing finished\n");
639  // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
640  InitBlockIndex(chainparams);
641  }
642 
643  // hardcoded $DATADIR/bootstrap.dat
644  boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
645  if (boost::filesystem::exists(pathBootstrap)) {
646  FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
647  if (file) {
648  boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
649  LogPrintf("Importing bootstrap.dat...\n");
650  LoadExternalBlockFile(chainparams, file);
651  RenameOver(pathBootstrap, pathBootstrapOld);
652  } else {
653  LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
654  }
655  }
656 
657  // -loadblock=
658  BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
659  FILE *file = fopen(path.string().c_str(), "rb");
660  if (file) {
661  LogPrintf("Importing blocks file %s...\n", path.string());
662  LoadExternalBlockFile(chainparams, file);
663  } else {
664  LogPrintf("Warning: Could not open blocks file %s\n", path.string());
665  }
666  }
667 
668  // scan for better chains in the block chain database, that are not yet connected in the active best chain
669  CValidationState state;
670  if (!ActivateBestChain(state, chainparams)) {
671  LogPrintf("Failed to connect best block");
672  StartShutdown();
673  }
674 
675  if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
676  LogPrintf("Stopping after block import\n");
677  StartShutdown();
678  }
679  } // End scope of CImportingNow
680  LoadMempool();
682 }
683 
688 bool InitSanityCheck(void)
689 {
690  if(!ECC_InitSanityCheck()) {
691  InitError("Elliptic curve cryptography sanity check failure. Aborting.");
692  return false;
693  }
695  return false;
696 
697  return true;
698 }
699 
700 bool AppInitServers(boost::thread_group& threadGroup)
701 {
705  if (!InitHTTPServer())
706  return false;
707  if (!StartRPC())
708  return false;
709  if (!StartHTTPRPC())
710  return false;
711  if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
712  return false;
713  if (!StartHTTPServer())
714  return false;
715  return true;
716 }
717 
718 // Parameter interaction based on rules
720 {
721  // when specifying an explicit binding address, you want to listen on it
722  // even when -connect or -proxy is specified
723  if (IsArgSet("-bind")) {
724  if (SoftSetBoolArg("-listen", true))
725  LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
726  }
727  if (IsArgSet("-whitebind")) {
728  if (SoftSetBoolArg("-listen", true))
729  LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
730  }
731 
732  if (mapMultiArgs.count("-connect") && mapMultiArgs.at("-connect").size() > 0) {
733  // when only connecting to trusted nodes, do not seed via DNS, or listen by default
734  if (SoftSetBoolArg("-dnsseed", false))
735  LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
736  if (SoftSetBoolArg("-listen", false))
737  LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
738  }
739 
740  if (IsArgSet("-proxy")) {
741  // to protect privacy, do not listen by default if a default proxy server is specified
742  if (SoftSetBoolArg("-listen", false))
743  LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
744  // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
745  // to listen locally, so don't rely on this happening through -listen below.
746  if (SoftSetBoolArg("-upnp", false))
747  LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
748  // to protect privacy, do not discover addresses by default
749  if (SoftSetBoolArg("-discover", false))
750  LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
751  }
752 
753  if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
754  // do not map ports or try to retrieve public IP when not listening (pointless)
755  if (SoftSetBoolArg("-upnp", false))
756  LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
757  if (SoftSetBoolArg("-discover", false))
758  LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
759  if (SoftSetBoolArg("-listenonion", false))
760  LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
761  }
762 
763  if (IsArgSet("-externalip")) {
764  // if an explicit public IP is specified, do not try to find others
765  if (SoftSetBoolArg("-discover", false))
766  LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
767  }
768 
769  // disable whitelistrelay in blocksonly mode
770  if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
771  if (SoftSetBoolArg("-whitelistrelay", false))
772  LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
773  }
774 
775  // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
776  if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
777  if (SoftSetBoolArg("-whitelistrelay", true))
778  LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
779  }
780 }
781 
782 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
783 {
784  return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
785 }
786 
788 {
789  fPrintToConsole = GetBoolArg("-printtoconsole", false);
790  fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
791  fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
792  fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
793 
794  LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
795  LogPrintf("Dogecoin version %s\n", FormatFullVersion());
796 }
797 
798 namespace { // Variables internal to initialization process only
799 
800 ServiceFlags nRelevantServices = NODE_NETWORK;
801 int nMaxConnections;
802 int nUserMaxConnections;
803 int nFD;
804 ServiceFlags nLocalServices = NODE_NETWORK;
805 
806 }
807 
808 [[noreturn]] static void new_handler_terminate()
809 {
810  // Rather than throwing std::bad-alloc if allocation fails, terminate
811  // immediately to (try to) avoid chain corruption.
812  // Since LogPrintf may itself allocate memory, set the handler directly
813  // to terminate first.
814  std::set_new_handler(std::terminate);
815  LogPrintf("Error: Out of memory. Terminating.\n");
816 
817  // The log was successful, terminate now.
818  std::terminate();
819 };
820 
822 {
823  // ********************************************************* Step 1: setup
824 #ifdef _MSC_VER
825  // Turn off Microsoft heap dump noise
826  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
827  _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
828 #endif
829 #if _MSC_VER >= 1400
830  // Disable confusing "helpful" text message on abort, Ctrl-C
831  _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
832 #endif
833 #ifdef WIN32
834  // Enable Data Execution Prevention (DEP)
835  // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
836  // A failure is non-critical and needs no further attention!
837 #ifndef PROCESS_DEP_ENABLE
838  // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
839  // which is not correct. Can be removed, when GCCs winbase.h is fixed!
840 #define PROCESS_DEP_ENABLE 0x00000001
841 #endif
842  typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
843  PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
844  if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
845 #endif
846 
847  if (!SetupNetworking())
848  return InitError("Initializing networking failed");
849 
850 #ifndef WIN32
851  if (!GetBoolArg("-sysperms", false)) {
852  umask(077);
853  }
854 
855  // Clean shutdown on SIGTERM
856  struct sigaction sa;
857  sa.sa_handler = HandleSIGTERM;
858  sigemptyset(&sa.sa_mask);
859  sa.sa_flags = 0;
860  sigaction(SIGTERM, &sa, NULL);
861  sigaction(SIGINT, &sa, NULL);
862 
863  // Reopen debug.log on SIGHUP
864  struct sigaction sa_hup;
865  sa_hup.sa_handler = HandleSIGHUP;
866  sigemptyset(&sa_hup.sa_mask);
867  sa_hup.sa_flags = 0;
868  sigaction(SIGHUP, &sa_hup, NULL);
869 
870  // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
871  signal(SIGPIPE, SIG_IGN);
872 #endif
873 
874  std::set_new_handler(new_handler_terminate);
875 
876  return true;
877 }
878 
880 {
881  const CChainParams& chainparams = Params();
882  // ********************************************************* Step 2: parameter interactions
883 
884  // also see: InitParameterInteraction()
885 
886  // if using block pruning, then disallow txindex
887  if (GetArg("-prune", 0)) {
888  if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
889  return InitError(_("Prune mode is incompatible with -txindex."));
890  }
891 
892  // Make sure enough file descriptors are available
893  int nBind = std::max(
894  (mapMultiArgs.count("-bind") ? mapMultiArgs.at("-bind").size() : 0) +
895  (mapMultiArgs.count("-whitebind") ? mapMultiArgs.at("-whitebind").size() : 0), size_t(1));
896  nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
897  nMaxConnections = std::max(nUserMaxConnections, 0);
898 
899  // Trim requested connection counts, to fit into system limitations
900  nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0);
901  nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
902  if (nFD < MIN_CORE_FILEDESCRIPTORS)
903  return InitError(_("Not enough file descriptors available."));
904  nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
905 
906  if (nMaxConnections < nUserMaxConnections)
907  InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
908 
909  // ********************************************************* Step 3: parameter-to-internal-flags
910 
911  fDebug = mapMultiArgs.count("-debug");
912  // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
913  if (fDebug) {
914  const std::vector<std::string>& categories = mapMultiArgs.at("-debug");
915  if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), std::string("0")) != categories.end())
916  fDebug = false;
917  }
918 
919  // Check for -debugnet
920  if (GetBoolArg("-debugnet", false))
921  InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
922  // Check for -socks - as this is a privacy risk to continue, exit here
923  if (IsArgSet("-socks"))
924  return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
925  // Check for -tor - as this is a privacy risk to continue, exit here
926  if (GetBoolArg("-tor", false))
927  return InitError(_("Unsupported argument -tor found, use -onion."));
928 
929  if (GetBoolArg("-benchmark", false))
930  InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
931 
932  if (GetBoolArg("-whitelistalwaysrelay", false))
933  InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
934 
935  if (IsArgSet("-blockminsize"))
936  InitWarning("Unsupported argument -blockminsize ignored.");
937 
938  // Checkmempool and checkblockindex default to true in regtest mode
939  int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
940  if (ratio != 0) {
941  mempool.setSanityCheck(1.0 / ratio);
942  }
943  fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
944  fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
945 
946  hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus(0).defaultAssumeValid.GetHex()));
947  if (!hashAssumeValid.IsNull())
948  LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
949  else
950  LogPrintf("Validating signatures for all blocks.\n");
951 
952  // mempool limits
953  int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
954  int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
955  if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
956  return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
957  // incremental relay fee sets the minimimum feerate increase necessary for BIP 125 replacement in the mempool
958  // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
959  if (IsArgSet("-incrementalrelayfee"))
960  {
961  CAmount n = 0;
962  if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n))
963  return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", "")));
965  }
966 
967  // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
968  nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
969  if (nScriptCheckThreads <= 0)
971  if (nScriptCheckThreads <= 1)
973  else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
974  nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
975 
976  // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
977  int64_t nPruneArg = GetArg("-prune", 0);
978  if (nPruneArg < 0) {
979  return InitError(_("Prune cannot be configured with a negative value."));
980  }
981  nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
982  if (nPruneArg == 1) { // manual pruning: -prune=1
983  LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
984  nPruneTarget = std::numeric_limits<uint64_t>::max();
985  fPruneMode = true;
986  } else if (nPruneTarget) {
987  if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
988  return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
989  }
990  LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
991  fPruneMode = true;
992  }
993 
994  RegisterAllCoreRPCCommands(tableRPC);
995 #ifdef ENABLE_WALLET
997 #endif
998 
999  nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1000  if (nConnectTimeout <= 0)
1001  nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1002 
1003  // Fee-per-kilobyte amount considered the same as "free"
1004  // If you are mining, be careful setting this:
1005  // if you set it to zero then
1006  // a transaction spammer can cheaply fill blocks using
1007  // 1-satoshi-fee transactions. It should be set above the real
1008  // cost to you of processing a transaction.
1009  if (IsArgSet("-minrelaytxfee"))
1010  {
1011  CAmount n = 0;
1012  if (!ParseMoney(GetArg("-minrelaytxfee", ""), n) || 0 == n)
1013  return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", "")));
1014  // High fee check is done afterward in CWallet::ParameterInteraction()
1016  } else if (incrementalRelayFee > ::minRelayTxFee) {
1017  // Allow only setting incrementalRelayFee to control both
1019  LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1020  }
1021 
1022  // Sanity check argument for min fee for including tx in block
1023  // TODO: Harmonize which arguments need sanity checking and where that happens
1024  if (IsArgSet("-blockmintxfee"))
1025  {
1026  CAmount n = 0;
1027  if (!ParseMoney(GetArg("-blockmintxfee", ""), n))
1028  return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", "")));
1029  }
1030 
1031  // Feerate used to define dust. Shouldn't be changed lightly as old
1032  // implementations may inadvertently create non-standard transactions
1033  if (IsArgSet("-dustrelayfee"))
1034  {
1035  CAmount n = 0;
1036  if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n)
1037  return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", "")));
1038  dustRelayFee = CFeeRate(n);
1039  }
1040 
1041  fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1042  if (chainparams.RequireStandard() && !fRequireStandard)
1043  return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1044  nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
1045 
1046 #ifdef ENABLE_WALLET
1048  return false;
1049 #endif
1050 
1051  fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1052  fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1053  nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
1054 
1055  fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
1056 
1057  // Option to startup with mocktime set (used for regression testing):
1058  SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1059 
1060  if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1061  nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1062 
1063  if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1064  return InitError("rpcserialversion must be non-negative.");
1065 
1066  if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1067  return InitError("unknown rpcserialversion requested.");
1068 
1069  nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1070 
1071  fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1072  if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) {
1073  // Minimal effort at forwards compatibility
1074  std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
1075  std::vector<std::string> vstrReplacementModes;
1076  boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1077  fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1078  }
1079 
1080  if (mapMultiArgs.count("-bip9params")) {
1081  // Allow overriding BIP9 parameters for testing
1082  if (!chainparams.MineBlocksOnDemand()) {
1083  return InitError("BIP9 parameters may only be overridden on regtest.");
1084  }
1085  const std::vector<std::string>& deployments = mapMultiArgs.at("-bip9params");
1086  for (auto i : deployments) {
1087  std::vector<std::string> vDeploymentParams;
1088  boost::split(vDeploymentParams, i, boost::is_any_of(":"));
1089  if (vDeploymentParams.size() != 3) {
1090  return InitError("BIP9 parameters malformed, expecting deployment:start:end");
1091  }
1092  int64_t nStartTime, nTimeout;
1093  if (!ParseInt64(vDeploymentParams[1], &nStartTime)) {
1094  return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1]));
1095  }
1096  if (!ParseInt64(vDeploymentParams[2], &nTimeout)) {
1097  return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2]));
1098  }
1099  bool found = false;
1100  for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j)
1101  {
1102  if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) {
1103  UpdateRegtestBIP9Parameters(Consensus::DeploymentPos(j), nStartTime, nTimeout);
1104  found = true;
1105  LogPrintf("Setting BIP9 activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout);
1106  break;
1107  }
1108  }
1109  if (!found) {
1110  return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0]));
1111  }
1112  }
1113  }
1114  return true;
1115 }
1116 
1117 static bool LockDataDirectory(bool probeOnly)
1118 {
1119  std::string strDataDir = GetDataDir().string();
1120 
1121  // Make sure only a single Bitcoin process is using the data directory.
1122  boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
1123  FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
1124  if (file) fclose(file);
1125 
1126  try {
1127  static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
1128  if (!lock.try_lock()) {
1129  return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME)));
1130  }
1131  if (probeOnly) {
1132  lock.unlock();
1133  }
1134  } catch(const boost::interprocess::interprocess_exception& e) {
1135  return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what()));
1136  }
1137  return true;
1138 }
1139 
1141 {
1142  // ********************************************************* Step 4: sanity checks
1143 
1144  // Initialize elliptic curve code
1145  ECC_Start();
1146  globalVerifyHandle.reset(new ECCVerifyHandle());
1147 
1148  // Sanity check
1149  if (!InitSanityCheck())
1150  return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME)));
1151 
1152  // Probe the data directory lock to give an early error message, if possible
1153  return LockDataDirectory(true);
1154 }
1155 
1156 bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
1157 {
1158  const CChainParams& chainparams = Params();
1159  // ********************************************************* Step 4a: application initialization
1160  // After daemonization get the data directory lock again and hold on to it until exit
1161  // This creates a slight window for a race condition to happen, however this condition is harmless: it
1162  // will at most make us exit without printing a message to console.
1163  if (!LockDataDirectory(false)) {
1164  // Detailed error printed inside LockDataDirectory
1165  return false;
1166  }
1167 
1168 #ifndef WIN32
1169  CreatePidFile(GetPidFile(), getpid());
1170 #endif
1171  if (GetBoolArg("-shrinkdebugfile", !fDebug)) {
1172  // Do this first since it both loads a bunch of debug.log into memory,
1173  // and because this needs to happen before any other debug.log printing
1174  ShrinkDebugFile();
1175  }
1176 
1177  if (fPrintToDebugLog)
1178  OpenDebugLog();
1179 
1180  if (!fLogTimestamps)
1181  LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
1182  LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1183  LogPrintf("Using data directory %s\n", GetDataDir().string());
1184  LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string());
1185  LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1186 
1188 
1189  LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1190  if (nScriptCheckThreads) {
1191  for (int i=0; i<nScriptCheckThreads-1; i++)
1192  threadGroup.create_thread(&ThreadScriptCheck);
1193  }
1194 
1195  // Start the lightweight task scheduler thread
1196  CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
1197  threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1198 
1199  /* Start the RPC server already. It will be started in "warmup" mode
1200  * and not really process calls already (but it will signify connections
1201  * that the server is there and will be ready later). Warmup mode will
1202  * be disabled when initialisation is finished.
1203  */
1204  if (GetBoolArg("-server", false))
1205  {
1207  if (!AppInitServers(threadGroup))
1208  return InitError(_("Unable to start HTTP server. See debug log for details."));
1209  }
1210 
1211  int64_t nStart;
1212 
1213 #if defined(USE_SSE2)
1214  scrypt_detect_sse2();
1215 #endif
1216 
1217  // ********************************************************* Step 5: verify wallet database integrity
1218 #ifdef ENABLE_WALLET
1219  if (!CWallet::Verify())
1220  return false;
1221 #endif
1222  // ********************************************************* Step 6: network initialization
1223  // Note that we absolutely cannot open any actual connections
1224  // until the very end ("start node") as the UTXO/block state
1225  // is not yet setup and may end up being set up twice if we
1226  // need to reindex later.
1227 
1228  assert(!g_connman);
1229  g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1230  CConnman& connman = *g_connman;
1231 
1232  peerLogic.reset(new PeerLogicValidation(&connman));
1235 
1236  // sanitize comments per BIP-0014, format user agent and check total size
1237  std::vector<std::string> uacomments;
1238  if (mapMultiArgs.count("-uacomment")) {
1239  BOOST_FOREACH(std::string cmt, mapMultiArgs.at("-uacomment"))
1240  {
1241  if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1242  return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1243  uacomments.push_back(cmt);
1244  }
1245  }
1246  strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1247  if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1248  return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1249  strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1250  }
1251 
1252  if (mapMultiArgs.count("-onlynet")) {
1253  std::set<enum Network> nets;
1254  BOOST_FOREACH(const std::string& snet, mapMultiArgs.at("-onlynet")) {
1255  enum Network net = ParseNetwork(snet);
1256  if (net == NET_UNROUTABLE)
1257  return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1258  nets.insert(net);
1259  }
1260  for (int n = 0; n < NET_MAX; n++) {
1261  enum Network net = (enum Network)n;
1262  if (!nets.count(net))
1263  SetLimited(net);
1264  }
1265  }
1266 
1267  if (mapMultiArgs.count("-whitelist")) {
1268  BOOST_FOREACH(const std::string& net, mapMultiArgs.at("-whitelist")) {
1269  CSubNet subnet;
1270  LookupSubNet(net.c_str(), subnet);
1271  if (!subnet.IsValid())
1272  return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1273  connman.AddWhitelistedRange(subnet);
1274  }
1275  }
1276 
1277  bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1278  // -proxy sets a proxy for all outgoing network traffic
1279  // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1280  std::string proxyArg = GetArg("-proxy", "");
1282  if (proxyArg != "" && proxyArg != "0") {
1283  CService resolved(LookupNumeric(proxyArg.c_str(), 9050));
1284  proxyType addrProxy = proxyType(resolved, proxyRandomize);
1285  if (!addrProxy.IsValid())
1286  return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
1287 
1288  SetProxy(NET_IPV4, addrProxy);
1289  SetProxy(NET_IPV6, addrProxy);
1290  SetProxy(NET_TOR, addrProxy);
1291  SetNameProxy(addrProxy);
1292  SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
1293  }
1294 
1295  // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1296  // -noonion (or -onion=0) disables connecting to .onion entirely
1297  // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1298  std::string onionArg = GetArg("-onion", "");
1299  if (onionArg != "") {
1300  if (onionArg == "0") { // Handle -noonion/-onion=0
1301  SetLimited(NET_TOR); // set onions as unreachable
1302  } else {
1303  CService resolved(LookupNumeric(onionArg.c_str(), 9050));
1304  proxyType addrOnion = proxyType(resolved, proxyRandomize);
1305  if (!addrOnion.IsValid())
1306  return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
1307  SetProxy(NET_TOR, addrOnion);
1308  SetLimited(NET_TOR, false);
1309  }
1310  }
1311 
1312  // see Step 2: parameter interactions for more information about these
1313  fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
1314  fDiscover = GetBoolArg("-discover", true);
1315  fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1316  fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1317 
1318  if (fListen) {
1319  bool fBound = false;
1320  if (mapMultiArgs.count("-bind")) {
1321  BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-bind")) {
1322  CService addrBind;
1323  if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
1324  return InitError(ResolveErrMsg("bind", strBind));
1325  fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
1326  }
1327  }
1328  if (mapMultiArgs.count("-whitebind")) {
1329  BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-whitebind")) {
1330  CService addrBind;
1331  if (!Lookup(strBind.c_str(), addrBind, 0, false))
1332  return InitError(ResolveErrMsg("whitebind", strBind));
1333  if (addrBind.GetPort() == 0)
1334  return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1335  fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
1336  }
1337  }
1338  if (!mapMultiArgs.count("-bind") && !mapMultiArgs.count("-whitebind")) {
1339  struct in_addr inaddr_any;
1340  inaddr_any.s_addr = INADDR_ANY;
1341  fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
1342  fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
1343  }
1344  if (!fBound)
1345  return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
1346  }
1347 
1348  if (mapMultiArgs.count("-externalip")) {
1349  BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-externalip")) {
1350  CService addrLocal;
1351  if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1352  AddLocal(addrLocal, LOCAL_MANUAL);
1353  else
1354  return InitError(ResolveErrMsg("externalip", strAddr));
1355  }
1356  }
1357 
1358  if (mapMultiArgs.count("-seednode")) {
1359  BOOST_FOREACH(const std::string& strDest, mapMultiArgs.at("-seednode"))
1360  connman.AddOneShot(strDest);
1361  }
1362 
1363 #if ENABLE_ZMQ
1364  pzmqNotificationInterface = CZMQNotificationInterface::Create();
1365 
1366  if (pzmqNotificationInterface) {
1367  RegisterValidationInterface(pzmqNotificationInterface);
1368  }
1369 #endif
1370  uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1371  uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1372 
1373  if (IsArgSet("-maxuploadtarget")) {
1374  nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1375  }
1376 
1377  // ********************************************************* Step 7: load block chain
1378 
1379  fReindex = GetBoolArg("-reindex", false);
1380  bool fReindexChainState = GetBoolArg("-reindex-chainstate", false);
1381 
1382  // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
1383  boost::filesystem::path blocksDir = GetDataDir() / "blocks";
1384  if (!boost::filesystem::exists(blocksDir))
1385  {
1386  boost::filesystem::create_directories(blocksDir);
1387  bool linked = false;
1388  for (unsigned int i = 1; i < 10000; i++) {
1389  boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
1390  if (!boost::filesystem::exists(source)) break;
1391  boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
1392  try {
1393  boost::filesystem::create_hard_link(source, dest);
1394  LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
1395  linked = true;
1396  } catch (const boost::filesystem::filesystem_error& e) {
1397  // Note: hardlink creation failing is not a disaster, it just means
1398  // blocks will get re-downloaded from peers.
1399  LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
1400  break;
1401  }
1402  }
1403  if (linked)
1404  {
1405  fReindex = true;
1406  }
1407  }
1408 
1409  // cache size calculations
1410  int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
1411  nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1412  nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1413  int64_t nBlockTreeDBCache = nTotalCache / 8;
1414  nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20);
1415  nTotalCache -= nBlockTreeDBCache;
1416  int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1417  nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1418  nTotalCache -= nCoinDBCache;
1419  nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1420  int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1421  LogPrintf("Cache configuration:\n");
1422  LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1423  LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1424  LogPrintf("* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
1425 
1426  bool fLoaded = false;
1427  while (!fLoaded) {
1428  bool fReset = fReindex;
1429  std::string strLoadError;
1430 
1431  uiInterface.InitMessage(_("Loading block index..."));
1432 
1433  nStart = GetTimeMillis();
1434  do {
1435  try {
1436  UnloadBlockIndex();
1437  delete pcoinsTip;
1438  delete pcoinsdbview;
1439  delete pcoinscatcher;
1440  delete pblocktree;
1441 
1442  pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
1443  pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState);
1444  pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
1445  pcoinsTip = new CCoinsViewCache(pcoinscatcher);
1446 
1447  if (fReindex) {
1448  pblocktree->WriteReindexing(true);
1449  //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1450  if (fPruneMode)
1452  }
1453 
1454  if (!LoadBlockIndex(chainparams)) {
1455  strLoadError = _("Error loading block database");
1456  break;
1457  }
1458 
1459  // If the loaded chain has a wrong genesis, bail out immediately
1460  // (we're likely using a testnet datadir, or the other way around).
1461  if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus(0).hashGenesisBlock) == 0)
1462  return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1463 
1464  // Initialize the block index (no-op if non-empty database was already loaded)
1465  if (!InitBlockIndex(chainparams)) {
1466  strLoadError = _("Error initializing block database");
1467  break;
1468  }
1469 
1470  // Check for changed -txindex state
1471  if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1472  strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex");
1473  break;
1474  }
1475 
1476  // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1477  // in the past, but is now trying to run unpruned.
1478  if (fHavePruned && !fPruneMode) {
1479  strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1480  break;
1481  }
1482 
1483  if (!fReindex && chainActive.Tip() != NULL) {
1484  uiInterface.InitMessage(_("Rewinding blocks..."));
1485  if (!RewindBlockIndex(chainparams)) {
1486  strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1487  break;
1488  }
1489  }
1490 
1491  uiInterface.InitMessage(_("Verifying blocks..."));
1492  if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1493  LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks",
1494  MIN_BLOCKS_TO_KEEP);
1495  }
1496 
1497  {
1498  LOCK(cs_main);
1499  CBlockIndex* tip = chainActive.Tip();
1500  RPCNotifyBlockChange(true, tip);
1501  if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1502  strLoadError = _("The block database contains a block which appears to be from the future. "
1503  "This may be due to your computer's date and time being set incorrectly. "
1504  "Only rebuild the block database if you are sure that your computer's date and time are correct");
1505  break;
1506  }
1507  }
1508 
1509  if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1510  GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1511  strLoadError = _("Corrupted block database detected");
1512  break;
1513  }
1514  } catch (const std::exception& e) {
1515  if (fDebug) LogPrintf("%s\n", e.what());
1516  strLoadError = _("Error opening block database");
1517  break;
1518  }
1519 
1520  fLoaded = true;
1521  } while(false);
1522 
1523  if (!fLoaded) {
1524  // first suggest a reindex
1525  if (!fReset) {
1526  bool fRet = uiInterface.ThreadSafeQuestion(
1527  strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1528  strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1530  if (fRet) {
1531  fReindex = true;
1532  fRequestShutdown = false;
1533  } else {
1534  LogPrintf("Aborted block database rebuild. Exiting.\n");
1535  return false;
1536  }
1537  } else {
1538  return InitError(strLoadError);
1539  }
1540  }
1541  }
1542 
1543  // As LoadBlockIndex can take several minutes, it's possible the user
1544  // requested to kill the GUI during the last operation. If so, exit.
1545  // As the program has not fully started yet, Shutdown() is possibly overkill.
1546  if (fRequestShutdown)
1547  {
1548  LogPrintf("Shutdown requested. Exiting.\n");
1549  return false;
1550  }
1551  LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
1552 
1553  boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1554  CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
1555  // Allowed to fail as this file IS missing on first startup.
1556  if (!est_filein.IsNull())
1557  mempool.ReadFeeEstimates(est_filein);
1558  fFeeEstimatesInitialized = true;
1559 
1560  // ********************************************************* Step 8: load wallet
1561 #ifdef ENABLE_WALLET
1562  if (!CWallet::InitLoadWallet())
1563  return false;
1564 #else
1565  LogPrintf("No wallet support compiled in!\n");
1566 #endif
1567 
1568  // ********************************************************* Step 9: data directory maintenance
1569 
1570  // if pruning, unset the service bit and perform the initial blockstore prune
1571  // after any wallet rescanning has taken place.
1572  if (fPruneMode) {
1573  LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1574  nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1575  if (!fReindex) {
1576  uiInterface.InitMessage(_("Pruning blockstore..."));
1577  PruneAndFlush();
1578  }
1579  }
1580 
1582  // Only advertise witness capabilities if they have a reasonable start time.
1583  // This allows us to have the code merged without a defined softfork, by setting its
1584  // end time to 0.
1585  // Note that setting NODE_WITNESS is never required: the only downside from not
1586  // doing so is that after activation, no upgraded nodes will fetch from you.
1587  nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1588  // Only care about others providing witness capabilities if there is a softfork
1589  // defined.
1590  nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS);
1591  }
1592 
1593  // ********************************************************* Step 10: import blocks
1594 
1595  if (!CheckDiskSpace())
1596  return false;
1597 
1598  // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1599  // No locking, as this happens before any background thread is started.
1600  if (chainActive.Tip() == NULL) {
1601  uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait);
1602  } else {
1603  fHaveGenesis = true;
1604  }
1605 
1606  if (IsArgSet("-blocknotify"))
1607  uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
1608 
1609  std::vector<boost::filesystem::path> vImportFiles;
1610  if (mapMultiArgs.count("-loadblock"))
1611  {
1612  BOOST_FOREACH(const std::string& strFile, mapMultiArgs.at("-loadblock"))
1613  vImportFiles.push_back(strFile);
1614  }
1615 
1616  threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1617 
1618  // Wait for genesis block to be processed
1619  {
1620  boost::unique_lock<boost::mutex> lock(cs_GenesisWait);
1621  while (!fHaveGenesis) {
1622  condvar_GenesisWait.wait(lock);
1623  }
1624  uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait);
1625  }
1626 
1627  // ********************************************************* Step 11: start node
1628 
1630  LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1631  LogPrintf("nBestHeight = %d\n", chainActive.Height());
1632  if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1633  StartTorControl(threadGroup, scheduler);
1634 
1635  Discover(threadGroup);
1636 
1637  // Map ports with UPnP
1638  MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
1639 
1640  std::string strNodeError;
1641  CConnman::Options connOptions;
1642  connOptions.nLocalServices = nLocalServices;
1643  connOptions.nRelevantServices = nRelevantServices;
1644  connOptions.nMaxConnections = nMaxConnections;
1645  connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1646  connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1647  connOptions.nMaxFeeler = 1;
1648  connOptions.nBestHeight = chainActive.Height();
1649  connOptions.uiInterface = &uiInterface;
1650  connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1651  connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1652 
1653  connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1654  connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1655 
1656  if (!connman.Start(scheduler, strNodeError, connOptions))
1657  return InitError(strNodeError);
1658 
1659  // ********************************************************* Step 12: finished
1660 
1661  // Dogecoin: Do we need to do any RPC mining init here?
1662 
1664  uiInterface.InitMessage(_("Done loading"));
1665 
1666 #ifdef ENABLE_WALLET
1667  if (pwalletMain)
1668  pwalletMain->postInitProcess(threadGroup);
1669 #endif
1670 
1671  return !fRequestShutdown;
1672 }
CWallet * pwalletMain
Definition: wallet.cpp:38
const std::string CURRENCY_UNIT
Definition: amount.cpp:10
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:15
int flags
Definition: bitcoin-tx.cpp:468
void RPCNotifyBlockChange(bool ibd, const CBlockIndex *pindex)
Definition: blockchain.cpp:223
const CChainParams & Params()
Return the currently selected parameters.
void UpdateRegtestBIP9Parameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
Allows modifying the BIP9 regtest parameters.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
void AppendParamsHelpMessages(std::string &strUsage, bool debugHelp)
Append the help messages for the chainparams options to the parameter string.
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:456
bool IsNull() const
Return true if the wrapped FILE* is NULL, false otherwise.
Definition: streams.h:500
static const std::string TESTNET
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:158
unsigned int nTime
Definition: chain.h:199
uint256 GetBlockHash() const
Definition: chain.h:268
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:170
Access to the block database (blocks/index/)
Definition: txdb.h:109
bool WriteReindexing(bool fReindex)
Definition: txdb.cpp:77
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: chain.h:443
int Height() const
Return the maximal height in the chain.
Definition: chain.h:474
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:47
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
Definition: chainparams.h:71
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:78
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
Definition: chainparams.h:73
bool MineBlocksOnDemand() const
Make miner stop after a block is found.
Definition: chainparams.h:76
const Consensus::Params & GetConsensus(uint32_t nTargetHeight) const
Definition: chainparams.h:59
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyBlockTip
New block has been accepted.
Definition: ui_interface.h:104
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: ui_interface.h:77
boost::signals2::signal< bool(const std::string &message, const std::string &noninteractive_message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeQuestion
If possible, ask the user a question.
Definition: ui_interface.h:80
boost::signals2::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
Definition: ui_interface.h:83
Pruned version of CTransaction: only retains metadata and unspent transaction outputs.
Definition: coins.h:75
CCoinsView backed by another CCoinsView.
Definition: coins.h:333
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: coins.cpp:52
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:372
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:72
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: init.cpp:149
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: init.cpp:152
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: init.cpp:151
Abstract view on the open txout dataset.
Definition: coins.h:307
Definition: net.h:125
void AddWhitelistedRange(const CSubNet &subnet)
Definition: net.cpp:594
bool Start(CScheduler &scheduler, std::string &strNodeError, Options options)
Definition: net.cpp:2217
bool BindListenPort(const CService &bindAddr, std::string &strError, bool fWhitelisted=false)
Definition: net.cpp:2024
void AddOneShot(const std::string &strDest)
Definition: net.cpp:83
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
Definition: sync.h:93
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: amount.h:38
std::string ToString() const
Definition: amount.cpp:45
bool IsValid() const
Definition: netaddress.cpp:188
bool okSafeMode
Definition: server.h:144
void serviceQueue()
Definition: scheduler.cpp:30
boost::function< void(void)> Function
Definition: scheduler.h:42
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:134
unsigned short GetPort() const
Definition: netaddress.cpp:494
bool IsValid() const
Definition: netaddress.cpp:698
bool ReadFeeEstimates(CAutoFile &filein)
Definition: txmempool.cpp:909
bool WriteFeeEstimates(CAutoFile &fileout) const
Write/Read estimates to disk.
Definition: txmempool.cpp:893
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:389
void setSanityCheck(double dFrequency=1.0)
Definition: txmempool.h:530
Capture information about block/transaction validation.
Definition: validation.h:22
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:523
void postInitProcess(boost::thread_group &threadGroup)
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
Definition: wallet.cpp:3819
static bool ParameterInteraction()
Definition: wallet.cpp:3831
static bool InitLoadWallet()
Definition: wallet.cpp:3798
static std::string GetWalletHelpString(bool showDebug)
Definition: wallet.cpp:3578
static CZMQNotificationInterface * Create()
Users of this module must hold an ECCVerifyHandle.
Definition: pubkey.h:245
bool IsNull() const
Definition: uint256.h:32
std::string GetHex() const
Definition: uint256.cpp:21
bool IsValid() const
Definition: netbase.h:34
256-bit opaque blob.
Definition: uint256.h:123
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...
std::string FormatFullVersion()
#define COPYRIGHT_YEAR
Copyright year (2009-this) Todo: update this when changing our copyright comments in the source.
Definition: clientversion.h:29
const std::string CLIENT_NAME
bool glibc_sanity_test()
bool glibcxx_sanity_test()
void Flush(bool shutdown=false)
Flush wallet (bitdb flush)
Definition: wallet.cpp:436
static bool Verify()
Verify the wallet database and perform salvage if required.
Definition: wallet.cpp:441
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:248
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:253
bool StartHTTPRPC()
Start HTTP RPC subsystem.
Definition: httprpc.cpp:234
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:629
bool StartREST()
Start HTTP REST subsystem.
Definition: rest.cpp:618
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:625
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:464
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:378
bool StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:448
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:479
void ThreadImport(std::vector< boost::filesystem::path > vImportFiles)
Definition: init.cpp:614
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:75
bool AppInitMain(boost::thread_group &threadGroup, CScheduler &scheduler)
Bitcoin core main initialization.
Definition: init.cpp:1156
BindFlags
Used to pass flags to the Bind() function.
Definition: init.cpp:92
@ BF_REPORT_ERROR
Definition: init.cpp:95
@ BF_NONE
Definition: init.cpp:93
@ BF_EXPLICIT
Definition: init.cpp:94
@ BF_WHITELIST
Definition: init.cpp:96
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:88
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:719
std::string HelpMessage(HelpMessageMode mode)
Help for options shared between UI and daemon (for -help)
Definition: init.cpp:319
std::atomic< bool > fDumpMempoolLater(false)
bool fFeeEstimatesInitialized
Definition: init.cpp:69
bool ShutdownRequested()
Definition: init.cpp:138
void HandleSIGHUP(int)
Definition: init.cpp:281
bool AppInitServers(boost::thread_group &threadGroup)
Definition: init.cpp:700
void CleanupBlockRevFiles()
Definition: init.cpp:579
bool InitSanityCheck(void)
Sanity checks Ensure that Bitcoin is running in a usable environment with all necessary library suppo...
Definition: init.cpp:688
void OnRPCPreCommand(const CRPCCommand &cmd)
Definition: init.cpp:310
bool AppInitParameterInteraction()
Initialization: parameter interaction.
Definition: init.cpp:879
bool AppInitBasicSetup()
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:821
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:1140
void InitLogging()
Initialize the logging infrastructure.
Definition: init.cpp:787
void OnRPCStarted()
Definition: init.cpp:297
void Shutdown()
Definition: init.cpp:184
void StartShutdown()
Definition: init.cpp:134
std::string LicenseInfo()
Returns licensing information (for -version)
Definition: init.cpp:510
std::atomic< bool > fRequestShutdown(false)
void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do, so:
Definition: init.cpp:276
void OnRPCStopped()
Definition: init.cpp:302
void Interrupt(boost::thread_group &threadGroup)
Interrupt threads.
Definition: init.cpp:172
std::unique_ptr< PeerLogicValidation > peerLogic
Definition: init.cpp:76
HelpMessageMode
The help message mode determines what help message to show.
Definition: init.h:54
@ HMM_BITCOIN_QT
Definition: init.h:56
@ HMM_BITCOIND
Definition: init.h:55
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:292
void ECC_Start()
Initialize the elliptic curve support.
Definition: key.cpp:299
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition: key.cpp:316
DeploymentPos
Definition: params.h:16
@ DEPLOYMENT_SEGWIT
Definition: params.h:19
@ MAX_VERSION_BITS_DEPLOYMENTS
Definition: params.h:21
void OnStopped(boost::function< void()> slot)
Definition: server.cpp:54
void OnPreCommand(boost::function< void(const CRPCCommand &)> slot)
Definition: server.cpp:59
void OnStarted(boost::function< void()> slot)
Definition: server.cpp:49
void SetLimited(enum Network net, bool fLimited)
Make a particular network entirely off-limits (no automatic connects to it)
Definition: net.cpp:236
bool fDiscover
Definition: net.cpp:69
CNodeSignals & GetNodeSignals()
Definition: net.cpp:81
bool fListen
Definition: net.cpp:70
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
Definition: net.cpp:75
bool fRelayTxes
Definition: net.cpp:71
void Discover(boost::thread_group &threadGroup)
Definition: net.cpp:2122
void MapPort(bool)
Definition: net.cpp:1532
bool IsLimited(enum Network net)
Definition: net.cpp:244
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:196
unsigned short GetListenPort()
Definition: net.cpp:89
@ LOCAL_MANUAL
Definition: net.h:448
void UnregisterNodeSignals(CNodeSignals &nodeSignals)
Unregister a network node.
void RegisterNodeSignals(CNodeSignals &nodeSignals)
Register with a network node to receive its signals.
Network
Definition: netaddress.h:20
@ NET_MAX
Definition: netaddress.h:26
@ NET_IPV6
Definition: netaddress.h:23
@ NET_TOR
Definition: netaddress.h:24
@ NET_IPV4
Definition: netaddress.h:22
@ NET_UNROUTABLE
Definition: netaddress.h:21
enum Network ParseNetwork(std::string net)
Definition: netbase.cpp:43
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:618
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Definition: netbase.cpp:155
CService LookupNumeric(const char *pszName, int portDefault)
Definition: netbase.cpp:183
bool fNameLookup
Definition: netbase.cpp:37
int nConnectTimeout
Definition: netbase.cpp:36
bool SetNameProxy(const proxyType &addrProxy)
Definition: netbase.cpp:523
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:505
CFeeRate incrementalRelayFee
Definition: policy.cpp:209
CFeeRate dustRelayFee
Definition: policy.cpp:210
unsigned int nBytesPerSigOp
Definition: policy.cpp:211
ServiceFlags
nServices flags
Definition: protocol.h:256
@ NODE_WITNESS
Definition: protocol.h:273
@ NODE_BLOOM
Definition: protocol.h:270
@ NODE_NETWORK
Definition: protocol.h:262
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:153
UniValue JSONRPCError(int code, const string &message)
Definition: protocol.cpp:56
@ RPC_FORBIDDEN_BY_SAFE_MODE
Server is in safe mode, and command is not allowed in safe mode.
Definition: protocol.h:42
const char * source
Definition: rpcconsole.cpp:58
void RegisterWalletRPCCommands(CRPCTable &t)
Definition: rpcwallet.cpp:3078
@ SER_DISK
Definition: serialize.h:147
void SetRPCWarmupFinished()
Definition: server.cpp:359
void StopRPC()
Definition: server.cpp:340
void InterruptRPC()
Definition: server.cpp:333
bool StartRPC()
Definition: server.cpp:325
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:353
CRPCTable tableRPC
Definition: server.cpp:569
void InitSignatureCache()
Definition: sigcache.cpp:94
bool fAcceptDatacarrier
Definition: standard.cpp:19
unsigned nMaxDatacarrierBytes
Definition: standard.cpp:20
unsigned int nReceiveFloodSize
Definition: net.h:146
uint64_t nMaxOutboundLimit
Definition: net.h:148
CClientUIInterface * uiInterface
Definition: net.h:144
int nMaxOutbound
Definition: net.h:140
int nBestHeight
Definition: net.h:143
int nMaxFeeler
Definition: net.h:142
uint64_t nMaxOutboundTimeframe
Definition: net.h:147
int nMaxConnections
Definition: net.h:139
ServiceFlags nLocalServices
Definition: net.h:137
ServiceFlags nRelevantServices
Definition: net.h:138
unsigned int nSendBufferMaxSize
Definition: net.h:145
int nMaxAddnode
Definition: net.h:141
~CImportingNow()
Definition: init.cpp:566
CImportingNow()
Definition: init.cpp:561
int64_t nTimeout
Timeout/expiry MedianTime for the deployment attempt.
Definition: params.h:33
uint256 defaultAssumeValid
Definition: params.h:76
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:60
uint256 hashGenesisBlock
Definition: params.h:40
#define LOCK(cs)
Definition: sync.h:177
#define TRY_LOCK(cs, name)
Definition: sync.h:179
boost::condition_variable CConditionVariable
Just a typedef for boost::condition_variable, can be wrapped later if desired.
Definition: sync.h:105
int64_t GetAdjustedTime()
Definition: timedata.cpp:36
#define strprintf
Definition: tinyformat.h:1047
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:33
void InterruptTorControl()
Definition: torcontrol.cpp:706
void StartTorControl(boost::thread_group &threadGroup, CScheduler &scheduler)
Definition: torcontrol.cpp:689
void StopTorControl()
Definition: torcontrol.cpp:714
std::string AmountErrMsg(const char *const optname, const std::string &strValue)
bool InitError(const std::string &str)
Show error message.
CClientUIInterface uiInterface
Definition: ui_interface.cpp:8
void InitWarning(const std::string &str)
Show warning message.
uint256 uint256S(const char *str)
Definition: uint256.h:144
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
Definition: util.cpp:594
boost::filesystem::path GetConfigFile(const std::string &confPath)
Definition: util.cpp:551
void OpenDebugLog()
Definition: util.cpp:212
bool fLogTimeMicros
Definition: util.cpp:118
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:395
bool fDebug
Definition: util.cpp:113
std::string CopyrightHolders(const std::string &strPrefix)
Definition: util.cpp:847
void ShrinkDebugFile()
Definition: util.cpp:729
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:411
bool SetupNetworking()
Definition: util.cpp:826
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: util.cpp:664
void RenameThread(const char *name)
Definition: util.cpp:781
bool fLogIPs
Definition: util.cpp:119
boost::filesystem::path GetPidFile()
Definition: util.cpp:587
const char *const BITCOIN_PID_FILENAME
Definition: util.cpp:107
bool fPrintToConsole
Definition: util.cpp:114
const map< string, vector< string > > & mapMultiArgs
Definition: util.cpp:112
bool fLogTimestamps
Definition: util.cpp:117
void runCommand(const std::string &strCommand)
Definition: util.cpp:774
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: util.cpp:448
boost::filesystem::path GetDefaultDataDir()
Definition: util.cpp:482
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:513
const char *const BITCOIN_CONF_FILENAME
Definition: util.cpp:106
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: util.cpp:428
bool IsArgSet(const std::string &strArg)
Return true if the given argument has been manually set.
Definition: util.cpp:389
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
Definition: util.cpp:605
bool fPrintToDebugLog
Definition: util.cpp:115
int GetNumCores()
Return the number of physical cores available on the current system.
Definition: util.cpp:838
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:452
std::atomic< bool > fReopenDebugLog
#define LogPrint(category,...)
Definition: util.h:76
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
Definition: util.h:62
#define LogPrintf(...)
Definition: util.h:82
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
bool ParseMoney(const string &str, CAmount &nRet)
string SanitizeString(const string &str, int rule)
int atoi(const std::string &str)
bool ParseInt64(const std::string &str, int64_t *out)
Convert string to signed 64-bit integer with strict parse error feedback.
#define PAIRTYPE(t1, t2)
This is needed because the foreach macro can't get over the comma in pair<t1, t2>
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
int64_t GetTimeMillis()
Definition: utiltime.cpp:33
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units.
Definition: utiltime.cpp:19
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:80
void SetMockTime(int64_t nMockTimeIn)
Definition: utiltime.cpp:28
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:224
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:84
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
Definition: validation.cpp:79
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:223
CCriticalSection cs_main
Global state.
Definition: validation.cpp:61
bool fCheckBlockIndex
Definition: validation.cpp:76
int nScriptCheckThreads
Definition: validation.cpp:68
bool fEnableReplacement
Definition: validation.cpp:82
bool fAlerts
Definition: validation.cpp:80
bool RewindBlockIndex(const CChainParams &params)
When there are blocks in the active chain with missing data, rewind the chainstate and remove them fr...
boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:72
CTxMemPool mempool(::minRelayTxFee)
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:86
void DumpMempool(void)
Dump the mempool to disk.
bool fTxIndex
Definition: validation.cpp:71
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
BlockMap mapBlockIndex
Definition: validation.cpp:63
void ThreadScriptCheck()
Run an instance of the script checking thread.
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Make the best chain active, in multiple steps.
bool fReindex
Definition: validation.cpp:70
bool InitBlockIndex(const CChainParams &chainparams)
Initialize a new block tree database + block data on disk.
bool fPruneMode
True if we're running in -prune mode.
Definition: validation.cpp:73
size_t nCoinCacheUsage
Definition: validation.cpp:78
bool LoadBlockIndex(const CChainParams &chainparams)
Load the block tree and coins database from disk.
bool fIsBareMultisigStd
Definition: validation.cpp:74
void UnloadBlockIndex()
Unload database information.
bool fCheckpointsEnabled
Definition: validation.cpp:77
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:64
CConditionVariable cvBlockChange
Definition: validation.cpp:67
bool LoadMempool(void)
Load the mempool from disk.
bool fRequireStandard
Definition: validation.cpp:75
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
Definition: validation.cpp:81
void PruneAndFlush()
Prune block files and flush state to disk.
std::atomic_bool fImporting
std::string GetWarnings(const std::string &strFor)
Format a string that describes several potential problems detected by the core.
Definition: warnings.cpp:51
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
void UnregisterAllValidationInterfaces()
Unregister all wallets from core.
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
const struct BIP9DeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
Definition: versionbits.cpp:9