6#include <bitcoin-build-config.h>
112#include <condition_variable>
126#include <system_error>
142#ifdef ENABLE_EMBEDDED_ASMAP
143#include <node/data/ip_asn.dat.h>
180#define MIN_LEVELDB_FDS 0
182#define MIN_LEVELDB_FDS 150
224 if (std::error_code error; !fs::remove(pid_path, error)) {
225 std::string msg{error ? error.message() :
"File does not exist"};
226 LogWarning(
"Unable to remove PID file (%s): %s", fs::PathToString(pid_path), msg);
241 if (!(*
node.shutdown_signal)())
return false;
277 std::vector<std::thread> threads;
279 threads.emplace_back(runCommand,
cmd);
281 for (
auto& t : threads) {
290 ShutdownNotify(*
node.args);
293 if (
node.notifications)
WITH_LOCK(
node.notifications->m_tip_block_mutex,
node.notifications->m_tip_block_cv.notify_all());
298 if (
node.tor_controller) {
299 node.tor_controller->Interrupt();
303 node.connman->Interrupt();
304 for (
auto* index :
node.indexes) {
311 static Mutex g_shutdown_mutex;
312 TRY_LOCK(g_shutdown_mutex, lock_shutdown);
313 if (!lock_shutdown)
return;
314 LogInfo(
"Shutdown in progress...");
322 if (
node.mempool)
node.mempool->AddTransactionsUpdated(1);
328 for (
auto& client :
node.chain_clients) {
340 if (
node.peerman &&
node.validation_signals)
node.validation_signals->UnregisterValidationInterface(
node.peerman.get());
341 if (
node.connman)
node.connman->Stop();
343 if (
node.tor_controller) {
344 node.tor_controller->Join();
345 node.tor_controller.reset();
348 if (
node.background_init_thread.joinable())
node.background_init_thread.join();
352 if (
node.scheduler)
node.scheduler->stop();
356 node.peerman.reset();
357 node.connman.reset();
359 node.addrman.reset();
360 node.netgroupman.reset();
369 for (
const auto& chainstate :
node.chainman->m_chainstates) {
370 if (chainstate->CanFlushToDisk()) {
371 chainstate->ForceFlushStateToDisk();
378 if (
node.validation_signals)
node.validation_signals->FlushBackgroundCallbacks();
381 if (
node.fee_estimator_man) {
382 node.fee_estimator_man->ShutdownFlush();
383 if (
node.validation_signals) {
384 node.validation_signals->UnregisterValidationInterface(
node.fee_estimator_man.get());
389 for (
auto* index :
node.indexes) index->Stop();
394 node.indexes.clear();
399 for (
const auto& chainstate :
node.chainman->m_chainstates) {
400 if (chainstate->CanFlushToDisk()) {
401 chainstate->ForceFlushStateToDisk();
402 chainstate->ResetCoinsViews();
410 ipc->disconnectIncoming();
420 node.chain_clients.clear();
421 if (
node.validation_signals) {
422 node.validation_signals->UnregisterAllValidationInterfaces();
424 node.fee_estimator_man.reset();
425 node.mempool.reset();
426 node.chainman.reset();
427 node.validation_signals.reset();
428 node.scheduler.reset();
429 node.ecc_context.reset();
455static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
458 LogError(
"Failed to send shutdown signal on Ctrl-C\n");
470 sa.sa_handler = handler;
471 sigemptyset(&sa.sa_mask);
473 sigaction(signal, &sa,
nullptr);
496 std::vector<std::string> hidden_args = {
497 "-dbcrashratio",
"-forcecompactdb",
499 "-choosedatadir",
"-lang=<lang>",
"-min",
"-resetguisettings",
"-splash",
"-uiplatform"};
505 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);
507 argsman.
AddArg(
"-blocksxor",
508 strprintf(
"Whether an XOR-key applies to blocksdir *.dat files. "
509 "The created XOR-key will be zeros for an existing blocksdir or when `-blocksxor=0` is "
510 "set, and random for a freshly initialized blocksdir. "
530 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);
531 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)",
535 argsman.
AddArg(
"-persistmempoolv1",
536 strprintf(
"Whether a mempool.dat file created by -persistmempool or the savemempool RPC will be written in the legacy format "
537 "(version 1) or the current format (version 2). This temporary option will be removed in the future. (default: %u)",
541 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. "
542 "Warning: Reverting this setting requires re-downloading the entire blockchain. Wallets and indexes should be loaded at startup and kept active while pruning is enabled so they stay synchronized before old block data is deleted; wallets or indexes that fall behind pruned data may require a reindex. "
544 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);
545 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);
549 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);
553 argsman.
AddArg(
"-blockfilterindex=<type>",
555 " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
559 argsman.
AddArg(
"-asmap=<file>",
strprintf(
"Specify asn mapping used for bucketing of the peers. Relative paths will be prefixed by the net-specific datadir location.%s",
560 #ifdef ENABLE_EMBEDDED_ASMAP
561 " If a bool arg is given (-asmap or -asmap=1), the embedded mapping data in the binary will be used."
567 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);
578 argsman.
AddArg(
"-maxconnections=<n>",
strprintf(
"Maintain at most <n> automatic connections to peers (default: %u, maximum: %u). %u slots of these are reserved for outgoing connections. See -inboundrelaypercent for more information about limits applied to transaction relay inbound peers. "
579 "This limit does not apply to connections manually added via -addnode or the addnode RPC, which have a separate limit of %u. "
580 "It does not apply to short-lived private broadcast connections either, which have a separate limit of %u.",
587#ifdef HAVE_SOCKADDR_UN
599 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);
600 const std::string proxy_doc_for_value =
601#ifdef HAVE_SOCKADDR_UN
602 "<ip>[:<port>]|unix:<path>";
606 const std::string proxy_doc_for_unix_socket =
607#ifdef HAVE_SOCKADDR_UN
608 "May be a local file path prefixed with 'unix:' if the proxy supports it. ";
612 argsman.
AddArg(
"-proxy=" + proxy_doc_for_value +
"[=<network>]",
613 "Connect through SOCKS5 proxy, set -noproxy to disable. " +
614 proxy_doc_for_unix_socket +
615 "Could end in =network to set the proxy only for that network. " +
617 "(default: disabled)",
621 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);
628 argsman.
AddArg(
"-whitebind=<[permissions@]addr>",
"Bind to the given address and add permission flags to the peers connecting to it. "
632 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 "
633 "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as "
635 "Additional flags \"in\" and \"out\" control whether permissions apply to incoming connections and/or manual (default: incoming only). "
652 hidden_args.emplace_back(
"-zmqpubhashblock=<address>");
653 hidden_args.emplace_back(
"-zmqpubhashtx=<address>");
654 hidden_args.emplace_back(
"-zmqpubrawblock=<address>");
655 hidden_args.emplace_back(
"-zmqpubrawtx=<address>");
656 hidden_args.emplace_back(
"-zmqpubsequence=<n>");
657 hidden_args.emplace_back(
"-zmqpubhashblockhwm=<n>");
658 hidden_args.emplace_back(
"-zmqpubhashtxhwm=<n>");
659 hidden_args.emplace_back(
"-zmqpubrawblockhwm=<n>");
660 hidden_args.emplace_back(
"-zmqpubrawtxhwm=<n>");
661 hidden_args.emplace_back(
"-zmqpubsequencehwm=<n>");
687 argsman.
AddArg(
"-maxtipage=<n>",
688 strprintf(
"Maximum tip age in seconds to consider node in initial block download (default: %u)",
702 argsman.
AddArg(
"-datacarriersize",
703 strprintf(
"Relay and mine transactions whose data-carrying raw scriptPubKeys in aggregate "
704 "are of this size or less, allowing multiple outputs (default: %u)",
709 argsman.
AddArg(
"-minrelaytxfee=<amt>",
strprintf(
"Fees (in %s/kvB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
711 argsman.
AddArg(
"-txsendrate=<n>",
712 strprintf(
"Set the maximum ongoing rate for sending transactions to (inbound) peers (default: %u tx/s)",
715 argsman.
AddArg(
"-privatebroadcast",
717 "EXPERIMENTAL: Broadcast transactions submitted via sendrawtransaction RPC using short-lived "
718 "connections through the Tor or I2P networks, without putting them in the mempool first. "
719 "This provides best-effort concealment of the transaction's origin. "
720 "Transactions submitted through the wallet are not affected by this option "
735 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);
736 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);
737 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);
743 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);
747 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);
748 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);
751 if (can_listen_ipc) {
752 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. Enabling this gives local processes that can access the socket unauthenticated RPC access, so it's important to choose a path with secure permissions if customizing this.",
ArgsManager::ALLOW_ANY,
OptionsCategory::IPC);
759 hidden_args.emplace_back(
"-daemon");
760 hidden_args.emplace_back(
"-daemonwait");
772 std::thread
t(runCommand,
cmd);
800 LogInfo(
"parameter interaction: -bind set -> setting -listen=1\n");
804 LogInfo(
"parameter interaction: -whitebind set -> setting -listen=1\n");
811 LogInfo(
"parameter interaction: -connect or -maxconnections=0 set -> setting -dnsseed=0\n");
813 LogInfo(
"parameter interaction: -connect or -maxconnections=0 set -> setting -listen=0\n");
816 std::string proxy_arg =
args.
GetArg(
"-proxy",
"");
817 if (proxy_arg !=
"" && proxy_arg !=
"0") {
820 LogInfo(
"parameter interaction: -proxy set -> setting -listen=0\n");
824 LogInfo(
"parameter interaction: -proxy set -> setting -natpmp=0\n");
828 LogInfo(
"parameter interaction: -proxy set -> setting -discover=0\n");
834 LogInfo(
"parameter interaction: -listen=0 -> setting -natpmp=0\n");
837 LogInfo(
"parameter interaction: -listen=0 -> setting -discover=0\n");
839 LogInfo(
"parameter interaction: -listen=0 -> setting -listenonion=0\n");
841 LogInfo(
"parameter interaction: -listen=0 -> setting -i2pacceptincoming=0\n");
848 LogInfo(
"parameter interaction: -externalip set -> setting -discover=0\n");
854 LogInfo(
"parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n");
863 LogInfo(
"parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n");
866 if (!onlynets.empty()) {
867 bool clearnet_reachable = std::any_of(onlynets.begin(), onlynets.end(), [](
const auto& net) {
868 const auto n = ParseNetwork(net);
869 return n == NET_IPV4 || n == NET_IPV6;
872 LogInfo(
"parameter interaction: -onlynet excludes IPv4 and IPv6 -> setting -dnsseed=0\n");
891int num_p2p_max_connections;
894int64_t peer_connect_timeout;
895std::set<BlockFilterType> g_enabled_filter_types;
905 std::set_new_handler(std::terminate);
906 LogError(
"Out of memory. Terminating.\n");
917 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
918 _CrtSetReportFile(_CRT_WARN, CreateFileA(
"NUL", GENERIC_WRITE, 0,
nullptr, OPEN_EXISTING, 0, 0));
920 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
924 HeapSetInformation(
nullptr, HeapEnableTerminationOnCorruption,
nullptr, 0);
939 signal(SIGPIPE, SIG_IGN);
941 SetConsoleCtrlHandler(consoleCtrlHandler,
true);
958 InitWarning(
_(
"Option '-checkpoints' is set but checkpoints were removed. This option has no effect."));
961 InitWarning(
_(
"Option '-limitancestorsize' is given but ancestor size limits have been replaced with cluster size limits (see -limitclustersize). This option has no effect."));
964 InitWarning(
_(
"Option '-limitdescendantsize' is given but descendant size limits have been replaced with cluster size limits (see -limitclustersize). This option has no effect."));
979 if (!errors.
empty()) {
985 LogInfo(
"Warning: Support for testnet3 is deprecated and will be removed in an upcoming release. Consider switching to testnet4.\n");
994 if (!warnings.
empty()) {
1004 if (blockfilterindex_value ==
"" || blockfilterindex_value ==
"1") {
1006 }
else if (blockfilterindex_value !=
"0") {
1007 const std::vector<std::string> names =
args.
GetArgs(
"-blockfilterindex");
1008 for (
const auto& name : names) {
1013 g_enabled_filter_types.insert(filter_type);
1025 return InitError(
_(
"Cannot set -peerblockfilters without -blockfilterindex."));
1033 return InitError(
_(
"Prune mode is incompatible with -txindex."));
1035 return InitError(
_(
"Prune mode is incompatible with -txospenderindex."));
1037 return InitError(
_(
"Prune mode is incompatible with -reindex-chainstate. Use full -reindex instead."));
1043 return InitError(
_(
"Cannot set -forcednsseed to true when setting -dnsseed to false."));
1061 int num_p2p_bind = std::max(num_user_p2p_bind,
size_t(1));
1064 if (user_p2p_max_connections < 0) {
1078 int num_rpc_bind = std::max(
args.
GetArgs(
"-rpcbind").size(),
size_t(2));
1081 if (user_rpc_max_connections < 1) {
1082 return InitError(
Untranslated(
"-rpcmaxconnections must be greater than zero. Use -server=0 to disable HTTP."));
1086 user_rpc_max_connections = 0;
1096 user_rpc_max_connections +
1097 user_p2p_max_connections +
1098 static_cast<int64_t
>(max_private);
1099 if (total_fds > std::numeric_limits<int>::max()) {
1100 return InitError(
Untranslated(
"Too many file descriptors requested. Try lower values for -rpcmaxconnections "
1101 "or -maxconnections, or fewer settings of "
1102 "-rpcbind, -bind and -whitebind"));
1110 user_rpc_max_connections;
1116 available_fds = std::min(FD_SETSIZE, available_fds);
1119 if (available_fds < min_required_fds)
1120 return InitError(
strprintf(
_(
"Not enough file descriptors available. %d available, %d required."), available_fds, min_required_fds));
1123 if (available_fds < total_fds) {
1127 "Try reducing -rpcmaxconnections or using the default value of %d"),
1133 num_p2p_max_connections = std::min(available_fds - min_required_fds, user_p2p_max_connections);
1135 if (num_p2p_max_connections < user_p2p_max_connections)
1136 InitWarning(
strprintf(
_(
"Reducing -maxconnections from %d to %d, because of system limitations."), user_p2p_max_connections, num_p2p_max_connections));
1148 if (peer_connect_timeout <= 0) {
1153 if (!mining_result) {
1169 const std::vector<std::string> test_options =
args.
GetArgs(
"-test");
1170 if (!test_options.empty()) {
1174 for (
const std::string& option : test_options) {
1176 size_t pos = doc_option.find(
" (");
1177 return (pos != std::string::npos) && (doc_option.substr(0, pos) == option);
1188 return InitError(
_(
"The -testactivationheight option may not be used on mainnet."));
1191 return InitError(
_(
"The -vbparams option may not be used on mainnet."));
1199 .chainparams = chainparams,
1201 .notifications = notifications,
1204 if (!chainman_result) {
1217 if (!blockman_result) {
1222 if (!mempool_result) {
1235 return InitError(
strprintf(
_(
"Cannot write to directory '%s'; check permissions."), fs::PathToString(dir)));
1237 return InitError(
strprintf(
_(
"Cannot obtain a lock on directory %s. %s is probably already running."), fs::PathToString(dir), CLIENT_NAME));
1254 return InitError(
strprintf(
_(
"Initialization sanity check failed. %s is shutting down."), CLIENT_NAME));
1258 return InitError(
strprintf(
_(
"Elliptic curve cryptography sanity check failure. %s is shutting down."), CLIENT_NAME));
1289 for (
const std::string port_option : {
1293 if (
const auto port{
args.
GetArg(port_option)}) {
1295 if (!n || *n == 0) {
1301 for ([[maybe_unused]]
const auto& [param_name, unix, suffix_allowed] : std::vector<std::tuple<std::string, bool, bool>>{
1303 {
"-i2psam",
false,
false},
1304 {
"-onion",
true,
false},
1305 {
"-proxy",
true,
true},
1306 {
"-bind",
false,
true},
1307 {
"-rpcbind",
false,
false},
1308 {
"-torcontrol",
false,
false},
1309 {
"-whitebind",
false,
false},
1310 {
"-zmqpubhashblock",
true,
false},
1311 {
"-zmqpubhashtx",
true,
false},
1312 {
"-zmqpubrawblock",
true,
false},
1313 {
"-zmqpubrawtx",
true,
false},
1314 {
"-zmqpubsequence",
true,
false},
1316 for (
const std::string& param_value :
args.
GetArgs(param_name)) {
1317 const std::string param_value_hostport{
1318 suffix_allowed ? param_value.substr(0, param_value.rfind(
'=')) : param_value};
1319 std::string host_out;
1320 uint16_t port_out{0};
1321 if (!
SplitHostPort(param_value_hostport, port_out, host_out)) {
1322#ifdef HAVE_SOCKADDR_UN
1345 std::set<CService> seen;
1349 if (!seen.insert(wb.m_service).second) {
1350 return wb.m_service;
1355 for (
const auto& bind : conn_options.
vBinds) {
1356 if (!seen.insert(bind).second) {
1362 for (
const auto& onion_bind : conn_options.
onion_binds) {
1363 if (!seen.insert(onion_bind).second) {
1368 return std::nullopt;
1376 const bool do_reindex_chainstate,
1381 node.notifications->setChainstateLoaded(
false);
1382 node.mempool.reset();
1383 node.chainman.reset();
1389 .signals =
node.validation_signals.get(),
1394 node.mempool = std::make_unique<CTxMemPool>(mempool_opts, mempool_error);
1395 if (!mempool_error.
empty()) {
1396 return {ChainstateLoadStatus::FAILURE_FATAL, mempool_error};
1400 node.mining_args = std::move(*mining_args);
1401 LogInfo(
"* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)",
1402 cache_sizes.
coins /
double(1_MiB),
1405 .chainparams = chainparams,
1407 .notifications = *
node.notifications,
1408 .signals =
node.validation_signals.get(),
1419 .wipe_data = do_reindex,
1429 node.chainman = std::make_unique<ChainstateManager>(*
Assert(
node.shutdown_signal), chainman_opts, blockman_opts);
1432 return {ChainstateLoadStatus::FAILURE,
_(
"Error opening block database")};
1433 }
catch (std::exception& e) {
1434 return {ChainstateLoadStatus::FAILURE_FATAL,
Untranslated(
strprintf(
"Failed to initialize ChainstateManager: %s", e.what()))};
1437 if (chainman.
m_interrupt)
return {ChainstateLoadStatus::INTERRUPTED, {}};
1443 if (!
node.chainman->m_blockman.IsPruneMode()) {
1444 LogInfo(
"[snapshot] re-enabling NODE_NETWORK services");
1447 LogInfo(
"[snapshot] restarting indexes");
1450 Assert(
node.validation_signals)->SyncWithValidationInterfaceQueue();
1451 for (
auto* index :
node.indexes) {
1454 if (!(index->Init() && index->StartBackgroundSync())) {
1455 LogWarning(
"[snapshot] Failed to restart index %s on snapshot chain", index->GetName());
1468 _(
"Error reading from database, shutting down."),
1475 }
catch (
const std::exception& e) {
1480 auto [status, error] = catch_exceptions([&] {
return LoadChainstate(chainman, cache_sizes, options); });
1484 LogWarning(
"pruned datadir may not have more than %d blocks; only checking available blocks\n",
1489 LogInfo(
"Block index and chainstate loaded");
1490 node.notifications->setChainstateLoaded(
true);
1493 return {status, error};
1502 if (!opt_max_upload) {
1516 LogInfo(
"Using at most %i automatic connections (%i file descriptors available)", num_p2p_max_connections, available_fds);
1520 LogWarning(
"Relative datadir option '%s' specified, which will be interpreted relative to the "
1521 "current working directory '%s'. This is fragile, because if bitcoin is started in the future "
1522 "from a different location, it will be unable to locate the current data files. There could "
1523 "also be data loss if bitcoin is started while in a temporary directory.",
1524 args.
GetArg(
"-datadir",
""), fs::PathToString(fs::current_path()));
1528 node.scheduler = std::make_unique<CScheduler>();
1529 auto& scheduler = *
node.scheduler;
1532 scheduler.m_service_thread = std::thread(
util::TraceThread,
"scheduler", [&] { scheduler.serviceQueue(); });
1535 scheduler.scheduleEvery([]{
1537 }, std::chrono::minutes{1});
1540 scheduler.scheduleEvery([&
args, &
node]{
1541 constexpr uint64_t min_disk_space{50_MiB};
1543 LogError(
"Shutting down due to lack of disk space!\n");
1545 LogError(
"Failed to send shutdown signal after disk space check\n");
1548 }, std::chrono::minutes{5});
1552 [&scheduler](
auto func,
auto window) { scheduler.scheduleEvery(std::move(func), window); },
1556 LogInfo(
"Log rate limiting disabled");
1560 node.validation_signals = std::make_unique<ValidationSignals>(std::make_unique<SerialTaskRunner>(scheduler));
1561 auto& validation_signals = *
node.validation_signals;
1568 ReadNotificationArgs(
args, *
node.notifications);
1578 for (std::string address :
gArgs.
GetArgs(
"-ipcbind")) {
1580 ipc->listenAddress(address);
1581 }
catch (
const std::exception& e) {
1584 LogInfo(
"Listening for IPC requests on address %s", address);
1591 RegisterAllCoreRPCCommands(
tableRPC);
1592 for (
const auto& client :
node.chain_clients) {
1593 client->registerRpcs();
1605 if (!onlynets.empty()) {
1607 for (
const std::string& snet : onlynets) {
1618 _(
"Outbound connections restricted to CJDNS (-onlynet=cjdns) but "
1619 "-cjdnsreachable is not provided"));
1636 return InitError(
_(
"Unable to start HTTP server. See debug log for details."));
1640 for (
const auto& client :
node.chain_clients) {
1641 if (!client->verify()) {
1665 if (!asmap_path.is_absolute()) {
1671 if (!fs::exists(asmap_path)) {
1672 InitError(
strprintf(
_(
"Could not find asmap file %s"), fs::quoted(fs::PathToString(asmap_path))));
1677 std::vector<std::byte> asmap{
DecodeAsmap(asmap_path)};
1678 if (asmap.empty()) {
1679 InitError(
strprintf(
_(
"Could not parse asmap file %s"), fs::quoted(fs::PathToString(asmap_path))));
1684 #ifdef ENABLE_EMBEDDED_ASMAP
1686 std::span<const std::byte> asmap{node::data::ip_asn};
1692 LogInfo(
"Opened asmap data (%zu bytes) from embedded byte array\n", asmap.size());
1700 LogInfo(
"Using asmap version %s for IP bucketing",
HexStr(
node.netgroupman->GetAsmapVersion()));
1703 LogInfo(
"Using /16 prefix for IP bucketing");
1711 node.addrman = std::move(*addrman);
1722 for (
const std::string& socket_addr :
args.
GetArgs(
"-bind")) {
1723 std::string host_out;
1724 uint16_t port_out{0};
1725 std::string bind_socket_addr = socket_addr.substr(0, socket_addr.rfind(
'='));
1732 std::vector<std::string> uacomments;
1733 for (
const std::string& cmt :
args.
GetArgs(
"-uacomment")) {
1735 return InitError(
strprintf(
_(
"User Agent comment (%s) contains unsafe characters."), cmt));
1736 uacomments.push_back(cmt);
1740 return InitError(
strprintf(
_(
"Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1748 return InitError(
strprintf(
_(
"Incompatible options: -dnsseed=1 was explicitly specified, but -onlynet forbids connections to IPv4/IPv6")));
1762 for (
const std::string& param_value :
args.
GetArgs(
"-proxy")) {
1763 const auto eq_pos{param_value.rfind(
'=')};
1764 const std::string proxy_str{param_value.substr(0, eq_pos)};
1765 std::string net_str;
1766 if (eq_pos != std::string::npos) {
1767 if (eq_pos + 1 == param_value.length()) {
1768 return InitError(
strprintf(
_(
"Invalid -proxy address or hostname, ends with '=': '%s'"), param_value));
1770 net_str = param_value.substr(eq_pos + 1);
1774 if (!proxy_str.empty() && proxy_str !=
"0") {
1776 proxy =
Proxy{proxy_str, proxyRandomize};
1779 if (!addr.has_value()) {
1782 proxy =
Proxy{addr.value(), proxyRandomize};
1789 if (net_str.empty()) {
1790 ipv4_proxy = ipv6_proxy = name_proxy = cjdns_proxy = onion_proxy = proxy;
1793 case NET_IPV4: ipv4_proxy = name_proxy = proxy;
break;
1794 case NET_IPV6: ipv6_proxy = name_proxy = proxy;
break;
1795 case NET_ONION: onion_proxy = proxy;
break;
1796 case NET_CJDNS: cjdns_proxy = proxy;
break;
1801 return InitError(
strprintf(
_(
"Unrecognized network in -proxy='%s': '%s'"), param_value, net_str));
1823 std::string onionArg =
args.
GetArg(
"-onion",
"");
1824 if (onionArg !=
"") {
1825 if (onionArg ==
"0") {
1826 onion_proxy =
Proxy{};
1827 if (onlynet_used_with_onion) {
1829 _(
"Outbound connections restricted to Tor (-onlynet=onion) but the proxy for "
1830 "reaching the Tor network is explicitly forbidden: -onion=0"));
1834 onion_proxy =
Proxy(onionArg, proxyRandomize);
1837 if (!addr.has_value() || !addr->IsValid()) {
1841 onion_proxy =
Proxy(addr.value(), proxyRandomize);
1852 if (onlynet_used_with_onion && !listenonion) {
1854 _(
"Outbound connections restricted to Tor (-onlynet=onion) but the proxy for "
1855 "reaching the Tor network is not provided: none of -proxy, -onion or "
1856 "-listenonion is given"));
1861 for (
const std::string& strAddr :
args.
GetArgs(
"-externalip")) {
1863 if (addrLocal.has_value() && addrLocal->IsValid())
1871 [&chainman =
node.chainman](std::vector<std::byte>& block,
const CBlockIndex& index) {
1873 if (auto ret{chainman->m_blockman.ReadRawBlock(WITH_LOCK(cs_main, return index.GetBlockPos()))}) {
1874 block = std::move(*
ret);
1889 const auto [index_cache_sizes, kernel_cache_sizes] =
CalculateCacheSizes(
args, g_enabled_filter_types.size());
1891 LogInfo(
"Cache configuration:");
1892 LogInfo(
"* Using %.1f MiB for block index database", kernel_cache_sizes.block_tree_db /
double(1_MiB));
1894 LogInfo(
"* Using %.1f MiB for transaction index database", index_cache_sizes.tx_index /
double(1_MiB));
1897 LogInfo(
"* Using %.1f MiB for transaction output spender index database", index_cache_sizes.txospender_index /
double(1_MiB));
1900 LogInfo(
"* Using %.1f MiB for %s block filter index database",
1903 LogInfo(
"* Using %.1f MiB for chain state database", kernel_cache_sizes.coins_db /
double(1_MiB));
1909 const bool do_reindex_chainstate{
args.
GetBoolArg(
"-reindex-chainstate",
false)};
1915 do_reindex_chainstate,
1920 bool do_retry{
HasTestOption(
args,
"reindex_after_failure_noninteractive_yes") ||
1922 error +
Untranslated(
".\n\n") +
_(
"Do you want to rebuild the databases now?"),
1923 error.original +
".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1929 if (!
Assert(
node.shutdown_signal)->reset()) {
1930 LogError(
"Internal error: failed to reset shutdown signal.\n");
1935 do_reindex_chainstate,
1939 if (status != ChainstateLoadStatus::SUCCESS && status != ChainstateLoadStatus::INTERRUPTED) {
1946 LogInfo(
"Shutdown requested. Exiting.");
1955 if (!peerman_opts.ignore_incoming_txs) {
1958 return InitError(
strprintf(
_(
"acceptstalefeeestimates is not supported on %s chain."), chainparams.GetChainTypeString()));
1966 validation_signals.RegisterValidationInterface(fee_estimator_man);
1969 auto& kernel_notifications{*
Assert(
node.notifications)};
1973 node.banman.get(), chainman,
1976 validation_signals.RegisterValidationInterface(
node.peerman.get());
1990 for (
const auto& filter_type : g_enabled_filter_types) {
2001 for (
auto index :
node.indexes)
if (!index->Init())
return false;
2004 for (
const auto& client :
node.chain_clients) {
2005 if (!client->load()) {
2017 for (
const auto& chainstate : chainman.m_chainstates) {
2019 chainstate->PruneAndFlush();
2025 LogInfo(
"Setting NODE_NETWORK in non-prune mode");
2028 LogInfo(
"Running node in NODE_NETWORK_LIMITED mode until snapshot background sync completes");
2046 if (!do_reindex && !do_reindex_chainstate && chain_active_height <= 1) {
2047 uint64_t assumed_chain_bytes{chainparams.AssumedBlockchainSize() * 1_GiB};
2048 uint64_t additional_bytes_needed{
2051 assumed_chain_bytes};
2055 "Disk space for %s may not accommodate the block files. " \
2056 "Approximately %u GB of data will be stored in this directory."
2059 chainparams.AssumedBlockchainSize()
2065 auto check_and_warn_fs{[&](
const fs::path& path, std::string_view desc) {
2066 const auto path_desc{
strprintf(
"%s (\"%s\")", desc, fs::PathToString(path))};
2067 switch (GetFilesystemType(path)) {
2069 InitWarning(
strprintf(
_(
"The %s path uses exFAT, which is known to have intermittent corruption problems on macOS. "
2070 "Move this directory to a different filesystem to avoid data loss."), path_desc));
2073 LogInfo(
"Failed to detect filesystem type for %s", path_desc);
2085 const std::string block_notify =
args.
GetArg(
"-blocknotify",
"");
2086 if (!block_notify.empty()) {
2089 std::string
command = block_notify;
2091 std::thread
t(runCommand,
command);
2097 std::vector<fs::path> vImportFiles;
2098 for (
const std::string& strFile :
args.
GetArgs(
"-loadblock")) {
2099 vImportFiles.push_back(fs::PathFromString(strFile));
2112 WITH_LOCK(kernel_notifications.m_tip_block_mutex, kernel_notifications.m_tip_block_cv.notify_all());
2115 LogInfo(
"Stopping after block import");
2117 LogError(
"Failed to send shutdown signal after finishing block import\n");
2124 bilingual_str err_str =
_(
"Failed to start indexes, shutting down…");
2134 node.fee_estimator_man->MempoolLoadFailed();
2152 WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
2153 kernel_notifications.m_tip_block_cv.wait(lock, [&]()
EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
2154 return kernel_notifications.TipBlock() || ShutdownRequested(node);
2164 int64_t best_block_time{};
2169 chain_active_height = tip.nHeight;
2170 best_block_time = tip.GetBlockTime();
2172 tip_info->block_height = chain_active_height;
2173 tip_info->block_time = best_block_time;
2176 if (tip_info && chainman.m_best_header) {
2177 tip_info->header_height = chainman.m_best_header->nHeight;
2178 tip_info->header_time = chainman.m_best_header->GetBlockTime();
2181 LogInfo(
"nBestHeight = %d", chain_active_height);
2182 if (
node.peerman)
node.peerman->SetBestBlock(chain_active_height, std::chrono::seconds{best_block_time});
2196 for (
const std::string& added_node :
args.
GetArgs(
"-addnode")) {
2212 const uint16_t default_bind_port =
2215 const uint16_t default_bind_port_onion = default_bind_port + 1;
2217 const auto BadPortWarning = [](
const char* prefix, uint16_t port) {
2218 return strprintf(
_(
"%s request to listen on port %u. This port is considered \"bad\" and "
2219 "thus it is unlikely that any peer will connect to it. See "
2220 "doc/p2p-bad-ports.md for details and a full list."),
2225 for (
const std::string& bind_arg :
args.
GetArgs(
"-bind")) {
2226 std::optional<CService> bind_addr;
2227 const size_t index = bind_arg.rfind(
'=');
2228 if (index == std::string::npos) {
2229 bind_addr =
Lookup(bind_arg, default_bind_port,
false);
2230 if (bind_addr.has_value()) {
2231 connOptions.
vBinds.push_back(bind_addr.value());
2232 if (
IsBadPort(bind_addr.value().GetPort())) {
2233 InitWarning(BadPortWarning(
"-bind", bind_addr.value().GetPort()));
2238 const std::string network_type = bind_arg.substr(index + 1);
2239 if (network_type ==
"onion") {
2240 const std::string truncated_bind_arg = bind_arg.substr(0, index);
2241 bind_addr =
Lookup(truncated_bind_arg, default_bind_port_onion,
false);
2242 if (bind_addr.has_value()) {
2243 connOptions.
onion_binds.push_back(bind_addr.value());
2251 for (
const std::string& strBind :
args.
GetArgs(
"-whitebind")) {
2273 onion_service_target = connOptions.
onion_binds.front();
2274 }
else if (!connOptions.
vBinds.empty()) {
2275 onion_service_target = connOptions.
vBinds.front();
2278 connOptions.
onion_binds.push_back(onion_service_target);
2284 "for the automatically created Tor onion service."),
2291 if (!should_discover) {
2292 for (
const auto& bind : connOptions.
vBinds) {
2293 if (bind.IsBindAny()) {
2294 should_discover =
true;
2300 if (!should_discover) {
2301 for (
const auto& whitebind : connOptions.
vWhiteBinds) {
2303 should_discover =
true;
2309 if (should_discover) {
2315 for (
const auto& net :
args.
GetArgs(
"-whitelist")) {
2336 if (connect.size() != 1 || connect[0] !=
"0") {
2340 LogInfo(
"-seednode is ignored when -connect is used");
2344 LogInfo(
"-dnsseed is ignored when -connect is used and -proxy is specified");
2348 const std::string& i2psam_arg =
args.
GetArg(
"-i2psam",
"");
2349 if (!i2psam_arg.empty()) {
2351 if (!addr.has_value() || !addr->IsValid()) {
2358 _(
"Outbound connections restricted to i2p (-onlynet=i2p) but "
2359 "-i2psam is not provided"));
2368 _(
"Duplicate binding configuration for address %s. "
2369 "Please check your -bind, -bind=...=onion and -whitebind settings."),
2370 conflict->ToStringAddrPort()));
2377 const bool onion_may_become_reachable{listenonion && (!
args.
IsArgSet(
"-onlynet") || onlynet_used_with_onion)};
2380 !onion_may_become_reachable) {
2381 return InitError(
_(
"Private broadcast of own transactions requested (-privatebroadcast), "
2382 "but none of Tor or I2P networks is reachable"));
2385 return InitError(
_(
"Private broadcast of own transactions requested (-privatebroadcast), "
2386 "but -connect is also configured. They are incompatible because the "
2387 "private broadcast needs to open new connections to randomly "
2388 "chosen Tor or I2P peers. Consider using -maxconnections=0 -addnode=... "
2392 InitWarning(
_(
"Private broadcast of own transactions requested (-privatebroadcast) and "
2393 "-proxyrandomize is disabled. Tor circuits for private broadcast connections "
2394 "may be correlated to other connections over Tor. To reduce this risk, set "
2395 "-proxyrandomize=1."));
2399 if (!
node.connman->Start(scheduler, connOptions)) {
2413 for (
const auto& client :
node.chain_clients) {
2414 client->start(scheduler);
2418 scheduler.scheduleEvery([banman]{
2422 if (
node.peerman)
node.peerman->StartScheduledTasks(scheduler);
2425 StartupNotify(
args);
2452 std::optional<const CBlockIndex*> block_start;
2453 std::string block_start_name;
2454 std::optional<const CBlockIndex*> undo_start;
2455 std::string undo_start_name;
2457 for (
const auto& index :
node.indexes) {
2459 if (summary.
synced)
continue;
2467 LogWarning(
"Failed to find block manager entry for best block %s from %s, falling back to genesis for index sync",
2469 }
else if (!index_chain.
Contains(*pindex)) {
2470 pindex = index_chain.
FindFork(*pindex);
2474 pindex = index_chain.
Genesis();
2477 bool need_undo = index->CustomOptions().connect_undo_data;
2478 auto& op_start_index = need_undo ? undo_start : block_start;
2479 auto& name_index = need_undo ? undo_start_name : block_start_name;
2481 if (op_start_index && pindex->
nHeight >= op_start_index.value()->nHeight)
continue;
2482 op_start_index = pindex;
2483 name_index = summary.
name;
2489 if (!chainman.
m_blockman.CheckBlockDataAvailability(*index_chain.
Tip(), *
Assert(undo_start.value()),
BlockStatus{BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO})) {
2490 return InitError(
Untranslated(
strprintf(
"%s best block of the index goes beyond pruned data (including undo data). Please disable the index or reindex (which will download the whole blockchain again)", undo_start_name)));
2495 if (block_start && !(undo_start && undo_start.value()->nHeight <= block_start.value()->nHeight)) {
2498 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)", block_start_name)));
2504 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.
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...
constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
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...
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.
std::string_view TrimStringView(std::string_view str LIFETIMEBOUND, std::string_view pattern=" \f\n\r\t\v")
constexpr bool DEFAULT_ACCEPT_STALE_FEE_ESTIMATES
constexpr std::chrono::hours MAX_FILE_AGE
Block policy estimate files that are more than 60 hours (2.5 days) old will not be read,...
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.
bool BlockFilterTypeByName(std::string_view name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
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.
constexpr const char * 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.
constexpr int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
constexpr int32_t DEFAULT_PREVOUTFETCH_THREADS
constexpr auto DEFAULT_MAX_TIP_AGE
std::string ChainTypeToString(ChainType chain)
#define Assert(val)
Identity function.
std::vector< std::string > GetArgs(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return a vector of strings of the given argument.
ChainType GetChainType() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Returns the appropriate chain type from the program arguments.
@ ALLOW_ANY
disable validation
@ DISALLOW_NEGATION
disallow -nofoo syntax
@ DISALLOW_ELISION
disallow -foo syntax that doesn't assign any value
std::list< SectionInfo > GetUnrecognizedSections() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Log warnings for unrecognized section names in the config file.
fs::path GetBlocksDirPath() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get blocks directory path.
bool SoftSetArg(const std::string &strArg, const std::string &strValue) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Set an argument if it doesn't already have a value.
std::set< std::string > GetUnsuitableSectionOnlyArgs() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Log warnings for options in m_section_only_args when they are specified in the default section but no...
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Add argument.
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return path argument or default value.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return string argument or default value.
void AddHiddenArgs(const std::vector< std::string > &args) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Add many hidden arguments.
bool IsArgSet(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return true if the given argument has been manually set.
bool SoftSetBoolArg(const std::string &strArg, bool fValue) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Set a boolean argument if it doesn't already have a value.
fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path with appended network identifier.
bool IsArgNegated(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return true if the argument was originally passed as a negated option, i.e.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
bool GetBoolArg(const std::string &strArg, bool fDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return boolean 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)
kernel::BlockManagerOpts Options
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
An in-memory indexed chain of blocks.
bool Contains(const CBlockIndex &index) const
Efficiently check whether a block is present in this chain.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
const CBlockIndex * FindFork(const CBlockIndex &index) const
Find the last common block between this chain and a block index entry.
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.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const MessageStartChars & MessageStart() const
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
ChainType GetChainType() const
Return the chain type.
btcsignals::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
btcsignals::signal< bool(const bilingual_str &message, const std::string &noninteractive_message, unsigned int style), btcsignals::any_of > ThreadSafeQuestion
If possible, ask the user a question.
btcsignals::signal< void()> InitWallet
Wallet loader created.
btcsignals::signal< void(const bilingual_str &message, unsigned int style)> ThreadSafeMessageBox
Show message box.
btcsignals::signal< void(SynchronizationState, const CBlockIndex &block, double verification_progress)> NotifyBlockTip
New block has been accepted.
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToStringAddrPort() const
kernel::MemPoolOptions Options
static constexpr 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.
CTxMemPool * GetMempool()
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
kernel::ChainstateManagerOpts Options
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
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())
Chainstate & ActiveChainstate() const
const util::SignalInterrupt & m_interrupt
Chainstate & ValidatedChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
std::function< void()> snapshot_download_completed
void UpdateIBDStatus() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update and possibly latch the IBD status.
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
node::BlockManager m_blockman
uint64_t rand64() noexcept
Generate a random 64-bit integer.
Manages fee rate estimators.
void IntervalFlush()
Flush recorded data to disk.
static NetGroupManager NoAsmap()
static NetGroupManager WithEmbeddedAsmap(std::span< const std::byte > asmap)
static NetGroupManager WithLoadedAsmap(std::vector< std::byte > &&asmap)
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 GetHex() const
std::string ToString() const
connection connect(Callable &&func) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
A base class defining functions for notifying about certain kernel events.
virtual void fatalError(const bilingual_str &message)
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)
CBlockFileInfo *GetBlockFileInfo(size_t n) EXCLUSIVE_LOCKS_REQUIRED(bool WriteBlockUndo(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePos WriteBlock(const CBlock &block, int nHeight) EXCLUSIVE_LOCKS_REQUIRED(void UpdateBlockInfo(const CBlock &block, unsigned int nHeight, const FlatFilePos &pos) EXCLUSIVE_LOCKS_REQUIRED(bool IsPruneMode() const
Get block file info entry for one block file.
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.
uint64_t CalculateCurrentUsage() EXCLUSIVE_LOCKS_REQUIRED(bool CheckBlockDataAvailability(const CBlockIndex &upper_block, const CBlockIndex &lower_block, BlockStatus block_status=BLOCK_HAVE_DATA) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex &GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, uint32_t status_mask, const CBlockIndex *lower_block LIFETIMEBOUND=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(bool m_have_pruned
Calculate the amount of disk space the block & undo files currently use.
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
constexpr int CLIENT_VERSION
uint32_t current_height
Current height in the simulation.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
constexpr bool DEFAULT_COINSTATSINDEX
void ReplaceAll(std::string &in_out, std::string_view search, std::string_view substitute)
Replace every non-overlapping occurrence of search with substitute, treating both literally; the repl...
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
const WalletInitInterface & g_wallet_init_interface
fs::path MempoolPolicyEstimatorPath(const ArgsManager &argsman)
void MaybeMigrateLegacyFeeEstimates(const ArgsManager &argsman)
Move a legacy fee_estimates.dat file to the current block policy fee estimator path,...
fs::path BlockPolicyFeeEstPath(const ArgsManager &argsman)
constexpr std::chrono::hours FEE_FLUSH_INTERVAL
const std::string CURRENCY_UNIT
int RaiseFileDescriptorLimit(int min_fd)
Try 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()
Initialize HTTP server.
void StopHTTPServer()
Stop HTTP server.
bilingual_str InvalidPortErrMsg(const std::string &optname, const std::string &invalid_value)
constexpr int DEFAULT_MAX_HTTP_CONNECTIONS
Maximum number of connected HTTP clients.
constexpr int DEFAULT_HTTP_SERVER_TIMEOUT
constexpr int DEFAULT_HTTP_THREADS
The default value for -rpcthreads.
constexpr int DEFAULT_HTTP_WORKQUEUE
The default value for -rpcworkqueue.
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 InitLogging(const ArgsManager &args)
Initialize global loggers.
static bool AppInitServers(NodeContext &node)
static bool LockDirectories(bool probeOnly)
static constexpr int MIN_CORE_FDS
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
CacheSizes CalculateCacheSizes(const ArgsManager &args, size_t n_indexes)
static void HandleSIGHUP(int)
fs::path MempoolPath(const ArgsManager &argsman)
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)
bool DumpMempool(const CTxMemPool &pool, const fs::path &dump_path, fsbridge::FopenFn mockable_fopen_function=fsbridge::fopen, bool skip_file_commit=false)
Dump the mempool to a file.
static std::optional< CService > CheckBindingConflicts(const CConnman::Options &conn_options)
Checks for duplicate bindings across all binding configurations.
bool ShouldPersistMempool(const ArgsManager &argsman)
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.
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
static constexpr bool DEFAULT_REST_ENABLE
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.
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
static void registerSignalHandler(int signal, void(*handler)(int))
constexpr bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool, indicating whether the node should attempt to automatically load the mem...
bool AppInitMain(NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
constexpr int DEFAULT_STOPATHEIGHT
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()
constexpr bool DEFAULT_PRINT_MODIFIED_FEE
void ImportBlocks(ChainstateManager &chainman, std::span< const fs::path > import_paths)
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
constexpr bool DEFAULT_DAEMON
Default value for -daemon option.
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.
constexpr uint64_t DEFAULT_DB_CACHE_BATCH
Default LevelDB write batch size.
constexpr uint64_t MIN_DBCACHE_BYTES
Minimum total database cache (bytes).
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
#define LogDebug(category,...)
BCLog::Logger & LogInstance()
void StartMapPort(bool enable)
constexpr bool DEFAULT_NATPMP
util::Result< void > ApplyArgsManOptions(const ArgsManager &argsman, const CChainParams &chainparams, MemPoolOptions &mempool_opts)
Overlay the options set in argsman on top of corresponding members in mempool_opts.
constexpr unsigned int DEFAULT_MAX_MEMPOOL_SIZE_MB
Default for -maxmempool, maximum megabytes of mempool memory usage.
constexpr bool DEFAULT_ACCEPT_NON_STD_TXN
Default for -acceptnonstdtxn.
constexpr unsigned int DEFAULT_MEMPOOL_EXPIRY_HOURS
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
constexpr unsigned int DEFAULT_BLOCKSONLY_MAX_MEMPOOL_SIZE_MB
Default for -maxmempool when blocksonly is set.
constexpr bool DEFAULT_PERSIST_V1_DAT
Whether to fall back to legacy V1 serialization when writing mempool.dat.
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 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< Mining > MakeMining(const node::NodeContext &node, bool wait_loaded=true)
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
constexpr bool DEFAULT_XOR_BLOCKSDIR
util::Result< void > SanityChecks(const Context &)
Ensure a usable environment with all necessary library support.
@ 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)
Result< BlockCreateOptions > ReadMiningArgs(const ArgsManager &args)
Read the mining options set in args.
bool DumpMempool(const CTxMemPool &pool, const fs::path &dump_path, FopenFn mockable_fopen_function, bool skip_file_commit)
Dump the mempool to a file.
bool ShouldPersistMempool(const ArgsManager &argsman)
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.
constexpr bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool, indicating whether the node should attempt to automatically load the mem...
constexpr int DEFAULT_STOPATHEIGHT
uint64_t GetDefaultDBCache()
constexpr bool DEFAULT_PRINT_MODIFIED_FEE
void ImportBlocks(ChainstateManager &chainman, std::span< const fs::path > import_paths)
void ThreadRename(const std::string &)
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_view TrimStringView(std::string_view str LIFETIMEBOUND, std::string_view pattern=" \f\n\r\t\v")
void ReplaceAll(std::string &in_out, std::string_view search, std::string_view substitute)
Replace every non-overlapping occurrence of search with substitute, treating both literally; the repl...
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.
LockResult LockDirectory(const fs::path &directory, const fs::path &lockfile_name, bool probe_only)
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
bool AddLocal(const CService &addr_, int nScore, bool add_even_if_unreachable)
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
constexpr bool DEFAULT_LISTEN
-listen default
constexpr bool DEFAULT_PRIVATE_BROADCAST
Default for -privatebroadcast.
constexpr unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
constexpr int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
constexpr bool DEFAULT_BLOCKSONLY
Default for blocks only.
constexpr int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
constexpr size_t DEFAULT_MAXSENDBUFFER
constexpr bool DEFAULT_FIXEDSEEDS
constexpr unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
constexpr int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
constexpr size_t DEFAULT_MAXRECEIVEBUFFER
const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
constexpr bool DEFAULT_FORCEDNSSEED
constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS
Maximum number of private broadcast connections.
constexpr bool DEFAULT_DNSSEED
constexpr int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
constexpr int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
constexpr int DEFAULT_FULL_RELAY_INBOUND_PCT
Default percentage of inbound connection slots that tx-relaying peers can use.
constexpr bool DEFAULT_V2_TRANSPORT
constexpr int MAX_PEER_CONNECTIONS
Maximum value of -maxconnections.
constexpr int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
const std::vector< std::string > NET_PERMISSIONS_DOC
constexpr bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
constexpr bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
constexpr unsigned int DEFAULT_TX_SEND_RATE
Default maximum per-second rate for sending transaction inventory to peers.
constexpr bool DEFAULT_PEERBLOOMFILTERS
constexpr bool DEFAULT_TXRECONCILIATION_ENABLE
Whether transaction reconciliation protocol should be enabled by default.
constexpr bool DEFAULT_PEERBLOCKFILTERS
constexpr uint32_t DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of non-mempool transactions to keep around for block reconstruction.
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
@ NET_ONION
TOR (v2 or v3).
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
std::string GetNetworkName(enum Network net)
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.
constexpr int DEFAULT_CONNECT_TIMEOUT
-timeout default
const std::string ADDR_PREFIX_UNIX
Prefix for unix domain socket addresses (which are local filesystem paths).
constexpr int DEFAULT_NAME_LOOKUP
-dns default
unsigned int nBytesPerSigOp
constexpr unsigned int DEFAULT_BLOCK_MIN_TX_FEE
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
constexpr unsigned int MAX_OP_RETURN_RELAY
Default setting for -datacarriersize in vbytes.
constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
constexpr bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
constexpr unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
constexpr bool DEFAULT_ACCEPT_DATACARRIER
Default for -datacarrier.
constexpr unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
constexpr unsigned int DEFAULT_BYTES_PER_SIGOP
Default for -bytespersigop.
constexpr unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create.
constexpr unsigned int DEFAULT_CLUSTER_SIZE_LIMIT_KVB
Maximum size of cluster in virtual kilobytes.
constexpr unsigned int DEFAULT_BLOCK_RESERVED_WEIGHT
Default for -blockreservedweight.
constexpr unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
constexpr unsigned int DEFAULT_CLUSTER_LIMIT
Maximum number of transactions per cluster (default).
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.
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
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.
constexpr size_t DEFAULT_VALIDATION_CACHE_BYTES
std::optional< T > ToIntegral(std::string_view str, size_t base=10)
Convert string to integral type T.
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
unsigned int nReceiveFloodSize
int m_full_relay_inbound_percent
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.
Block and header tip information.
Notifications & notifications
const CChainParams & chainparams
bool require_full_verification
std::function< void()> coins_error_cb
#define WAIT_LOCK(cs, name)
AnnotatedMixin< std::mutex > Mutex
Wrapped mutex: supports waiting but not recursive locking.
#define WITH_LOCK(cs, code)
#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.
CService DefaultOnionServiceTarget(uint16_t port)
constexpr uint16_t DEFAULT_TOR_SOCKS_PORT
Functionality for communicating with Tor.
constexpr 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.
constexpr unsigned MAX_CLUSTER_COUNT_LIMIT
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
constexpr bool DEFAULT_TXINDEX
std::unique_ptr< TxoSpenderIndex > g_txospenderindex
The global txo spender index. May be null.
constexpr bool DEFAULT_TXOSPENDERINDEX
bool CheckStandardAsmap(const std::span< const std::byte > data)
Provides a safe interface for validating ASMap data before use.
std::vector< std::byte > DecodeAsmap(fs::path path)
Loads an ASMap file from disk and validates it.
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 SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
void SetMockTime(std::chrono::time_point< NodeClock, std::chrono::seconds > mock)
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
constexpr signed int DEFAULT_CHECKBLOCKS
constexpr int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
constexpr int DEFAULT_CHECKLEVEL
SynchronizationState
Current sync state passed to tip changed callbacks.
constexpr uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
constexpr int32_t MAX_PREVOUTFETCH_THREADS
Maximum number of dedicated threads allowed for prefetching block input prevouts.
constexpr unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
std::unique_ptr< CZMQNotificationInterface > g_zmq_notification_interface
void RegisterZMQRPCCommands(CRPCTable &t)