Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
init.cpp
Go to the documentation of this file.
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
14
15#include <addrman.h>
16#include <avalanche/avalanche.h>
17#include <avalanche/processor.h>
18#include <avalanche/proof.h> // For AVALANCHE_LEGACY_PROOF_DEFAULT
20#include <avalanche/voterecord.h> // For AVALANCHE_VOTE_STALE_*
21#include <banman.h>
22#include <blockfilter.h>
23#include <chain.h>
24#include <chainparams.h>
25#include <common/args.h>
26#include <compat/sanity.h>
27#include <config.h>
28#include <consensus/amount.h>
29#include <currencyunit.h>
30#include <flatfile.h>
31#include <hash.h>
32#include <httprpc.h>
33#include <httpserver.h>
36#include <index/txindex.h>
37#include <init/common.h>
38#include <interfaces/chain.h>
39#include <interfaces/node.h>
40#include <mapport.h>
41#include <mempool_args.h>
42#include <net.h>
43#include <net_permissions.h>
44#include <net_processing.h>
45#include <netbase.h>
47#include <node/blockstorage.h>
48#include <node/caches.h>
49#include <node/chainstate.h>
51#include <node/context.h>
54#include <node/miner.h>
55#include <node/peerman_args.h>
56#include <node/ui_interface.h>
58#include <policy/block/rtt.h>
59#include <policy/policy.h>
60#include <policy/settings.h>
61#include <rpc/blockchain.h>
62#include <rpc/register.h>
63#include <rpc/server.h>
64#include <rpc/util.h>
65#include <scheduler.h>
66#include <script/scriptcache.h>
67#include <script/sigcache.h>
68#include <script/standard.h>
69#include <shutdown.h>
70#include <sync.h>
71#include <timedata.h>
72#include <torcontrol.h>
73#include <txdb.h>
74#include <txmempool.h>
75#include <util/asmap.h>
76#include <util/check.h>
77#include <util/fs.h>
78#include <util/fs_helpers.h>
79#include <util/moneystr.h>
80#include <util/string.h>
81#include <util/syserror.h>
82#include <util/thread.h>
83#include <util/threadnames.h>
84#include <util/translation.h>
85#include <validation.h>
86#include <validationinterface.h>
87#include <walletinitinterface.h>
88
89#include <boost/signals2/signal.hpp>
90
91#if ENABLE_CHRONIK
92#include <chronik-cpp/chronik.h>
93#endif
94
95#if ENABLE_ZMQ
98#include <zmq/zmqrpc.h>
99#endif
100
101#ifndef WIN32
102#include <cerrno>
103#include <csignal>
104#include <sys/stat.h>
105#endif
106#include <algorithm>
107#include <condition_variable>
108#include <cstdint>
109#include <cstdio>
110#include <fstream>
111#include <functional>
112#include <set>
113#include <string>
114#include <thread>
115#include <vector>
116
120
123using node::CacheSizes;
126using node::fReindex;
134
135static const bool DEFAULT_PROXYRANDOMIZE = true;
136static const bool DEFAULT_REST_ENABLE = false;
137static constexpr bool DEFAULT_CHRONIK = false;
138
139#ifdef WIN32
140// Win32 LevelDB doesn't use filedescriptors, and the ones used for accessing
141// block files don't count towards the fd_set size limit anyway.
142#define MIN_CORE_FILEDESCRIPTORS 0
143#else
144#define MIN_CORE_FILEDESCRIPTORS 150
145#endif
146
147static const char *DEFAULT_ASMAP_FILENAME = "ip_asn.map";
148
149static const std::string HEADERS_TIME_FILE_NAME{"headerstime.dat"};
150
154static const char *BITCOIN_PID_FILENAME = "bitcoind.pid";
155
156static fs::path GetPidFile(const ArgsManager &args) {
157 return AbsPathForConfigVal(args,
158 args.GetPathArg("-pid", BITCOIN_PID_FILENAME));
159}
160
161[[nodiscard]] static bool CreatePidFile(const ArgsManager &args) {
162 std::ofstream file{GetPidFile(args)};
163 if (file) {
164#ifdef WIN32
165 tfm::format(file, "%d\n", GetCurrentProcessId());
166#else
167 tfm::format(file, "%d\n", getpid());
168#endif
169 return true;
170 } else {
171 return InitError(strprintf(_("Unable to create the PID file '%s': %s"),
174 }
175}
176
178//
179// Shutdown
180//
181
182//
183// Thread management and startup/shutdown:
184//
185// The network-processing threads are all part of a thread group created by
186// AppInit() or the Qt main() function.
187//
188// A clean exit happens when StartShutdown() or the SIGTERM signal handler sets
189// fRequestShutdown, which makes main thread's WaitForShutdown() interrupts the
190// thread group.
191// And then, WaitForShutdown() makes all other on-going threads in the thread
192// group join the main thread.
193// Shutdown() is then called to clean up database connections, and stop other
194// threads that should only be stopped after the main network-processing threads
195// have exited.
196//
197// Shutdown for Qt is very similar, only it uses a QTimer to detect
198// ShutdownRequested() getting set, and then does the normal Qt shutdown thing.
199//
200
204 InterruptRPC();
208 if (node.avalanche) {
209 // Avalanche needs to be stopped before we interrupt the thread group as
210 // the scheduler will stop working then.
211 node.avalanche->stopEventLoop();
212 }
213 if (node.connman) {
214 node.connman->Interrupt();
215 }
216 if (g_txindex) {
217 g_txindex->Interrupt();
218 }
219 ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Interrupt(); });
220 if (g_coin_stats_index) {
221 g_coin_stats_index->Interrupt();
222 }
223}
224
226 static Mutex g_shutdown_mutex;
228 if (!lock_shutdown) {
229 return;
230 }
231 LogPrintf("%s: In progress...\n", __func__);
232 Assert(node.args);
233
238 util::ThreadRename("shutoff");
239 if (node.mempool) {
240 node.mempool->AddTransactionsUpdated(1);
241 }
242
243 StopHTTPRPC();
244 StopREST();
245 StopRPC();
247 for (const auto &client : node.chain_clients) {
248 client->flush();
249 }
250 StopMapPort();
251
252 // Because avalanche and the network depend on each other, it is important
253 // to shut them down in this order:
254 // 1. Stop avalanche event loop.
255 // 2. Shutdown network processing.
256 // 3. Destroy avalanche::Processor.
257 // 4. Destroy CConnman
258 if (node.avalanche) {
259 node.avalanche->stopEventLoop();
260 }
261
262 // Because these depend on each-other, we make sure that neither can be
263 // using the other before destroying them.
264 if (node.peerman) {
265 UnregisterValidationInterface(node.peerman.get());
266 }
267 if (node.connman) {
268 node.connman->Stop();
269 }
270
272
273 // After everything has been shut down, but before things get flushed, stop
274 // the CScheduler/checkqueue, scheduler and load block thread.
275 if (node.scheduler) {
276 node.scheduler->stop();
277 }
278 if (node.chainman && node.chainman->m_load_block.joinable()) {
279 node.chainman->m_load_block.join();
280 }
282
283 // After the threads that potentially access these pointers have been
284 // stopped, destruct and reset all to nullptr.
285 node.peerman.reset();
286
287 // Destroy various global instances
288 node.avalanche.reset();
289 node.connman.reset();
290 node.banman.reset();
291 node.addrman.reset();
292
293 if (node.mempool && node.mempool->GetLoadTried() &&
294 ShouldPersistMempool(*node.args)) {
295 DumpMempool(*node.mempool, MempoolPath(*node.args));
296 }
297
298 // FlushStateToDisk generates a ChainStateFlushed callback, which we should
299 // avoid missing
300 if (node.chainman) {
301 LOCK(cs_main);
302 for (Chainstate *chainstate : node.chainman->GetAll()) {
303 if (chainstate->CanFlushToDisk()) {
304 chainstate->ForceFlushStateToDisk();
305 }
306 }
307 }
308
309 // After there are no more peers/RPC left to give us new data which may
310 // generate CValidationInterface callbacks, flush them...
312
313#if ENABLE_CHRONIK
314 if (node.args->GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
315 chronik::Stop();
316 }
317#endif
318
319 // Stop and delete all indexes only after flushing background callbacks.
320 if (g_txindex) {
321 g_txindex->Stop();
322 g_txindex.reset();
323 }
324 if (g_coin_stats_index) {
325 g_coin_stats_index->Stop();
326 g_coin_stats_index.reset();
327 }
328 ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Stop(); });
330
331 // Any future callbacks will be dropped. This should absolutely be safe - if
332 // missing a callback results in an unrecoverable situation, unclean
333 // shutdown would too. The only reason to do the above flushes is to let the
334 // wallet catch up with our current chain to avoid any strange pruning edge
335 // cases and make next startup faster by avoiding rescan.
336
337 if (node.chainman) {
338 LOCK(cs_main);
339 for (Chainstate *chainstate : node.chainman->GetAll()) {
340 if (chainstate->CanFlushToDisk()) {
341 chainstate->ForceFlushStateToDisk();
342 chainstate->ResetCoinsViews();
343 }
344 }
345
346 node.chainman->DumpRecentHeadersTime(node.chainman->m_options.datadir /
348 }
349 for (const auto &client : node.chain_clients) {
350 client->stop();
351 }
352
353#if ENABLE_ZMQ
357 }
358#endif
359
360 node.chain_clients.clear();
364 node.mempool.reset();
365 node.chainman.reset();
366 node.scheduler.reset();
367
368 try {
369 if (!fs::remove(GetPidFile(*node.args))) {
370 LogPrintf("%s: Unable to remove PID file: File does not exist\n",
371 __func__);
372 }
373 } catch (const fs::filesystem_error &e) {
374 LogPrintf("%s: Unable to remove PID file: %s\n", __func__,
376 }
377
378 LogPrintf("%s: done\n", __func__);
379}
380
386#ifndef WIN32
387static void HandleSIGTERM(int) {
389}
390
391static void HandleSIGHUP(int) {
392 LogInstance().m_reopen_file = true;
393}
394#else
398 return true;
399}
400#endif
401
402#ifndef WIN32
403static void registerSignalHandler(int signal, void (*handler)(int)) {
404 struct sigaction sa;
405 sa.sa_handler = handler;
406 sigemptyset(&sa.sa_mask);
407 sa.sa_flags = 0;
409}
410#endif
411
412static boost::signals2::connection rpc_notify_block_change_connection;
413static void OnRPCStarted() {
414 rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(
415 std::bind(RPCNotifyBlockChange, std::placeholders::_2));
416}
417
418static void OnRPCStopped() {
420 RPCNotifyBlockChange(nullptr);
421 g_best_block_cv.notify_all();
422 LogPrint(BCLog::RPC, "RPC stopped.\n");
423}
424
426 assert(!node.args);
427 node.args = &gArgs;
428 ArgsManager &argsman = *node.args;
429
432 // server-only for now
433 argsman.AddArg("-help-debug",
434 "Print help message with debugging options and exit", false,
436
438
439 const auto defaultBaseParams =
441 const auto testnetBaseParams =
443 const auto regtestBaseParams =
445 const auto defaultChainParams =
447 const auto testnetChainParams =
449 const auto regtestChainParams =
451
452 // Hidden Options
453 std::vector<std::string> hidden_args = {
454 "-dbcrashratio",
455 "-forcecompactdb",
456 "-maxaddrtosend",
457 "-parkdeepreorg",
458 "-automaticunparking",
459 "-replayprotectionactivationtime",
460 "-enableminerfund",
461 "-chronikallowpause",
462 "-chronikcors",
463 // GUI args. These will be overwritten by SetupUIArgs for the GUI
464 "-allowselfsignedrootcertificates",
465 "-choosedatadir",
466 "-lang=<lang>",
467 "-min",
468 "-resetguisettings",
469 "-rootcertificates=<file>",
470 "-splash",
471 "-uiplatform",
472 // TODO remove after the Nov. 2024 upgrade
473 "-augustoactivationtime",
474 };
475
476 // Set all of the args and their help
477 // When adding new options to the categories, please keep and ensure
478 // alphabetical ordering. Do not translate _(...) -help-debug options, Many
479 // technical terms, and only a very small audience, so is unnecessary stress
480 // to translators.
481 argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY,
483#if defined(HAVE_SYSTEM)
484 argsman.AddArg(
485 "-alertnotify=<cmd>",
486 "Execute command when a relevant alert is received or we see "
487 "a really long fork (%s in cmd is replaced by message)",
489#endif
490 argsman.AddArg(
491 "-assumevalid=<hex>",
492 strprintf(
493 "If this block is in the chain assume that it and its ancestors "
494 "are valid and potentially skip their script verification (0 to "
495 "verify all, default: %s, testnet: %s)",
496 defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(),
497 testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()),
499 argsman.AddArg("-blocksdir=<dir>",
500 "Specify directory to hold blocks subdirectory for *.dat "
501 "files (default: <datadir>)",
503 argsman.AddArg("-fastprune",
504 "Use smaller block files and lower minimum prune height for "
505 "testing purposes",
508#if defined(HAVE_SYSTEM)
509 argsman.AddArg("-blocknotify=<cmd>",
510 "Execute command when the best block changes (%s in cmd is "
511 "replaced by block hash)",
513#endif
514 argsman.AddArg("-blockreconstructionextratxn=<n>",
515 strprintf("Extra transactions to keep in memory for compact "
516 "block reconstructions (default: %u)",
519 argsman.AddArg(
520 "-blocksonly",
521 strprintf("Whether to reject transactions from network peers. "
522 "Disables automatic broadcast and rebroadcast of "
523 "transactions, unless the source peer has the "
524 "'forcerelay' permission. RPC transactions are"
525 " not affected. (default: %u)",
528 argsman.AddArg("-coinstatsindex",
529 strprintf("Maintain coinstats index used by the "
530 "gettxoutsetinfo RPC (default: %u)",
533 argsman.AddArg(
534 "-conf=<file>",
535 strprintf("Specify path to read-only configuration file. Relative "
536 "paths will be prefixed by datadir location. (default: %s)",
539 argsman.AddArg("-datadir=<dir>", "Specify data directory",
541 argsman.AddArg(
542 "-dbbatchsize",
543 strprintf("Maximum database write batch size in bytes (default: %u)",
547 argsman.AddArg(
548 "-dbcache=<n>",
549 strprintf("Set database cache size in MiB (%d to %d, default: %d)",
552 argsman.AddArg(
553 "-includeconf=<file>",
554 "Specify additional configuration file, relative to the -datadir path "
555 "(only useable from configuration file, not command line)",
557 argsman.AddArg("-loadblock=<file>",
558 "Imports blocks from external file on startup",
560 argsman.AddArg("-maxmempool=<n>",
561 strprintf("Keep the transaction memory pool below <n> "
562 "megabytes (default: %u)",
565 argsman.AddArg("-maxorphantx=<n>",
566 strprintf("Keep at most <n> unconnectable transactions in "
567 "memory (default: %u)",
570 argsman.AddArg("-mempoolexpiry=<n>",
571 strprintf("Do not keep transactions in the mempool longer "
572 "than <n> hours (default: %u)",
575 argsman.AddArg(
576 "-minimumchainwork=<hex>",
577 strprintf(
578 "Minimum work assumed to exist on a valid chain in hex "
579 "(default: %s, testnet: %s)",
580 defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(),
581 testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()),
584 argsman.AddArg(
585 "-par=<n>",
586 strprintf("Set the number of script verification threads (%u to %d, 0 "
587 "= auto, <0 = leave that many cores free, default: %d)",
591 argsman.AddArg("-persistmempool",
592 strprintf("Whether to save the mempool on shutdown and load "
593 "on restart (default: %u)",
594 DEFAULT_PERSIST_MEMPOOL),
596 argsman.AddArg(
597 "-persistrecentheaderstime",
598 strprintf(
599 "Whether the node stores the recent headers reception time to a "
600 "file and load it upon startup. This is intended for mining nodes "
601 "to overestimate the real time target upon restart (default: %u)",
604 argsman.AddArg(
605 "-pid=<file>",
606 strprintf("Specify pid file. Relative paths will be prefixed "
607 "by a net-specific datadir location. (default: %s)",
610 argsman.AddArg(
611 "-prune=<n>",
612 strprintf("Reduce storage requirements by enabling pruning (deleting) "
613 "of old blocks. This allows the pruneblockchain RPC to be "
614 "called to delete specific blocks, and enables automatic "
615 "pruning of old blocks if a target size in MiB is provided. "
616 "This mode is incompatible with -txindex, -coinstatsindex "
617 "and -rescan. Warning: Reverting this setting requires "
618 "re-downloading the entire blockchain. (default: 0 = disable "
619 "pruning blocks, 1 = allow manual pruning via RPC, >=%u = "
620 "automatically prune block files to stay under the specified "
621 "target size in MiB)",
622 MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024),
624 argsman.AddArg(
625 "-reindex-chainstate",
626 "Rebuild chain state from the currently indexed blocks. When "
627 "in pruning mode or if blocks on disk might be corrupted, use "
628 "full -reindex instead.",
630 argsman.AddArg(
631 "-reindex",
632 "Rebuild chain state and block index from the blk*.dat files on disk",
634 argsman.AddArg(
635 "-settings=<file>",
636 strprintf(
637 "Specify path to dynamic settings data file. Can be disabled with "
638 "-nosettings. File is written at runtime and not meant to be "
639 "edited by users (use %s instead for custom settings). Relative "
640 "paths will be prefixed by datadir location. (default: %s)",
643#if HAVE_SYSTEM
644 argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.",
646#endif
647#ifndef WIN32
648 argsman.AddArg(
649 "-sysperms",
650 "Create new files with system default permissions, instead of umask "
651 "077 (only effective with disabled wallet functionality)",
653#else
654 hidden_args.emplace_back("-sysperms");
655#endif
656 argsman.AddArg("-txindex",
657 strprintf("Maintain a full transaction index, used by the "
658 "getrawtransaction rpc call (default: %d)",
661#if ENABLE_CHRONIK
662 argsman.AddArg(
663 "-chronik",
664 strprintf("Enable the Chronik indexer, which can be read via a "
665 "dedicated HTTP/Protobuf interface (default: %d)",
668 argsman.AddArg(
669 "-chronikbind=<addr>[:port]",
670 strprintf(
671 "Bind the Chronik indexer to the given address to listen for "
672 "HTTP/Protobuf connections to access the index. Unlike the "
673 "JSON-RPC, it's ok to have this publicly exposed on the internet. "
674 "This option can be specified multiple times (default: %s; default "
675 "port: %u, testnet: %u, regtest: %u)",
676 Join(chronik::DEFAULT_BINDS, ", "),
677 defaultBaseParams->ChronikPort(), testnetBaseParams->ChronikPort(),
678 regtestBaseParams->ChronikPort()),
681 argsman.AddArg("-chroniktokenindex",
682 "Enable token indexing in Chronik (default: 1)",
684 argsman.AddArg("-chroniklokadidindex",
685 "Enable LOKAD ID indexing in Chronik (default: 1)",
687 argsman.AddArg("-chronikreindex",
688 "Reindex the Chronik indexer from genesis, but leave the "
689 "other indexes untouched",
691 argsman.AddArg(
692 "-chroniktxnumcachebuckets",
693 strprintf(
694 "Tuning param of the TxNumCache, specifies how many buckets "
695 "to use on the belt. Caution against setting this too high, "
696 "it may slow down indexing. Set to 0 to disable. (default: %d)",
697 chronik::DEFAULT_TX_NUM_CACHE_BUCKETS),
699 argsman.AddArg(
700 "-chroniktxnumcachebucketsize",
701 strprintf(
702 "Tuning param of the TxNumCache, specifies the size of each bucket "
703 "on the belt. Unlike the number of buckets, this may be increased "
704 "without much danger of slowing the indexer down. The total cache "
705 "size will be `num_buckets * bucket_size * 40B`, so by default the "
706 "cache will require %dkB of memory. (default: %d)",
707 chronik::DEFAULT_TX_NUM_CACHE_BUCKETS *
708 chronik::DEFAULT_TX_NUM_CACHE_BUCKET_SIZE * 40 / 1000,
709 chronik::DEFAULT_TX_NUM_CACHE_BUCKET_SIZE),
711 argsman.AddArg("-chronikperfstats",
712 "Output some performance statistics (e.g. num cache hits, "
713 "seconds spent) into a <datadir>/perf folder. (default: 0)",
715 argsman.AddArg(
716 "-chronikscripthashindex",
717 "Enable the scripthash index for the Chronik indexer (default: 0) ",
719 argsman.AddArg(
720 "-chronikelectrumbind=<addr>[:port][:t|s]",
721 strprintf(
722 "Bind the Chronik Electrum interface to the given "
723 "address:port:protocol. If not set, the Electrum interface will "
724 "not start. This option can be specified multiple times. The "
725 "protocol is selected by a single letter, where 't' means TCP and "
726 "'s' means TLS. If TLS is selected, the certificate chain and "
727 "private key must both be passed (see -chronikelectrumcert and "
728 "-chronikelectrumprivkey (default: disabled; default port: %u, "
729 "testnet: %u, regtest: %u; default protocol: TCP)",
730 defaultBaseParams->ChronikElectrumPort(),
731 testnetBaseParams->ChronikElectrumPort(),
732 regtestBaseParams->ChronikElectrumPort()),
735 argsman.AddArg(
736 "-chronikelectrumcert",
737 "Path to the certificate file to be used by the Chronik Electrum "
738 "server when the TLS protocol is selected. The file should contain "
739 "the whole certificate chain (typically a .pem file). If used the "
740 "-chronikelectrumprivkey must be set as well.",
743 argsman.AddArg(
744 "-chronikelectrumprivkey",
745 "Path to the private key file to be used by the Chronik Electrum "
746 "server when the TLS protocol is selected. If used the "
747 "-chronikelectrumcert must be set as well.",
750#endif
751 argsman.AddArg(
752 "-blockfilterindex=<type>",
753 strprintf("Maintain an index of compact filters by block "
754 "(default: %s, values: %s).",
756 " If <type> is not supplied or if <type> = 1, indexes for "
757 "all known types are enabled.",
759 argsman.AddArg(
760 "-usecashaddr",
761 "Use Cash Address for destination encoding instead of base58 "
762 "(activate by default on Jan, 14)",
764
765 argsman.AddArg(
766 "-addnode=<ip>",
767 "Add a node to connect to and attempt to keep the connection "
768 "open (see the `addnode` RPC command help for more info)",
771 argsman.AddArg("-asmap=<file>",
772 strprintf("Specify asn mapping used for bucketing of the "
773 "peers (default: %s). Relative paths will be "
774 "prefixed by the net-specific datadir location.",
777 argsman.AddArg("-bantime=<n>",
778 strprintf("Default duration (in seconds) of manually "
779 "configured bans (default: %u)",
782 argsman.AddArg(
783 "-bind=<addr>[:<port>][=onion]",
784 strprintf("Bind to given address and always listen on it (default: "
785 "0.0.0.0). Use [host]:port notation for IPv6. Append =onion "
786 "to tag any incoming connections to that address and port as "
787 "incoming Tor connections (default: 127.0.0.1:%u=onion, "
788 "testnet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)",
789 defaultBaseParams->OnionServiceTargetPort(),
790 testnetBaseParams->OnionServiceTargetPort(),
791 regtestBaseParams->OnionServiceTargetPort()),
794 argsman.AddArg(
795 "-connect=<ip>",
796 "Connect only to the specified node(s); -connect=0 disables automatic "
797 "connections (the rules for this peer are the same as for -addnode)",
800 argsman.AddArg(
801 "-discover",
802 "Discover own IP addresses (default: 1 when listening and no "
803 "-externalip or -proxy)",
805 argsman.AddArg("-dns",
806 strprintf("Allow DNS lookups for -addnode, -seednode and "
807 "-connect (default: %d)",
810 argsman.AddArg(
811 "-dnsseed",
812 strprintf(
813 "Query for peer addresses via DNS lookup, if low on addresses "
814 "(default: %u unless -connect used)",
817 argsman.AddArg("-externalip=<ip>", "Specify your own public address",
819 argsman.AddArg(
820 "-fixedseeds",
821 strprintf(
822 "Allow fixed seeds if DNS seeds don't provide peers (default: %u)",
825 argsman.AddArg(
826 "-forcednsseed",
827 strprintf(
828 "Always query for peer addresses via DNS lookup (default: %d)",
831 argsman.AddArg("-overridednsseed",
832 "If set, only use the specified DNS seed when "
833 "querying for peer addresses via DNS lookup.",
835 argsman.AddArg(
836 "-listen",
837 "Accept connections from outside (default: 1 if no -proxy or -connect)",
839 argsman.AddArg(
840 "-listenonion",
841 strprintf("Automatically create Tor onion service (default: %d)",
844 argsman.AddArg(
845 "-maxconnections=<n>",
846 strprintf("Maintain at most <n> connections to peers. The effective "
847 "limit depends on system limitations and might be lower than "
848 "the specified value (default: %u)",
851 argsman.AddArg("-maxreceivebuffer=<n>",
852 strprintf("Maximum per-connection receive buffer, <n>*1000 "
853 "bytes (default: %u)",
856 argsman.AddArg(
857 "-maxsendbuffer=<n>",
858 strprintf(
859 "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)",
862 argsman.AddArg(
863 "-maxtimeadjustment",
864 strprintf("Maximum allowed median peer time offset adjustment. Local "
865 "perspective of time may be influenced by peers forward or "
866 "backward by this amount. (default: %u seconds)",
869 argsman.AddArg("-onion=<ip:port>",
870 strprintf("Use separate SOCKS5 proxy to reach peers via Tor "
871 "onion services (default: %s)",
872 "-proxy"),
874 argsman.AddArg("-i2psam=<ip:port>",
875 "I2P SAM proxy to reach I2P peers and accept I2P "
876 "connections (default: none)",
878 argsman.AddArg(
879 "-i2pacceptincoming",
880 "If set and -i2psam is also set then incoming I2P connections are "
881 "accepted via the SAM proxy. If this is not set but -i2psam is set "
882 "then only outgoing connections will be made to the I2P network. "
883 "Ignored if -i2psam is not set. Listening for incoming I2P connections "
884 "is done through the SAM proxy, not by binding to a local address and "
885 "port (default: 1)",
887
888 argsman.AddArg(
889 "-onlynet=<net>",
890 "Make outgoing connections only through network <net> (" +
891 Join(GetNetworkNames(), ", ") +
892 "). Incoming connections are not affected by this option. This "
893 "option can be specified multiple times to allow multiple "
894 "networks. Warning: if it is used with non-onion networks "
895 "and the -onion or -proxy option is set, then outbound onion "
896 "connections will still be made; use -noonion or -onion=0 to "
897 "disable outbound onion connections in this case",
899 argsman.AddArg("-peerbloomfilters",
900 strprintf("Support filtering of blocks and transaction with "
901 "bloom filters (default: %d)",
904 argsman.AddArg(
905 "-peerblockfilters",
906 strprintf(
907 "Serve compact block filters to peers per BIP 157 (default: %u)",
910 argsman.AddArg("-permitbaremultisig",
911 strprintf("Relay non-P2SH multisig (default: %d)",
914 // TODO: remove the sentence "Nodes not using ... incoming connections."
915 // once the changes from https://github.com/bitcoin/bitcoin/pull/23542 have
916 // become widespread.
917 argsman.AddArg("-port=<port>",
918 strprintf("Listen for connections on <port>. Nodes not "
919 "using the default ports (default: %u, "
920 "testnet: %u, regtest: %u) are unlikely to get "
921 "incoming connections. Not relevant for I2P (see "
922 "doc/i2p.md).",
923 defaultChainParams->GetDefaultPort(),
924 testnetChainParams->GetDefaultPort(),
925 regtestChainParams->GetDefaultPort()),
928 argsman.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy",
930 argsman.AddArg(
931 "-proxyrandomize",
932 strprintf("Randomize credentials for every proxy connection. "
933 "This enables Tor stream isolation (default: %d)",
936 argsman.AddArg(
937 "-seednode=<ip>",
938 "Connect to a node to retrieve peer addresses, and disconnect",
940 argsman.AddArg(
941 "-networkactive",
942 "Enable all P2P network activity (default: 1). Can be changed "
943 "by the setnetworkactive RPC command",
945 argsman.AddArg("-timeout=<n>",
946 strprintf("Specify connection timeout in milliseconds "
947 "(minimum: 1, default: %d)",
950 argsman.AddArg(
951 "-peertimeout=<n>",
952 strprintf("Specify p2p connection timeout in seconds. This option "
953 "determines the amount of time a peer may be inactive before "
954 "the connection to it is dropped. (minimum: 1, default: %d)",
957 argsman.AddArg(
958 "-torcontrol=<ip>:<port>",
959 strprintf(
960 "Tor control port to use if onion listening enabled (default: %s)",
963 argsman.AddArg("-torpassword=<pass>",
964 "Tor control port password (default: empty)",
967#ifdef USE_UPNP
968#if USE_UPNP
969 argsman.AddArg("-upnp",
970 "Use UPnP to map the listening port (default: 1 when "
971 "listening and no -proxy)",
973#else
974 argsman.AddArg(
975 "-upnp",
976 strprintf("Use UPnP to map the listening port (default: %u)", 0),
978#endif
979#else
980 hidden_args.emplace_back("-upnp");
981#endif
982#ifdef USE_NATPMP
983 argsman.AddArg(
984 "-natpmp",
985 strprintf("Use NAT-PMP to map the listening port (default: %s)",
986 DEFAULT_NATPMP ? "1 when listening and no -proxy" : "0"),
988#else
989 hidden_args.emplace_back("-natpmp");
990#endif // USE_NATPMP
991 argsman.AddArg(
992 "-whitebind=<[permissions@]addr>",
993 "Bind to the given address and add permission flags to the peers "
994 "connecting to it."
995 "Use [host]:port notation for IPv6. Allowed permissions: " +
997 ". "
998 "Specify multiple permissions separated by commas (default: "
999 "download,noban,mempool,relay). Can be specified multiple times.",
1001
1002 argsman.AddArg("-whitelist=<[permissions@]IP address or network>",
1003 "Add permission flags to the peers using the given "
1004 "IP address (e.g. 1.2.3.4) or CIDR-notated network "
1005 "(e.g. 1.2.3.0/24). "
1006 "Uses the same permissions as -whitebind. "
1007 "Additional flags \"in\" and \"out\" control whether "
1008 "permissions apply to incoming connections and/or manual "
1009 "(default: incoming only). "
1010 "Can be specified multiple times.",
1012 argsman.AddArg(
1013 "-maxuploadtarget=<n>",
1014 strprintf("Tries to keep outbound traffic under the given target (in "
1015 "MiB per 24h). Limit does not apply to peers with 'download' "
1016 "permission. 0 = no limit (default: %d)",
1019
1021
1022#if ENABLE_ZMQ
1023 argsman.AddArg("-zmqpubhashblock=<address>",
1024 "Enable publish hash block in <address>",
1026 argsman.AddArg("-zmqpubhashtx=<address>",
1027 "Enable publish hash transaction in <address>",
1029 argsman.AddArg("-zmqpubrawblock=<address>",
1030 "Enable publish raw block in <address>",
1032 argsman.AddArg("-zmqpubrawtx=<address>",
1033 "Enable publish raw transaction in <address>",
1035 argsman.AddArg("-zmqpubsequence=<address>",
1036 "Enable publish hash block and tx sequence in <address>",
1038 argsman.AddArg(
1039 "-zmqpubhashblockhwm=<n>",
1040 strprintf("Set publish hash block outbound message high water "
1041 "mark (default: %d)",
1044 argsman.AddArg(
1045 "-zmqpubhashtxhwm=<n>",
1046 strprintf("Set publish hash transaction outbound message high "
1047 "water mark (default: %d)",
1049 false, OptionsCategory::ZMQ);
1050 argsman.AddArg(
1051 "-zmqpubrawblockhwm=<n>",
1052 strprintf("Set publish raw block outbound message high water "
1053 "mark (default: %d)",
1056 argsman.AddArg(
1057 "-zmqpubrawtxhwm=<n>",
1058 strprintf("Set publish raw transaction outbound message high "
1059 "water mark (default: %d)",
1062 argsman.AddArg("-zmqpubsequencehwm=<n>",
1063 strprintf("Set publish hash sequence message high water mark"
1064 " (default: %d)",
1067#else
1068 hidden_args.emplace_back("-zmqpubhashblock=<address>");
1069 hidden_args.emplace_back("-zmqpubhashtx=<address>");
1070 hidden_args.emplace_back("-zmqpubrawblock=<address>");
1071 hidden_args.emplace_back("-zmqpubrawtx=<address>");
1072 hidden_args.emplace_back("-zmqpubsequence=<n>");
1073 hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
1074 hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
1075 hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
1076 hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
1077 hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
1078#endif
1079
1080 argsman.AddArg(
1081 "-checkblocks=<n>",
1082 strprintf("How many blocks to check at startup (default: %u, 0 = all)",
1086 argsman.AddArg("-checklevel=<n>",
1087 strprintf("How thorough the block verification of "
1088 "-checkblocks is: %s (0-4, default: %u)",
1092 argsman.AddArg("-checkblockindex",
1093 strprintf("Do a consistency check for the block tree, "
1094 "chainstate, and other validation data structures "
1095 "occasionally. (default: %u, regtest: %u)",
1096 defaultChainParams->DefaultConsistencyChecks(),
1097 regtestChainParams->DefaultConsistencyChecks()),
1100 argsman.AddArg("-checkaddrman=<n>",
1101 strprintf("Run addrman consistency checks every <n> "
1102 "operations. Use 0 to disable. (default: %u)",
1106 argsman.AddArg(
1107 "-checkmempool=<n>",
1108 strprintf("Run mempool consistency checks every <n> transactions. Use "
1109 "0 to disable. (default: %u, regtest: %u)",
1110 defaultChainParams->DefaultConsistencyChecks(),
1111 regtestChainParams->DefaultConsistencyChecks()),
1114 argsman.AddArg("-checkpoints",
1115 strprintf("Only accept block chain matching built-in "
1116 "checkpoints (default: %d)",
1120 argsman.AddArg("-deprecatedrpc=<method>",
1121 "Allows deprecated RPC method(s) to be used",
1124 argsman.AddArg(
1125 "-stopafterblockimport",
1126 strprintf("Stop running after importing blocks from disk (default: %d)",
1127 DEFAULT_STOPAFTERBLOCKIMPORT),
1130 argsman.AddArg("-stopatheight",
1131 strprintf("Stop running after reaching the given height in "
1132 "the main chain (default: %u)",
1136 argsman.AddArg("-addrmantest", "Allows to test address relay on localhost",
1139 argsman.AddArg("-capturemessages", "Capture all P2P messages to disk",
1142 argsman.AddArg("-mocktime=<n>",
1143 "Replace actual time with " + UNIX_EPOCH_TIME +
1144 " (default: 0)",
1147 argsman.AddArg(
1148 "-maxsigcachesize=<n>",
1149 strprintf("Limit size of signature cache to <n> MiB (default: %u)",
1153 argsman.AddArg(
1154 "-maxscriptcachesize=<n>",
1155 strprintf("Limit size of script cache to <n> MiB (default: %u)",
1159 argsman.AddArg("-maxtipage=<n>",
1160 strprintf("Maximum tip age in seconds to consider node in "
1161 "initial block download (default: %u)",
1165
1166 argsman.AddArg("-uacomment=<cmt>",
1167 "Append comment to the user agent string",
1169 argsman.AddArg("-uaclientname=<clientname>", "Set user agent client name",
1171 argsman.AddArg("-uaclientversion=<clientversion>",
1172 "Set user agent client version", ArgsManager::ALLOW_ANY,
1174
1176
1177 argsman.AddArg(
1178 "-acceptnonstdtxn",
1179 strprintf(
1180 "Relay and mine \"non-standard\" transactions (%sdefault: %u)",
1181 "testnet/regtest only; ", defaultChainParams->RequireStandard()),
1184 argsman.AddArg("-excessiveblocksize=<n>",
1185 strprintf("Do not accept blocks larger than this limit, in "
1186 "bytes (default: %d)",
1190 const auto &ticker = Currency::get().ticker;
1191 argsman.AddArg(
1192 "-dustrelayfee=<amt>",
1193 strprintf("Fee rate (in %s/kB) used to define dust, the value of an "
1194 "output such that it will cost about 1/3 of its value in "
1195 "fees at this fee rate to spend it. (default: %s)",
1199
1200 argsman.AddArg(
1201 "-bytespersigcheck",
1202 strprintf("Equivalent bytes per sigCheck in transactions for relay and "
1203 "mining (default: %u).",
1206 argsman.AddArg(
1207 "-bytespersigop",
1208 strprintf("DEPRECATED: Equivalent bytes per sigCheck in transactions "
1209 "for relay and mining (default: %u). This has been "
1210 "deprecated since v0.26.8 and will be removed in the future, "
1211 "please use -bytespersigcheck instead.",
1214 argsman.AddArg(
1215 "-datacarrier",
1216 strprintf("Relay and mine data carrier transactions (default: %d)",
1219 argsman.AddArg(
1220 "-datacarriersize",
1221 strprintf("Maximum size of data in data carrier transactions "
1222 "we relay and mine (default: %u)",
1225 argsman.AddArg(
1226 "-minrelaytxfee=<amt>",
1227 strprintf("Fees (in %s/kB) smaller than this are rejected for "
1228 "relaying, mining and transaction creation (default: %s)",
1231 argsman.AddArg(
1232 "-whitelistrelay",
1233 strprintf("Add 'relay' permission to whitelisted peers "
1234 "with default permissions. This will accept relayed "
1235 "transactions even when not relaying transactions "
1236 "(default: %d)",
1239 argsman.AddArg(
1240 "-whitelistforcerelay",
1241 strprintf("Add 'forcerelay' permission to whitelisted peers "
1242 "with default permissions. This will relay transactions "
1243 "even if the transactions were already in the mempool "
1244 "(default: %d)",
1247
1248 argsman.AddArg("-blockmaxsize=<n>",
1249 strprintf("Set maximum block size in bytes (default: %d)",
1252 argsman.AddArg(
1253 "-blockmintxfee=<amt>",
1254 strprintf("Set lowest fee rate (in %s/kB) for transactions to "
1255 "be included in block creation. (default: %s)",
1258
1259 argsman.AddArg("-blockversion=<n>",
1260 "Override block version to test forking scenarios",
1263
1264 argsman.AddArg("-server", "Accept command line and JSON-RPC commands",
1266 argsman.AddArg("-rest",
1267 strprintf("Accept public REST requests (default: %d)",
1270 argsman.AddArg(
1271 "-rpcbind=<addr>[:port]",
1272 "Bind to given address to listen for JSON-RPC connections. Do not "
1273 "expose the RPC server to untrusted networks such as the public "
1274 "internet! This option is ignored unless -rpcallowip is also passed. "
1275 "Port is optional and overrides -rpcport. Use [host]:port notation "
1276 "for IPv6. This option can be specified multiple times (default: "
1277 "127.0.0.1 and ::1 i.e., localhost)",
1281 argsman.AddArg(
1282 "-rpcdoccheck",
1283 strprintf("Throw a non-fatal error at runtime if the documentation for "
1284 "an RPC is incorrect (default: %u)",
1287 argsman.AddArg(
1288 "-rpccookiefile=<loc>",
1289 "Location of the auth cookie. Relative paths will be prefixed "
1290 "by a net-specific datadir location. (default: data dir)",
1292 argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections",
1295 argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections",
1298 argsman.AddArg(
1299 "-rpcwhitelist=<whitelist>",
1300 "Set a whitelist to filter incoming RPC calls for a specific user. The "
1301 "field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc "
1302 "2>,...,<rpc n>. If multiple whitelists are set for a given user, they "
1303 "are set-intersected. See -rpcwhitelistdefault documentation for "
1304 "information on default whitelist behavior.",
1306 argsman.AddArg(
1307 "-rpcwhitelistdefault",
1308 "Sets default behavior for rpc whitelisting. Unless "
1309 "rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc "
1310 "server acts as if all rpc users are subject to "
1311 "empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault "
1312 "is set to 1 and no -rpcwhitelist is set, rpc server acts as if all "
1313 "rpc users are subject to empty whitelists.",
1315 argsman.AddArg(
1316 "-rpcauth=<userpw>",
1317 "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. "
1318 "The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A "
1319 "canonical python script is included in share/rpcauth. The client then "
1320 "connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> "
1321 "pair of arguments. This option can be specified multiple times",
1323 argsman.AddArg("-rpcport=<port>",
1324 strprintf("Listen for JSON-RPC connections on <port> "
1325 "(default: %u, testnet: %u, regtest: %u)",
1326 defaultBaseParams->RPCPort(),
1327 testnetBaseParams->RPCPort(),
1328 regtestBaseParams->RPCPort()),
1331 argsman.AddArg(
1332 "-rpcallowip=<ip>",
1333 "Allow JSON-RPC connections from specified source. Valid for "
1334 "<ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. "
1335 "1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). "
1336 "This option can be specified multiple times",
1338 argsman.AddArg(
1339 "-rpcthreads=<n>",
1340 strprintf(
1341 "Set the number of threads to service RPC calls (default: %d)",
1344 argsman.AddArg(
1345 "-rpccorsdomain=value",
1346 "Domain from which to accept cross origin requests (browser enforced)",
1348
1349 argsman.AddArg("-rpcworkqueue=<n>",
1350 strprintf("Set the depth of the work queue to service RPC "
1351 "calls (default: %d)",
1355 argsman.AddArg("-rpcservertimeout=<n>",
1356 strprintf("Timeout during HTTP requests (default: %d)",
1360
1361#if HAVE_DECL_FORK
1362 argsman.AddArg("-daemon",
1363 strprintf("Run in the background as a daemon and accept "
1364 "commands (default: %d)",
1367 argsman.AddArg("-daemonwait",
1368 strprintf("Wait for initialization to be finished before "
1369 "exiting. This implies -daemon (default: %d)",
1372#else
1373 hidden_args.emplace_back("-daemon");
1374 hidden_args.emplace_back("-daemonwait");
1375#endif
1376
1377 // Avalanche options.
1378 argsman.AddArg("-avalanche",
1379 strprintf("Enable the avalanche feature (default: %u)",
1382 argsman.AddArg(
1383 "-avalanchestakingrewards",
1384 strprintf("Enable the avalanche staking rewards feature (default: %u, "
1385 "testnet: %u, regtest: %u)",
1386 defaultChainParams->GetConsensus().enableStakingRewards,
1387 testnetChainParams->GetConsensus().enableStakingRewards,
1388 regtestChainParams->GetConsensus().enableStakingRewards),
1390 argsman.AddArg("-avalancheconflictingproofcooldown",
1391 strprintf("Mandatory cooldown before a proof conflicting "
1392 "with an already registered one can be considered "
1393 "in seconds (default: %u)",
1396 argsman.AddArg("-avalanchepeerreplacementcooldown",
1397 strprintf("Mandatory cooldown before a peer can be replaced "
1398 "in seconds (default: %u)",
1401 argsman.AddArg(
1402 "-avaminquorumstake",
1403 strprintf(
1404 "Minimum amount of known stake for a usable quorum (default: %s)",
1407 argsman.AddArg(
1408 "-avaminquorumconnectedstakeratio",
1409 strprintf("Minimum proportion of known stake we"
1410 " need nodes for to have a usable quorum (default: %s). "
1411 "This parameter is parsed with a maximum precision of "
1412 "0.000001.",
1415 argsman.AddArg(
1416 "-avaminavaproofsnodecount",
1417 strprintf("Minimum number of node that needs to send us an avaproofs"
1418 " message before we consider we have a usable quorum"
1419 " (default: %s)",
1422 argsman.AddArg(
1423 "-avastalevotethreshold",
1424 strprintf("Number of avalanche votes before a voted item goes stale "
1425 "when voting confidence is low (default: %u)",
1428 argsman.AddArg(
1429 "-avastalevotefactor",
1430 strprintf(
1431 "Factor affecting the number of avalanche votes before a voted "
1432 "item goes stale when voting confidence is high (default: %u)",
1435 argsman.AddArg("-avacooldown",
1436 strprintf("Mandatory cooldown between two avapoll in "
1437 "milliseconds (default: %u)",
1440 argsman.AddArg(
1441 "-avatimeout",
1442 strprintf("Avalanche query timeout in milliseconds (default: %u)",
1445 argsman.AddArg(
1446 "-avadelegation",
1447 "Avalanche proof delegation to the master key used by this node "
1448 "(default: none). Should be used in conjunction with -avaproof and "
1449 "-avamasterkey",
1451 argsman.AddArg("-avaproof",
1452 "Avalanche proof to be used by this node (default: none)",
1454 argsman.AddArg(
1455 "-avaproofstakeutxoconfirmations",
1456 strprintf(
1457 "Minimum number of confirmations before a stake utxo is mature"
1458 " enough to be included into a proof. Utxos in the mempool are not "
1459 "accepted (i.e this value must be greater than 0) (default: %s)",
1462 argsman.AddArg("-avaproofstakeutxodustthreshold",
1463 strprintf("Minimum value each stake utxo must have to be "
1464 "considered valid (default: %s)",
1467 argsman.AddArg("-avamasterkey",
1468 "Master key associated with the proof. If a proof is "
1469 "required, this is mandatory.",
1472 argsman.AddArg("-avasessionkey", "Avalanche session key (default: random)",
1475 argsman.AddArg("-enablertt",
1476 strprintf("Whether to enforce Real Time Targeting via "
1477 "Avalanche, default (%u)",
1480 argsman.AddArg(
1481 "-maxavalancheoutbound",
1482 strprintf(
1483 "Set the maximum number of avalanche outbound peers to connect to. "
1484 "Note that this option takes precedence over the -maxconnections "
1485 "option (default: %u).",
1488 argsman.AddArg(
1489 "-persistavapeers",
1490 strprintf("Whether to save the avalanche peers upon shutdown and load "
1491 "them upon startup (default: %u).",
1494
1495 hidden_args.emplace_back("-avalanchepreconsensus");
1496 hidden_args.emplace_back("-avalanchestakingpreconsensus");
1497
1498 // Add the hidden options
1499 argsman.AddHiddenArgs(hidden_args);
1500}
1501
1502static bool fHaveGenesis = false;
1504static std::condition_variable g_genesis_wait_cv;
1505
1507 if (pBlockIndex != nullptr) {
1508 {
1510 fHaveGenesis = true;
1511 }
1512 g_genesis_wait_cv.notify_all();
1513 }
1514}
1515
1516#if HAVE_SYSTEM
1517static void StartupNotify(const ArgsManager &args) {
1518 std::string cmd = args.GetArg("-startupnotify", "");
1519 if (!cmd.empty()) {
1520 std::thread t(runCommand, cmd);
1521 // thread runs free
1522 t.detach();
1523 }
1524}
1525#endif
1526
1527static bool AppInitServers(Config &config,
1529 NodeContext &node) {
1530 const ArgsManager &args = *Assert(node.args);
1533 if (!InitHTTPServer(config)) {
1534 return false;
1535 }
1536
1537 StartRPC();
1538 node.rpc_interruption_point = RpcInterruptionPoint;
1539
1541 return false;
1542 }
1543 if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) {
1544 StartREST(&node);
1545 }
1546
1548 return true;
1549}
1550
1551// Parameter interaction based on rules
1553 // when specifying an explicit binding address, you want to listen on it
1554 // even when -connect or -proxy is specified.
1555 if (args.IsArgSet("-bind")) {
1556 if (args.SoftSetBoolArg("-listen", true)) {
1557 LogPrintf(
1558 "%s: parameter interaction: -bind set -> setting -listen=1\n",
1559 __func__);
1560 }
1561 }
1562 if (args.IsArgSet("-whitebind")) {
1563 if (args.SoftSetBoolArg("-listen", true)) {
1564 LogPrintf("%s: parameter interaction: -whitebind set -> setting "
1565 "-listen=1\n",
1566 __func__);
1567 }
1568 }
1569
1570 if (args.IsArgSet("-connect")) {
1571 // when only connecting to trusted nodes, do not seed via DNS, or listen
1572 // by default.
1573 if (args.SoftSetBoolArg("-dnsseed", false)) {
1574 LogPrintf("%s: parameter interaction: -connect set -> setting "
1575 "-dnsseed=0\n",
1576 __func__);
1577 }
1578 if (args.SoftSetBoolArg("-listen", false)) {
1579 LogPrintf("%s: parameter interaction: -connect set -> setting "
1580 "-listen=0\n",
1581 __func__);
1582 }
1583 }
1584
1585 if (args.IsArgSet("-proxy")) {
1586 // to protect privacy, do not listen by default if a default proxy
1587 // server is specified.
1588 if (args.SoftSetBoolArg("-listen", false)) {
1589 LogPrintf(
1590 "%s: parameter interaction: -proxy set -> setting -listen=0\n",
1591 __func__);
1592 }
1593 // to protect privacy, do not map ports when a proxy is set. The user
1594 // may still specify -listen=1 to listen locally, so don't rely on this
1595 // happening through -listen below.
1596 if (args.SoftSetBoolArg("-upnp", false)) {
1597 LogPrintf(
1598 "%s: parameter interaction: -proxy set -> setting -upnp=0\n",
1599 __func__);
1600 }
1601 if (args.SoftSetBoolArg("-natpmp", false)) {
1602 LogPrintf(
1603 "%s: parameter interaction: -proxy set -> setting -natpmp=0\n",
1604 __func__);
1605 }
1606 // to protect privacy, do not discover addresses by default
1607 if (args.SoftSetBoolArg("-discover", false)) {
1608 LogPrintf("%s: parameter interaction: -proxy set -> setting "
1609 "-discover=0\n",
1610 __func__);
1611 }
1612 }
1613
1614 if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1615 // do not map ports or try to retrieve public IP when not listening
1616 // (pointless)
1617 if (args.SoftSetBoolArg("-upnp", false)) {
1618 LogPrintf(
1619 "%s: parameter interaction: -listen=0 -> setting -upnp=0\n",
1620 __func__);
1621 }
1622 if (args.SoftSetBoolArg("-natpmp", false)) {
1623 LogPrintf(
1624 "%s: parameter interaction: -listen=0 -> setting -natpmp=0\n",
1625 __func__);
1626 }
1627 if (args.SoftSetBoolArg("-discover", false)) {
1628 LogPrintf(
1629 "%s: parameter interaction: -listen=0 -> setting -discover=0\n",
1630 __func__);
1631 }
1632 if (args.SoftSetBoolArg("-listenonion", false)) {
1633 LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1634 "-listenonion=0\n",
1635 __func__);
1636 }
1637 if (args.SoftSetBoolArg("-i2pacceptincoming", false)) {
1638 LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1639 "-i2pacceptincoming=0\n",
1640 __func__);
1641 }
1642 }
1643
1644 if (args.IsArgSet("-externalip")) {
1645 // if an explicit public IP is specified, do not try to find others
1646 if (args.SoftSetBoolArg("-discover", false)) {
1647 LogPrintf("%s: parameter interaction: -externalip set -> setting "
1648 "-discover=0\n",
1649 __func__);
1650 }
1651 }
1652
1653 // disable whitelistrelay in blocksonly mode
1654 if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
1655 if (args.SoftSetBoolArg("-whitelistrelay", false)) {
1656 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting "
1657 "-whitelistrelay=0\n",
1658 __func__);
1659 }
1660 }
1661
1662 // Forcing relay from whitelisted hosts implies we will accept relays from
1663 // them in the first place.
1664 if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
1665 if (args.SoftSetBoolArg("-whitelistrelay", true)) {
1666 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> "
1667 "setting -whitelistrelay=1\n",
1668 __func__);
1669 }
1670 }
1671
1672 // If avalanche is set, soft set all the feature flags accordingly.
1673 if (args.IsArgSet("-avalanche")) {
1674 const bool fAvalanche =
1675 args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1676 args.SoftSetBoolArg("-automaticunparking", !fAvalanche);
1677 }
1678}
1679
1686void InitLogging(const ArgsManager &args) {
1689}
1690
1691namespace { // Variables internal to initialization process only
1692
1693int nMaxConnections;
1695int nFD;
1698std::set<BlockFilterType> g_enabled_filter_types;
1699
1700} // namespace
1701
1703 // Rather than throwing std::bad-alloc if allocation fails, terminate
1704 // immediately to (try to) avoid chain corruption. Since LogPrintf may
1705 // itself allocate memory, set the handler directly to terminate first.
1706 std::set_new_handler(std::terminate);
1707 LogPrintf("Error: Out of memory. Terminating.\n");
1708
1709 // The log was successful, terminate now.
1710 std::terminate();
1711};
1712
1714// Step 1: setup
1715#ifdef _MSC_VER
1716 // Turn off Microsoft heap dump noise
1719 OPEN_EXISTING, 0, 0));
1720 // Disable confusing "helpful" text message on abort, Ctrl-C
1722#endif
1723#ifdef WIN32
1724 // Enable Data Execution Prevention (DEP)
1726#endif
1727 if (!InitShutdownState()) {
1728 return InitError(
1729 Untranslated("Initializing wait-for-shutdown state failed."));
1730 }
1731
1732 if (!SetupNetworking()) {
1733 return InitError(Untranslated("Initializing networking failed"));
1734 }
1735
1736#ifndef WIN32
1737 if (!args.GetBoolArg("-sysperms", false)) {
1738 umask(077);
1739 }
1740
1741 // Clean shutdown on SIGTERM
1744
1745 // Reopen debug.log on SIGHUP
1747
1748 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client
1749 // closes unexpectedly
1751#else
1753#endif
1754
1755 std::set_new_handler(new_handler_terminate);
1756
1757 return true;
1758}
1759
1761 const CChainParams &chainparams = config.GetChainParams();
1762 // Step 2: parameter interactions
1763
1764 // also see: InitParameterInteraction()
1765
1766 // Error if network-specific options (-addnode, -connect, etc) are
1767 // specified in default section of config file, but not overridden
1768 // on the command line or in this network's section of the config file.
1769 std::string network = args.GetChainName();
1771 for (const auto &arg : args.GetUnsuitableSectionOnlyArgs()) {
1772 errors += strprintf(_("Config setting for %s only applied on %s "
1773 "network when in [%s] section.") +
1774 Untranslated("\n"),
1775 arg, network, network);
1776 }
1777
1778 if (!errors.empty()) {
1779 return InitError(errors);
1780 }
1781
1782 // Warn if unrecognized section name are present in the config file.
1784 for (const auto &section : args.GetUnrecognizedSections()) {
1785 warnings += strprintf(Untranslated("%s:%i ") +
1786 _("Section [%s] is not recognized.") +
1787 Untranslated("\n"),
1788 section.m_file, section.m_line, section.m_name);
1789 }
1790
1791 if (!warnings.empty()) {
1793 }
1794
1795 if (!fs::is_directory(args.GetBlocksDirPath())) {
1796 return InitError(
1797 strprintf(_("Specified blocks directory \"%s\" does not exist."),
1798 args.GetArg("-blocksdir", "")));
1799 }
1800
1801 // parse and validate enabled filter types
1802 std::string blockfilterindex_value =
1803 args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
1804 if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
1806 } else if (blockfilterindex_value != "0") {
1807 const std::vector<std::string> names =
1808 args.GetArgs("-blockfilterindex");
1809 for (const auto &name : names) {
1812 return InitError(
1813 strprintf(_("Unknown -blockfilterindex value %s."), name));
1814 }
1816 }
1817 }
1818
1819 // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index
1820 // are both enabled.
1821 if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
1823 return InitError(
1824 _("Cannot set -peerblockfilters without -blockfilterindex."));
1825 }
1826
1827 nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS);
1828 }
1829
1830 if (args.GetIntArg("-prune", 0)) {
1831 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1832 return InitError(_("Prune mode is incompatible with -txindex."));
1833 }
1834 if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
1835 return InitError(
1836 _("Prune mode is incompatible with -coinstatsindex."));
1837 }
1838 if (args.GetBoolArg("-reindex-chainstate", false)) {
1839 return InitError(
1840 _("Prune mode is incompatible with -reindex-chainstate. Use "
1841 "full -reindex instead."));
1842 }
1843 if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
1844 return InitError(_("Prune mode is incompatible with -chronik."));
1845 }
1846 }
1847
1848 // -bind and -whitebind can't be set when not listening
1849 size_t nUserBind =
1850 args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
1851 if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1852 return InitError(Untranslated(
1853 "Cannot set -bind or -whitebind together with -listen=0"));
1854 }
1855
1856 // Make sure enough file descriptors are available
1857 int nBind = std::max(nUserBind, size_t(1));
1859 args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1860 nMaxConnections = std::max(nUserMaxConnections, 0);
1861
1862 // -maxavalancheoutbound takes precedence over -maxconnections
1863 const int maxAvalancheOutbound = args.GetIntArg(
1864 "-maxavalancheoutbound", DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS);
1865 const bool fAvalanche =
1866 args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1867 if (fAvalanche && maxAvalancheOutbound > nMaxConnections) {
1868 nMaxConnections = std::max(maxAvalancheOutbound, nMaxConnections);
1869 // Indicate the value set by the user
1870 LogPrintf("Increasing -maxconnections from %d to %d to comply with "
1871 "-maxavalancheoutbound\n",
1872 nUserMaxConnections, nMaxConnections);
1873 }
1874
1875 // Trim requested connection counts, to fit into system limitations
1876 // <int> in std::min<int>(...) to work around FreeBSD compilation issue
1877 // described in #2695
1879 nMaxConnections + nBind + MIN_CORE_FILEDESCRIPTORS +
1881#ifdef USE_POLL
1882 int fd_max = nFD;
1883#else
1884 int fd_max = FD_SETSIZE;
1885#endif
1886 nMaxConnections = std::max(
1887 std::min<int>(nMaxConnections,
1890 0);
1892 return InitError(_("Not enough file descriptors available."));
1893 }
1894 nMaxConnections =
1896 nMaxConnections);
1897
1898 if (nMaxConnections < nUserMaxConnections) {
1899 // Not categorizing as "Warning" because this is the normal behavior for
1900 // platforms using the select() interface for which FD_SETSIZE is
1901 // usually 1024.
1902 LogPrintf("Reducing -maxconnections from %d to %d, because of system "
1903 "limitations.\n",
1904 nUserMaxConnections, nMaxConnections);
1905 }
1906
1907 // Step 3: parameter-to-internal-flags
1909
1910 // Configure excessive block size.
1912 args.GetIntArg("-excessiveblocksize", DEFAULT_MAX_BLOCK_SIZE);
1913 if (nProposedExcessiveBlockSize <= 0 ||
1915 return InitError(
1916 _("Excessive block size must be > 1,000,000 bytes (1MB)"));
1917 }
1918
1919 // Check blockmaxsize does not exceed maximum accepted block size.
1921 args.GetIntArg("-blockmaxsize", DEFAULT_MAX_GENERATED_BLOCK_SIZE);
1923 return InitError(_("Max generated block size must be greater than 0"));
1924 }
1926 return InitError(_("Max generated block size (blockmaxsize) cannot "
1927 "exceed the excessive block size "
1928 "(excessiveblocksize)"));
1929 }
1930
1932 if (nConnectTimeout <= 0) {
1934 }
1935
1937 args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
1938 if (peer_connect_timeout <= 0) {
1939 return InitError(Untranslated(
1940 "peertimeout cannot be configured with a negative value."));
1941 }
1942
1943 // Sanity check argument for min fee for including tx in block
1944 // TODO: Harmonize which arguments need sanity checking and where that
1945 // happens.
1946 if (args.IsArgSet("-blockmintxfee")) {
1947 Amount n = Amount::zero();
1948 if (!ParseMoney(args.GetArg("-blockmintxfee", ""), n)) {
1949 return InitError(AmountErrMsg("blockmintxfee",
1950 args.GetArg("-blockmintxfee", "")));
1951 }
1952 }
1953
1955 args.IsArgSet("-bytespersigcheck")
1956 ? args.GetIntArg("-bytespersigcheck", nBytesPerSigCheck)
1957 : args.GetIntArg("-bytespersigop", nBytesPerSigCheck);
1958
1960 return false;
1961 }
1962
1963 // Option to startup with mocktime set (used for regression testing):
1964 SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1965
1966 if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) {
1967 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1968 }
1969
1970 if (args.IsArgSet("-proxy") && args.GetArg("-proxy", "").empty()) {
1971 return InitError(_(
1972 "No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
1973 }
1974
1975 // Avalanche parameters
1977 args.GetIntArg("-avaproofstakeutxoconfirmations",
1979
1980 if (!chainparams.IsTestChain() &&
1983 return InitError(_("Avalanche stake UTXO minimum confirmations can "
1984 "only be set on test chains."));
1985 }
1986
1987 if (stakeUtxoMinConfirmations <= 0) {
1988 return InitError(_("Avalanche stake UTXO minimum confirmations must be "
1989 "a positive integer."));
1990 }
1991
1992 if (args.IsArgSet("-avaproofstakeutxodustthreshold")) {
1993 Amount amount = Amount::zero();
1994 auto parsed = ParseMoney(
1995 args.GetArg("-avaproofstakeutxodustthreshold", ""), amount);
1996 if (!parsed || Amount::zero() == amount) {
1997 return InitError(AmountErrMsg(
1998 "avaproofstakeutxodustthreshold",
1999 args.GetArg("-avaproofstakeutxodustthreshold", "")));
2000 }
2001
2002 if (!chainparams.IsTestChain() &&
2004 return InitError(_("Avalanche stake UTXO dust threshold can "
2005 "only be set on test chains."));
2006 }
2007 }
2008
2009 // This is a staking node
2010 if (fAvalanche && args.IsArgSet("-avaproof")) {
2011 if (!args.GetBoolArg("-listen", true)) {
2012 return InitError(_("Running a staking node requires accepting "
2013 "inbound connections. Please enable -listen."));
2014 }
2015 if (args.IsArgSet("-proxy")) {
2016 return InitError(_("Running a staking node behind a proxy is not "
2017 "supported. Please disable -proxy."));
2018 }
2019 if (args.IsArgSet("-i2psam")) {
2020 return InitError(_("Running a staking node behind I2P is not "
2021 "supported. Please disable -i2psam."));
2022 }
2023 if (args.IsArgSet("-onlynet")) {
2024 return InitError(
2025 _("Restricting the outbound network is not supported when "
2026 "running a staking node. Please disable -onlynet."));
2027 }
2028 }
2029
2030 // Also report errors from parsing before daemonization
2031 {
2032 KernelNotifications notifications{};
2034 .config = config,
2035 .datadir = args.GetDataDirNet(),
2036 .notifications = notifications,
2037 };
2038 if (const auto error{ApplyArgsManOptions(args, chainman_opts_dummy)}) {
2039 return InitError(*error);
2040 }
2042 .chainparams = chainman_opts_dummy.config.GetChainParams(),
2043 .blocks_dir = args.GetBlocksDirPath(),
2044 };
2045 if (const auto error{ApplyArgsManOptions(args, blockman_opts_dummy)}) {
2046 return InitError(*error);
2047 }
2048 }
2049
2050 return true;
2051}
2052
2053static bool LockDataDirectory(bool probeOnly) {
2054 // Make sure only a single Bitcoin process is using the data directory.
2055 fs::path datadir = gArgs.GetDataDirNet();
2056 if (!DirIsWritable(datadir)) {
2057 return InitError(strprintf(
2058 _("Cannot write to data directory '%s'; check permissions."),
2059 fs::PathToString(datadir)));
2060 }
2061 if (!LockDirectory(datadir, ".lock", probeOnly)) {
2062 return InitError(strprintf(_("Cannot obtain a lock on data directory "
2063 "%s. %s is probably already running."),
2064 fs::PathToString(datadir), PACKAGE_NAME));
2065 }
2066 return true;
2067}
2068
2070 // Step 4: sanity checks
2071
2073
2074 // Sanity check
2075 if (!init::SanityChecks()) {
2076 return InitError(strprintf(
2077 _("Initialization sanity check failed. %s is shutting down."),
2078 PACKAGE_NAME));
2079 }
2080
2081 // Probe the data directory lock to give an early error message, if possible
2082 // We cannot hold the data directory lock here, as the forking for daemon()
2083 // hasn't yet happened, and a fork will cause weird behavior to it.
2084 return LockDataDirectory(true);
2085}
2086
2088 // After daemonization get the data directory lock again and hold on to it
2089 // until exit. This creates a slight window for a race condition to happen,
2090 // however this condition is harmless: it will at most make us exit without
2091 // printing a message to console.
2092 if (!LockDataDirectory(false)) {
2093 // Detailed error printed inside LockDataDirectory
2094 return false;
2095 }
2096 return true;
2097}
2098
2101 // Create client interfaces for wallets that are supposed to be loaded
2102 // according to -wallet and -disablewallet options. This only constructs
2103 // the interfaces, it doesn't load wallet data. Wallets actually get loaded
2104 // when load() and start() interface methods are called below.
2106 return true;
2107}
2108
2109bool AppInitMain(Config &config, RPCServer &rpcServer,
2113 // Step 4a: application initialization
2114 const ArgsManager &args = *Assert(node.args);
2115 const CChainParams &chainparams = config.GetChainParams();
2116
2117 if (!CreatePidFile(args)) {
2118 // Detailed error printed inside CreatePidFile().
2119 return false;
2120 }
2121 if (!init::StartLogging(args)) {
2122 // Detailed error printed inside StartLogging().
2123 return false;
2124 }
2125
2126 LogPrintf("Using at most %i automatic connections (%i file descriptors "
2127 "available)\n",
2128 nMaxConnections, nFD);
2129
2130 // Warn about relative -datadir path.
2131 if (args.IsArgSet("-datadir") &&
2132 !args.GetPathArg("-datadir").is_absolute()) {
2133 LogPrintf("Warning: relative datadir option '%s' specified, which will "
2134 "be interpreted relative to the current working directory "
2135 "'%s'. This is fragile, because if bitcoin is started in the "
2136 "future from a different location, it will be unable to "
2137 "locate the current data files. There could also be data "
2138 "loss if bitcoin is started while in a temporary "
2139 "directory.\n",
2140 args.GetArg("-datadir", ""),
2141 fs::PathToString(fs::current_path()));
2142 }
2143
2146
2147 if (!InitSignatureCache(validation_cache_sizes.signature_cache_bytes)) {
2148 return InitError(strprintf(
2149 _("Unable to allocate memory for -maxsigcachesize: '%s' MiB"),
2150 args.GetIntArg("-maxsigcachesize",
2152 }
2154 validation_cache_sizes.script_execution_cache_bytes)) {
2155 return InitError(strprintf(
2156 _("Unable to allocate memory for -maxscriptcachesize: '%s' MiB"),
2157 args.GetIntArg("-maxscriptcachesize",
2159 }
2160
2162 if (script_threads <= 0) {
2163 // -par=0 means autodetect (number of cores - 1 script threads)
2164 // -par=-n means "leave n cores free" (number of cores - n - 1 script
2165 // threads)
2167 }
2168
2169 // Subtract 1 because the main thread counts towards the par threads
2170 script_threads = std::max(script_threads - 1, 0);
2171
2172 // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
2174
2175 LogPrintf("Script verification uses %d additional threads\n",
2177 if (script_threads >= 1) {
2179 }
2180
2181 assert(!node.scheduler);
2182 node.scheduler = std::make_unique<CScheduler>();
2183
2184 // Start the lightweight task scheduler thread
2185 node.scheduler->m_service_thread =
2186 std::thread(&util::TraceThread, "scheduler",
2187 [&] { node.scheduler->serviceQueue(); });
2188
2189 // Gather some entropy once per minute.
2190 node.scheduler->scheduleEvery(
2191 [] {
2193 return true;
2194 },
2195 std::chrono::minutes{1});
2196
2198
2203 RegisterAllRPCCommands(config, rpcServer, tableRPC);
2204 for (const auto &client : node.chain_clients) {
2205 client->registerRpcs();
2206 }
2207#if ENABLE_ZMQ
2209#endif
2210
2217 if (args.GetBoolArg("-server", false)) {
2218 uiInterface.InitMessage_connect(SetRPCWarmupStatus);
2220 return InitError(
2221 _("Unable to start HTTP server. See debug log for details."));
2222 }
2223 }
2224
2225 // Step 5: verify wallet database integrity
2226 for (const auto &client : node.chain_clients) {
2227 if (!client->verify()) {
2228 return false;
2229 }
2230 }
2231
2232 // Step 6: network initialization
2233
2234 // Note that we absolutely cannot open any actual connections
2235 // until the very end ("start node") as the UTXO/block state
2236 // is not yet setup and may end up being set up twice if we
2237 // need to reindex later.
2238
2239 fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
2240 fDiscover = args.GetBoolArg("-discover", true);
2241
2242 {
2243 // Initialize addrman
2244 assert(!node.addrman);
2245
2246 // Read asmap file if configured
2247 std::vector<bool> asmap;
2248 if (args.IsArgSet("-asmap")) {
2250 args.GetPathArg("-asmap", DEFAULT_ASMAP_FILENAME);
2251 if (!asmap_path.is_absolute()) {
2253 }
2254 if (!fs::exists(asmap_path)) {
2255 InitError(strprintf(_("Could not find asmap file %s"),
2257 return false;
2258 }
2260 if (asmap.size() == 0) {
2261 InitError(strprintf(_("Could not parse asmap file %s"),
2263 return false;
2264 }
2265 const uint256 asmap_version = (HashWriter{} << asmap).GetHash();
2266 LogPrintf("Using asmap version %s for IP bucketing\n",
2267 asmap_version.ToString());
2268 } else {
2269 LogPrintf("Using /16 prefix for IP bucketing\n");
2270 }
2271
2272 uiInterface.InitMessage(_("Loading P2P addresses...").translated);
2273 auto addrman{LoadAddrman(chainparams, asmap, args)};
2274 if (!addrman) {
2275 return InitError(util::ErrorString(addrman));
2276 }
2277 node.addrman = std::move(*addrman);
2278 }
2279
2280 assert(!node.banman);
2281 node.banman = std::make_unique<BanMan>(
2282 args.GetDataDirNet() / "banlist.dat", config.GetChainParams(),
2284 assert(!node.connman);
2285 node.connman = std::make_unique<CConnman>(
2286 config, GetRand<uint64_t>(), GetRand<uint64_t>(), *node.addrman,
2287 args.GetBoolArg("-networkactive", true));
2288
2289 // sanitize comments per BIP-0014, format user agent and check total size
2290 std::vector<std::string> uacomments;
2291 for (const std::string &cmt : args.GetArgs("-uacomment")) {
2293 return InitError(strprintf(
2294 _("User Agent comment (%s) contains unsafe characters."), cmt));
2295 }
2296 uacomments.push_back(cmt);
2297 }
2298 const std::string client_name = args.GetArg("-uaclientname", CLIENT_NAME);
2299 const std::string client_version =
2300 args.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
2302 return InitError(strprintf(
2303 _("-uaclientname (%s) contains invalid characters."), client_name));
2304 }
2305 if (client_version !=
2307 return InitError(
2308 strprintf(_("-uaclientversion (%s) contains invalid characters."),
2310 }
2311 const std::string strSubVersion =
2313 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
2314 return InitError(strprintf(
2315 _("Total length of network version string (%i) exceeds maximum "
2316 "length (%i). Reduce the number or size of uacomments."),
2318 }
2319
2320 if (args.IsArgSet("-onlynet")) {
2321 std::set<enum Network> nets;
2322 for (const std::string &snet : args.GetArgs("-onlynet")) {
2323 enum Network net = ParseNetwork(snet);
2324 if (net == NET_UNROUTABLE) {
2325 return InitError(strprintf(
2326 _("Unknown network specified in -onlynet: '%s'"), snet));
2327 }
2328 nets.insert(net);
2329 }
2330 for (int n = 0; n < NET_MAX; n++) {
2331 enum Network net = (enum Network)n;
2332 if (!nets.count(net)) {
2333 SetReachable(net, false);
2334 }
2335 }
2336 }
2337
2338 // Check for host lookup allowed before parsing any network related
2339 // parameters
2341
2342 bool proxyRandomize =
2343 args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
2344 // -proxy sets a proxy for all outgoing network traffic
2345 // -noproxy (or -proxy=0) as well as the empty string can be used to not set
2346 // a proxy, this is the default
2347 std::string proxyArg = args.GetArg("-proxy", "");
2348 SetReachable(NET_ONION, false);
2349 if (proxyArg != "" && proxyArg != "0") {
2351 if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) {
2352 return InitError(strprintf(
2353 _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2354 }
2355
2357 if (!addrProxy.IsValid()) {
2358 return InitError(strprintf(
2359 _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2360 }
2361
2366 // by default, -proxy sets onion as reachable, unless -noonion later
2367 SetReachable(NET_ONION, true);
2368 }
2369
2370 // -onion can be used to set only a proxy for .onion, or override normal
2371 // proxy for .onion addresses.
2372 // -noonion (or -onion=0) disables connecting to .onion entirely. An empty
2373 // string is used to not override the onion proxy (in which case it defaults
2374 // to -proxy set above, or none)
2375 std::string onionArg = args.GetArg("-onion", "");
2376 if (onionArg != "") {
2377 if (onionArg == "0") {
2378 // Handle -noonion/-onion=0
2379 SetReachable(NET_ONION, false);
2380 } else {
2382 if (!Lookup(onionArg, onionProxy, 9050, fNameLookup)) {
2383 return InitError(strprintf(
2384 _("Invalid -onion address or hostname: '%s'"), onionArg));
2385 }
2387 if (!addrOnion.IsValid()) {
2388 return InitError(strprintf(
2389 _("Invalid -onion address or hostname: '%s'"), onionArg));
2390 }
2392 SetReachable(NET_ONION, true);
2393 }
2394 }
2395
2396 for (const std::string &strAddr : args.GetArgs("-externalip")) {
2397 CService addrLocal;
2398 if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) &&
2399 addrLocal.IsValid()) {
2400 AddLocal(addrLocal, LOCAL_MANUAL);
2401 } else {
2402 return InitError(ResolveErrMsg("externalip", strAddr));
2403 }
2404 }
2405
2406#if ENABLE_ZMQ
2408 [&chainman = node.chainman](CBlock &block, const CBlockIndex &index) {
2409 assert(chainman);
2410 return chainman->m_blockman.ReadBlockFromDisk(block, index);
2411 });
2412
2415 }
2416#endif
2417
2418 // Step 7: load block chain
2419
2420 node.notifications = std::make_unique<KernelNotifications>();
2421 fReindex = args.GetBoolArg("-reindex", false);
2422 bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
2423
2425 .config = config,
2426 .datadir = args.GetDataDirNet(),
2427 .adjusted_time_callback = GetAdjustedTime,
2428 .notifications = *node.notifications,
2429 };
2430 // no error can happen, already checked in AppInitParameterInteraction
2432
2433 if (chainman_opts.checkpoints_enabled) {
2434 LogPrintf("Checkpoints will be verified.\n");
2435 } else {
2436 LogPrintf("Skipping checkpoint verification.\n");
2437 }
2438
2440 .chainparams = chainman_opts.config.GetChainParams(),
2441 .blocks_dir = args.GetBlocksDirPath(),
2442 };
2443 // no error can happen, already checked in AppInitParameterInteraction
2445
2446 // cache size calculations
2448 CalculateCacheSizes(args, g_enabled_filter_types.size());
2449
2450 LogPrintf("Cache configuration:\n");
2451 LogPrintf("* Using %.1f MiB for block index database\n",
2452 cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
2453 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2454 LogPrintf("* Using %.1f MiB for transaction index database\n",
2455 cache_sizes.tx_index * (1.0 / 1024 / 1024));
2456 }
2458 LogPrintf("* Using %.1f MiB for %s block filter index database\n",
2459 cache_sizes.filter_index * (1.0 / 1024 / 1024),
2461 }
2462 LogPrintf("* Using %.1f MiB for chain state database\n",
2463 cache_sizes.coins_db * (1.0 / 1024 / 1024));
2464
2465 assert(!node.mempool);
2466 assert(!node.chainman);
2467
2469 .check_ratio = chainparams.DefaultConsistencyChecks() ? 1 : 0,
2470 };
2471 if (const auto err{ApplyArgsManOptions(args, chainparams, mempool_opts)}) {
2472 return InitError(*err);
2473 }
2474 mempool_opts.check_ratio =
2475 std::clamp<int>(mempool_opts.check_ratio, 0, 1'000'000);
2476
2477 // FIXME: this legacy limit comes from the DEFAULT_DESCENDANT_SIZE_LIMIT
2478 // (101) that was enforced before the wellington activation. While it's
2479 // still a good idea to have some minimum mempool size, using this value as
2480 // a threshold is no longer relevant.
2481 int64_t nMempoolSizeMin = 101 * 1000 * 40;
2482 if (mempool_opts.max_size_bytes < 0 ||
2483 (!chainparams.IsTestChain() &&
2484 mempool_opts.max_size_bytes < nMempoolSizeMin)) {
2485 return InitError(strprintf(_("-maxmempool must be at least %d MB"),
2486 std::ceil(nMempoolSizeMin / 1000000.0)));
2487 }
2488 LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of "
2489 "unused mempool space)\n",
2490 cache_sizes.coins * (1.0 / 1024 / 1024),
2491 mempool_opts.max_size_bytes * (1.0 / 1024 / 1024));
2492
2493 for (bool fLoaded = false; !fLoaded && !ShutdownRequested();) {
2494 node.mempool = std::make_unique<CTxMemPool>(mempool_opts);
2495
2496 node.chainman =
2497 std::make_unique<ChainstateManager>(chainman_opts, blockman_opts);
2498 ChainstateManager &chainman = *node.chainman;
2499
2501 options.mempool = Assert(node.mempool.get());
2502 options.reindex = node::fReindex;
2504 options.prune = chainman.m_blockman.IsPruneMode();
2505 options.check_blocks =
2506 args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
2507 options.check_level = args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL);
2509 args.IsArgSet("-checkblocks") || args.IsArgSet("-checklevel");
2511 options.coins_error_cb = [] {
2512 uiInterface.ThreadSafeMessageBox(
2513 _("Error reading from database, shutting down."), "",
2515 };
2516
2517 uiInterface.InitMessage(_("Loading block index...").translated);
2518
2520 auto catch_exceptions = [](auto &&f) {
2521 try {
2522 return f();
2523 } catch (const std::exception &e) {
2524 LogPrintf("%s\n", e.what());
2525 return std::make_tuple(node::ChainstateLoadStatus::FAILURE,
2526 _("Error opening block database"));
2527 }
2528 };
2529 auto [status, error] = catch_exceptions(
2530 [&] { return LoadChainstate(chainman, cache_sizes, options); });
2532 uiInterface.InitMessage(_("Verifying blocks...").translated);
2533 if (chainman.m_blockman.m_have_pruned &&
2534 options.check_blocks > MIN_BLOCKS_TO_KEEP) {
2536 "pruned datadir may not have more than %d "
2537 "blocks; only checking available blocks\n",
2539 }
2540 std::tie(status, error) = catch_exceptions(
2541 [&] { return VerifyLoadedChainstate(chainman, options); });
2543 WITH_LOCK(cs_main, return node.chainman->LoadRecentHeadersTime(
2544 node.chainman->m_options.datadir /
2546 fLoaded = true;
2547 LogPrintf(" block index %15dms\n",
2549 }
2550 }
2551
2554 status ==
2556 return InitError(error);
2557 }
2558
2559 if (!fLoaded && !ShutdownRequested()) {
2560 // first suggest a reindex
2561 if (!options.reindex) {
2562 bool fRet = uiInterface.ThreadSafeQuestion(
2563 error + Untranslated(".\n\n") +
2564 _("Do you want to rebuild the block database now?"),
2565 error.original + ".\nPlease restart with -reindex or "
2566 "-reindex-chainstate to recover.",
2567 "",
2570 if (fRet) {
2571 fReindex = true;
2572 AbortShutdown();
2573 } else {
2574 LogPrintf("Aborted block database rebuild. Exiting.\n");
2575 return false;
2576 }
2577 } else {
2578 return InitError(error);
2579 }
2580 }
2581 }
2582
2583 // As LoadBlockIndex can take several minutes, it's possible the user
2584 // requested to kill the GUI during the last operation. If so, exit.
2585 // As the program has not fully started yet, Shutdown() is possibly
2586 // overkill.
2587 if (ShutdownRequested()) {
2588 LogPrintf("Shutdown requested. Exiting.\n");
2589 return false;
2590 }
2591
2592 ChainstateManager &chainman = *Assert(node.chainman);
2593
2594 if (args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED)) {
2595 // Initialize Avalanche.
2598 args, *node.chain, node.connman.get(), chainman, node.mempool.get(),
2599 *node.scheduler, avalancheError);
2600 if (!node.avalanche) {
2602 return false;
2603 }
2604
2605 if (node.avalanche->isAvalancheServiceAvailable()) {
2606 nLocalServices = ServiceFlags(nLocalServices | NODE_AVALANCHE);
2607 }
2608 }
2609
2612
2613 assert(!node.peerman);
2614 node.peerman = PeerManager::make(*node.connman, *node.addrman,
2615 node.banman.get(), chainman, *node.mempool,
2616 node.avalanche.get(), peerman_opts);
2617 RegisterValidationInterface(node.peerman.get());
2618
2619 // Encoded addresses using cashaddr instead of base58.
2620 // We do this by default to avoid confusion with BTC addresses.
2621 config.SetCashAddrEncoding(args.GetBoolArg("-usecashaddr", true));
2622
2623 // Step 8: load indexers
2624 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2625 auto result{
2627 chainman.m_blockman.m_block_tree_db)))};
2628 if (!result) {
2629 return InitError(util::ErrorString(result));
2630 }
2631
2632 g_txindex =
2633 std::make_unique<TxIndex>(cache_sizes.tx_index, false, fReindex);
2634 if (!g_txindex->Start(chainman.ActiveChainstate())) {
2635 return false;
2636 }
2637 }
2638
2639 for (const auto &filter_type : g_enabled_filter_types) {
2640 InitBlockFilterIndex(filter_type, cache_sizes.filter_index, false,
2641 fReindex);
2643 ->Start(chainman.ActiveChainstate())) {
2644 return false;
2645 }
2646 }
2647
2648 if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
2649 g_coin_stats_index = std::make_unique<CoinStatsIndex>(
2650 /* cache size */ 0, false, fReindex);
2651 if (!g_coin_stats_index->Start(chainman.ActiveChainstate())) {
2652 return false;
2653 }
2654 }
2655
2656#if ENABLE_CHRONIK
2657 if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
2658 const bool fReindexChronik =
2659 fReindex || args.GetBoolArg("-chronikreindex", false);
2660 if (!chronik::Start(args, config, node, fReindexChronik)) {
2661 return false;
2662 }
2663 }
2664#endif
2665
2666 // Step 9: load wallet
2667 for (const auto &client : node.chain_clients) {
2668 if (!client->load()) {
2669 return false;
2670 }
2671 }
2672
2673 // Step 10: data directory maintenance
2674
2675 // if pruning, unset the service bit and perform the initial blockstore
2676 // prune after any wallet rescanning has taken place.
2677 if (chainman.m_blockman.IsPruneMode()) {
2678 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
2679 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
2680 if (!fReindex) {
2681 LOCK(cs_main);
2682 for (Chainstate *chainstate : chainman.GetAll()) {
2683 uiInterface.InitMessage(_("Pruning blockstore...").translated);
2684 chainstate->PruneAndFlush();
2685 }
2686 }
2687 }
2688
2689 // Step 11: import blocks
2690 if (!CheckDiskSpace(args.GetDataDirNet())) {
2691 InitError(
2692 strprintf(_("Error: Disk space is low for %s"),
2694 return false;
2695 }
2696 if (!CheckDiskSpace(args.GetBlocksDirPath())) {
2697 InitError(
2698 strprintf(_("Error: Disk space is low for %s"),
2700 return false;
2701 }
2702
2703 // Either install a handler to notify us when genesis activates, or set
2704 // fHaveGenesis directly.
2705 // No locking, as this happens before any background thread is started.
2706 boost::signals2::connection block_notify_genesis_wait_connection;
2707 if (WITH_LOCK(chainman.GetMutex(),
2708 return chainman.ActiveChain().Tip() == nullptr)) {
2710 uiInterface.NotifyBlockTip_connect(
2711 std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
2712 } else {
2713 fHaveGenesis = true;
2714 }
2715
2716#if defined(HAVE_SYSTEM)
2717 const std::string block_notify = args.GetArg("-blocknotify", "");
2718 if (!block_notify.empty()) {
2719 uiInterface.NotifyBlockTip_connect([block_notify](
2721 const CBlockIndex *pBlockIndex) {
2723 return;
2724 }
2725 std::string command = block_notify;
2726 ReplaceAll(command, "%s", pBlockIndex->GetBlockHash().GetHex());
2727 std::thread t(runCommand, command);
2728 // thread runs free
2729 t.detach();
2730 });
2731 }
2732#endif
2733
2734 std::vector<fs::path> vImportFiles;
2735 for (const std::string &strFile : args.GetArgs("-loadblock")) {
2736 vImportFiles.push_back(fs::PathFromString(strFile));
2737 }
2738
2739 avalanche::Processor *const avalanche = node.avalanche.get();
2740 chainman.m_load_block =
2741 std::thread(&util::TraceThread, "loadblk", [=, &chainman, &args] {
2742 ThreadImport(chainman, avalanche, vImportFiles,
2743 ShouldPersistMempool(args) ? MempoolPath(args)
2744 : fs::path{});
2745 });
2746
2747 // Wait for genesis block to be processed
2748 {
2750 // We previously could hang here if StartShutdown() is called prior to
2751 // ThreadImport getting started, so instead we just wait on a timer to
2752 // check ShutdownRequested() regularly.
2753 while (!fHaveGenesis && !ShutdownRequested()) {
2754 g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
2755 }
2757 }
2758
2759 if (ShutdownRequested()) {
2760 return false;
2761 }
2762
2763 // Step 12: start node
2764
2766
2768 {
2769 LOCK(cs_main);
2770 LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
2771 chain_active_height = chainman.ActiveChain().Height();
2772 if (tip_info) {
2773 tip_info->block_height = chain_active_height;
2774 tip_info->block_time =
2775 chainman.ActiveChain().Tip()
2776 ? chainman.ActiveChain().Tip()->GetBlockTime()
2777 : chainman.GetParams().GenesisBlock().GetBlockTime();
2778 tip_info->verification_progress = GuessVerificationProgress(
2779 chainman.GetParams().TxData(), chainman.ActiveChain().Tip());
2780 }
2781 if (tip_info && chainman.m_best_header) {
2782 tip_info->header_height = chainman.m_best_header->nHeight;
2783 tip_info->header_time = chainman.m_best_header->GetBlockTime();
2784 }
2785 }
2786 LogPrintf("nBestHeight = %d\n", chain_active_height);
2787 if (node.peerman) {
2788 node.peerman->SetBestHeight(chain_active_height);
2789 }
2790
2791 // Map ports with UPnP or NAT-PMP.
2792 StartMapPort(args.GetBoolArg("-upnp", DEFAULT_UPNP),
2793 args.GetBoolArg("-natpmp", DEFAULT_NATPMP));
2794
2796 connOptions.nLocalServices = nLocalServices;
2797 connOptions.nMaxConnections = nMaxConnections;
2798 connOptions.m_max_avalanche_outbound =
2799 node.avalanche
2800 ? args.GetIntArg("-maxavalancheoutbound",
2802 : 0;
2803 connOptions.m_max_outbound_full_relay = std::min(
2805 connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound);
2806 connOptions.m_max_outbound_block_relay = std::min(
2808 connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound -
2809 connOptions.m_max_outbound_full_relay);
2812 connOptions.uiInterface = &uiInterface;
2813 connOptions.m_banman = node.banman.get();
2814 connOptions.m_msgproc.push_back(node.peerman.get());
2815 if (node.avalanche) {
2816 connOptions.m_msgproc.push_back(node.avalanche.get());
2817 }
2818 connOptions.nSendBufferMaxSize =
2819 1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
2820 connOptions.nReceiveFloodSize =
2821 1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
2822 connOptions.m_added_nodes = args.GetArgs("-addnode");
2823
2824 connOptions.nMaxOutboundLimit =
2825 1024 * 1024 *
2826 args.GetIntArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
2827 connOptions.m_peer_connect_timeout = peer_connect_timeout;
2828 connOptions.whitelist_forcerelay =
2829 args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY);
2830 connOptions.whitelist_relay =
2831 args.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY);
2832
2833 // Port to bind to if `-bind=addr` is provided without a `:port` suffix.
2834 const uint16_t default_bind_port = static_cast<uint16_t>(
2835 args.GetIntArg("-port", config.GetChainParams().GetDefaultPort()));
2836
2837 const auto BadPortWarning = [](const char *prefix, uint16_t port) {
2838 return strprintf(_("%s request to listen on port %u. This port is "
2839 "considered \"bad\" and "
2840 "thus it is unlikely that any Bitcoin ABC peers "
2841 "connect to it. See "
2842 "doc/p2p-bad-ports.md for details and a full list."),
2843 prefix, port);
2844 };
2845
2846 for (const std::string &bind_arg : args.GetArgs("-bind")) {
2848 const size_t index = bind_arg.rfind('=');
2849 if (index == std::string::npos) {
2851 /*fAllowLookup=*/false)) {
2852 connOptions.vBinds.push_back(bind_addr);
2853 if (IsBadPort(bind_addr.GetPort())) {
2854 InitWarning(BadPortWarning("-bind", bind_addr.GetPort()));
2855 }
2856 continue;
2857 }
2858 } else {
2859 const std::string network_type = bind_arg.substr(index + 1);
2860 if (network_type == "onion") {
2861 const std::string truncated_bind_arg =
2862 bind_arg.substr(0, index);
2864 BaseParams().OnionServiceTargetPort(), false)) {
2865 connOptions.onion_binds.push_back(bind_addr);
2866 continue;
2867 }
2868 }
2869 }
2870 return InitError(ResolveErrMsg("bind", bind_arg));
2871 }
2872
2873 for (const std::string &strBind : args.GetArgs("-whitebind")) {
2877 return InitError(error);
2878 }
2879 connOptions.vWhiteBinds.push_back(whitebind);
2880 }
2881
2882 // If the user did not specify -bind= or -whitebind= then we bind
2883 // on any address - 0.0.0.0 (IPv4) and :: (IPv6).
2884 connOptions.bind_on_any =
2885 args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
2886
2887 // Emit a warning if a bad port is given to -port= but only if -bind and
2888 // -whitebind are not given, because if they are, then -port= is ignored.
2889 if (connOptions.bind_on_any && args.IsArgSet("-port")) {
2890 const uint16_t port_arg = args.GetIntArg("-port", 0);
2891 if (IsBadPort(port_arg)) {
2893 }
2894 }
2895
2897 if (!connOptions.onion_binds.empty()) {
2898 onion_service_target = connOptions.onion_binds.front();
2899 } else {
2901 connOptions.onion_binds.push_back(onion_service_target);
2902 }
2903
2904 if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
2905 if (connOptions.onion_binds.size() > 1) {
2907 _("More than one onion bind address is provided. Using %s "
2908 "for the automatically created Tor onion service."),
2909 onion_service_target.ToStringIPPort()));
2910 }
2912 }
2913
2914 if (connOptions.bind_on_any) {
2915 // Only add all IP addresses of the machine if we would be listening on
2916 // any address - 0.0.0.0 (IPv4) and :: (IPv6).
2917 Discover();
2918 }
2919
2920 for (const auto &net : args.GetArgs("-whitelist")) {
2926 return InitError(error);
2927 }
2929 connOptions.vWhitelistedRangeIncoming.push_back(subnet);
2930 }
2932 connOptions.vWhitelistedRangeOutgoing.push_back(subnet);
2933 }
2934 }
2935
2936 connOptions.vSeedNodes = args.GetArgs("-seednode");
2937
2938 // Initiate outbound connections unless connect=0
2939 connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect");
2940 if (!connOptions.m_use_addrman_outgoing) {
2941 const auto connect = args.GetArgs("-connect");
2942 if (connect.size() != 1 || connect[0] != "0") {
2943 connOptions.m_specified_outgoing = connect;
2944 }
2945 }
2946
2947 const std::string &i2psam_arg = args.GetArg("-i2psam", "");
2948 if (!i2psam_arg.empty()) {
2949 CService addr;
2950 if (!Lookup(i2psam_arg, addr, 7656, fNameLookup) || !addr.IsValid()) {
2951 return InitError(strprintf(
2952 _("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
2953 }
2954 SetReachable(NET_I2P, true);
2955 SetProxy(NET_I2P, proxyType{addr});
2956 } else {
2957 SetReachable(NET_I2P, false);
2958 }
2959
2960 connOptions.m_i2p_accept_incoming =
2961 args.GetBoolArg("-i2pacceptincoming", true);
2962
2963 if (!node.connman->Start(*node.scheduler, connOptions)) {
2964 return false;
2965 }
2966
2967 // Step 13: finished
2968
2969 // At this point, the RPC is "started", but still in warmup, which means it
2970 // cannot yet be called. Before we make it callable, we need to make sure
2971 // that the RPC's view of the best block is valid and consistent with
2972 // ChainstateManager's active tip.
2973 //
2974 // If we do not do this, RPC's view of the best block will be height=0 and
2975 // hash=0x0. This will lead to erroroneous responses for things like
2976 // waitforblockheight.
2978 WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip()));
2980
2981 uiInterface.InitMessage(_("Done loading").translated);
2982
2983 for (const auto &client : node.chain_clients) {
2984 client->start(*node.scheduler);
2985 }
2986
2987 BanMan *banman = node.banman.get();
2988 node.scheduler->scheduleEvery(
2989 [banman] {
2990 banman->DumpBanlist();
2991 return true;
2992 },
2994
2995 // Start Avalanche's event loop.
2996 if (node.avalanche) {
2997 node.avalanche->startEventLoop(*node.scheduler);
2998 }
2999
3000 if (node.peerman) {
3001 node.peerman->StartScheduledTasks(*node.scheduler);
3002 }
3003
3004#if HAVE_SYSTEM
3005 StartupNotify(args);
3006#endif
3007
3008 return true;
3009}
util::Result< std::unique_ptr< AddrMan > > LoadAddrman(const CChainParams &chainparams, const std::vector< bool > &asmap, const ArgsManager &args)
Returns an error string on failure.
Definition addrdb.cpp:164
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS
Default for -checkaddrman.
Definition addrman.h:28
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition args.cpp:737
const char *const BITCOIN_SETTINGS_FILENAME
Definition args.cpp:36
ArgsManager gArgs
Definition args.cpp:38
const char *const BITCOIN_CONF_FILENAME
Definition args.cpp:35
fs::path AbsPathForConfigVal(const ArgsManager &args, const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
std::vector< bool > DecodeAsmap(fs::path path)
Read asmap from provided binary file.
Definition asmap.cpp:294
static constexpr bool DEFAULT_PERSIST_AVAPEERS
Default for -persistavapeers.
Definition avalanche.h:63
static constexpr double AVALANCHE_DEFAULT_MIN_QUORUM_CONNECTED_STAKE_RATIO
Default minimum percentage of stake-weighted peers we must have a node for to constitute a usable quo...
Definition avalanche.h:53
static constexpr size_t AVALANCHE_DEFAULT_PEER_REPLACEMENT_COOLDOWN
Peer replacement cooldown time default value in seconds.
Definition avalanche.h:34
static constexpr double AVALANCHE_DEFAULT_MIN_AVAPROOFS_NODE_COUNT
Default minimum number of nodes that sent us an avaproofs message before we can consider our quorum s...
Definition avalanche.h:60
static constexpr Amount AVALANCHE_DEFAULT_MIN_QUORUM_STAKE
Default minimum cumulative stake of all known peers that constitutes a usable quorum.
Definition avalanche.h:46
static constexpr size_t AVALANCHE_DEFAULT_CONFLICTING_PROOF_COOLDOWN
Conflicting proofs cooldown time default value in seconds.
Definition avalanche.h:28
static constexpr bool AVALANCHE_DEFAULT_ENABLED
Is avalanche enabled by default.
Definition avalanche.h:22
static constexpr size_t AVALANCHE_DEFAULT_COOLDOWN
Avalanche default cooldown in milliseconds.
Definition avalanche.h:40
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition banman.h:20
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
Definition banman.h:22
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
const std::set< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
BlockFilterType
Definition blockfilter.h:88
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
bool InitBlockFilterIndex(BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe)
Initialize a block filter index for the given type if one does not already exist.
static const char *const DEFAULT_BLOCKFILTERINDEX
std::unique_ptr< const CChainParams > CreateChainParams(const ArgsManager &args, const std::string &chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
const CChainParams & Params()
Return the currently selected parameters.
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
static constexpr bool DEFAULT_CHECKPOINTS_ENABLED
static constexpr auto DEFAULT_MAX_TIP_AGE
static constexpr bool DEFAULT_STORE_RECENT_HEADERS_TIME
#define Assert(val)
Identity function.
Definition check.h:84
const std::set< std::string > GetUnsuitableSectionOnlyArgs() const
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition args.cpp:133
@ NETWORK_ONLY
Definition args.h:110
@ ALLOW_ANY
Definition args.h:103
@ DEBUG_ONLY
Definition args.h:104
@ ALLOW_INT
Definition args.h:101
@ ALLOW_BOOL
Definition args.h:100
@ ALLOW_STRING
Definition args.h:102
@ SENSITIVE
Definition args.h:112
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition args.cpp:371
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition args.h:215
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition args.cpp:381
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition args.cpp:526
fs::path GetBlocksDirPath() const
Get blocks directory path.
Definition args.cpp:289
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition args.cpp:494
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition args.cpp:589
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition args.cpp:556
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition args.cpp:275
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition args.cpp:157
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition args.cpp:793
std::atomic< bool > m_reopen_file
Definition logging.h:120
void DumpBanlist()
Definition banman.cpp:49
void Stop()
Stops the instance from staying in sync with blockchain updates.
Definition base.cpp:392
bool BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(void Interrupt()
Blocks the current thread until the index is caught up to the current state of the block chain.
Definition base.cpp:374
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
static const std::string REGTEST
static const std::string TESTNET
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
int64_t GetBlockTime() const
Definition block.h:57
Definition block.h:60
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition blockindex.h:25
int64_t GetBlockTime() const
Definition blockindex.h:180
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition chain.h:150
int Height() const
Return the maximal height in the chain.
Definition chain.h:186
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition chainparams.h:80
const CBlock & GenesisBlock() const
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
const ChainTxData & TxData() const
bool IsTestChain() const
If this chain is exclusively used for testing.
uint16_t GetDefaultPort() const
Definition chainparams.h:95
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once)
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
bool IsValid() const
A combination of a network address (CNetAddr) and a (TCP) port.
Definition netaddress.h:545
static const int DEFAULT_ZMQ_SNDHWM
static std::unique_ptr< CZMQNotificationInterface > Create(std::function< bool(CBlock &, const CBlockIndex &)> get_block_by_index)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition validation.h:699
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
SnapshotCompletionResult MaybeCompleteSnapshotValidation(std::function< void(bilingual_str)> shutdown_fnc=[](bilingual_str msg) { AbortNode(msg.original, msg);}) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & ActiveChainstate() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
const CChainParams & GetParams() const
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
std::thread m_load_block
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
virtual uint64_t GetMaxBlockSize() const =0
virtual const CChainParams & GetChainParams() const =0
virtual bool SetMaxBlockSize(uint64_t maxBlockSize)=0
virtual void SetCashAddrEncoding(bool)=0
Different type to mark Mutex at global scope.
Definition sync.h:144
A writer stream (for serialization) that computes a 256-bit hash.
Definition hash.h:100
static bool TryParse(const std::string &str, NetWhitebindPermissions &output, bilingual_str &error)
static bool TryParse(const std::string &str, NetWhitelistPermissions &output, ConnectionDirection &output_connection_direction, bilingual_str &error)
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, avalanche::Processor *const avalanche, Options opts)
Class for registering and managing all RPC calls.
Definition server.h:40
virtual void AddWalletOptions(ArgsManager &argsman) const =0
Get wallet help string.
virtual void Construct(node::NodeContext &node) const =0
Add wallets that should be opened to list of chain clients.
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
static std::unique_ptr< Processor > MakeProcessor(const ArgsManager &argsman, interfaces::Chain &chain, CConnman *connman, ChainstateManager &chainman, CTxMemPool *mempoolIn, CScheduler &scheduler, bilingual_str &error)
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition fs.h:30
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
const CBlockIndex *GetFirstStoredBlock(const CBlockIndex &start_block) EXCLUSIVE_LOCKS_REQUIRED(bool m_have_pruned
Find the first block that is not pruned.
bool IsPruneMode() const
Whether running in -prune mode.
kernel::BlockManagerOpts Options
256-bit opaque blob.
Definition uint256.h:129
std::string FormatVersion(int nVersion)
std::string FormatUserAgent(const std::string &name, const std::string &version, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec.
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
const std::string CLIENT_NAME
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static constexpr bool DEFAULT_COINSTATSINDEX
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
Definition consensus.h:20
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition cs_main.cpp:7
void SetupCurrencyUnitOptions(ArgsManager &argsman)
const WalletInitInterface & g_wallet_init_interface
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition error.cpp:53
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
Definition error.cpp:44
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
bool DirIsWritable(const fs::path &directory)
int RaiseFileDescriptorLimit(int nMinFD)
This function tries to raise the file descriptor limit to the requested number.
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition httprpc.cpp:477
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition httprpc.cpp:481
bool StartHTTPRPC(HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Start HTTP RPC subsystem.
Definition httprpc.cpp:456
void StartREST(const std::any &context)
Start HTTP REST subsystem.
Definition rest.cpp:832
void StopREST()
Stop HTTP REST subsystem.
Definition rest.cpp:844
void InterruptREST()
Interrupt RPC REST subsystem.
Definition rest.cpp:842
void InterruptHTTPServer()
Interrupt HTTP server threads.
void StartHTTPServer()
Start HTTP server.
void StopHTTPServer()
Stop HTTP server.
bool InitHTTPServer(Config &config)
Initialize HTTP server.
static const int DEFAULT_HTTP_SERVER_TIMEOUT
Definition httpserver.h:14
static const int DEFAULT_HTTP_WORKQUEUE
Definition httpserver.h:13
static const int DEFAULT_HTTP_THREADS
Definition httpserver.h:12
Common init functions shared by bitcoin-node, bitcoin-wallet, etc.
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
Definition init.cpp:154
static bool CreatePidFile(const ArgsManager &args)
Definition init.cpp:161
static const bool DEFAULT_PROXYRANDOMIZE
Definition init.cpp:135
void Interrupt(NodeContext &node)
Interrupt threads.
Definition init.cpp:201
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition init.cpp:1686
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition init.cpp:2087
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition init.cpp:425
static bool AppInitServers(Config &config, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node)
Definition init.cpp:1527
#define MIN_CORE_FILEDESCRIPTORS
Definition init.cpp:144
static bool fHaveGenesis
Definition init.cpp:1502
void Shutdown(NodeContext &node)
Definition init.cpp:225
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
Definition init.cpp:387
static GlobalMutex g_genesis_wait_mutex
Definition init.cpp:1503
static void OnRPCStarted()
Definition init.cpp:413
static void HandleSIGHUP(int)
Definition init.cpp:391
static fs::path GetPidFile(const ArgsManager &args)
Definition init.cpp:156
static std::condition_variable g_genesis_wait_cv
Definition init.cpp:1504
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
Definition init.cpp:2109
static constexpr bool DEFAULT_CHRONIK
Definition init.cpp:137
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin: Basic context setup.
Definition init.cpp:1713
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition init.cpp:2069
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition init.cpp:2099
static const char * DEFAULT_ASMAP_FILENAME
Definition init.cpp:147
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition init.cpp:1552
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
Definition init.cpp:1506
static void OnRPCStopped()
Definition init.cpp:418
static bool LockDataDirectory(bool probeOnly)
Definition init.cpp:2053
static void registerSignalHandler(int signal, void(*handler)(int))
Definition init.cpp:403
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
Definition init.cpp:1760
static const bool DEFAULT_REST_ENABLE
Definition init.cpp:136
static boost::signals2::connection rpc_notify_block_change_connection
Definition init.cpp:412
static void new_handler_terminate()
Definition init.cpp:1702
static const std::string HEADERS_TIME_FILE_NAME
Definition init.cpp:149
static constexpr bool DEFAULT_DAEMON
Default value for -daemon option.
Definition init.h:16
static constexpr bool DEFAULT_DAEMONWAIT
Default value for -daemonwait option.
Definition init.h:18
BCLog::Logger & LogInstance()
Definition logging.cpp:21
bool error(const char *fmt, const Args &...args)
Definition logging.h:263
#define LogPrint(category,...)
Definition logging.h:238
#define LogPrintfCategory(category,...)
Definition logging.h:231
#define LogPrintf(...)
Definition logging.h:227
void StartMapPort(bool use_upnp, bool use_natpmp)
Definition mapport.cpp:362
void StopMapPort()
Definition mapport.cpp:368
void InterruptMapPort()
Definition mapport.cpp:365
static constexpr bool DEFAULT_NATPMP
Definition mapport.h:17
static constexpr bool DEFAULT_UPNP
Definition mapport.h:11
std::optional< bilingual_str > ApplyArgsManOptions(const ArgsManager &argsman, const CChainParams &chainparams, MemPoolOptions &mempool_opts)
Overlay the options set in argsman on top of corresponding members in mempool_opts.
static constexpr unsigned int DEFAULT_MAX_MEMPOOL_SIZE_MB
Default for -maxmempool, maximum megabytes of mempool memory usage.
static constexpr unsigned int DEFAULT_MEMPOOL_EXPIRY_HOURS
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
std::string FormatMoney(const Amount amt)
Do not use these functions to represent or parse monetary amounts to or from JSON but use AmountFromV...
Definition moneystr.cpp:13
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
Definition moneystr.cpp:37
@ RPC
Definition logging.h:47
@ PRUNE
Definition logging.h:54
void OnStarted(std::function< void()> slot)
Definition server.cpp:113
void OnStopped(std::function< void()> slot)
Definition server.cpp:117
static constexpr Amount PROOF_DUST_THRESHOLD
Minimum amount per utxo.
Definition proof.h:40
static auto quoted(const std::string &s)
Definition fs.h:107
static bool exists(const path &p)
Definition fs.h:102
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition fs.h:142
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition fs.h:165
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition fs.cpp:142
void AddLoggingArgs(ArgsManager &argsman)
Definition common.cpp:65
void SetLoggingCategories(const ArgsManager &args)
Definition common.cpp:161
bool SanityChecks()
Ensure a usable environment with all necessary library support.
Definition common.cpp:43
void SetGlobals()
Definition common.cpp:30
bool StartLogging(const ArgsManager &args)
Definition common.cpp:189
void SetLoggingOptions(const ArgsManager &args)
Definition common.cpp:140
void UnsetGlobals()
Definition common.cpp:38
void LogPackageVersion()
Definition common.cpp:236
std::unique_ptr< Chain > MakeChain(node::NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
bool DumpMempool(const CTxMemPool &pool, const fs::path &dump_path, FopenFn mockable_fopen_function, bool skip_file_commit)
Definition init.h:28
@ FAILURE_FATAL
Fatal error which should not prompt to reindex.
@ FAILURE
Generic failure which reindexing may fix.
CacheSizes CalculateCacheSizes(const ArgsManager &args, size_t n_indexes)
Definition caches.cpp:12
fs::path MempoolPath(const ArgsManager &argsman)
bool ShouldPersistMempool(const ArgsManager &argsman)
void ThreadImport(ChainstateManager &chainman, avalanche::Processor *const avalanche, std::vector< fs::path > vImportFiles, const fs::path &mempool_path)
std::optional< bilingual_str > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
This sequence can have 4 types of outcomes:
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
static constexpr bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool, indicating whether the node should attempt to automatically load the mem...
std::atomic_bool fReindex
void format(std::ostream &out, const char *fmt, const Args &...args)
Format list of arguments to the stream according to given format string.
bilingual_str ErrorString(const Result< T > &result)
Definition result.h:78
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition thread.cpp:13
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
uint16_t GetListenPort()
Definition net.cpp:137
bool fDiscover
Definition net.cpp:125
bool fListen
Definition net.cpp:126
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition net.cpp:317
bool AddLocal(const CService &addr, int nScore)
Definition net.cpp:278
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
Definition net.cpp:2642
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition net.h:90
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition net.h:66
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition net.h:73
static const size_t DEFAULT_MAXSENDBUFFER
Definition net.h:104
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition net.h:98
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition net.h:94
static const bool DEFAULT_FORCEDNSSEED
Definition net.h:100
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition net.h:92
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition net.h:103
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
Definition net.h:80
static const bool DEFAULT_FIXEDSEEDS
Definition net.h:102
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition net.h:82
static const bool DEFAULT_LISTEN
-listen default
Definition net.h:84
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition net.h:96
static const bool DEFAULT_DNSSEED
Definition net.h:101
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition net.h:71
@ LOCAL_MANUAL
Definition net.h:239
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition net.h:75
const std::vector< std::string > NET_PERMISSIONS_DOC
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
static const uint32_t DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of non-mempool transactions to keep around for block reconstruction.
static const uint32_t DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
static const bool DEFAULT_PEERBLOCKFILTERS
Network
A network type.
Definition netaddress.h:44
@ NET_I2P
I2P.
Definition netaddress.h:59
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition netaddress.h:69
@ NET_ONION
TOR (v2 or v3)
Definition netaddress.h:56
@ NET_IPV6
IPv6.
Definition netaddress.h:53
@ NET_IPV4
IPv4.
Definition netaddress.h:50
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition netaddress.h:47
enum Network ParseNetwork(const std::string &net_in)
Definition netbase.cpp:92
bool Lookup(const std::string &name, std::vector< CService > &vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition netbase.cpp:223
bool fNameLookup
Definition netbase.cpp:38
int nConnectTimeout
Definition netbase.cpp:37
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition netbase.cpp:725
bool IsBadPort(uint16_t port)
Determine if a port is "bad" from the perspective of attempting to connect to a node on that port.
Definition netbase.cpp:854
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition netbase.cpp:705
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition netbase.cpp:137
ConnectionDirection
Definition netbase.h:32
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition netbase.h:30
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition netbase.h:28
uint32_t nBytesPerSigCheck
Definition settings.cpp:10
static constexpr uint64_t DEFAULT_MAX_GENERATED_BLOCK_SIZE
Default for -blockmaxsize, which controls the maximum size of block the mining code will create.
Definition policy.h:25
static constexpr Amount DUST_RELAY_TX_FEE(1000 *SATOSHI)
Min feerate for defining dust.
static constexpr bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
Definition policy.h:56
static constexpr Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
static constexpr unsigned int DEFAULT_BYTES_PER_SIGCHECK
Default for -bytespersigcheck .
Definition policy.h:54
static constexpr Amount DEFAULT_BLOCK_MIN_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
static constexpr std::chrono::milliseconds AVALANCHE_DEFAULT_QUERY_TIMEOUT
How long before we consider that a query timed out.
Definition processor.h:58
static constexpr int AVALANCHE_DEFAULT_STAKE_UTXO_CONFIRMATIONS
Minimum number of confirmations before a stake utxo is mature enough to be included into a proof.
Definition proof.h:35
ServiceFlags
nServices flags.
Definition protocol.h:335
@ NODE_NETWORK_LIMITED
Definition protocol.h:365
@ NODE_BLOOM
Definition protocol.h:352
@ NODE_NETWORK
Definition protocol.h:342
@ NODE_COMPACT_FILTERS
Definition protocol.h:360
@ NODE_AVALANCHE
Definition protocol.h:380
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
Definition random.cpp:645
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
static void RegisterAllRPCCommands(const Config &config, RPCServer &rpcServer, CRPCTable &rpcTable)
Register all context-sensitive RPC commands.
Definition register.h:42
const char * prefix
Definition rest.cpp:817
bool(* handler)(Config &config, const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition rest.cpp:818
const char * name
Definition rest.cpp:47
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Definition util.cpp:22
static constexpr bool DEFAULT_RPC_DOC_CHECK
Definition util.h:29
static constexpr bool DEFAULT_ENABLE_RTT
Default for -enablertt.
Definition rtt.h:20
bool InitScriptExecutionCache(size_t max_size_bytes)
Initializes the script-execution cache.
static constexpr size_t DEFAULT_MAX_SCRIPT_CACHE_BYTES
Definition scriptcache.h:45
void SetRPCWarmupFinished()
Mark warmup as done.
Definition server.cpp:393
void StartRPC()
Definition server.cpp:348
void StopRPC()
Definition server.cpp:365
void InterruptRPC()
Definition server.cpp:354
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition server.cpp:388
CRPCTable tableRPC
Definition server.cpp:683
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
Definition server.cpp:382
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition shutdown.cpp:85
bool InitShutdownState()
Initialize shutdown state.
Definition shutdown.cpp:43
void StartShutdown()
Request shutdown of the application.
Definition shutdown.cpp:55
void AbortShutdown()
Clear shutdown flag.
Definition shutdown.cpp:76
bool InitSignatureCache(size_t max_size_bytes)
Definition sigcache.cpp:85
static constexpr size_t DEFAULT_MAX_SIG_CACHE_BYTES
Definition sigcache.h:18
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
Definition standard.h:36
static const bool DEFAULT_ACCEPT_DATACARRIER
Definition standard.h:17
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
Definition string.cpp:10
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition string.h:63
static constexpr Amount zero() noexcept
Definition amount.h:32
ServiceFlags nLocalServices
Definition net.h:859
static const Currency & get()
Definition amount.cpp:18
std::string ticker
Definition amount.h:150
Bilingual messages:
Definition translation.h:17
std::string translated
Definition translation.h:19
std::string original
Definition translation.h:18
Block and header tip information.
Definition node.h:50
const CChainParams & chainparams
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
Options struct containing options for constructing a CTxMemPool.
int check_ratio
The ratio used to determine how often sanity checks will run.
std::function< void()> coins_error_cb
Definition chainstate.h:37
std::function< bool()> check_interrupt
Definition chainstate.h:36
NodeContext struct containing references to chain state and connection state.
Definition context.h:43
#define WAIT_LOCK(cs, name)
Definition sync.h:317
#define LOCK(cs)
Definition sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition sync.h:357
#define TRY_LOCK(cs, name)
Definition sync.h:314
std::string SysErrorString(int err)
Return system error string from errno value.
Definition syserror.cpp:14
bool SetupNetworking()
Definition system.cpp:98
int GetNumCores()
Return the number of cores available on the current system.
Definition system.cpp:111
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition time.cpp:101
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition time.cpp:89
NodeClock::time_point GetAdjustedTime()
Definition timedata.cpp:35
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
Definition timedata.h:16
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
CService DefaultOnionServiceTarget()
const std::string DEFAULT_TOR_CONTROL
Default control port.
void InterruptTorControl()
void StartTorControl(CService onion_service_target)
void StopTorControl()
static const bool DEFAULT_LISTEN_ONION
Definition torcontrol.h:16
bilingual_str _(const char *psz)
Translation function.
Definition translation.h:68
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition translation.h:36
util::Result< void > CheckLegacyTxindex(CBlockTreeDB &block_tree_db)
Definition txdb.cpp:37
static constexpr int64_t MAX_DB_CACHE_MB
max. -dbcache (MiB)
Definition txdb.h:38
static constexpr int64_t MIN_DB_CACHE_MB
min. -dbcache (MiB)
Definition txdb.h:36
static constexpr int64_t DEFAULT_DB_BATCH_SIZE
-dbbatchsize default (bytes)
Definition txdb.h:42
static constexpr int64_t DEFAULT_DB_CACHE_MB
-dbcache default (MiB)
Definition txdb.h:40
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition txindex.cpp:16
static constexpr bool DEFAULT_TXINDEX
Definition txindex.h:15
CClientUIInterface uiInterface
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
std::condition_variable g_best_block_cv
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
assert(!tx.IsCoinBase())
static constexpr int DEFAULT_CHECKLEVEL
Definition validation.h:97
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev?...
Definition validation.h:111
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition validation.h:95
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition validation.h:83
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition validation.h:114
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition validation.h:85
static const signed int DEFAULT_CHECKBLOCKS
Definition validation.h:96
static const bool DEFAULT_PEERBLOOMFILTERS
Definition validation.h:87
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition validation.h:90
CMainSignals & GetMainSignals()
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
static constexpr uint32_t AVALANCHE_VOTE_STALE_FACTOR
Scaling factor applied to confidence to determine staleness threshold.
Definition voterecord.h:35
static constexpr uint32_t AVALANCHE_VOTE_STALE_THRESHOLD
Number of votes before a record may be considered as stale.
Definition voterecord.h:22
std::unique_ptr< CZMQNotificationInterface > g_zmq_notification_interface
void RegisterZMQRPCCommands(CRPCTable &t)
Definition zmqrpc.cpp:68