1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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 <banman.h>
15 #include <chain.h>
16 #include <chainparams.h>
17 #include <checkpoints.h>
18 #include <compat/sanity.h>
19 #include <consensus/validation.h>
20 #include <fs.h>
21 #include <httpserver.h>
22 #include <httprpc.h>
23 #include <interfaces/chain.h>
24 #include <index/txindex.h>
25 #include <key.h>
26 #include <validation.h>
27 #include <miner.h>
28 #include <netbase.h>
29 #include <net.h>
30 #include <net_processing.h>
31 #include <policy/feerate.h>
32 #include <policy/fees.h>
33 #include <policy/policy.h>
34 #include <rpc/server.h>
35 #include <rpc/register.h>
36 #include <rpc/blockchain.h>
37 #include <rpc/util.h>
38 #include <script/standard.h>
39 #include <script/sigcache.h>
40 #include <scheduler.h>
41 #include <shutdown.h>
42 #include <timedata.h>
43 #include <txdb.h>
44 #include <txmempool.h>
45 #include <torcontrol.h>
46 #include <ui_interface.h>
47 #include <util/system.h>
48 #include <util/moneystr.h>
49 #include <validationinterface.h>
50 #include <warnings.h>
51 #include <walletinitinterface.h>
52 #include <stdint.h>
53 #include <stdio.h>
54
55 #ifndef WIN32
56 #include <attributes.h>
57 #include <cerrno>
58 #include <signal.h>
59 #include <sys/stat.h>
60 #endif
61
62 #include <boost/algorithm/string/classification.hpp>
63 #include <boost/algorithm/string/replace.hpp>
64 #include <boost/algorithm/string/split.hpp>
65 #include <boost/thread.hpp>
66 #include <openssl/crypto.h>
67
68 #if ENABLE_ZMQ
69 #include <zmq/zmqabstractnotifier.h>
70 #include <zmq/zmqnotificationinterface.h>
71 #include <zmq/zmqrpc.h>
72 #endif
73
74 #ifdef USE_SSE2
75 #include <crypto/scrypt.h>
76 #endif
77
78 bool fFeeEstimatesInitialized = false;
79 static const bool DEFAULT_PROXYRANDOMIZE = true;
80 static const bool DEFAULT_REST_ENABLE = false;
81 static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
82
83 // Dump addresses to banlist.dat every 15 minutes (900s)
84 static constexpr int DUMP_BANS_INTERVAL = 60 * 15;
85
86 std::unique_ptr<CConnman> g_connman;
87 std::unique_ptr<PeerLogicValidation> peerLogic;
88 std::unique_ptr<BanMan> g_banman;
89
90 #ifdef WIN32
91 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
92 // accessing block files don't count towards the fd_set size limit
93 // anyway.
94 #define MIN_CORE_FILEDESCRIPTORS 0
95 #else
96 #define MIN_CORE_FILEDESCRIPTORS 150
97 #endif
98
99 static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
100
101 /**
102 * The PID file facilities.
103 */
104 static const char* BITCOIN_PID_FILENAME = "litecoind.pid";
105
GetPidFile()106 static fs::path GetPidFile()
107 {
108 return AbsPathForConfigVal(fs::path(gArgs.GetArg("-pid", BITCOIN_PID_FILENAME)));
109 }
110
CreatePidFile()111 NODISCARD static bool CreatePidFile()
112 {
113 fsbridge::ofstream file{GetPidFile()};
114 if (file) {
115 #ifdef WIN32
116 tfm::format(file, "%d\n", GetCurrentProcessId());
117 #else
118 tfm::format(file, "%d\n", getpid());
119 #endif
120 return true;
121 } else {
122 return InitError(strprintf(_("Unable to create the PID file '%s': %s"), GetPidFile().string(), std::strerror(errno)));
123 }
124 }
125
126 //////////////////////////////////////////////////////////////////////////////
127 //
128 // Shutdown
129 //
130
131 //
132 // Thread management and startup/shutdown:
133 //
134 // The network-processing threads are all part of a thread group
135 // created by AppInit() or the Qt main() function.
136 //
137 // A clean exit happens when StartShutdown() or the SIGTERM
138 // signal handler sets ShutdownRequested(), which makes main thread's
139 // WaitForShutdown() interrupts the thread group.
140 // And then, WaitForShutdown() makes all other on-going threads
141 // in the thread group join the main thread.
142 // Shutdown() is then called to clean up database connections, and stop other
143 // threads that should only be stopped after the main network-processing
144 // threads have exited.
145 //
146 // Shutdown for Qt is very similar, only it uses a QTimer to detect
147 // ShutdownRequested() getting set, and then does the normal Qt
148 // shutdown thing.
149 //
150
151 /**
152 * This is a minimally invasive approach to shutdown on LevelDB read errors from the
153 * chainstate, while keeping user interface out of the common library, which is shared
154 * between bitcoind, and bitcoin-qt and non-server tools.
155 */
156 class CCoinsViewErrorCatcher final : public CCoinsViewBacked
157 {
158 public:
CCoinsViewErrorCatcher(CCoinsView * view)159 explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
GetCoin(const COutPoint & outpoint,Coin & coin) const160 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override {
161 try {
162 return CCoinsViewBacked::GetCoin(outpoint, coin);
163 } catch(const std::runtime_error& e) {
164 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
165 LogPrintf("Error reading from database: %s\n", e.what());
166 // Starting the shutdown sequence and returning false to the caller would be
167 // interpreted as 'entry not found' (as opposed to unable to read data), and
168 // could lead to invalid interpretation. Just exit immediately, as we can't
169 // continue anyway, and all writes should be atomic.
170 abort();
171 }
172 }
173 // Writes do not need similar protection, as failure to write is handled by the caller.
174 };
175
176 static std::unique_ptr<CCoinsViewErrorCatcher> pcoinscatcher;
177 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
178
179 static boost::thread_group threadGroup;
180 static CScheduler scheduler;
181
Interrupt()182 void Interrupt()
183 {
184 InterruptHTTPServer();
185 InterruptHTTPRPC();
186 InterruptRPC();
187 InterruptREST();
188 InterruptTorControl();
189 InterruptMapPort();
190 if (g_connman)
191 g_connman->Interrupt();
192 if (g_txindex) {
193 g_txindex->Interrupt();
194 }
195 }
196
Shutdown(InitInterfaces & interfaces)197 void Shutdown(InitInterfaces& interfaces)
198 {
199 LogPrintf("%s: In progress...\n", __func__);
200 static CCriticalSection cs_Shutdown;
201 TRY_LOCK(cs_Shutdown, lockShutdown);
202 if (!lockShutdown)
203 return;
204
205 /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
206 /// for example if the data directory was found to be locked.
207 /// Be sure that anything that writes files or flushes caches only does this if the respective
208 /// module was initialized.
209 RenameThread("litecoin-shutoff");
210 mempool.AddTransactionsUpdated(1);
211
212 StopHTTPRPC();
213 StopREST();
214 StopRPC();
215 StopHTTPServer();
216 for (const auto& client : interfaces.chain_clients) {
217 client->flush();
218 }
219 StopMapPort();
220
221 // Because these depend on each-other, we make sure that neither can be
222 // using the other before destroying them.
223 if (peerLogic) UnregisterValidationInterface(peerLogic.get());
224 if (g_connman) g_connman->Stop();
225 if (g_txindex) g_txindex->Stop();
226
227 StopTorControl();
228
229 // After everything has been shut down, but before things get flushed, stop the
230 // CScheduler/checkqueue threadGroup
231 threadGroup.interrupt_all();
232 threadGroup.join_all();
233
234 // After the threads that potentially access these pointers have been stopped,
235 // destruct and reset all to nullptr.
236 peerLogic.reset();
237 g_connman.reset();
238 g_banman.reset();
239 g_txindex.reset();
240
241 if (g_is_mempool_loaded && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
242 DumpMempool();
243 }
244
245 if (fFeeEstimatesInitialized)
246 {
247 ::feeEstimator.FlushUnconfirmed();
248 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
249 CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
250 if (!est_fileout.IsNull())
251 ::feeEstimator.Write(est_fileout);
252 else
253 LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
254 fFeeEstimatesInitialized = false;
255 }
256
257 // FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing
258 if (pcoinsTip != nullptr) {
259 FlushStateToDisk();
260 }
261
262 // After there are no more peers/RPC left to give us new data which may generate
263 // CValidationInterface callbacks, flush them...
264 GetMainSignals().FlushBackgroundCallbacks();
265
266 // Any future callbacks will be dropped. This should absolutely be safe - if
267 // missing a callback results in an unrecoverable situation, unclean shutdown
268 // would too. The only reason to do the above flushes is to let the wallet catch
269 // up with our current chain to avoid any strange pruning edge cases and make
270 // next startup faster by avoiding rescan.
271
272 {
273 LOCK(cs_main);
274 if (pcoinsTip != nullptr) {
275 FlushStateToDisk();
276 }
277 pcoinsTip.reset();
278 pcoinscatcher.reset();
279 pcoinsdbview.reset();
280 pblocktree.reset();
281 }
282 for (const auto& client : interfaces.chain_clients) {
283 client->stop();
284 }
285
286 #if ENABLE_ZMQ
287 if (g_zmq_notification_interface) {
288 UnregisterValidationInterface(g_zmq_notification_interface);
289 delete g_zmq_notification_interface;
290 g_zmq_notification_interface = nullptr;
291 }
292 #endif
293
294 try {
295 if (!fs::remove(GetPidFile())) {
296 LogPrintf("%s: Unable to remove PID file: File does not exist\n", __func__);
297 }
298 } catch (const fs::filesystem_error& e) {
299 LogPrintf("%s: Unable to remove PID file: %s\n", __func__, fsbridge::get_filesystem_error_message(e));
300 }
301 interfaces.chain_clients.clear();
302 UnregisterAllValidationInterfaces();
303 GetMainSignals().UnregisterBackgroundSignalScheduler();
304 GetMainSignals().UnregisterWithMempoolSignals(mempool);
305 globalVerifyHandle.reset();
306 ECC_Stop();
307 LogPrintf("%s: done\n", __func__);
308 }
309
310 /**
311 * Signal handlers are very limited in what they are allowed to do.
312 * The execution context the handler is invoked in is not guaranteed,
313 * so we restrict handler operations to just touching variables:
314 */
315 #ifndef WIN32
HandleSIGTERM(int)316 static void HandleSIGTERM(int)
317 {
318 StartShutdown();
319 }
320
HandleSIGHUP(int)321 static void HandleSIGHUP(int)
322 {
323 LogInstance().m_reopen_file = true;
324 }
325 #else
consoleCtrlHandler(DWORD dwCtrlType)326 static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
327 {
328 StartShutdown();
329 Sleep(INFINITE);
330 return true;
331 }
332 #endif
333
334 #ifndef WIN32
registerSignalHandler(int signal,void (* handler)(int))335 static void registerSignalHandler(int signal, void(*handler)(int))
336 {
337 struct sigaction sa;
338 sa.sa_handler = handler;
339 sigemptyset(&sa.sa_mask);
340 sa.sa_flags = 0;
341 sigaction(signal, &sa, nullptr);
342 }
343 #endif
344
OnRPCStarted()345 static void OnRPCStarted()
346 {
347 uiInterface.NotifyBlockTip_connect(&RPCNotifyBlockChange);
348 }
349
OnRPCStopped()350 static void OnRPCStopped()
351 {
352 uiInterface.NotifyBlockTip_disconnect(&RPCNotifyBlockChange);
353 RPCNotifyBlockChange(false, nullptr);
354 g_best_block_cv.notify_all();
355 LogPrint(BCLog::RPC, "RPC stopped.\n");
356 }
357
SetupServerArgs()358 void SetupServerArgs()
359 {
360 SetupHelpOptions(gArgs);
361 gArgs.AddArg("-help-debug", "Print help message with debugging options and exit", false, OptionsCategory::DEBUG_TEST); // server-only for now
362
363 const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
364 const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
365 const auto regtestBaseParams = CreateBaseChainParams(CBaseChainParams::REGTEST);
366 const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
367 const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET);
368 const auto regtestChainParams = CreateChainParams(CBaseChainParams::REGTEST);
369
370 // Hidden Options
371 std::vector<std::string> hidden_args = {
372 "-dbcrashratio", "-forcecompactdb",
373 // GUI args. These will be overwritten by SetupUIArgs for the GUI
374 "-allowselfsignedrootcertificates", "-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-rootcertificates=<file>", "-splash", "-uiplatform"};
375
376 gArgs.AddArg("-version", "Print version and exit", false, OptionsCategory::OPTIONS);
377 gArgs.AddArg("-alertnotify=<cmd>", "Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)", false, OptionsCategory::OPTIONS);
378 gArgs.AddArg("-assumevalid=<hex>", strprintf("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()), false, OptionsCategory::OPTIONS);
379 gArgs.AddArg("-blocksdir=<dir>", "Specify blocks directory (default: <datadir>/blocks)", false, OptionsCategory::OPTIONS);
380 gArgs.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", false, OptionsCategory::OPTIONS);
381 gArgs.AddArg("-blockreconstructionextratxn=<n>", strprintf("Extra transactions to keep in memory for compact block reconstructions (default: %u)", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), false, OptionsCategory::OPTIONS);
382 gArgs.AddArg("-blocksonly", strprintf("Whether to reject transactions from network peers. Transactions from the wallet or RPC are not affected. (default: %u)", DEFAULT_BLOCKSONLY), false, OptionsCategory::OPTIONS);
383 gArgs.AddArg("-conf=<file>", strprintf("Specify configuration file. Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME), false, OptionsCategory::OPTIONS);
384 gArgs.AddArg("-datadir=<dir>", "Specify data directory", false, OptionsCategory::OPTIONS);
385 gArgs.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), true, OptionsCategory::OPTIONS);
386 gArgs.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (%d to %d, default: %d). In addition, unused mempool memory is shared for this cache (see -maxmempool).", nMinDbCache, nMaxDbCache, nDefaultDbCache), false, OptionsCategory::OPTIONS);
387 gArgs.AddArg("-debuglogfile=<file>", strprintf("Specify location of debug log file. Relative paths will be prefixed by a net-specific datadir location. (-nodebuglogfile to disable; default: %s)", DEFAULT_DEBUGLOGFILE), false, OptionsCategory::OPTIONS);
388 gArgs.AddArg("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER), true, OptionsCategory::OPTIONS);
389 gArgs.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", false, OptionsCategory::OPTIONS);
390 gArgs.AddArg("-loadblock=<file>", "Imports blocks from external blk000??.dat file on startup", false, OptionsCategory::OPTIONS);
391 gArgs.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE), false, OptionsCategory::OPTIONS);
392 gArgs.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), false, OptionsCategory::OPTIONS);
393 gArgs.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY), false, OptionsCategory::OPTIONS);
394 gArgs.AddArg("-minimumchainwork=<hex>", strprintf("Minimum work assumed to exist on a valid chain in hex (default: %s, testnet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()), true, OptionsCategory::OPTIONS);
395 gArgs.AddArg("-par=<n>", strprintf("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)",
396 -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), false, OptionsCategory::OPTIONS);
397 gArgs.AddArg("-persistmempool", strprintf("Whether to save the mempool on shutdown and load on restart (default: %u)", DEFAULT_PERSIST_MEMPOOL), false, OptionsCategory::OPTIONS);
398 gArgs.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", BITCOIN_PID_FILENAME), false, OptionsCategory::OPTIONS);
399 gArgs.AddArg("-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. "
400 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
401 "(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), false, OptionsCategory::OPTIONS);
402 gArgs.AddArg("-reindex", "Rebuild chain state and block index from the blk*.dat files on disk", false, OptionsCategory::OPTIONS);
403 gArgs.AddArg("-reindex-chainstate", "Rebuild chain state from the currently indexed blocks. When in pruning mode or if blocks on disk might be corrupted, use full -reindex instead.", false, OptionsCategory::OPTIONS);
404 #ifndef WIN32
405 gArgs.AddArg("-sysperms", "Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)", false, OptionsCategory::OPTIONS);
406 #else
407 hidden_args.emplace_back("-sysperms");
408 #endif
409 gArgs.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), false, OptionsCategory::OPTIONS);
410
411 gArgs.AddArg("-addnode=<ip>", "Add a node to connect to and attempt to keep the connection open (see the `addnode` RPC command help for more info). This option can be specified multiple times to add multiple nodes.", false, OptionsCategory::CONNECTION);
412 gArgs.AddArg("-banscore=<n>", strprintf("Threshold for disconnecting misbehaving peers (default: %u)", DEFAULT_BANSCORE_THRESHOLD), false, OptionsCategory::CONNECTION);
413 gArgs.AddArg("-bantime=<n>", strprintf("Number of seconds to keep misbehaving peers from reconnecting (default: %u)", DEFAULT_MISBEHAVING_BANTIME), false, OptionsCategory::CONNECTION);
414 gArgs.AddArg("-bind=<addr>", "Bind to given address and always listen on it. Use [host]:port notation for IPv6", false, OptionsCategory::CONNECTION);
415 gArgs.AddArg("-connect=<ip>", "Connect only to the specified node; -noconnect disables automatic connections (the rules for this peer are the same as for -addnode). This option can be specified multiple times to connect to multiple nodes.", false, OptionsCategory::CONNECTION);
416 gArgs.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", false, OptionsCategory::CONNECTION);
417 gArgs.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), false, OptionsCategory::CONNECTION);
418 gArgs.AddArg("-dnsseed", "Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)", false, OptionsCategory::CONNECTION);
419 gArgs.AddArg("-enablebip61", strprintf("Send reject messages per BIP61 (default: %u)", DEFAULT_ENABLE_BIP61), false, OptionsCategory::CONNECTION);
420 gArgs.AddArg("-externalip=<ip>", "Specify your own public address", false, OptionsCategory::CONNECTION);
421 gArgs.AddArg("-forcednsseed", strprintf("Always query for peer addresses via DNS lookup (default: %u)", DEFAULT_FORCEDNSSEED), false, OptionsCategory::CONNECTION);
422 gArgs.AddArg("-listen", "Accept connections from outside (default: 1 if no -proxy or -connect)", false, OptionsCategory::CONNECTION);
423 gArgs.AddArg("-listenonion", strprintf("Automatically create Tor hidden service (default: %d)", DEFAULT_LISTEN_ONION), false, OptionsCategory::CONNECTION);
424 gArgs.AddArg("-maxconnections=<n>", strprintf("Maintain at most <n> connections to peers (default: %u)", DEFAULT_MAX_PEER_CONNECTIONS), false, OptionsCategory::CONNECTION);
425 gArgs.AddArg("-maxreceivebuffer=<n>", strprintf("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXRECEIVEBUFFER), false, OptionsCategory::CONNECTION);
426 gArgs.AddArg("-maxsendbuffer=<n>", strprintf("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXSENDBUFFER), false, OptionsCategory::CONNECTION);
427 gArgs.AddArg("-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), false, OptionsCategory::CONNECTION);
428 gArgs.AddArg("-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), false, OptionsCategory::CONNECTION);
429 gArgs.AddArg("-onion=<ip:port>", "Use separate SOCKS5 proxy to reach peers via Tor hidden services, set -noonion to disable (default: -proxy)", false, OptionsCategory::CONNECTION);
430 gArgs.AddArg("-onlynet=<net>", "Make outgoing connections only through network <net> (ipv4, ipv6 or onion). Incoming connections are not affected by this option. This option can be specified multiple times to allow multiple networks.", false, OptionsCategory::CONNECTION);
431 gArgs.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), false, OptionsCategory::CONNECTION);
432 gArgs.AddArg("-permitbaremultisig", strprintf("Relay non-P2SH multisig (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), false, OptionsCategory::CONNECTION);
433 gArgs.AddArg("-port=<port>", strprintf("Listen for connections on <port> (default: %u, testnet: %u, regtest: %u)", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), false, OptionsCategory::CONNECTION);
434 gArgs.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", false, OptionsCategory::CONNECTION);
435 gArgs.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), false, OptionsCategory::CONNECTION);
436 gArgs.AddArg("-seednode=<ip>", "Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes.", false, OptionsCategory::CONNECTION);
437 gArgs.AddArg("-timeout=<n>", strprintf("Specify connection timeout in milliseconds (minimum: 1, default: %d)", DEFAULT_CONNECT_TIMEOUT), false, OptionsCategory::CONNECTION);
438 gArgs.AddArg("-peertimeout=<n>", strprintf("Specify p2p connection timeout in seconds. This option determines the amount of time a peer may be inactive before the connection to it is dropped. (minimum: 1, default: %d)", DEFAULT_PEER_CONNECT_TIMEOUT), true, OptionsCategory::CONNECTION);
439 gArgs.AddArg("-torcontrol=<ip>:<port>", strprintf("Tor control port to use if onion listening enabled (default: %s)", DEFAULT_TOR_CONTROL), false, OptionsCategory::CONNECTION);
440 gArgs.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", false, OptionsCategory::CONNECTION);
441 #ifdef USE_UPNP
442 #if USE_UPNP
443 gArgs.AddArg("-upnp", "Use UPnP to map the listening port (default: 1 when listening and no -proxy)", false, OptionsCategory::CONNECTION);
444 #else
445 gArgs.AddArg("-upnp", strprintf("Use UPnP to map the listening port (default: %u)", 0), false, OptionsCategory::CONNECTION);
446 #endif
447 #else
448 hidden_args.emplace_back("-upnp");
449 #endif
450 gArgs.AddArg("-whitebind=<addr>", "Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6", false, OptionsCategory::CONNECTION);
451 gArgs.AddArg("-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."
452 " Whitelisted peers cannot be DoS banned", false, OptionsCategory::CONNECTION);
453
454 g_wallet_init_interface.AddWalletOptions();
455
456 #if ENABLE_ZMQ
457 gArgs.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", false, OptionsCategory::ZMQ);
458 gArgs.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", false, OptionsCategory::ZMQ);
459 gArgs.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", false, OptionsCategory::ZMQ);
460 gArgs.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", false, OptionsCategory::ZMQ);
461 gArgs.AddArg("-zmqpubhashblockhwm=<n>", strprintf("Set publish hash block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), false, OptionsCategory::ZMQ);
462 gArgs.AddArg("-zmqpubhashtxhwm=<n>", strprintf("Set publish hash transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), false, OptionsCategory::ZMQ);
463 gArgs.AddArg("-zmqpubrawblockhwm=<n>", strprintf("Set publish raw block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), false, OptionsCategory::ZMQ);
464 gArgs.AddArg("-zmqpubrawtxhwm=<n>", strprintf("Set publish raw transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), false, OptionsCategory::ZMQ);
465 #else
466 hidden_args.emplace_back("-zmqpubhashblock=<address>");
467 hidden_args.emplace_back("-zmqpubhashtx=<address>");
468 hidden_args.emplace_back("-zmqpubrawblock=<address>");
469 hidden_args.emplace_back("-zmqpubrawtx=<address>");
470 hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
471 hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
472 hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
473 hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
474 #endif
475
476 gArgs.AddArg("-checkblocks=<n>", strprintf("How many blocks to check at startup (default: %u, 0 = all)", DEFAULT_CHECKBLOCKS), true, OptionsCategory::DEBUG_TEST);
477 gArgs.AddArg("-checklevel=<n>", strprintf("How thorough the block verification of -checkblocks is: "
478 "level 0 reads the blocks from disk, "
479 "level 1 verifies block validity, "
480 "level 2 verifies undo data, "
481 "level 3 checks disconnection of tip blocks, "
482 "and level 4 tries to reconnect the blocks, "
483 "each level includes the checks of the previous levels "
484 "(0-4, default: %u)", DEFAULT_CHECKLEVEL), true, OptionsCategory::DEBUG_TEST);
485 gArgs.AddArg("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST);
486 gArgs.AddArg("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST);
487 gArgs.AddArg("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED), true, OptionsCategory::DEBUG_TEST);
488 gArgs.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", true, OptionsCategory::DEBUG_TEST);
489 gArgs.AddArg("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages", true, OptionsCategory::DEBUG_TEST);
490 gArgs.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), true, OptionsCategory::DEBUG_TEST);
491 gArgs.AddArg("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT), true, OptionsCategory::DEBUG_TEST);
492 gArgs.AddArg("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT), true, OptionsCategory::DEBUG_TEST);
493 gArgs.AddArg("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT), true, OptionsCategory::DEBUG_TEST);
494 gArgs.AddArg("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT), true, OptionsCategory::DEBUG_TEST);
495 gArgs.AddArg("-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), true, OptionsCategory::DEBUG_TEST);
496 gArgs.AddArg("-addrmantest", "Allows to test address relay on localhost", true, OptionsCategory::DEBUG_TEST);
497 gArgs.AddArg("-debug=<category>", "Output debugging information (default: -nodebug, supplying <category> is optional). "
498 "If <category> is not supplied or if <category> = 1, output all debugging information. <category> can be: " + ListLogCategories() + ".", false, OptionsCategory::DEBUG_TEST);
499 gArgs.AddArg("-debugexclude=<category>", strprintf("Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except one or more specified categories."), false, OptionsCategory::DEBUG_TEST);
500 gArgs.AddArg("-logips", strprintf("Include IP addresses in debug output (default: %u)", DEFAULT_LOGIPS), false, OptionsCategory::DEBUG_TEST);
501 gArgs.AddArg("-logtimestamps", strprintf("Prepend debug output with timestamp (default: %u)", DEFAULT_LOGTIMESTAMPS), false, OptionsCategory::DEBUG_TEST);
502 gArgs.AddArg("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS), true, OptionsCategory::DEBUG_TEST);
503 gArgs.AddArg("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)", true, OptionsCategory::DEBUG_TEST);
504 gArgs.AddArg("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE), true, OptionsCategory::DEBUG_TEST);
505 gArgs.AddArg("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE), true, OptionsCategory::DEBUG_TEST);
506 gArgs.AddArg("-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)",
507 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)), false, OptionsCategory::DEBUG_TEST);
508 gArgs.AddArg("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY), true, OptionsCategory::DEBUG_TEST);
509 gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -daemon. To disable logging to file, set -nodebuglogfile)", false, OptionsCategory::DEBUG_TEST);
510 gArgs.AddArg("-shrinkdebugfile", "Shrink debug.log file on client startup (default: 1 when no -debug)", false, OptionsCategory::DEBUG_TEST);
511 gArgs.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", false, OptionsCategory::DEBUG_TEST);
512
513 SetupChainParamsBaseOptions();
514
515 gArgs.AddArg("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()), true, OptionsCategory::NODE_RELAY);
516 gArgs.AddArg("-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)), true, OptionsCategory::NODE_RELAY);
517 gArgs.AddArg("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to defined dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)), true, OptionsCategory::NODE_RELAY);
518 gArgs.AddArg("-bytespersigop", strprintf("Equivalent bytes per sigop in transactions for relay and mining (default: %u)", DEFAULT_BYTES_PER_SIGOP), false, OptionsCategory::NODE_RELAY);
519 gArgs.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), false, OptionsCategory::NODE_RELAY);
520 gArgs.AddArg("-datacarriersize", strprintf("Maximum size of data in data carrier transactions we relay and mine (default: %u)", MAX_OP_RETURN_RELAY), false, OptionsCategory::NODE_RELAY);
521 gArgs.AddArg("-mempoolreplacement", strprintf("Enable transaction replacement in the memory pool (default: %u)", DEFAULT_ENABLE_REPLACEMENT), false, OptionsCategory::NODE_RELAY);
522 gArgs.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
523 CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)), false, OptionsCategory::NODE_RELAY);
524 gArgs.AddArg("-whitelistforcerelay", strprintf("Force relay of transactions from whitelisted peers even if the transactions were already in the mempool or violate local relay policy (default: %d)", DEFAULT_WHITELISTFORCERELAY), false, OptionsCategory::NODE_RELAY);
525 gArgs.AddArg("-whitelistrelay", strprintf("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)", DEFAULT_WHITELISTRELAY), false, OptionsCategory::NODE_RELAY);
526
527
528 gArgs.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), false, OptionsCategory::BLOCK_CREATION);
529 gArgs.AddArg("-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)), false, OptionsCategory::BLOCK_CREATION);
530 gArgs.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", true, OptionsCategory::BLOCK_CREATION);
531
532 gArgs.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), false, OptionsCategory::RPC);
533 gArgs.AddArg("-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", false, OptionsCategory::RPC);
534 gArgs.AddArg("-rpcauth=<userpw>", "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcauth. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times", false, OptionsCategory::RPC);
535 gArgs.AddArg("-rpcbind=<addr>[:port]", "Bind to given address to listen for JSON-RPC connections. Do not expose the RPC server to untrusted networks such as the public internet! This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost)", false, OptionsCategory::RPC);
536 gArgs.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", false, OptionsCategory::RPC);
537 gArgs.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", false, OptionsCategory::RPC);
538 gArgs.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u, testnet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), false, OptionsCategory::RPC);
539 gArgs.AddArg("-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), false, OptionsCategory::RPC);
540 gArgs.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), true, OptionsCategory::RPC);
541 gArgs.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), false, OptionsCategory::RPC);
542 gArgs.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", false, OptionsCategory::RPC);
543 gArgs.AddArg("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), true, OptionsCategory::RPC);
544 gArgs.AddArg("-server", "Accept command line and JSON-RPC commands", false, OptionsCategory::RPC);
545
546 #if HAVE_DECL_DAEMON
547 gArgs.AddArg("-daemon", "Run in the background as a daemon and accept commands", false, OptionsCategory::OPTIONS);
548 #else
549 hidden_args.emplace_back("-daemon");
550 #endif
551
552 // Add the hidden options
553 gArgs.AddHiddenArgs(hidden_args);
554 }
555
LicenseInfo()556 std::string LicenseInfo()
557 {
558 const std::string URL_SOURCE_CODE = "<https://github.com/litecoin-project/litecoin>";
559 const std::string URL_WEBSITE = "<https://litecoin.org>";
560
561 return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2011, COPYRIGHT_YEAR) + " ") + "\n" +
562 "\n" +
563 strprintf(_("Please contribute if you find %s useful. "
564 "Visit %s for further information about the software."),
565 PACKAGE_NAME, URL_WEBSITE) +
566 "\n" +
567 strprintf(_("The source code is available from %s."),
568 URL_SOURCE_CODE) +
569 "\n" +
570 "\n" +
571 _("This is experimental software.") + "\n" +
572 strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
573 "\n" +
574 strprintf(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard."), "<https://www.openssl.org>") +
575 "\n";
576 }
577
BlockNotifyCallback(bool initialSync,const CBlockIndex * pBlockIndex)578 static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
579 {
580 if (initialSync || !pBlockIndex)
581 return;
582
583 std::string strCmd = gArgs.GetArg("-blocknotify", "");
584 if (!strCmd.empty()) {
585 boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
586 std::thread t(runCommand, strCmd);
587 t.detach(); // thread runs free
588 }
589 }
590
591 static bool fHaveGenesis = false;
592 static Mutex g_genesis_wait_mutex;
593 static std::condition_variable g_genesis_wait_cv;
594
BlockNotifyGenesisWait(bool,const CBlockIndex * pBlockIndex)595 static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
596 {
597 if (pBlockIndex != nullptr) {
598 {
599 LOCK(g_genesis_wait_mutex);
600 fHaveGenesis = true;
601 }
602 g_genesis_wait_cv.notify_all();
603 }
604 }
605
606 struct CImportingNow
607 {
CImportingNowCImportingNow608 CImportingNow() {
609 assert(fImporting == false);
610 fImporting = true;
611 }
612
~CImportingNowCImportingNow613 ~CImportingNow() {
614 assert(fImporting == true);
615 fImporting = false;
616 }
617 };
618
619
620 // If we're using -prune with -reindex, then delete block files that will be ignored by the
621 // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
622 // is missing, do the same here to delete any later block files after a gap. Also delete all
623 // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
624 // is in sync with what's actually on disk by the time we start downloading, so that pruning
625 // works correctly.
CleanupBlockRevFiles()626 static void CleanupBlockRevFiles()
627 {
628 std::map<std::string, fs::path> mapBlockFiles;
629
630 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
631 // Remove the rev files immediately and insert the blk file paths into an
632 // ordered map keyed by block file index.
633 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
634 fs::path blocksdir = GetBlocksDir();
635 for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
636 if (fs::is_regular_file(*it) &&
637 it->path().filename().string().length() == 12 &&
638 it->path().filename().string().substr(8,4) == ".dat")
639 {
640 if (it->path().filename().string().substr(0,3) == "blk")
641 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
642 else if (it->path().filename().string().substr(0,3) == "rev")
643 remove(it->path());
644 }
645 }
646
647 // Remove all block files that aren't part of a contiguous set starting at
648 // zero by walking the ordered map (keys are block file indices) by
649 // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
650 // start removing block files.
651 int nContigCounter = 0;
652 for (const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
653 if (atoi(item.first) == nContigCounter) {
654 nContigCounter++;
655 continue;
656 }
657 remove(item.second);
658 }
659 }
660
ThreadImport(std::vector<fs::path> vImportFiles)661 static void ThreadImport(std::vector<fs::path> vImportFiles)
662 {
663 const CChainParams& chainparams = Params();
664 RenameThread("litecoin-loadblk");
665 ScheduleBatchPriority();
666
667 {
668 CImportingNow imp;
669
670 // -reindex
671 if (fReindex) {
672 int nFile = 0;
673 while (true) {
674 CDiskBlockPos pos(nFile, 0);
675 if (!fs::exists(GetBlockPosFilename(pos, "blk")))
676 break; // No block files left to reindex
677 FILE *file = OpenBlockFile(pos, true);
678 if (!file)
679 break; // This error is logged in OpenBlockFile
680 LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
681 LoadExternalBlockFile(chainparams, file, &pos);
682 nFile++;
683 }
684 pblocktree->WriteReindexing(false);
685 fReindex = false;
686 LogPrintf("Reindexing finished\n");
687 // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
688 LoadGenesisBlock(chainparams);
689 }
690
691 // hardcoded $DATADIR/bootstrap.dat
692 fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
693 if (fs::exists(pathBootstrap)) {
694 FILE *file = fsbridge::fopen(pathBootstrap, "rb");
695 if (file) {
696 fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
697 LogPrintf("Importing bootstrap.dat...\n");
698 LoadExternalBlockFile(chainparams, file);
699 RenameOver(pathBootstrap, pathBootstrapOld);
700 } else {
701 LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
702 }
703 }
704
705 // -loadblock=
706 for (const fs::path& path : vImportFiles) {
707 FILE *file = fsbridge::fopen(path, "rb");
708 if (file) {
709 LogPrintf("Importing blocks file %s...\n", path.string());
710 LoadExternalBlockFile(chainparams, file);
711 } else {
712 LogPrintf("Warning: Could not open blocks file %s\n", path.string());
713 }
714 }
715
716 // scan for better chains in the block chain database, that are not yet connected in the active best chain
717 CValidationState state;
718 if (!ActivateBestChain(state, chainparams)) {
719 LogPrintf("Failed to connect best block (%s)\n", FormatStateMessage(state));
720 StartShutdown();
721 return;
722 }
723
724 if (gArgs.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
725 LogPrintf("Stopping after block import\n");
726 StartShutdown();
727 return;
728 }
729 } // End scope of CImportingNow
730 if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
731 LoadMempool();
732 }
733 g_is_mempool_loaded = !ShutdownRequested();
734 }
735
736 /** Sanity checks
737 * Ensure that Bitcoin is running in a usable environment with all
738 * necessary library support.
739 */
InitSanityCheck()740 static bool InitSanityCheck()
741 {
742 if(!ECC_InitSanityCheck()) {
743 InitError("Elliptic curve cryptography sanity check failure. Aborting.");
744 return false;
745 }
746
747 if (!glibc_sanity_test() || !glibcxx_sanity_test())
748 return false;
749
750 if (!Random_SanityCheck()) {
751 InitError("OS cryptographic RNG sanity check failure. Aborting.");
752 return false;
753 }
754
755 return true;
756 }
757
AppInitServers()758 static bool AppInitServers()
759 {
760 RPCServer::OnStarted(&OnRPCStarted);
761 RPCServer::OnStopped(&OnRPCStopped);
762 if (!InitHTTPServer())
763 return false;
764 StartRPC();
765 if (!StartHTTPRPC())
766 return false;
767 if (gArgs.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) StartREST();
768 StartHTTPServer();
769 return true;
770 }
771
772 // Parameter interaction based on rules
InitParameterInteraction()773 void InitParameterInteraction()
774 {
775 // when specifying an explicit binding address, you want to listen on it
776 // even when -connect or -proxy is specified
777 if (gArgs.IsArgSet("-bind")) {
778 if (gArgs.SoftSetBoolArg("-listen", true))
779 LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
780 }
781 if (gArgs.IsArgSet("-whitebind")) {
782 if (gArgs.SoftSetBoolArg("-listen", true))
783 LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
784 }
785
786 if (gArgs.IsArgSet("-connect")) {
787 // when only connecting to trusted nodes, do not seed via DNS, or listen by default
788 if (gArgs.SoftSetBoolArg("-dnsseed", false))
789 LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
790 if (gArgs.SoftSetBoolArg("-listen", false))
791 LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
792 }
793
794 if (gArgs.IsArgSet("-proxy")) {
795 // to protect privacy, do not listen by default if a default proxy server is specified
796 if (gArgs.SoftSetBoolArg("-listen", false))
797 LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
798 // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
799 // to listen locally, so don't rely on this happening through -listen below.
800 if (gArgs.SoftSetBoolArg("-upnp", false))
801 LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
802 // to protect privacy, do not discover addresses by default
803 if (gArgs.SoftSetBoolArg("-discover", false))
804 LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
805 }
806
807 if (!gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
808 // do not map ports or try to retrieve public IP when not listening (pointless)
809 if (gArgs.SoftSetBoolArg("-upnp", false))
810 LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
811 if (gArgs.SoftSetBoolArg("-discover", false))
812 LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
813 if (gArgs.SoftSetBoolArg("-listenonion", false))
814 LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
815 }
816
817 if (gArgs.IsArgSet("-externalip")) {
818 // if an explicit public IP is specified, do not try to find others
819 if (gArgs.SoftSetBoolArg("-discover", false))
820 LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
821 }
822
823 // disable whitelistrelay in blocksonly mode
824 if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
825 if (gArgs.SoftSetBoolArg("-whitelistrelay", false))
826 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
827 }
828
829 // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
830 if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
831 if (gArgs.SoftSetBoolArg("-whitelistrelay", true))
832 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
833 }
834
835 // Warn if network-specific options (-addnode, -connect, etc) are
836 // specified in default section of config file, but not overridden
837 // on the command line or in this network's section of the config file.
838 std::string network = gArgs.GetChainName();
839 for (const auto& arg : gArgs.GetUnsuitableSectionOnlyArgs()) {
840 InitWarning(strprintf(_("Config setting for %s only applied on %s network when in [%s] section."), arg, network, network));
841 }
842
843 // Warn if unrecognized section name are present in the config file.
844 for (const auto& section : gArgs.GetUnrecognizedSections()) {
845 InitWarning(strprintf(_("Section [%s] is not recognized."), section));
846 }
847 }
848
ResolveErrMsg(const char * const optname,const std::string & strBind)849 static std::string ResolveErrMsg(const char * const optname, const std::string& strBind)
850 {
851 return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind);
852 }
853
854 /**
855 * Initialize global loggers.
856 *
857 * Note that this is called very early in the process lifetime, so you should be
858 * careful about what global state you rely on here.
859 */
InitLogging()860 void InitLogging()
861 {
862 LogInstance().m_print_to_file = !gArgs.IsArgNegated("-debuglogfile");
863 LogInstance().m_file_path = AbsPathForConfigVal(gArgs.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE));
864
865 // Add newlines to the logfile to distinguish this execution from the last
866 // one; called before console logging is set up, so this is only sent to
867 // debug.log.
868 LogPrintf("\n\n\n\n\n");
869
870 LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", !gArgs.GetBoolArg("-daemon", false));
871 LogInstance().m_log_timestamps = gArgs.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
872 LogInstance().m_log_time_micros = gArgs.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
873
874 fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS);
875
876 std::string version_string = FormatFullVersion();
877 #ifdef DEBUG
878 version_string += " (debug build)";
879 #else
880 version_string += " (release build)";
881 #endif
882 LogPrintf(PACKAGE_NAME " version %s\n", version_string);
883 }
884
885 namespace { // Variables internal to initialization process only
886
887 int nMaxConnections;
888 int nUserMaxConnections;
889 int nFD;
890 ServiceFlags nLocalServices = ServiceFlags(NODE_NETWORK | NODE_NETWORK_LIMITED);
891 int64_t peer_connect_timeout;
892
893 } // namespace
894
new_handler_terminate()895 [[noreturn]] static void new_handler_terminate()
896 {
897 // Rather than throwing std::bad-alloc if allocation fails, terminate
898 // immediately to (try to) avoid chain corruption.
899 // Since LogPrintf may itself allocate memory, set the handler directly
900 // to terminate first.
901 std::set_new_handler(std::terminate);
902 LogPrintf("Error: Out of memory. Terminating.\n");
903
904 // The log was successful, terminate now.
905 std::terminate();
906 };
907
AppInitBasicSetup()908 bool AppInitBasicSetup()
909 {
910 // ********************************************************* Step 1: setup
911 #ifdef _MSC_VER
912 // Turn off Microsoft heap dump noise
913 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
914 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
915 // Disable confusing "helpful" text message on abort, Ctrl-C
916 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
917 #endif
918 #ifdef WIN32
919 // Enable Data Execution Prevention (DEP)
920 SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
921 #endif
922
923 if (!SetupNetworking())
924 return InitError("Initializing networking failed");
925
926 #ifndef WIN32
927 if (!gArgs.GetBoolArg("-sysperms", false)) {
928 umask(077);
929 }
930
931 // Clean shutdown on SIGTERM
932 registerSignalHandler(SIGTERM, HandleSIGTERM);
933 registerSignalHandler(SIGINT, HandleSIGTERM);
934
935 // Reopen debug.log on SIGHUP
936 registerSignalHandler(SIGHUP, HandleSIGHUP);
937
938 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
939 signal(SIGPIPE, SIG_IGN);
940 #else
941 SetConsoleCtrlHandler(consoleCtrlHandler, true);
942 #endif
943
944 std::set_new_handler(new_handler_terminate);
945
946 return true;
947 }
948
AppInitParameterInteraction()949 bool AppInitParameterInteraction()
950 {
951 const CChainParams& chainparams = Params();
952 // ********************************************************* Step 2: parameter interactions
953
954 // also see: InitParameterInteraction()
955
956 if (!fs::is_directory(GetBlocksDir())) {
957 return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist."), gArgs.GetArg("-blocksdir", "").c_str()));
958 }
959
960 // if using block pruning, then disallow txindex
961 if (gArgs.GetArg("-prune", 0)) {
962 if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX))
963 return InitError(_("Prune mode is incompatible with -txindex."));
964 }
965
966 // -bind and -whitebind can't be set when not listening
967 size_t nUserBind = gArgs.GetArgs("-bind").size() + gArgs.GetArgs("-whitebind").size();
968 if (nUserBind != 0 && !gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
969 return InitError("Cannot set -bind or -whitebind together with -listen=0");
970 }
971
972 // Make sure enough file descriptors are available
973 int nBind = std::max(nUserBind, size_t(1));
974 nUserMaxConnections = gArgs.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
975 nMaxConnections = std::max(nUserMaxConnections, 0);
976
977 // Trim requested connection counts, to fit into system limitations
978 // <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695
979 nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
980 #ifdef USE_POLL
981 int fd_max = nFD;
982 #else
983 int fd_max = FD_SETSIZE;
984 #endif
985 nMaxConnections = std::max(std::min<int>(nMaxConnections, fd_max - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS), 0);
986 if (nFD < MIN_CORE_FILEDESCRIPTORS)
987 return InitError(_("Not enough file descriptors available."));
988 nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
989
990 if (nMaxConnections < nUserMaxConnections)
991 InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
992
993 // ********************************************************* Step 3: parameter-to-internal-flags
994 if (gArgs.IsArgSet("-debug")) {
995 // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
996 const std::vector<std::string> categories = gArgs.GetArgs("-debug");
997
998 if (std::none_of(categories.begin(), categories.end(),
999 [](std::string cat){return cat == "0" || cat == "none";})) {
1000 for (const auto& cat : categories) {
1001 if (!LogInstance().EnableCategory(cat)) {
1002 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
1003 }
1004 }
1005 }
1006 }
1007
1008 // Now remove the logging categories which were explicitly excluded
1009 for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
1010 if (!LogInstance().DisableCategory(cat)) {
1011 InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
1012 }
1013 }
1014
1015 // Checkmempool and checkblockindex default to true in regtest mode
1016 int ratio = std::min<int>(std::max<int>(gArgs.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
1017 if (ratio != 0) {
1018 mempool.setSanityCheck(1.0 / ratio);
1019 }
1020 fCheckBlockIndex = gArgs.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
1021 fCheckpointsEnabled = gArgs.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
1022
1023 hashAssumeValid = uint256S(gArgs.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
1024 if (!hashAssumeValid.IsNull())
1025 LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
1026 else
1027 LogPrintf("Validating signatures for all blocks.\n");
1028
1029 if (gArgs.IsArgSet("-minimumchainwork")) {
1030 const std::string minChainWorkStr = gArgs.GetArg("-minimumchainwork", "");
1031 if (!IsHexNumber(minChainWorkStr)) {
1032 return InitError(strprintf("Invalid non-hex (%s) minimum chain work value specified", minChainWorkStr));
1033 }
1034 nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
1035 } else {
1036 nMinimumChainWork = UintToArith256(chainparams.GetConsensus().nMinimumChainWork);
1037 }
1038 LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
1039 if (nMinimumChainWork < UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
1040 LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex());
1041 }
1042
1043 // mempool limits
1044 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1045 int64_t nMempoolSizeMin = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
1046 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
1047 return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
1048 // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
1049 // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
1050 if (gArgs.IsArgSet("-incrementalrelayfee"))
1051 {
1052 CAmount n = 0;
1053 if (!ParseMoney(gArgs.GetArg("-incrementalrelayfee", ""), n))
1054 return InitError(AmountErrMsg("incrementalrelayfee", gArgs.GetArg("-incrementalrelayfee", "")));
1055 incrementalRelayFee = CFeeRate(n);
1056 }
1057
1058 // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
1059 nScriptCheckThreads = gArgs.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
1060 if (nScriptCheckThreads <= 0)
1061 nScriptCheckThreads += GetNumCores();
1062 if (nScriptCheckThreads <= 1)
1063 nScriptCheckThreads = 0;
1064 else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
1065 nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
1066
1067 // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
1068 int64_t nPruneArg = gArgs.GetArg("-prune", 0);
1069 if (nPruneArg < 0) {
1070 return InitError(_("Prune cannot be configured with a negative value."));
1071 }
1072 nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
1073 if (nPruneArg == 1) { // manual pruning: -prune=1
1074 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1075 nPruneTarget = std::numeric_limits<uint64_t>::max();
1076 fPruneMode = true;
1077 } else if (nPruneTarget) {
1078 if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
1079 return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1080 }
1081 LogPrintf("Prune configured to target %u MiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
1082 fPruneMode = true;
1083 }
1084
1085 nConnectTimeout = gArgs.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1086 if (nConnectTimeout <= 0) {
1087 nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1088 }
1089
1090 peer_connect_timeout = gArgs.GetArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
1091 if (peer_connect_timeout <= 0) {
1092 return InitError("peertimeout cannot be configured with a negative value.");
1093 }
1094
1095 if (gArgs.IsArgSet("-minrelaytxfee")) {
1096 CAmount n = 0;
1097 if (!ParseMoney(gArgs.GetArg("-minrelaytxfee", ""), n)) {
1098 return InitError(AmountErrMsg("minrelaytxfee", gArgs.GetArg("-minrelaytxfee", "")));
1099 }
1100 // High fee check is done afterward in WalletParameterInteraction()
1101 ::minRelayTxFee = CFeeRate(n);
1102 } else if (incrementalRelayFee > ::minRelayTxFee) {
1103 // Allow only setting incrementalRelayFee to control both
1104 ::minRelayTxFee = incrementalRelayFee;
1105 LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
1106 }
1107
1108 // Sanity check argument for min fee for including tx in block
1109 // TODO: Harmonize which arguments need sanity checking and where that happens
1110 if (gArgs.IsArgSet("-blockmintxfee"))
1111 {
1112 CAmount n = 0;
1113 if (!ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n))
1114 return InitError(AmountErrMsg("blockmintxfee", gArgs.GetArg("-blockmintxfee", "")));
1115 }
1116
1117 // Feerate used to define dust. Shouldn't be changed lightly as old
1118 // implementations may inadvertently create non-standard transactions
1119 if (gArgs.IsArgSet("-dustrelayfee"))
1120 {
1121 CAmount n = 0;
1122 if (!ParseMoney(gArgs.GetArg("-dustrelayfee", ""), n))
1123 return InitError(AmountErrMsg("dustrelayfee", gArgs.GetArg("-dustrelayfee", "")));
1124 dustRelayFee = CFeeRate(n);
1125 }
1126
1127 // This is required by both the wallet and node
1128 if (gArgs.IsArgSet("-maxtxfee"))
1129 {
1130 CAmount nMaxFee = 0;
1131 if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee))
1132 return InitError(AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", "")));
1133 if (nMaxFee > HIGH_MAX_TX_FEE)
1134 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
1135 maxTxFee = nMaxFee;
1136 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
1137 {
1138 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
1139 gArgs.GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
1140 }
1141 }
1142
1143 fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
1144 if (chainparams.RequireStandard() && !fRequireStandard)
1145 return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
1146 nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp);
1147
1148 if (!g_wallet_init_interface.ParameterInteraction()) return false;
1149
1150 fIsBareMultisigStd = gArgs.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
1151 fAcceptDatacarrier = gArgs.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
1152 nMaxDatacarrierBytes = gArgs.GetArg("-datacarriersize", nMaxDatacarrierBytes);
1153
1154 // Option to startup with mocktime set (used for regression testing):
1155 SetMockTime(gArgs.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1156
1157 if (gArgs.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1158 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1159
1160 if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1161 return InitError("rpcserialversion must be non-negative.");
1162
1163 if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1164 return InitError("unknown rpcserialversion requested.");
1165
1166 nMaxTipAge = gArgs.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
1167
1168 fEnableReplacement = gArgs.GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
1169 if ((!fEnableReplacement) && gArgs.IsArgSet("-mempoolreplacement")) {
1170 // Minimal effort at forwards compatibility
1171 std::string strReplacementModeList = gArgs.GetArg("-mempoolreplacement", ""); // default is impossible
1172 std::vector<std::string> vstrReplacementModes;
1173 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
1174 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
1175 }
1176
1177 return true;
1178 }
1179
LockDataDirectory(bool probeOnly)1180 static bool LockDataDirectory(bool probeOnly)
1181 {
1182 // Make sure only a single Bitcoin process is using the data directory.
1183 fs::path datadir = GetDataDir();
1184 if (!DirIsWritable(datadir)) {
1185 return InitError(strprintf(_("Cannot write to data directory '%s'; check permissions."), datadir.string()));
1186 }
1187 if (!LockDirectory(datadir, ".lock", probeOnly)) {
1188 return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), datadir.string(), PACKAGE_NAME));
1189 }
1190 return true;
1191 }
1192
AppInitSanityChecks()1193 bool AppInitSanityChecks()
1194 {
1195 // ********************************************************* Step 4: sanity checks
1196
1197 // Initialize elliptic curve code
1198 std::string sha256_algo = SHA256AutoDetect();
1199 LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
1200 RandomInit();
1201 ECC_Start();
1202 globalVerifyHandle.reset(new ECCVerifyHandle());
1203
1204 // Sanity check
1205 if (!InitSanityCheck())
1206 return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), PACKAGE_NAME));
1207
1208 // Probe the data directory lock to give an early error message, if possible
1209 // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened,
1210 // and a fork will cause weird behavior to it.
1211 return LockDataDirectory(true);
1212 }
1213
AppInitLockDataDirectory()1214 bool AppInitLockDataDirectory()
1215 {
1216 // After daemonization get the data directory lock again and hold on to it until exit
1217 // This creates a slight window for a race condition to happen, however this condition is harmless: it
1218 // will at most make us exit without printing a message to console.
1219 if (!LockDataDirectory(false)) {
1220 // Detailed error printed inside LockDataDirectory
1221 return false;
1222 }
1223 return true;
1224 }
1225
AppInitMain(InitInterfaces & interfaces)1226 bool AppInitMain(InitInterfaces& interfaces)
1227 {
1228 const CChainParams& chainparams = Params();
1229 // ********************************************************* Step 4a: application initialization
1230 if (!CreatePidFile()) {
1231 // Detailed error printed inside CreatePidFile().
1232 return false;
1233 }
1234 if (LogInstance().m_print_to_file) {
1235 if (gArgs.GetBoolArg("-shrinkdebugfile", LogInstance().DefaultShrinkDebugFile())) {
1236 // Do this first since it both loads a bunch of debug.log into memory,
1237 // and because this needs to happen before any other debug.log printing
1238 LogInstance().ShrinkDebugFile();
1239 }
1240 if (!LogInstance().OpenDebugLog()) {
1241 return InitError(strprintf("Could not open debug log file %s",
1242 LogInstance().m_file_path.string()));
1243 }
1244 }
1245
1246 if (!LogInstance().m_log_timestamps)
1247 LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
1248 LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
1249 LogPrintf("Using data directory %s\n", GetDataDir().string());
1250
1251 // Only log conf file usage message if conf file actually exists.
1252 fs::path config_file_path = GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME));
1253 if (fs::exists(config_file_path)) {
1254 LogPrintf("Config file: %s\n", config_file_path.string());
1255 } else if (gArgs.IsArgSet("-conf")) {
1256 // Warn if no conf file exists at path provided by user
1257 InitWarning(strprintf(_("The specified config file %s does not exist\n"), config_file_path.string()));
1258 } else {
1259 // Not categorizing as "Warning" because it's the default behavior
1260 LogPrintf("Config file: %s (not found, skipping)\n", config_file_path.string());
1261 }
1262
1263 LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1264
1265 // Warn about relative -datadir path.
1266 if (gArgs.IsArgSet("-datadir") && !fs::path(gArgs.GetArg("-datadir", "")).is_absolute()) {
1267 LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " /* Continued */
1268 "current working directory '%s'. This is fragile, because if litecoin is started in the future "
1269 "from a different location, it will be unable to locate the current data files. There could "
1270 "also be data loss if litecoin is started while in a temporary directory.\n",
1271 gArgs.GetArg("-datadir", ""), fs::current_path().string());
1272 }
1273
1274 InitSignatureCache();
1275 InitScriptExecutionCache();
1276
1277 LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
1278 if (nScriptCheckThreads) {
1279 for (int i=0; i<nScriptCheckThreads-1; i++)
1280 threadGroup.create_thread(&ThreadScriptCheck);
1281 }
1282
1283 // Start the lightweight task scheduler thread
1284 CScheduler::Function serviceLoop = std::bind(&CScheduler::serviceQueue, &scheduler);
1285 threadGroup.create_thread(std::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
1286
1287 GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);
1288 GetMainSignals().RegisterWithMempoolSignals(mempool);
1289
1290 // Create client interfaces for wallets that are supposed to be loaded
1291 // according to -wallet and -disablewallet options. This only constructs
1292 // the interfaces, it doesn't load wallet data. Wallets actually get loaded
1293 // when load() and start() interface methods are called below.
1294 g_wallet_init_interface.Construct(interfaces);
1295
1296 /* Register RPC commands regardless of -server setting so they will be
1297 * available in the GUI RPC console even if external calls are disabled.
1298 */
1299 RegisterAllCoreRPCCommands(tableRPC);
1300 for (const auto& client : interfaces.chain_clients) {
1301 client->registerRpcs();
1302 }
1303 g_rpc_interfaces = &interfaces;
1304 #if ENABLE_ZMQ
1305 RegisterZMQRPCCommands(tableRPC);
1306 #endif
1307
1308 /* Start the RPC server already. It will be started in "warmup" mode
1309 * and not really process calls already (but it will signify connections
1310 * that the server is there and will be ready later). Warmup mode will
1311 * be disabled when initialisation is finished.
1312 */
1313 if (gArgs.GetBoolArg("-server", false))
1314 {
1315 uiInterface.InitMessage_connect(SetRPCWarmupStatus);
1316 if (!AppInitServers())
1317 return InitError(_("Unable to start HTTP server. See debug log for details."));
1318 }
1319
1320 #if defined(USE_SSE2)
1321 std::string sse2detect = scrypt_detect_sse2();
1322 LogPrintf("%s\n", sse2detect);
1323 #endif
1324
1325 // ********************************************************* Step 5: verify wallet database integrity
1326 for (const auto& client : interfaces.chain_clients) {
1327 if (!client->verify()) {
1328 return false;
1329 }
1330 }
1331
1332 // ********************************************************* Step 6: network initialization
1333 // Note that we absolutely cannot open any actual connections
1334 // until the very end ("start node") as the UTXO/block state
1335 // is not yet setup and may end up being set up twice if we
1336 // need to reindex later.
1337
1338 assert(!g_banman);
1339 g_banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", &uiInterface, gArgs.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
1340 assert(!g_connman);
1341 g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
1342
1343 peerLogic.reset(new PeerLogicValidation(g_connman.get(), g_banman.get(), scheduler, gArgs.GetBoolArg("-enablebip61", DEFAULT_ENABLE_BIP61)));
1344 RegisterValidationInterface(peerLogic.get());
1345
1346 // sanitize comments per BIP-0014, format user agent and check total size
1347 std::vector<std::string> uacomments;
1348 for (const std::string& cmt : gArgs.GetArgs("-uacomment")) {
1349 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1350 return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1351 uacomments.push_back(cmt);
1352 }
1353 strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
1354 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1355 return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1356 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1357 }
1358
1359 if (gArgs.IsArgSet("-onlynet")) {
1360 std::set<enum Network> nets;
1361 for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
1362 enum Network net = ParseNetwork(snet);
1363 if (net == NET_UNROUTABLE)
1364 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1365 nets.insert(net);
1366 }
1367 for (int n = 0; n < NET_MAX; n++) {
1368 enum Network net = (enum Network)n;
1369 if (!nets.count(net))
1370 SetReachable(net, false);
1371 }
1372 }
1373
1374 // Check for host lookup allowed before parsing any network related parameters
1375 fNameLookup = gArgs.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1376
1377 bool proxyRandomize = gArgs.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1378 // -proxy sets a proxy for all outgoing network traffic
1379 // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1380 std::string proxyArg = gArgs.GetArg("-proxy", "");
1381 SetReachable(NET_ONION, false);
1382 if (proxyArg != "" && proxyArg != "0") {
1383 CService proxyAddr;
1384 if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
1385 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1386 }
1387
1388 proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
1389 if (!addrProxy.IsValid())
1390 return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1391
1392 SetProxy(NET_IPV4, addrProxy);
1393 SetProxy(NET_IPV6, addrProxy);
1394 SetProxy(NET_ONION, addrProxy);
1395 SetNameProxy(addrProxy);
1396 SetReachable(NET_ONION, true); // by default, -proxy sets onion as reachable, unless -noonion later
1397 }
1398
1399 // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
1400 // -noonion (or -onion=0) disables connecting to .onion entirely
1401 // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
1402 std::string onionArg = gArgs.GetArg("-onion", "");
1403 if (onionArg != "") {
1404 if (onionArg == "0") { // Handle -noonion/-onion=0
1405 SetReachable(NET_ONION, false);
1406 } else {
1407 CService onionProxy;
1408 if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
1409 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1410 }
1411 proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
1412 if (!addrOnion.IsValid())
1413 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
1414 SetProxy(NET_ONION, addrOnion);
1415 SetReachable(NET_ONION, true);
1416 }
1417 }
1418
1419 // see Step 2: parameter interactions for more information about these
1420 fListen = gArgs.GetBoolArg("-listen", DEFAULT_LISTEN);
1421 fDiscover = gArgs.GetBoolArg("-discover", true);
1422 g_relay_txes = !gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
1423
1424 for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
1425 CService addrLocal;
1426 if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
1427 AddLocal(addrLocal, LOCAL_MANUAL);
1428 else
1429 return InitError(ResolveErrMsg("externalip", strAddr));
1430 }
1431
1432 #if ENABLE_ZMQ
1433 g_zmq_notification_interface = CZMQNotificationInterface::Create();
1434
1435 if (g_zmq_notification_interface) {
1436 RegisterValidationInterface(g_zmq_notification_interface);
1437 }
1438 #endif
1439 uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
1440 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1441
1442 if (gArgs.IsArgSet("-maxuploadtarget")) {
1443 nMaxOutboundLimit = gArgs.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1444 }
1445
1446 // ********************************************************* Step 7: load block chain
1447
1448 fReindex = gArgs.GetBoolArg("-reindex", false);
1449 bool fReindexChainState = gArgs.GetBoolArg("-reindex-chainstate", false);
1450
1451 // cache size calculations
1452 int64_t nTotalCache = (gArgs.GetArg("-dbcache", nDefaultDbCache) << 20);
1453 nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
1454 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
1455 int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20);
1456 nTotalCache -= nBlockTreeDBCache;
1457 int64_t nTxIndexCache = std::min(nTotalCache / 8, gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0);
1458 nTotalCache -= nTxIndexCache;
1459 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
1460 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
1461 nTotalCache -= nCoinDBCache;
1462 nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
1463 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1464 LogPrintf("Cache configuration:\n");
1465 LogPrintf("* Using %.1f MiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1466 if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1467 LogPrintf("* Using %.1f MiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
1468 }
1469 LogPrintf("* Using %.1f MiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1470 LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
1471
1472 bool fLoaded = false;
1473 while (!fLoaded && !ShutdownRequested()) {
1474 bool fReset = fReindex;
1475 std::string strLoadError;
1476
1477 uiInterface.InitMessage(_("Loading block index..."));
1478
1479 do {
1480 const int64_t load_block_index_start_time = GetTimeMillis();
1481 bool is_coinsview_empty;
1482 try {
1483 LOCK(cs_main);
1484 UnloadBlockIndex();
1485 pcoinsTip.reset();
1486 pcoinsdbview.reset();
1487 pcoinscatcher.reset();
1488 // new CBlockTreeDB tries to delete the existing file, which
1489 // fails if it's still open from the previous loop. Close it first:
1490 pblocktree.reset();
1491 pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
1492
1493 if (fReset) {
1494 pblocktree->WriteReindexing(true);
1495 //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
1496 if (fPruneMode)
1497 CleanupBlockRevFiles();
1498 }
1499
1500 if (ShutdownRequested()) break;
1501
1502 // LoadBlockIndex will load fHavePruned if we've ever removed a
1503 // block file from disk.
1504 // Note that it also sets fReindex based on the disk flag!
1505 // From here on out fReindex and fReset mean something different!
1506 if (!LoadBlockIndex(chainparams)) {
1507 strLoadError = _("Error loading block database");
1508 break;
1509 }
1510
1511 // If the loaded chain has a wrong genesis, bail out immediately
1512 // (we're likely using a testnet datadir, or the other way around).
1513 if (!mapBlockIndex.empty() && !LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
1514 return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
1515 }
1516
1517 // Check for changed -prune state. What we are concerned about is a user who has pruned blocks
1518 // in the past, but is now trying to run unpruned.
1519 if (fHavePruned && !fPruneMode) {
1520 strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1521 break;
1522 }
1523
1524 // At this point blocktree args are consistent with what's on disk.
1525 // If we're not mid-reindex (based on disk + args), add a genesis block on disk
1526 // (otherwise we use the one already on disk).
1527 // This is called again in ThreadImport after the reindex completes.
1528 if (!fReindex && !LoadGenesisBlock(chainparams)) {
1529 strLoadError = _("Error initializing block database");
1530 break;
1531 }
1532
1533 // At this point we're either in reindex or we've loaded a useful
1534 // block tree into mapBlockIndex!
1535
1536 pcoinsdbview.reset(new CCoinsViewDB(nCoinDBCache, false, fReset || fReindexChainState));
1537 pcoinscatcher.reset(new CCoinsViewErrorCatcher(pcoinsdbview.get()));
1538
1539 // If necessary, upgrade from older database format.
1540 // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1541 if (!pcoinsdbview->Upgrade()) {
1542 strLoadError = _("Error upgrading chainstate database");
1543 break;
1544 }
1545
1546 // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
1547 if (!ReplayBlocks(chainparams, pcoinsdbview.get())) {
1548 strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1549 break;
1550 }
1551
1552 // The on-disk coinsdb is now in a good state, create the cache
1553 pcoinsTip.reset(new CCoinsViewCache(pcoinscatcher.get()));
1554
1555 is_coinsview_empty = fReset || fReindexChainState || pcoinsTip->GetBestBlock().IsNull();
1556 if (!is_coinsview_empty) {
1557 // LoadChainTip sets chainActive based on pcoinsTip's best block
1558 if (!LoadChainTip(chainparams)) {
1559 strLoadError = _("Error initializing block database");
1560 break;
1561 }
1562 assert(chainActive.Tip() != nullptr);
1563 }
1564 } catch (const std::exception& e) {
1565 LogPrintf("%s\n", e.what());
1566 strLoadError = _("Error opening block database");
1567 break;
1568 }
1569
1570 if (!fReset) {
1571 // Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate.
1572 // It both disconnects blocks based on chainActive, and drops block data in
1573 // mapBlockIndex based on lack of available witness data.
1574 uiInterface.InitMessage(_("Rewinding blocks..."));
1575 if (!RewindBlockIndex(chainparams)) {
1576 strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1577 break;
1578 }
1579 }
1580
1581 try {
1582 LOCK(cs_main);
1583 if (!is_coinsview_empty) {
1584 uiInterface.InitMessage(_("Verifying blocks..."));
1585 if (fHavePruned && gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
1586 LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
1587 MIN_BLOCKS_TO_KEEP);
1588 }
1589
1590 CBlockIndex* tip = chainActive.Tip();
1591 RPCNotifyBlockChange(true, tip);
1592 if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
1593 strLoadError = _("The block database contains a block which appears to be from the future. "
1594 "This may be due to your computer's date and time being set incorrectly. "
1595 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1596 break;
1597 }
1598
1599 if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview.get(), gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
1600 gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
1601 strLoadError = _("Corrupted block database detected");
1602 break;
1603 }
1604 }
1605 } catch (const std::exception& e) {
1606 LogPrintf("%s\n", e.what());
1607 strLoadError = _("Error opening block database");
1608 break;
1609 }
1610
1611 fLoaded = true;
1612 LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time);
1613 } while(false);
1614
1615 if (!fLoaded && !ShutdownRequested()) {
1616 // first suggest a reindex
1617 if (!fReset) {
1618 bool fRet = uiInterface.ThreadSafeQuestion(
1619 strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
1620 strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1621 "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
1622 if (fRet) {
1623 fReindex = true;
1624 AbortShutdown();
1625 } else {
1626 LogPrintf("Aborted block database rebuild. Exiting.\n");
1627 return false;
1628 }
1629 } else {
1630 return InitError(strLoadError);
1631 }
1632 }
1633 }
1634
1635 // As LoadBlockIndex can take several minutes, it's possible the user
1636 // requested to kill the GUI during the last operation. If so, exit.
1637 // As the program has not fully started yet, Shutdown() is possibly overkill.
1638 if (ShutdownRequested()) {
1639 LogPrintf("Shutdown requested. Exiting.\n");
1640 return false;
1641 }
1642
1643 fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
1644 CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
1645 // Allowed to fail as this file IS missing on first startup.
1646 if (!est_filein.IsNull())
1647 ::feeEstimator.Read(est_filein);
1648 fFeeEstimatesInitialized = true;
1649
1650 // ********************************************************* Step 8: start indexers
1651 if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1652 g_txindex = MakeUnique<TxIndex>(nTxIndexCache, false, fReindex);
1653 g_txindex->Start();
1654 }
1655
1656 // ********************************************************* Step 9: load wallet
1657 for (const auto& client : interfaces.chain_clients) {
1658 if (!client->load()) {
1659 return false;
1660 }
1661 }
1662
1663 // ********************************************************* Step 10: data directory maintenance
1664
1665 // if pruning, unset the service bit and perform the initial blockstore prune
1666 // after any wallet rescanning has taken place.
1667 if (fPruneMode) {
1668 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
1669 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
1670 if (!fReindex) {
1671 uiInterface.InitMessage(_("Pruning blockstore..."));
1672 PruneAndFlush();
1673 }
1674 }
1675
1676 if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
1677 // Only advertise witness capabilities if they have a reasonable start time.
1678 // This allows us to have the code merged without a defined softfork, by setting its
1679 // end time to 0.
1680 // Note that setting NODE_WITNESS is never required: the only downside from not
1681 // doing so is that after activation, no upgraded nodes will fetch from you.
1682 nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
1683 }
1684
1685 // ********************************************************* Step 11: import blocks
1686
1687 if (!CheckDiskSpace(/* additional_bytes */ 0, /* blocks_dir */ false)) {
1688 InitError(strprintf(_("Error: Disk space is low for %s"), GetDataDir()));
1689 return false;
1690 }
1691 if (!CheckDiskSpace(/* additional_bytes */ 0, /* blocks_dir */ true)) {
1692 InitError(strprintf(_("Error: Disk space is low for %s"), GetBlocksDir()));
1693 return false;
1694 }
1695
1696 // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
1697 // No locking, as this happens before any background thread is started.
1698 if (chainActive.Tip() == nullptr) {
1699 uiInterface.NotifyBlockTip_connect(BlockNotifyGenesisWait);
1700 } else {
1701 fHaveGenesis = true;
1702 }
1703
1704 if (gArgs.IsArgSet("-blocknotify"))
1705 uiInterface.NotifyBlockTip_connect(BlockNotifyCallback);
1706
1707 std::vector<fs::path> vImportFiles;
1708 for (const std::string& strFile : gArgs.GetArgs("-loadblock")) {
1709 vImportFiles.push_back(strFile);
1710 }
1711
1712 threadGroup.create_thread(std::bind(&ThreadImport, vImportFiles));
1713
1714 // Wait for genesis block to be processed
1715 {
1716 WAIT_LOCK(g_genesis_wait_mutex, lock);
1717 // We previously could hang here if StartShutdown() is called prior to
1718 // ThreadImport getting started, so instead we just wait on a timer to
1719 // check ShutdownRequested() regularly.
1720 while (!fHaveGenesis && !ShutdownRequested()) {
1721 g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
1722 }
1723 uiInterface.NotifyBlockTip_disconnect(BlockNotifyGenesisWait);
1724 }
1725
1726 if (ShutdownRequested()) {
1727 return false;
1728 }
1729
1730 // ********************************************************* Step 12: start node
1731
1732 int chain_active_height;
1733
1734 //// debug print
1735 {
1736 LOCK(cs_main);
1737 LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
1738 chain_active_height = chainActive.Height();
1739 }
1740 LogPrintf("nBestHeight = %d\n", chain_active_height);
1741
1742 if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
1743 StartTorControl();
1744
1745 Discover();
1746
1747 // Map ports with UPnP
1748 if (gArgs.GetBoolArg("-upnp", DEFAULT_UPNP)) {
1749 StartMapPort();
1750 }
1751
1752 CConnman::Options connOptions;
1753 connOptions.nLocalServices = nLocalServices;
1754 connOptions.nMaxConnections = nMaxConnections;
1755 connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections);
1756 connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1757 connOptions.nMaxFeeler = 1;
1758 connOptions.nBestHeight = chain_active_height;
1759 connOptions.uiInterface = &uiInterface;
1760 connOptions.m_banman = g_banman.get();
1761 connOptions.m_msgproc = peerLogic.get();
1762 connOptions.nSendBufferMaxSize = 1000*gArgs.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
1763 connOptions.nReceiveFloodSize = 1000*gArgs.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
1764 connOptions.m_added_nodes = gArgs.GetArgs("-addnode");
1765
1766 connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
1767 connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
1768 connOptions.m_peer_connect_timeout = peer_connect_timeout;
1769
1770 for (const std::string& strBind : gArgs.GetArgs("-bind")) {
1771 CService addrBind;
1772 if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) {
1773 return InitError(ResolveErrMsg("bind", strBind));
1774 }
1775 connOptions.vBinds.push_back(addrBind);
1776 }
1777 for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
1778 CService addrBind;
1779 if (!Lookup(strBind.c_str(), addrBind, 0, false)) {
1780 return InitError(ResolveErrMsg("whitebind", strBind));
1781 }
1782 if (addrBind.GetPort() == 0) {
1783 return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
1784 }
1785 connOptions.vWhiteBinds.push_back(addrBind);
1786 }
1787
1788 for (const auto& net : gArgs.GetArgs("-whitelist")) {
1789 CSubNet subnet;
1790 LookupSubNet(net.c_str(), subnet);
1791 if (!subnet.IsValid())
1792 return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
1793 connOptions.vWhitelistedRange.push_back(subnet);
1794 }
1795
1796 connOptions.vSeedNodes = gArgs.GetArgs("-seednode");
1797
1798 // Initiate outbound connections unless connect=0
1799 connOptions.m_use_addrman_outgoing = !gArgs.IsArgSet("-connect");
1800 if (!connOptions.m_use_addrman_outgoing) {
1801 const auto connect = gArgs.GetArgs("-connect");
1802 if (connect.size() != 1 || connect[0] != "0") {
1803 connOptions.m_specified_outgoing = connect;
1804 }
1805 }
1806 if (!g_connman->Start(scheduler, connOptions)) {
1807 return false;
1808 }
1809
1810 // ********************************************************* Step 13: finished
1811
1812 SetRPCWarmupFinished();
1813 uiInterface.InitMessage(_("Done loading"));
1814
1815 for (const auto& client : interfaces.chain_clients) {
1816 client->start(scheduler);
1817 }
1818
1819 scheduler.scheduleEvery([]{
1820 g_banman->DumpBanlist();
1821 }, DUMP_BANS_INTERVAL * 1000);
1822
1823 return true;
1824 }
1825