6#include <bitcoin-build-config.h>
98#include <condition_variable>
113#include <boost/signals2/signal.hpp>
155#define MIN_LEVELDB_FDS 0
157#define MIN_LEVELDB_FDS 150
200 if (std::error_code error; !fs::remove(pid_path, error)) {
201 std::string
msg{error ? error.message() :
"File does not exist"};
217 if (!(*
node.shutdown_signal)())
return false;
219 if (
node.notifications)
WITH_LOCK(
node.notifications->m_tip_block_mutex,
node.notifications->m_tip_block_cv.notify_all());
255 std::vector<std::thread> threads;
257 threads.emplace_back(runCommand,
cmd);
259 for (
auto& t : threads) {
268 ShutdownNotify(*
node.args);
277 node.connman->Interrupt();
278 for (
auto* index :
node.indexes) {
285 static Mutex g_shutdown_mutex;
286 TRY_LOCK(g_shutdown_mutex, lock_shutdown);
287 if (!lock_shutdown)
return;
288 LogInfo(
"Shutdown in progress...");
296 if (
node.mempool)
node.mempool->AddTransactionsUpdated(1);
302 for (
auto& client :
node.chain_clients) {
314 if (
node.peerman &&
node.validation_signals)
node.validation_signals->UnregisterValidationInterface(
node.peerman.get());
315 if (
node.connman)
node.connman->Stop();
319 if (
node.background_init_thread.joinable())
node.background_init_thread.join();
323 if (
node.scheduler)
node.scheduler->stop();
327 node.peerman.reset();
328 node.connman.reset();
330 node.addrman.reset();
331 node.netgroupman.reset();
339 if (
node.fee_estimator) {
340 node.fee_estimator->Flush();
341 if (
node.validation_signals) {
342 node.validation_signals->UnregisterValidationInterface(
node.fee_estimator.get());
350 if (chainstate->CanFlushToDisk()) {
351 chainstate->ForceFlushStateToDisk();
358 if (
node.validation_signals)
node.validation_signals->FlushBackgroundCallbacks();
361 for (
auto* index :
node.indexes) index->Stop();
365 node.indexes.clear();
376 if (chainstate->CanFlushToDisk()) {
377 chainstate->ForceFlushStateToDisk();
378 chainstate->ResetCoinsViews();
386 ipc->disconnectIncoming();
396 node.chain_clients.clear();
397 if (
node.validation_signals) {
398 node.validation_signals->UnregisterAllValidationInterfaces();
400 node.mempool.reset();
401 node.fee_estimator.reset();
402 node.chainman.reset();
403 node.validation_signals.reset();
404 node.scheduler.reset();
405 node.ecc_context.reset();
431static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
434 LogError(
"Failed to send shutdown signal on Ctrl-C\n");
447 sigemptyset(&sa.sa_mask);
449 sigaction(signal, &sa,
nullptr);
472 std::vector<std::string> hidden_args = {
473 "-dbcrashratio",
"-forcecompactdb",
475 "-choosedatadir",
"-lang=<lang>",
"-min",
"-resetguisettings",
"-splash",
"-uiplatform"};
481 argsman.
AddArg(
"-assumevalid=<hex>",
strprintf(
"If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet3: %s, testnet4: %s, signet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnet4ChainParams->GetConsensus().defaultAssumeValid.GetHex(), signetChainParams->GetConsensus().defaultAssumeValid.GetHex()),
ArgsManager::ALLOW_ANY,
OptionsCategory::OPTIONS);
483 argsman.
AddArg(
"-blocksxor",
484 strprintf(
"Whether an XOR-key applies to blocksdir *.dat files. "
485 "The created XOR-key will be zeros for an existing blocksdir or when `-blocksxor=0` is "
486 "set, and random for a freshly initialized blocksdir. "
508 argsman.
AddArg(
"-minimumchainwork=<hex>",
strprintf(
"Minimum work assumed to exist on a valid chain in hex (default: %s, testnet3: %s, testnet4: %s, signet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnet4ChainParams->GetConsensus().nMinimumChainWork.GetHex(), signetChainParams->GetConsensus().nMinimumChainWork.GetHex()),
ArgsManager::ALLOW_ANY |
ArgsManager::DEBUG_ONLY,
OptionsCategory::OPTIONS);
509 argsman.
AddArg(
"-par=<n>",
strprintf(
"Set the number of script verification threads (0 = auto, up to %d, <0 = leave that many cores free, default: %d)",
512 argsman.
AddArg(
"-persistmempoolv1",
513 strprintf(
"Whether a mempool.dat file created by -persistmempool or the savemempool RPC will be written in the legacy format "
514 "(version 1) or the current format (version 2). This temporary option will be removed in the future. (default: %u)",
518 argsman.
AddArg(
"-prune=<n>",
strprintf(
"Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex. "
519 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
521 argsman.
AddArg(
"-reindex",
"If enabled, wipe chain state and block index, and rebuild them from blk*.dat files on disk. Also wipe and rebuild other optional indexes that are active. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.",
ArgsManager::ALLOW_ANY,
OptionsCategory::OPTIONS);
522 argsman.
AddArg(
"-reindex-chainstate",
"If enabled, wipe chain state, and rebuild it from blk*.dat files on disk. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.",
ArgsManager::ALLOW_ANY,
OptionsCategory::OPTIONS);
526 argsman.
AddArg(
"-shutdownnotify=<cmd>",
"Execute command immediately before beginning shutdown. The need for shutdown may be urgent, so be careful not to delay it long (if the command doesn't require interaction with the server, consider having it fork into the background).",
ArgsManager::ALLOW_ANY,
OptionsCategory::OPTIONS);
529 argsman.
AddArg(
"-blockfilterindex=<type>",
531 " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
537 argsman.
AddArg(
"-bind=<addr>[:<port>][=onion]",
strprintf(
"Bind to given address and always listen on it (default: 0.0.0.0). Use [host]:port notation for IPv6. Append =onion to tag any incoming connections to that address and port as incoming Tor connections (default: 127.0.0.1:%u=onion, testnet3: 127.0.0.1:%u=onion, testnet4: 127.0.0.1:%u=onion, signet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)", defaultChainParams->GetDefaultPort() + 1, testnetChainParams->GetDefaultPort() + 1, testnet4ChainParams->GetDefaultPort() + 1, signetChainParams->GetDefaultPort() + 1, regtestChainParams->GetDefaultPort() + 1),
ArgsManager::ALLOW_ANY |
ArgsManager::NETWORK_ONLY,
OptionsCategory::CONNECTION);
552#ifdef HAVE_SOCKADDR_UN
564 argsman.
AddArg(
"-port=<port>",
strprintf(
"Listen for connections on <port> (default: %u, testnet3: %u, testnet4: %u, signet: %u, regtest: %u). Not relevant for I2P (see doc/i2p.md). If set to a value x, the default onion listening port will be set to x+1.", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), testnet4ChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()),
ArgsManager::ALLOW_ANY |
ArgsManager::NETWORK_ONLY,
OptionsCategory::CONNECTION);
565 const std::string proxy_doc_for_value =
566#ifdef HAVE_SOCKADDR_UN
567 "<ip>[:<port>]|unix:<path>";
571 const std::string proxy_doc_for_unix_socket =
572#ifdef HAVE_SOCKADDR_UN
573 "May be a local file path prefixed with 'unix:' if the proxy supports it. ";
577 argsman.
AddArg(
"-proxy=" + proxy_doc_for_value +
"[=<network>]",
578 "Connect through SOCKS5 proxy, set -noproxy to disable. " +
579 proxy_doc_for_unix_socket +
580 "Could end in =network to set the proxy only for that network. " +
581 "The network can be any of ipv4, ipv6, tor or cjdns. " +
582 "(default: disabled)",
586 argsman.
AddArg(
"-seednode=<ip>",
"Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes. During startup, seednodes will be tried before dnsseeds.",
ArgsManager::ALLOW_ANY,
OptionsCategory::CONNECTION);
593 argsman.
AddArg(
"-whitebind=<[permissions@]addr>",
"Bind to the given address and add permission flags to the peers connecting to it. "
597 argsman.
AddArg(
"-whitelist=<[permissions@]IP address or network>",
"Add permission flags to the peers using the given IP address (e.g. 1.2.3.4) or "
598 "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as "
600 "Additional flags \"in\" and \"out\" control whether permissions apply to incoming connections and/or manual (default: incoming only). "
617 hidden_args.emplace_back(
"-zmqpubhashblock=<address>");
618 hidden_args.emplace_back(
"-zmqpubhashtx=<address>");
619 hidden_args.emplace_back(
"-zmqpubrawblock=<address>");
620 hidden_args.emplace_back(
"-zmqpubrawtx=<address>");
621 hidden_args.emplace_back(
"-zmqpubsequence=<n>");
622 hidden_args.emplace_back(
"-zmqpubhashblockhwm=<n>");
623 hidden_args.emplace_back(
"-zmqpubhashtxhwm=<n>");
624 hidden_args.emplace_back(
"-zmqpubrawblockhwm=<n>");
625 hidden_args.emplace_back(
"-zmqpubrawtxhwm=<n>");
626 hidden_args.emplace_back(
"-zmqpubsequencehwm=<n>");
647 argsman.
AddArg(
"-maxtipage=<n>",
648 strprintf(
"Maximum tip age in seconds to consider node in initial block download (default: %u)",
662 argsman.
AddArg(
"-datacarriersize",
663 strprintf(
"Relay and mine transactions whose data-carrying raw scriptPubKeys in aggregate "
664 "are of this size or less, allowing multiple outputs (default: %u)",
669 argsman.
AddArg(
"-minrelaytxfee=<amt>",
strprintf(
"Fees (in %s/kvB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
681 argsman.
AddArg(
"-rpcallowip=<ip>",
"Allow JSON-RPC connections from specified source. Valid values for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0), a network/CIDR (e.g. 1.2.3.4/24), all ipv4 (0.0.0.0/0), or all ipv6 (::/0). RFC4193 is allowed only if -cjdnsreachable=0. This option can be specified multiple times",
ArgsManager::ALLOW_ANY,
OptionsCategory::RPC);
682 argsman.
AddArg(
"-rpcauth=<userpw>",
"Username and HMAC-SHA-256 hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcauth. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times",
ArgsManager::ALLOW_ANY |
ArgsManager::SENSITIVE,
OptionsCategory::RPC);
683 argsman.
AddArg(
"-rpcbind=<addr>[:port]",
"Bind to given address to listen for JSON-RPC connections. Do not expose the RPC server to untrusted networks such as the public internet! This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost)",
ArgsManager::ALLOW_ANY |
ArgsManager::NETWORK_ONLY,
OptionsCategory::RPC);
688 argsman.
AddArg(
"-rpcport=<port>",
strprintf(
"Listen for JSON-RPC connections on <port> (default: %u, testnet3: %u, testnet4: %u, signet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), testnet4BaseParams->RPCPort(), signetBaseParams->RPCPort(), regtestBaseParams->RPCPort()),
ArgsManager::ALLOW_ANY |
ArgsManager::NETWORK_ONLY,
OptionsCategory::RPC);
692 argsman.
AddArg(
"-rpcwhitelist=<whitelist>",
"Set a whitelist to filter incoming RPC calls for a specific user. The field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc 2>,...,<rpc n>. If multiple whitelists are set for a given user, they are set-intersected. See -rpcwhitelistdefault documentation for information on default whitelist behavior.",
ArgsManager::ALLOW_ANY,
OptionsCategory::RPC);
693 argsman.
AddArg(
"-rpcwhitelistdefault",
"Sets default behavior for rpc whitelisting. Unless rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc server acts as if all rpc users are subject to empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault is set to 1 and no -rpcwhitelist is set, rpc server acts as if all rpc users are subject to empty whitelists.",
ArgsManager::ALLOW_ANY,
OptionsCategory::RPC);
696 if (can_listen_ipc) {
697 argsman.
AddArg(
"-ipcbind=<address>",
"Bind to Unix socket address and listen for incoming connections. Valid address values are \"unix\" to listen on the default path, <datadir>/node.sock, or \"unix:/custom/path\" to specify a custom path. Can be specified multiple times to listen on multiple paths. Default behavior is not to listen on any path. If relative paths are specified, they are interpreted relative to the network data directory. If paths include any parent directory components and the parent directories do not exist, they will be created.",
ArgsManager::ALLOW_ANY,
OptionsCategory::IPC);
704 hidden_args.emplace_back(
"-daemon");
705 hidden_args.emplace_back(
"-daemonwait");
717 std::thread
t(runCommand,
cmd);
745 LogInfo(
"parameter interaction: -bind set -> setting -listen=1\n");
749 LogInfo(
"parameter interaction: -whitebind set -> setting -listen=1\n");
756 LogInfo(
"parameter interaction: -connect or -maxconnections=0 set -> setting -dnsseed=0\n");
758 LogInfo(
"parameter interaction: -connect or -maxconnections=0 set -> setting -listen=0\n");
761 std::string proxy_arg =
args.
GetArg(
"-proxy",
"");
762 if (proxy_arg !=
"" && proxy_arg !=
"0") {
765 LogInfo(
"parameter interaction: -proxy set -> setting -listen=0\n");
769 LogInfo(
"parameter interaction: -proxy set -> setting -natpmp=0\n");
773 LogInfo(
"parameter interaction: -proxy set -> setting -discover=0\n");
779 LogInfo(
"parameter interaction: -listen=0 -> setting -natpmp=0\n");
782 LogInfo(
"parameter interaction: -listen=0 -> setting -discover=0\n");
784 LogInfo(
"parameter interaction: -listen=0 -> setting -listenonion=0\n");
786 LogInfo(
"parameter interaction: -listen=0 -> setting -i2pacceptincoming=0\n");
793 LogInfo(
"parameter interaction: -externalip set -> setting -discover=0\n");
799 LogInfo(
"parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n");
808 LogInfo(
"parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n");
811 if (!onlynets.empty()) {
812 bool clearnet_reachable = std::any_of(onlynets.begin(), onlynets.end(), [](
const auto& net) {
813 const auto n = ParseNetwork(net);
814 return n == NET_IPV4 || n == NET_IPV6;
817 LogInfo(
"parameter interaction: -onlynet excludes IPv4 and IPv6 -> setting -dnsseed=0\n");
839int64_t peer_connect_timeout;
840std::set<BlockFilterType> g_enabled_filter_types;
850 std::set_new_handler(std::terminate);
851 LogError(
"Out of memory. Terminating.\n");
862 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
863 _CrtSetReportFile(_CRT_WARN, CreateFileA(
"NUL", GENERIC_WRITE, 0,
nullptr, OPEN_EXISTING, 0, 0));
865 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
869 HeapSetInformation(
nullptr, HeapEnableTerminationOnCorruption,
nullptr, 0);
884 signal(SIGPIPE, SIG_IGN);
886 SetConsoleCtrlHandler(consoleCtrlHandler,
true);
903 InitWarning(
_(
"Option '-checkpoints' is set but checkpoints were removed. This option has no effect."));
908 InitWarning(
_(
"Option '-maxorphantx' is set but no longer has any effect (see release notes). Please remove it from your configuration."));
923 if (!errors.
empty()) {
929 LogInfo(
"Warning: Support for testnet3 is deprecated and will be removed in an upcoming release. Consider switching to testnet4.\n");
938 if (!warnings.
empty()) {
948 if (blockfilterindex_value ==
"" || blockfilterindex_value ==
"1") {
950 }
else if (blockfilterindex_value !=
"0") {
951 const std::vector<std::string> names =
args.
GetArgs(
"-blockfilterindex");
952 for (
const auto&
name : names) {
957 g_enabled_filter_types.insert(filter_type);
969 return InitError(
_(
"Cannot set -peerblockfilters without -blockfilterindex."));
977 return InitError(
_(
"Prune mode is incompatible with -txindex."));
979 return InitError(
_(
"Prune mode is incompatible with -reindex-chainstate. Use full -reindex instead."));
985 return InitError(
_(
"Cannot set -forcednsseed to true when setting -dnsseed to false."));
1003 int nBind = std::max(nUserBind,
size_t(1));
1006 if (user_max_connection < 0) {
1016 available_fds = std::min(FD_SETSIZE, available_fds);
1018 if (available_fds < min_required_fds)
1019 return InitError(
strprintf(
_(
"Not enough file descriptors available. %d available, %d required."), available_fds, min_required_fds));
1022 nMaxConnections = std::min(available_fds - min_required_fds, user_max_connection);
1024 if (nMaxConnections < user_max_connection)
1025 InitWarning(
strprintf(
_(
"Reducing -maxconnections from %d to %d, because of system limitations."), user_max_connection, nMaxConnections));
1037 if (peer_connect_timeout <= 0) {
1041 if (
const auto arg{
args.
GetArg(
"-blockmintxfee")}) {
1076 const std::vector<std::string> test_options =
args.
GetArgs(
"-test");
1077 if (!test_options.empty()) {
1081 for (
const std::string& option : test_options) {
1083 size_t pos = doc_option.find(
" (");
1084 return (pos != std::string::npos) && (doc_option.substr(0, pos) == option);
1098 .notifications = notifications,
1101 if (!chainman_result) {
1104 BlockManager::Options blockman_opts_dummy{
1105 .chainparams = chainman_opts_dummy.chainparams,
1107 .notifications = chainman_opts_dummy.notifications,
1114 if (!blockman_result) {
1119 if (!mempool_result) {
1151 return InitError(
strprintf(
_(
"Initialization sanity check failed. %s is shutting down."), CLIENT_NAME));
1155 return InitError(
strprintf(
_(
"Elliptic curve cryptography sanity check failure. %s is shutting down."), CLIENT_NAME));
1178 node.chain =
node.init->makeChain();
1179 node.mining =
node.init->makeMining();
1184 for (
const std::string port_option : {
1188 if (
const auto port{
args.
GetArg(port_option)}) {
1189 const auto n{ToIntegral<uint16_t>(*port)};
1190 if (!n || *n == 0) {
1196 for ([[maybe_unused]]
const auto& [param_name, unix, suffix_allowed] : std::vector<std::tuple<std::string, bool, bool>>{
1198 {
"-i2psam",
false,
false},
1199 {
"-onion",
true,
false},
1200 {
"-proxy",
true,
true},
1201 {
"-bind",
false,
true},
1202 {
"-rpcbind",
false,
false},
1203 {
"-torcontrol",
false,
false},
1204 {
"-whitebind",
false,
false},
1205 {
"-zmqpubhashblock",
true,
false},
1206 {
"-zmqpubhashtx",
true,
false},
1207 {
"-zmqpubrawblock",
true,
false},
1208 {
"-zmqpubrawtx",
true,
false},
1209 {
"-zmqpubsequence",
true,
false},
1211 for (
const std::string& param_value :
args.
GetArgs(param_name)) {
1212 const std::string param_value_hostport{
1213 suffix_allowed ? param_value.substr(0, param_value.rfind(
'=')) : param_value};
1214 std::string host_out;
1215 uint16_t port_out{0};
1216 if (!
SplitHostPort(param_value_hostport, port_out, host_out)) {
1217#ifdef HAVE_SOCKADDR_UN
1240 std::set<CService> seen;
1244 if (!seen.insert(wb.m_service).second) {
1245 return wb.m_service;
1250 for (
const auto& bind : conn_options.
vBinds) {
1251 if (!seen.insert(bind).second) {
1257 for (
const auto& onion_bind : conn_options.
onion_binds) {
1258 if (!seen.insert(onion_bind).second) {
1263 return std::nullopt;
1271 const bool do_reindex_chainstate,
1276 node.notifications.reset();
1277 node.mempool.reset();
1278 node.chainman.reset();
1288 .signals =
node.validation_signals.get(),
1293 node.mempool = std::make_unique<CTxMemPool>(mempool_opts, mempool_error);
1294 if (!mempool_error.
empty()) {
1295 return {ChainstateLoadStatus::FAILURE_FATAL, mempool_error};
1297 LogInfo(
"* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)",
1298 cache_sizes.
coins * (1.0 / 1024 / 1024),
1299 mempool_opts.max_size_bytes * (1.0 / 1024 / 1024));
1303 .notifications = *
node.notifications,
1304 .signals =
node.validation_signals.get(),
1308 BlockManager::Options blockman_opts{
1309 .chainparams = chainman_opts.chainparams,
1311 .notifications = chainman_opts.notifications,
1315 .wipe_data = do_reindex,
1325 node.chainman = std::make_unique<ChainstateManager>(*
Assert(
node.shutdown_signal), chainman_opts, blockman_opts);
1328 return {ChainstateLoadStatus::FAILURE,
_(
"Error opening block database")};
1329 }
catch (std::exception& e) {
1330 return {ChainstateLoadStatus::FAILURE_FATAL,
Untranslated(
strprintf(
"Failed to initialize ChainstateManager: %s", e.what()))};
1333 if (chainman.
m_interrupt)
return {ChainstateLoadStatus::INTERRUPTED, {}};
1339 if (!
node.chainman->m_blockman.IsPruneMode()) {
1340 LogInfo(
"[snapshot] re-enabling NODE_NETWORK services");
1343 LogInfo(
"[snapshot] restarting indexes");
1346 Assert(
node.validation_signals)->SyncWithValidationInterfaceQueue();
1347 for (
auto* index :
node.indexes) {
1350 if (!(index->Init() && index->StartBackgroundSync())) {
1351 LogPrintf(
"[snapshot] WARNING failed to restart index %s on snapshot chain\n", index->GetName());
1364 _(
"Error reading from database, shutting down."),
1371 }
catch (
const std::exception& e) {
1376 auto [status, error] = catch_exceptions([&] {
return LoadChainstate(chainman, cache_sizes, options); });
1380 LogWarning(
"pruned datadir may not have more than %d blocks; only checking available blocks\n",
1385 LogInfo(
"Block index and chainstate loaded");
1388 return {status, error};
1397 if (!opt_max_upload) {
1411 LogInfo(
"Using at most %i automatic connections (%i file descriptors available)", nMaxConnections, available_fds);
1415 LogPrintf(
"Warning: relative datadir option '%s' specified, which will be interpreted relative to the "
1416 "current working directory '%s'. This is fragile, because if bitcoin is started in the future "
1417 "from a different location, it will be unable to locate the current data files. There could "
1418 "also be data loss if bitcoin is started while in a temporary directory.\n",
1423 node.scheduler = std::make_unique<CScheduler>();
1424 auto& scheduler = *
node.scheduler;
1427 scheduler.m_service_thread = std::thread(
util::TraceThread,
"scheduler", [&] { scheduler.serviceQueue(); });
1430 scheduler.scheduleEvery([]{
1432 }, std::chrono::minutes{1});
1435 scheduler.scheduleEvery([&
args, &
node]{
1436 constexpr uint64_t min_disk_space = 50 << 20;
1438 LogError(
"Shutting down due to lack of disk space!\n");
1440 LogError(
"Failed to send shutdown signal after disk space check\n");
1443 }, std::chrono::minutes{5});
1447 [&scheduler](
auto func,
auto window) { scheduler.scheduleEvery(std::move(func), window); },
1451 LogInfo(
"Log rate limiting disabled");
1455 node.validation_signals = std::make_unique<ValidationSignals>(std::make_unique<SerialTaskRunner>(scheduler));
1456 auto& validation_signals = *
node.validation_signals;
1466 for (std::string address :
gArgs.
GetArgs(
"-ipcbind")) {
1468 ipc->listenAddress(address);
1469 }
catch (
const std::exception& e) {
1472 LogInfo(
"Listening for IPC requests on address %s", address);
1480 for (
const auto& client :
node.chain_clients) {
1481 client->registerRpcs();
1493 if (!onlynets.empty()) {
1495 for (
const std::string& snet : onlynets) {
1506 _(
"Outbound connections restricted to CJDNS (-onlynet=cjdns) but "
1507 "-cjdnsreachable is not provided"));
1524 return InitError(
_(
"Unable to start HTTP server. See debug log for details."));
1528 for (
const auto& client :
node.chain_clients) {
1529 if (!client->verify()) {
1549 std::vector<bool> asmap;
1552 if (!asmap_path.is_absolute()) {
1560 if (asmap.size() == 0) {
1565 LogInfo(
"Using asmap version %s for IP bucketing", asmap_version.
ToString());
1567 LogInfo(
"Using /16 prefix for IP bucketing");
1572 node.netgroupman = std::make_unique<NetGroupManager>(std::move(asmap));
1576 uiInterface.InitMessage(
_(
"Loading P2P addresses…"));
1579 node.addrman = std::move(*addrman);
1586 node.connman = std::make_unique<CConnman>(rng.
rand64(),
1593 if (!peerman_opts.ignore_incoming_txs) {
1598 node.fee_estimator = std::make_unique<CBlockPolicyEstimator>(
FeeestPath(
args), read_stale_estimates);
1603 validation_signals.RegisterValidationInterface(fee_estimator);
1606 for (
const std::string& socket_addr :
args.
GetArgs(
"-bind")) {
1607 std::string host_out;
1608 uint16_t port_out{0};
1609 std::string bind_socket_addr = socket_addr.substr(0, socket_addr.rfind(
'='));
1616 std::vector<std::string> uacomments;
1617 for (
const std::string& cmt :
args.
GetArgs(
"-uacomment")) {
1619 return InitError(
strprintf(
_(
"User Agent comment (%s) contains unsafe characters."), cmt));
1620 uacomments.push_back(cmt);
1624 return InitError(
strprintf(
_(
"Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1632 return InitError(
strprintf(
_(
"Incompatible options: -dnsseed=1 was explicitly specified, but -onlynet forbids connections to IPv4/IPv6")));
1646 for (
const std::string& param_value :
args.
GetArgs(
"-proxy")) {
1647 const auto eq_pos{param_value.rfind(
'=')};
1648 const std::string proxy_str{param_value.substr(0, eq_pos)};
1649 std::string net_str;
1650 if (eq_pos != std::string::npos) {
1651 if (eq_pos + 1 == param_value.length()) {
1652 return InitError(
strprintf(
_(
"Invalid -proxy address or hostname, ends with '=': '%s'"), param_value));
1654 net_str =
ToLower(param_value.substr(eq_pos + 1));
1658 if (!proxy_str.empty() && proxy_str !=
"0") {
1660 proxy =
Proxy{proxy_str, proxyRandomize};
1663 if (!addr.has_value()) {
1666 proxy =
Proxy{addr.value(), proxyRandomize};
1673 if (net_str.empty()) {
1674 ipv4_proxy = ipv6_proxy = name_proxy = cjdns_proxy = onion_proxy = proxy;
1675 }
else if (net_str ==
"ipv4") {
1676 ipv4_proxy = name_proxy = proxy;
1677 }
else if (net_str ==
"ipv6") {
1678 ipv6_proxy = name_proxy = proxy;
1679 }
else if (net_str ==
"tor" || net_str ==
"onion") {
1680 onion_proxy = proxy;
1681 }
else if (net_str ==
"cjdns") {
1682 cjdns_proxy = proxy;
1684 return InitError(
strprintf(
_(
"Unrecognized network in -proxy='%s': '%s'"), param_value, net_str));
1705 std::string onionArg =
args.
GetArg(
"-onion",
"");
1706 if (onionArg !=
"") {
1707 if (onionArg ==
"0") {
1708 onion_proxy =
Proxy{};
1709 if (onlynet_used_with_onion) {
1711 _(
"Outbound connections restricted to Tor (-onlynet=onion) but the proxy for "
1712 "reaching the Tor network is explicitly forbidden: -onion=0"));
1716 onion_proxy =
Proxy(onionArg, proxyRandomize);
1719 if (!addr.has_value() || !addr->IsValid()) {
1723 onion_proxy =
Proxy(addr.value(), proxyRandomize);
1734 if (onlynet_used_with_onion && listenonion_disabled) {
1736 _(
"Outbound connections restricted to Tor (-onlynet=onion) but the proxy for "
1737 "reaching the Tor network is not provided: none of -proxy, -onion or "
1738 "-listenonion is given"));
1743 for (
const std::string& strAddr :
args.
GetArgs(
"-externalip")) {
1745 if (addrLocal.has_value() && addrLocal->IsValid())
1753 [&chainman =
node.chainman](std::vector<std::byte>& block,
const CBlockIndex& index) {
1755 return chainman->m_blockman.ReadRawBlock(block, WITH_LOCK(cs_main, return index.GetBlockPos()));
1767 const auto [index_cache_sizes, kernel_cache_sizes] =
CalculateCacheSizes(
args, g_enabled_filter_types.size());
1769 LogInfo(
"Cache configuration:");
1770 LogInfo(
"* Using %.1f MiB for block index database", kernel_cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
1772 LogInfo(
"* Using %.1f MiB for transaction index database", index_cache_sizes.tx_index * (1.0 / 1024 / 1024));
1775 LogInfo(
"* Using %.1f MiB for %s block filter index database",
1778 LogInfo(
"* Using %.1f MiB for chain state database", kernel_cache_sizes.coins_db * (1.0 / 1024 / 1024));
1784 const bool do_reindex_chainstate{
args.
GetBoolArg(
"-reindex-chainstate",
false)};
1790 do_reindex_chainstate,
1795 bool do_retry{
HasTestOption(
args,
"reindex_after_failure_noninteractive_yes") ||
1797 error +
Untranslated(
".\n\n") +
_(
"Do you want to rebuild the databases now?"),
1798 error.original +
".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1804 if (!
Assert(
node.shutdown_signal)->reset()) {
1805 LogError(
"Internal error: failed to reset shutdown signal.\n");
1810 do_reindex_chainstate,
1814 if (status != ChainstateLoadStatus::SUCCESS && status != ChainstateLoadStatus::INTERRUPTED) {
1821 LogInfo(
"Shutdown requested. Exiting.");
1826 auto& kernel_notifications{*
Assert(
node.notifications)};
1830 node.banman.get(), chainman,
1833 validation_signals.RegisterValidationInterface(
node.peerman.get());
1842 for (
const auto& filter_type : g_enabled_filter_types) {
1853 for (
auto index :
node.indexes)
if (!index->Init())
return false;
1856 for (
const auto& client :
node.chain_clients) {
1857 if (!client->load()) {
1871 chainstate->PruneAndFlush();
1877 LogInfo(
"Setting NODE_NETWORK on non-prune mode");
1880 LogInfo(
"Running node in NODE_NETWORK_LIMITED mode until snapshot background sync completes");
1898 if (!do_reindex && !do_reindex_chainstate && chain_active_height <= 1) {
1900 uint64_t additional_bytes_needed{
1903 assumed_chain_bytes};
1907 "Disk space for %s may not accommodate the block files. " \
1908 "Approximately %u GB of data will be stored in this directory."
1917 auto check_and_warn_fs{[&](
const fs::path& path, std::string_view desc) {
1919 switch (GetFilesystemType(path)) {
1921 InitWarning(
strprintf(
_(
"The %s path uses exFAT, which is known to have intermittent corruption problems on macOS. "
1922 "Move this directory to a different filesystem to avoid data loss."), path_desc));
1925 LogInfo(
"Failed to detect filesystem type for %s", path_desc);
1937 const std::string block_notify =
args.
GetArg(
"-blocknotify",
"");
1938 if (!block_notify.empty()) {
1941 std::string
command = block_notify;
1943 std::thread
t(runCommand,
command);
1949 std::vector<fs::path> vImportFiles;
1950 for (
const std::string& strFile :
args.
GetArgs(
"-loadblock")) {
1959 LogInfo(
"Stopping after block import");
1961 LogError(
"Failed to send shutdown signal after finishing block import\n");
1968 bilingual_str err_str =
_(
"Failed to start indexes, shutting down…");
1991 WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
1992 kernel_notifications.m_tip_block_cv.wait(lock, [&]()
EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
1993 return kernel_notifications.TipBlock() || ShutdownRequested(node);
2003 int64_t best_block_time{};
2008 chain_active_height = tip.nHeight;
2009 best_block_time = tip.GetBlockTime();
2015 if (tip_info && chainman.m_best_header) {
2017 tip_info->
header_time = chainman.m_best_header->GetBlockTime();
2020 LogInfo(
"nBestHeight = %d", chain_active_height);
2021 if (
node.peerman)
node.peerman->SetBestBlock(chain_active_height, std::chrono::seconds{best_block_time});
2041 const uint16_t default_bind_port =
2044 const uint16_t default_bind_port_onion = default_bind_port + 1;
2046 const auto BadPortWarning = [](
const char*
prefix, uint16_t port) {
2047 return strprintf(
_(
"%s request to listen on port %u. This port is considered \"bad\" and "
2048 "thus it is unlikely that any peer will connect to it. See "
2049 "doc/p2p-bad-ports.md for details and a full list."),
2054 for (
const std::string& bind_arg :
args.
GetArgs(
"-bind")) {
2055 std::optional<CService> bind_addr;
2056 const size_t index = bind_arg.rfind(
'=');
2057 if (index == std::string::npos) {
2058 bind_addr =
Lookup(bind_arg, default_bind_port,
false);
2059 if (bind_addr.has_value()) {
2060 connOptions.
vBinds.push_back(bind_addr.value());
2061 if (
IsBadPort(bind_addr.value().GetPort())) {
2062 InitWarning(BadPortWarning(
"-bind", bind_addr.value().GetPort()));
2067 const std::string network_type = bind_arg.substr(index + 1);
2068 if (network_type ==
"onion") {
2069 const std::string truncated_bind_arg = bind_arg.substr(0, index);
2070 bind_addr =
Lookup(truncated_bind_arg, default_bind_port_onion,
false);
2071 if (bind_addr.has_value()) {
2072 connOptions.
onion_binds.push_back(bind_addr.value());
2080 for (
const std::string& strBind :
args.
GetArgs(
"-whitebind")) {
2102 onion_service_target = connOptions.
onion_binds.front();
2103 }
else if (!connOptions.
vBinds.empty()) {
2104 onion_service_target = connOptions.
vBinds.front();
2107 connOptions.
onion_binds.push_back(onion_service_target);
2113 "for the automatically created Tor onion service."),
2125 for (
const auto& net :
args.
GetArgs(
"-whitelist")) {
2146 if (connect.size() != 1 || connect[0] !=
"0") {
2150 LogInfo(
"-seednode is ignored when -connect is used");
2154 LogInfo(
"-dnsseed is ignored when -connect is used and -proxy is specified");
2158 const std::string& i2psam_arg =
args.
GetArg(
"-i2psam",
"");
2159 if (!i2psam_arg.empty()) {
2161 if (!addr.has_value() || !addr->IsValid()) {
2168 _(
"Outbound connections restricted to i2p (-onlynet=i2p) but "
2169 "-i2psam is not provided"));
2178 _(
"Duplicate binding configuration for address %s. "
2179 "Please check your -bind, -bind=...=onion and -whitebind settings."),
2180 conflict->ToStringAddrPort()));
2183 if (!
node.connman->Start(scheduler, connOptions)) {
2197 for (
const auto& client :
node.chain_clients) {
2198 client->start(scheduler);
2202 scheduler.scheduleEvery([banman]{
2206 if (
node.peerman)
node.peerman->StartScheduledTasks(scheduler);
2209 StartupNotify(
args);
2221 std::optional<const CBlockIndex*> indexes_start_block;
2222 std::string older_index_name;
2227 for (
auto index :
node.indexes) {
2229 if (summary.
synced)
continue;
2234 if (!index_chain.
Contains(pindex)) {
2235 pindex = index_chain.
FindFork(pindex);
2238 if (!indexes_start_block || !pindex || pindex->
nHeight < indexes_start_block.value()->nHeight) {
2239 indexes_start_block = pindex;
2240 older_index_name = summary.
name;
2246 if (indexes_start_block) {
2248 const CBlockIndex* start_block = *indexes_start_block;
2250 if (!chainman.
m_blockman.CheckBlockDataAvailability(*index_chain.
Tip(), *
Assert(start_block))) {
2251 return InitError(
Untranslated(
strprintf(
"%s best block of the index goes beyond pruned data. Please disable the index or reindex (which will download the whole blockchain again)", older_index_name)));
2256 for (
auto index :
node.indexes)
if (!index->StartBackgroundSync())
return false;
util::Result< std::unique_ptr< AddrMan > > LoadAddrman(const NetGroupManager &netgroupman, const ArgsManager &args)
Returns an error string on failure.
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS
Default for -checkaddrman.
const std::vector< std::string > TEST_OPTIONS_DOC
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
const char *const BITCOIN_SETTINGS_FILENAME
bool HasTestOption(const ArgsManager &args, const std::string &test_option)
Checks if a particular test option is present in -test command-line arg options.
const char *const BITCOIN_CONF_FILENAME
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...
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
How often to dump banned addresses/subnets to disk.
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
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.
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
bool InitBlockFilterIndex(std::function< std::unique_ptr< interfaces::Chain >()> make_chain, 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 ChainType 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 ChainType chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 48334, 18445) have been chosen arbitra...
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
static constexpr int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
static constexpr auto DEFAULT_MAX_TIP_AGE
std::string ChainTypeToString(ChainType chain)
#define Assert(val)
Identity function.
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...
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
@ ALLOW_ANY
disable validation
@ DISALLOW_NEGATION
disallow -nofoo syntax
@ DISALLOW_ELISION
disallow -foo syntax that doesn't assign any value
ChainType GetChainType() const
Returns the appropriate chain type from the program arguments.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
fs::path GetBlocksDirPath() const
Get blocks directory path.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
static std::shared_ptr< LogRateLimiter > Create(SchedulerFunction &&scheduler_func, uint64_t max_bytes, std::chrono::seconds reset_window)
void SetRateLimiting(std::shared_ptr< LogRateLimiter > limiter) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
std::atomic< bool > m_reopen_file
void DumpBanlist() EXCLUSIVE_LOCKS_REQUIRED(!m_banned_mutex)
The block chain is a tree shaped structure starting with the genesis block at the root,...
uint256 GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
void FlushFeeEstimates() EXCLUSIVE_LOCKS_REQUIRED(!m_cs_fee_estimator)
Record current fee estimations.
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
int Height() const
Return the maximal height in the chain.
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
std::string GetChainTypeString() const
Return the chain type string.
const MessageStartChars & MessageStart() const
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
uint64_t AssumedBlockchainSize() const
Minimum free space (in GB) needed for data directory.
ChainType GetChainType() const
Return the chain type.
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToStringAddrPort() const
static const int DEFAULT_ZMQ_SNDHWM
static std::unique_ptr< CZMQNotificationInterface > Create(std::function< bool(std::vector< std::byte > &, const CBlockIndex &)> get_block_by_index)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
CChain m_chain
The current chain of blockheaders we consult and build on.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
double GuessVerificationProgress(const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
kernel::Notifications & GetNotifications() const
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
const util::SignalInterrupt & m_interrupt
std::function< void()> snapshot_download_completed
Function to restart active indexes; set dynamically to avoid a circular dependency on base/index....
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
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...
uint64_t rand64() noexcept
Generate a random 64-bit integer.
A writer stream (for serialization) that computes a 256-bit hash.
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, node::Warnings &warnings, Options opts)
void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
void Remove(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
void RemoveAll() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
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.
std::string ToString() const
std::string GetHex() const
Interface providing access to interprocess-communication (IPC) functionality.
Exception class thrown when a call to remote method fails due to an IPC error, like a socket getting ...
A base class defining functions for notifying about certain kernel events.
virtual void fatalError(const bilingual_str &message)
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::atomic_bool m_blockfiles_indexed
Whether all blockfiles have been added to the block tree database.
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
bool CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND, const CBlockIndex &lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, uint32_t status_mask, const CBlockIndex *lower_block=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(boo m_have_pruned)
Check if all blocks in the [upper_block, lower_block] range have data available.
bool IsPruneMode() const
Whether running in -prune mode.
std::string FormatSubVersion(const std::string &name, int nClientVersion, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip...
const std::string UA_NAME
static const int CLIENT_VERSION
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static constexpr bool DEFAULT_COINSTATSINDEX
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
const std::string CURRENCY_UNIT
fs::path FeeestPath(const ArgsManager &argsman)
static auto quoted(const std::string &s)
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to a byte string.
static path PathFromString(const std::string &string)
Convert byte string to path object.
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)
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
void StopHTTPRPC()
Stop HTTP RPC subsystem.
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
void StartREST(const std::any &context)
Start HTTP REST subsystem.
void StopREST()
Stop HTTP REST subsystem.
void InterruptREST()
Interrupt RPC REST subsystem.
void InterruptHTTPServer()
Interrupt HTTP server threads.
void StartHTTPServer()
Start HTTP server.
bool InitHTTPServer(const util::SignalInterrupt &interrupt)
Initialize HTTP server.
void StopHTTPServer()
Stop HTTP server.
static const int DEFAULT_HTTP_SERVER_TIMEOUT
static const int DEFAULT_HTTP_WORKQUEUE
The default value for -rpcworkqueue.
static const int DEFAULT_HTTP_THREADS
The default value for -rpcthreads.
Common init functions shared by bitcoin-node, bitcoin-wallet, etc.
static bool LockDirectory(const fs::path &dir, bool probeOnly)
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
static bool CreatePidFile(const ArgsManager &args)
static bool g_generated_pid
True if this process has created a PID file.
static std::optional< util::SignalInterrupt > g_shutdown
static void RemovePidFile(const ArgsManager &args)
void Interrupt(NodeContext &node)
Interrupt threads.
void InitLogging(const ArgsManager &args)
Initialize global loggers.
static bool AppInitServers(NodeContext &node)
static bool LockDirectories(bool probeOnly)
static constexpr int MIN_CORE_FDS
void Shutdown(NodeContext &node)
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
static void HandleSIGHUP(int)
bool AppInitBasicSetup(const ArgsManager &args, std::atomic< int > &exit_status)
Initialize bitcoin core: Basic context setup.
static fs::path GetPidFile(const ArgsManager &args)
static constexpr bool DEFAULT_PROXYRANDOMIZE
bool CheckHostPortOptions(const ArgsManager &args)
static std::optional< CService > CheckBindingConflicts(const CConnman::Options &conn_options)
Checks for duplicate bindings across all binding configurations.
static ChainstateLoadResult InitAndLoadChainstate(NodeContext &node, bool do_reindex, const bool do_reindex_chainstate, const kernel::CacheSizes &cache_sizes, const ArgsManager &args)
bool ShutdownRequested(node::NodeContext &node)
Return whether node shutdown was requested.
bool StartIndexBackgroundSync(NodeContext &node)
Validates requirements to run the indexes and spawns each index initial sync thread.
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
static const char * DEFAULT_ASMAP_FILENAME
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
static constexpr bool DEFAULT_REST_ENABLE
static void registerSignalHandler(int signal, void(*handler)(int))
bool AppInitMain(NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
static constexpr bool DEFAULT_I2P_ACCEPT_INCOMING
bool AppInitLockDirectories()
Lock bitcoin core critical directories.
void SetupServerArgs(ArgsManager &argsman, bool can_listen_ipc)
Register all arguments with the ArgsManager.
void InitContext(NodeContext &node)
Initialize node context shutdown and args variables.
static void new_handler_terminate()
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
static constexpr bool DEFAULT_DAEMON
Default value for -daemon option.
static constexpr bool DEFAULT_DAEMONWAIT
Default value for -daemonwait option.
CClientUIInterface uiInterface
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
BCLog::Logger & LogInstance()
#define LogDebug(category,...)
void StartMapPort(bool enable)
static constexpr bool DEFAULT_NATPMP
static constexpr unsigned int DEFAULT_MAX_MEMPOOL_SIZE_MB
Default for -maxmempool, maximum megabytes of mempool memory usage.
static constexpr bool DEFAULT_ACCEPT_NON_STD_TXN
Default for -acceptnonstdtxn.
static constexpr unsigned int DEFAULT_MEMPOOL_EXPIRY_HOURS
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
static constexpr unsigned int DEFAULT_BLOCKSONLY_MAX_MEMPOOL_SIZE_MB
Default for -maxmempool when blocksonly is set.
static constexpr bool DEFAULT_PERSIST_V1_DAT
Whether to fall back to legacy V1 serialization when writing mempool.dat.
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
constexpr auto RATELIMIT_WINDOW
constexpr bool DEFAULT_LOGRATELIMIT
constexpr uint64_t RATELIMIT_MAX_BYTES
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
bilingual_str InvalidPortErrMsg(const std::string &optname, const std::string &invalid_value)
void AddLoggingArgs(ArgsManager &argsman)
util::Result< void > SetLoggingCategories(const ArgsManager &args)
bool StartLogging(const ArgsManager &args)
util::Result< void > SetLoggingLevel(const ArgsManager &args)
void SetLoggingOptions(const ArgsManager &args)
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
static constexpr bool DEFAULT_XOR_BLOCKSDIR
util::Result< void > SanityChecks(const Context &)
Ensure a usable environment with all necessary library support.
ChainstateLoadStatus
Chainstate load status.
@ FAILURE
Generic failure which reindexing may fix.
std::tuple< ChainstateLoadStatus, bilingual_str > ChainstateLoadResult
Chainstate load status code and optional error string.
CacheSizes CalculateCacheSizes(const ArgsManager &args, size_t n_indexes)
fs::path MempoolPath(const ArgsManager &argsman)
void LogOversizedDbCache(const ArgsManager &args) noexcept
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
static const bool DEFAULT_PRINT_MODIFIED_FEE
bool ShouldPersistMempool(const ArgsManager &argsman)
void ReadNotificationArgs(const ArgsManager &args, KernelNotifications ¬ifications)
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
bool LoadMempool(CTxMemPool &pool, const fs::path &load_path, Chainstate &active_chainstate, ImportMempoolOptions &&opts)
Import the file and attempt to add its contents to the mempool.
static constexpr bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool, indicating whether the node should attempt to automatically load the mem...
static constexpr int DEFAULT_STOPATHEIGHT
void ImportBlocks(ChainstateManager &chainman, std::span< const fs::path > import_paths)
bool DumpMempool(const CTxMemPool &pool, const fs::path &dump_path, FopenFn mockable_fopen_function, bool skip_file_commit)
void ThreadRename(const std::string &)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
bilingual_str ErrorString(const Result< T > &result)
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
LockResult LockDirectory(const fs::path &directory, const fs::path &lockfile_name, bool probe_only)
bool AddLocal(const CService &addr_, int nScore)
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
static const size_t DEFAULT_MAXSENDBUFFER
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
static constexpr bool DEFAULT_FIXEDSEEDS
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
static const size_t DEFAULT_MAXRECEIVEBUFFER
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
static constexpr bool DEFAULT_FORCEDNSSEED
static constexpr bool DEFAULT_DNSSEED
static const bool DEFAULT_LISTEN
-listen default
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
static constexpr bool DEFAULT_V2_TRANSPORT
const std::vector< std::string > NET_PERMISSIONS_DOC
constexpr bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
constexpr 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 constexpr bool DEFAULT_TXRECONCILIATION_ENABLE
Whether transaction reconciliation protocol should be enabled by default.
static const bool DEFAULT_PEERBLOCKFILTERS
static const bool DEFAULT_PEERBLOOMFILTERS
@ NET_ONION
TOR (v2 or v3)
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
bool SetNameProxy(const Proxy &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
enum Network ParseNetwork(const std::string &net_in)
bool SetProxy(enum Network net, const Proxy &addrProxy)
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
ReachableNets g_reachable_nets
bool IsUnixSocketPath(const std::string &name)
Check if a string is a valid UNIX domain socket path.
bool IsBadPort(uint16_t port)
Determine if a port is "bad" from the perspective of attempting to connect to a node on that port.
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
static const int DEFAULT_NAME_LOOKUP
-dns default
const std::string ADDR_PREFIX_UNIX
Prefix for unix domain socket addresses (which are local filesystem paths)
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
static constexpr size_t MIN_DB_CACHE
min. -dbcache (bytes)
static constexpr size_t DEFAULT_DB_CACHE
-dbcache default (bytes)
static constexpr bool DEFAULT_ACCEPT_STALE_FEE_ESTIMATES
static constexpr std::chrono::hours MAX_FILE_AGE
fee_estimates.dat that are more than 60 hours (2.5 days) old will not be read, as fee estimates are b...
static constexpr std::chrono::hours FEE_FLUSH_INTERVAL
unsigned int nBytesPerSigOp
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for -datacarriersize in vbytes.
static constexpr unsigned int DEFAULT_BLOCK_MIN_TX_FEE
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
static constexpr unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT_KVB
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
static constexpr bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
static constexpr unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
static constexpr unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
static constexpr unsigned int DEFAULT_BYTES_PER_SIGOP
Default for -bytespersigop.
static constexpr unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT_KVB
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
static constexpr unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create.
static constexpr unsigned int DEFAULT_BLOCK_RESERVED_WEIGHT
Default for -blockreservedweight.
static const bool DEFAULT_ACCEPT_DATACARRIER
Default for -datacarrier.
static constexpr unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
static constexpr unsigned int MINIMUM_BLOCK_RESERVED_WEIGHT
This accounts for the block header, var_int encoding of the transaction count and a minimally viable ...
static constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
ServiceFlags
nServices flags
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
static void RegisterAllCoreRPCCommands(CRPCTable &t)
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
static constexpr bool DEFAULT_RPC_DOC_CHECK
void SetRPCWarmupFinished()
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
static constexpr size_t DEFAULT_VALIDATION_CACHE_BYTES
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
unsigned int nReceiveFloodSize
std::vector< NetWhitebindPermissions > vWhiteBinds
uint64_t nMaxOutboundLimit
CClientUIInterface * uiInterface
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
std::vector< CService > onion_binds
std::vector< std::string > m_specified_outgoing
NetEventsInterface * m_msgproc
std::vector< std::string > m_added_nodes
int64_t m_peer_connect_timeout
std::vector< CService > vBinds
unsigned int nSendBufferMaxSize
int m_max_automatic_connections
ServiceFlags m_local_services
bool m_i2p_accept_incoming
std::vector< std::string > vSeedNodes
bool m_use_addrman_outgoing
bool whitelist_forcerelay
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Application-specific storage settings.
fs::path path
Location in the filesystem where leveldb data will be stored.
Block and header tip information.
double verification_progress
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
const CChainParams & chainparams
Context struct holding the kernel library's logically global state, and passed to external libbitcoin...
Options struct containing options for constructing a CTxMemPool.
bool require_full_verification
Setting require_full_verification to true will require all checks at check_level (below) to succeed f...
std::function< void()> coins_error_cb
NodeContext struct containing references to chain state and connection state.
#define WAIT_LOCK(cs, name)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define TRY_LOCK(cs, name)
std::string SysErrorString(int err)
Return system error string from errno value.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
const std::string DEFAULT_TOR_CONTROL
Default control ip and port.
void InterruptTorControl()
CService DefaultOnionServiceTarget(uint16_t port)
void StartTorControl(CService onion_service_target)
constexpr uint16_t DEFAULT_TOR_SOCKS_PORT
Functionality for communicating with Tor.
static const bool DEFAULT_LISTEN_ONION
constexpr int DEFAULT_TOR_CONTROL_PORT
consteval auto _(util::TranslatedLiteral str)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
static const int64_t nDefaultDbBatchSize
-dbbatchsize default (bytes)
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
static constexpr bool DEFAULT_TXINDEX
std::vector< bool > DecodeAsmap(fs::path path)
Read asmap from provided binary file.
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
std::optional< uint64_t > ParseByteUnits(std::string_view str, ByteUnit default_multiplier)
Parse a string with suffix unit [k|K|m|M|g|G|t|T].
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
static constexpr int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
static constexpr int DEFAULT_CHECKLEVEL
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
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...
SynchronizationState
Current sync state passed to tip changed callbacks.
static const signed int DEFAULT_CHECKBLOCKS
const WalletInitInterface & g_wallet_init_interface
std::unique_ptr< CZMQNotificationInterface > g_zmq_notification_interface
void RegisterZMQRPCCommands(CRPCTable &t)