6 #if defined(HAVE_CONFIG_H) 93 #include <condition_variable> 106 #include <sys/stat.h> 109 #include <boost/signals2/signal.hpp> 146 #define MIN_CORE_FILEDESCRIPTORS 0 148 #define MIN_CORE_FILEDESCRIPTORS 150 188 if (std::error_code
error; !fs::remove(pid_path,
error)) {
189 std::string
msg{
error ?
error.message() :
"File does not exist"};
236 std::vector<std::thread> threads;
238 threads.emplace_back(runCommand,
cmd);
240 for (
auto& t : threads) {
249 ShutdownNotify(*
node.args);
258 node.connman->Interrupt();
270 static Mutex g_shutdown_mutex;
271 TRY_LOCK(g_shutdown_mutex, lock_shutdown);
272 if (!lock_shutdown)
return;
273 LogPrintf(
"%s: In progress...\n", __func__);
281 if (
node.mempool)
node.mempool->AddTransactionsUpdated(1);
287 for (
const auto& client :
node.chain_clients) {
295 if (
node.connman)
node.connman->Stop();
301 if (
node.scheduler)
node.scheduler->stop();
302 if (
node.chainman &&
node.chainman->m_thread_load.joinable())
node.chainman->m_thread_load.join();
306 node.peerman.reset();
307 node.connman.reset();
309 node.addrman.reset();
310 node.netgroupman.reset();
318 if (
node.fee_estimator) {
319 node.fee_estimator->Flush();
327 if (chainstate->CanFlushToDisk()) {
328 chainstate->ForceFlushStateToDisk();
358 if (chainstate->CanFlushToDisk()) {
359 chainstate->ForceFlushStateToDisk();
360 chainstate->ResetCoinsViews();
364 for (
const auto& client :
node.chain_clients) {
375 node.chain_clients.clear();
378 node.mempool.reset();
379 node.fee_estimator.reset();
380 node.chainman.reset();
381 node.scheduler.reset();
407 static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
410 LogPrintf(
"Error: failed to send shutdown signal on Ctrl-C\n");
423 sigemptyset(&sa.sa_mask);
425 sigaction(signal, &sa,
nullptr);
460 std::vector<std::string> hidden_args = {
461 "-dbcrashratio",
"-forcecompactdb",
463 "-choosedatadir",
"-lang=<lang>",
"-min",
"-resetguisettings",
"-splash",
"-uiplatform"};
469 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, testnet: %s, signet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex(), signetChainParams->GetConsensus().defaultAssumeValid.GetHex()),
ArgsManager::ALLOW_ANY,
OptionsCategory::OPTIONS);
489 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)",
492 argsman.
AddArg(
"-persistmempoolv1",
493 strprintf(
"Whether a mempool.dat file created by -persistmempool or the savemempool RPC will be written in the legacy format " 494 "(version 1) or the current format (version 2). This temporary option will be removed in the future. (default: %u)",
498 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. " 499 "Warning: Reverting this setting requires re-downloading the entire blockchain. " 501 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);
502 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);
506 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);
509 argsman.
AddArg(
"-blockfilterindex=<type>",
511 " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
517 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, testnet: 127.0.0.1:%u=onion, signet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)", defaultBaseParams->OnionServiceTargetPort(), testnetBaseParams->OnionServiceTargetPort(), signetBaseParams->OnionServiceTargetPort(), regtestBaseParams->OnionServiceTargetPort()),
ArgsManager::ALLOW_ANY |
ArgsManager::NETWORK_ONLY,
OptionsCategory::CONNECTION);
543 argsman.
AddArg(
"-port=<port>",
strprintf(
"Listen for connections on <port>. Nodes not using the default ports (default: %u, testnet: %u, signet: %u, regtest: %u) are unlikely to get incoming connections. Not relevant for I2P (see doc/i2p.md).", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()),
ArgsManager::ALLOW_ANY |
ArgsManager::NETWORK_ONLY,
OptionsCategory::CONNECTION);
559 hidden_args.emplace_back(
"-upnp");
564 hidden_args.emplace_back(
"-natpmp");
566 argsman.
AddArg(
"-whitebind=<[permissions@]addr>",
"Bind to the given address and add permission flags to the peers connecting to it. " 570 argsman.
AddArg(
"-whitelist=<[permissions@]IP address or network>",
"Add permission flags to the peers connecting from the given IP address (e.g. 1.2.3.4) or " 571 "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as " 588 hidden_args.emplace_back(
"-zmqpubhashblock=<address>");
589 hidden_args.emplace_back(
"-zmqpubhashtx=<address>");
590 hidden_args.emplace_back(
"-zmqpubrawblock=<address>");
591 hidden_args.emplace_back(
"-zmqpubrawtx=<address>");
592 hidden_args.emplace_back(
"-zmqpubsequence=<n>");
593 hidden_args.emplace_back(
"-zmqpubhashblockhwm=<n>");
594 hidden_args.emplace_back(
"-zmqpubhashtxhwm=<n>");
595 hidden_args.emplace_back(
"-zmqpubrawblockhwm=<n>");
596 hidden_args.emplace_back(
"-zmqpubrawtxhwm=<n>");
597 hidden_args.emplace_back(
"-zmqpubsequencehwm=<n>");
617 argsman.
AddArg(
"-maxtipage=<n>",
618 strprintf(
"Maximum tip age in seconds to consider node in initial block download (default: %u)",
632 argsman.
AddArg(
"-datacarriersize",
633 strprintf(
"Relay and mine transactions whose data-carrying raw scriptPubKey " 634 "is of this size or less (default: %u)",
640 argsman.
AddArg(
"-minrelaytxfee=<amt>",
strprintf(
"Fees (in %s/kvB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
651 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). This option can be specified multiple times",
ArgsManager::ALLOW_ANY,
OptionsCategory::RPC);
652 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);
653 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);
657 argsman.
AddArg(
"-rpcport=<port>",
strprintf(
"Listen for JSON-RPC connections on <port> (default: %u, testnet: %u, signet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), signetBaseParams->RPCPort(), regtestBaseParams->RPCPort()),
ArgsManager::ALLOW_ANY |
ArgsManager::NETWORK_ONLY,
OptionsCategory::RPC);
661 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);
662 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);
670 hidden_args.emplace_back(
"-daemon");
671 hidden_args.emplace_back(
"-daemonwait");
684 if (pBlockIndex !=
nullptr) {
698 std::thread
t(runCommand,
cmd);
728 LogPrintf(
"%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
732 LogPrintf(
"%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
738 LogPrintf(
"%s: parameter interaction: -connect or -maxconnections=0 set -> setting -dnsseed=0\n", __func__);
740 LogPrintf(
"%s: parameter interaction: -connect or -maxconnections=0 set -> setting -listen=0\n", __func__);
743 std::string proxy_arg =
args.
GetArg(
"-proxy",
"");
744 if (proxy_arg !=
"" && proxy_arg !=
"0") {
747 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
751 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
753 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -natpmp=0\n", __func__);
757 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
763 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
765 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -natpmp=0\n", __func__);
768 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
770 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
772 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -i2pacceptincoming=0\n", __func__);
779 LogPrintf(
"%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
785 LogPrintf(
"%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
794 LogPrintf(
"%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
798 bool clearnet_reachable = std::any_of(onlynets.begin(), onlynets.end(), [](
const auto& net) {
803 LogPrintf(
"%s: parameter interaction: -onlynet excludes IPv4 and IPv6 -> setting -dnsseed=0\n", __func__);
823 int nUserMaxConnections;
826 int64_t peer_connect_timeout;
827 std::set<BlockFilterType> g_enabled_filter_types;
837 std::set_new_handler(std::terminate);
838 LogPrintf(
"Error: Out of memory. Terminating.\n");
849 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
850 _CrtSetReportFile(_CRT_WARN, CreateFileA(
"NUL", GENERIC_WRITE, 0,
nullptr, OPEN_EXISTING, 0, 0));
852 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
856 HeapSetInformation(
nullptr, HeapEnableTerminationOnCorruption,
nullptr, 0);
871 signal(SIGPIPE, SIG_IGN);
873 SetConsoleCtrlHandler(consoleCtrlHandler,
true);
900 if (!errors.
empty()) {
910 if (!warnings.
empty()) {
920 if (blockfilterindex_value ==
"" || blockfilterindex_value ==
"1") {
922 }
else if (blockfilterindex_value !=
"0") {
923 const std::vector<std::string> names =
args.
GetArgs(
"-blockfilterindex");
924 for (
const auto&
name : names) {
929 g_enabled_filter_types.insert(filter_type);
941 return InitError(
_(
"Cannot set -peerblockfilters without -blockfilterindex."));
949 return InitError(
_(
"Prune mode is incompatible with -txindex."));
951 return InitError(
_(
"Prune mode is incompatible with -reindex-chainstate. Use full -reindex instead."));
957 return InitError(
_(
"Cannot set -forcednsseed to true when setting -dnsseed to false."));
972 int nBind = std::max(nUserBind,
size_t(1));
974 nMaxConnections = std::max(nUserMaxConnections, 0);
981 int fd_max = FD_SETSIZE;
987 return InitError(
_(
"Not enough file descriptors available."));
990 if (nMaxConnections < nUserMaxConnections)
991 InitWarning(
strprintf(
_(
"Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
1005 if (peer_connect_timeout <= 0) {
1033 .notifications = notifications,
1036 if (!chainman_result) {
1039 BlockManager::Options blockman_opts_dummy{
1040 .chainparams = chainman_opts_dummy.chainparams,
1042 .notifications = chainman_opts_dummy.notifications,
1045 if (!blockman_result) {
1096 node.chain =
node.init->makeChain();
1106 if (!opt_max_upload) {
1120 LogPrintf(
"Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1124 LogPrintf(
"Warning: relative datadir option '%s' specified, which will be interpreted relative to the " 1125 "current working directory '%s'. This is fragile, because if bitcoin is started in the future " 1126 "from a different location, it will be unable to locate the current data files. There could " 1127 "also be data loss if bitcoin is started while in a temporary directory.\n",
1140 node.scheduler = std::make_unique<CScheduler>();
1143 node.scheduler->m_service_thread = std::thread(
util::TraceThread,
"scheduler", [&] {
node.scheduler->serviceQueue(); });
1146 node.scheduler->scheduleEvery([]{
1148 }, std::chrono::minutes{1});
1152 constexpr uint64_t min_disk_space = 50 << 20;
1154 LogPrintf(
"Shutting down due to lack of disk space!\n");
1156 LogPrintf(
"Error: failed to send shutdown signal after disk space check\n");
1159 }, std::chrono::minutes{5});
1174 for (
const auto& client :
node.chain_clients) {
1175 client->registerRpcs();
1189 return InitError(
_(
"Unable to start HTTP server. See debug log for details."));
1193 for (
const auto& client :
node.chain_clients) {
1194 if (!client->verify()) {
1214 std::vector<bool> asmap;
1217 if (!asmap_path.is_absolute()) {
1225 if (asmap.size() == 0) {
1230 LogPrintf(
"Using asmap version %s for IP bucketing\n", asmap_version.
ToString());
1232 LogPrintf(
"Using /16 prefix for IP bucketing\n");
1237 node.netgroupman = std::make_unique<NetGroupManager>(std::move(asmap));
1241 uiInterface.InitMessage(
_(
"Loading P2P addresses…").translated);
1244 node.addrman = std::move(*addrman);
1250 node.connman = std::make_unique<CConnman>(GetRand<uint64_t>(),
1251 GetRand<uint64_t>(),
1257 if (!peerman_opts.ignore_incoming_txs) {
1262 node.fee_estimator = std::make_unique<CBlockPolicyEstimator>(
FeeestPath(
args), read_stale_estimates);
1266 node.scheduler->scheduleEvery([fee_estimator] { fee_estimator->FlushFeeEstimates(); },
FEE_FLUSH_INTERVAL);
1271 for (
const std::string port_option : {
1276 const std::string port =
args.
GetArg(port_option,
"");
1284 for (
const std::string port_option : {
1297 for (
const std::string& socket_addr :
args.
GetArgs(port_option)) {
1298 std::string host_out;
1299 uint16_t port_out{0};
1306 for (
const std::string& socket_addr :
args.
GetArgs(
"-bind")) {
1307 std::string host_out;
1308 uint16_t port_out{0};
1309 std::string bind_socket_addr = socket_addr.substr(0, socket_addr.rfind(
'='));
1316 std::vector<std::string> uacomments;
1317 for (
const std::string& cmt :
args.
GetArgs(
"-uacomment")) {
1319 return InitError(
strprintf(
_(
"User Agent comment (%s) contains unsafe characters."), cmt));
1320 uacomments.push_back(cmt);
1324 return InitError(
strprintf(
_(
"Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1330 for (
const std::string& snet :
args.
GetArgs(
"-onlynet")) {
1341 _(
"Outbound connections restricted to CJDNS (-onlynet=cjdns) but " 1342 "-cjdnsreachable is not provided"));
1355 return InitError(
strprintf(
_(
"Incompatible options: -dnsseed=1 was explicitly specified, but -onlynet forbids connections to IPv4/IPv6")));
1366 std::string proxyArg =
args.
GetArg(
"-proxy",
"");
1367 if (proxyArg !=
"" && proxyArg !=
"0") {
1369 if (!proxyAddr.has_value()) {
1373 Proxy addrProxy =
Proxy(proxyAddr.value(), proxyRandomize);
1381 onion_proxy = addrProxy;
1389 std::string onionArg =
args.
GetArg(
"-onion",
"");
1390 if (onionArg !=
"") {
1391 if (onionArg ==
"0") {
1392 onion_proxy =
Proxy{};
1393 if (onlynet_used_with_onion) {
1395 _(
"Outbound connections restricted to Tor (-onlynet=onion) but the proxy for " 1396 "reaching the Tor network is explicitly forbidden: -onion=0"));
1400 if (!addr.has_value() || !addr->IsValid()) {
1403 onion_proxy =
Proxy{addr.value(), proxyRandomize};
1413 if (onlynet_used_with_onion && listenonion_disabled) {
1415 _(
"Outbound connections restricted to Tor (-onlynet=onion) but the proxy for " 1416 "reaching the Tor network is not provided: none of -proxy, -onion or " 1417 "-listenonion is given"));
1422 for (
const std::string& strAddr :
args.
GetArgs(
"-externalip")) {
1424 if (addrLocal.has_value() && addrLocal->IsValid())
1434 return chainman->m_blockman.ReadBlockFromDisk(block, index);
1444 node.notifications = std::make_unique<KernelNotifications>(*
Assert(
node.shutdown),
node.exit_status);
1447 bool fReindexChainState =
args.
GetBoolArg(
"-reindex-chainstate",
false);
1451 .notifications = *
node.notifications,
1455 BlockManager::Options blockman_opts{
1456 .chainparams = chainman_opts.chainparams,
1458 .notifications = chainman_opts.notifications,
1466 LogPrintf(
"* Using %.1f MiB for block index database\n", cache_sizes.
block_tree_db * (1.0 / 1024 / 1024));
1468 LogPrintf(
"* Using %.1f MiB for transaction index database\n", cache_sizes.
tx_index * (1.0 / 1024 / 1024));
1471 LogPrintf(
"* Using %.1f MiB for %s block filter index database\n",
1474 LogPrintf(
"* Using %.1f MiB for chain state database\n", cache_sizes.
coins_db * (1.0 / 1024 / 1024));
1486 mempool_opts.check_ratio = std::clamp<int>(mempool_opts.check_ratio, 0, 1
'000'000);
1488 int64_t descendant_limit_bytes = mempool_opts.limits.descendant_size_vbytes * 40;
1489 if (mempool_opts.max_size_bytes < 0 || mempool_opts.max_size_bytes < descendant_limit_bytes) {
1490 return InitError(
strprintf(
_(
"-maxmempool must be at least %d MB"), std::ceil(descendant_limit_bytes / 1
'000'000.0)));
1492 LogPrintf(
"* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)\n", cache_sizes.
coins * (1.0 / 1024 / 1024), mempool_opts.max_size_bytes * (1.0 / 1024 / 1024));
1495 node.mempool = std::make_unique<CTxMemPool>(mempool_opts);
1497 node.chainman = std::make_unique<ChainstateManager>(*
Assert(
node.shutdown), chainman_opts, blockman_opts);
1503 chainman.restart_indexes = [&
node]() {
1504 LogPrintf(
"[snapshot] restarting indexes\n");
1510 for (
auto* index :
node.indexes) {
1513 if (!(index->Init() && index->StartBackgroundSync())) {
1514 LogPrintf(
"[snapshot] WARNING failed to restart index %s on snapshot chain\n", index->GetName());
1523 options.
prune = chainman.m_blockman.IsPruneMode();
1529 _(
"Error reading from database, shutting down."),
1533 uiInterface.InitMessage(
_(
"Loading block index…").translated);
1534 const auto load_block_index_start_time{SteadyClock::now()};
1535 auto catch_exceptions = [](
auto&& f) {
1538 }
catch (
const std::exception& e) {
1543 auto [status,
error] = catch_exceptions([&]{
return LoadChainstate(chainman, cache_sizes, options); });
1545 uiInterface.InitMessage(
_(
"Verifying blocks…").translated);
1547 LogWarning(
"pruned datadir may not have more than %d blocks; only checking available blocks\n",
1553 LogPrintf(
" block index %15dms\n", Ticks<std::chrono::milliseconds>(SteadyClock::now() - load_block_index_start_time));
1566 error.original +
".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1571 LogPrintf(
"Internal error: failed to reset shutdown signal.\n");
1574 LogPrintf(
"Aborted block database rebuild. Exiting.\n");
1587 LogPrintf(
"Shutdown requested. Exiting.\n");
1595 node.banman.get(), chainman,
1596 *
node.mempool, peerman_opts);
1606 for (
const auto& filter_type : g_enabled_filter_types) {
1617 for (
auto index :
node.indexes)
if (!index->Init())
return false;
1620 for (
const auto& client :
node.chain_clients) {
1621 if (!client->load()) {
1634 uiInterface.InitMessage(
_(
"Pruning blockstore…").translated);
1635 chainstate->PruneAndFlush();
1639 LogPrintf(
"Setting NODE_NETWORK on non-prune mode\n");
1657 if (!
fReindex && !fReindexChainState && chain_active_height <= 1) {
1659 uint64_t additional_bytes_needed{
1662 assumed_chain_bytes};
1666 "Disk space for %s may not accommodate the block files. " \
1667 "Approximately %u GB of data will be stored in this directory." 1677 boost::signals2::connection block_notify_genesis_wait_connection;
1685 const std::string block_notify =
args.
GetArg(
"-blocknotify",
"");
1686 if (!block_notify.empty()) {
1689 std::string
command = block_notify;
1691 std::thread
t(runCommand,
command);
1697 std::vector<fs::path> vImportFiles;
1698 for (
const std::string& strFile :
args.
GetArgs(
"-loadblock")) {
1706 LogPrintf(
"Stopping after block import\n");
1708 LogPrintf(
"Error: failed to send shutdown signal after finishing block import\n");
1715 bilingual_str err_str =
_(
"Failed to start indexes, shutting down..");
1735 block_notify_genesis_wait_connection.disconnect();
1745 int64_t best_block_time{};
1756 if (tip_info && chainman.m_best_header) {
1758 tip_info->
header_time = chainman.m_best_header->GetBlockTime();
1761 LogPrintf(
"nBestHeight = %d\n", chain_active_height);
1762 if (
node.peerman)
node.peerman->SetBestBlock(chain_active_height, std::chrono::seconds{best_block_time});
1769 connOptions.m_max_automatic_connections = nMaxConnections;
1771 connOptions.m_banman =
node.banman.get();
1772 connOptions.m_msgproc =
node.peerman.get();
1775 connOptions.m_added_nodes =
args.
GetArgs(
"-addnode");
1776 connOptions.nMaxOutboundLimit = *opt_max_upload;
1777 connOptions.m_peer_connect_timeout = peer_connect_timeout;
1780 const uint16_t default_bind_port =
1783 const auto BadPortWarning = [](
const char*
prefix, uint16_t port) {
1784 return strprintf(
_(
"%s request to listen on port %u. This port is considered \"bad\" and " 1785 "thus it is unlikely that any peer will connect to it. See " 1786 "doc/p2p-bad-ports.md for details and a full list."),
1791 for (
const std::string& bind_arg :
args.
GetArgs(
"-bind")) {
1792 std::optional<CService> bind_addr;
1793 const size_t index = bind_arg.rfind(
'=');
1794 if (index == std::string::npos) {
1795 bind_addr =
Lookup(bind_arg, default_bind_port,
false);
1796 if (bind_addr.has_value()) {
1797 connOptions.vBinds.push_back(bind_addr.value());
1798 if (
IsBadPort(bind_addr.value().GetPort())) {
1799 InitWarning(BadPortWarning(
"-bind", bind_addr.value().GetPort()));
1804 const std::string network_type = bind_arg.substr(index + 1);
1805 if (network_type ==
"onion") {
1806 const std::string truncated_bind_arg = bind_arg.substr(0, index);
1807 bind_addr =
Lookup(truncated_bind_arg,
BaseParams().OnionServiceTargetPort(),
false);
1808 if (bind_addr.has_value()) {
1809 connOptions.onion_binds.push_back(bind_addr.value());
1817 for (
const std::string& strBind :
args.
GetArgs(
"-whitebind")) {
1821 connOptions.vWhiteBinds.push_back(whitebind);
1830 if (connOptions.bind_on_any &&
args.
IsArgSet(
"-port")) {
1838 if (!connOptions.onion_binds.empty()) {
1839 onion_service_target = connOptions.onion_binds.front();
1842 connOptions.onion_binds.push_back(onion_service_target);
1846 if (connOptions.onion_binds.size() > 1) {
1848 "for the automatically created Tor onion service."),
1854 if (connOptions.bind_on_any) {
1860 for (
const auto& net :
args.
GetArgs(
"-whitelist")) {
1864 connOptions.vWhitelistedRange.push_back(subnet);
1867 connOptions.vSeedNodes =
args.
GetArgs(
"-seednode");
1870 connOptions.m_use_addrman_outgoing = !
args.
IsArgSet(
"-connect");
1871 if (!connOptions.m_use_addrman_outgoing) {
1873 if (connect.size() != 1 || connect[0] !=
"0") {
1874 connOptions.m_specified_outgoing = connect;
1876 if (!connOptions.m_specified_outgoing.empty() && !connOptions.vSeedNodes.empty()) {
1877 LogPrintf(
"-seednode is ignored when -connect is used\n");
1881 LogPrintf(
"-dnsseed is ignored when -connect is used and -proxy is specified\n");
1885 const std::string& i2psam_arg =
args.
GetArg(
"-i2psam",
"");
1886 if (!i2psam_arg.empty()) {
1888 if (!addr.has_value() || !addr->IsValid()) {
1895 _(
"Outbound connections restricted to i2p (-onlynet=i2p) but " 1896 "-i2psam is not provided"));
1903 if (!
node.connman->Start(*
node.scheduler, connOptions)) {
1922 for (
const auto& client :
node.chain_clients) {
1923 client->start(*
node.scheduler);
1927 node.scheduler->scheduleEvery([banman]{
1931 if (
node.peerman)
node.peerman->StartScheduledTasks(*
node.scheduler);
1934 StartupNotify(
args);
1946 std::optional<const CBlockIndex*> indexes_start_block;
1947 std::string older_index_name;
1952 for (
auto index :
node.indexes) {
1954 if (summary.
synced)
continue;
1959 if (!index_chain.Contains(pindex)) {
1960 pindex = index_chain.FindFork(pindex);
1963 if (!indexes_start_block || !pindex || pindex->
nHeight < indexes_start_block.value()->nHeight) {
1964 indexes_start_block = pindex;
1965 older_index_name = summary.
name;
1971 if (indexes_start_block) {
1973 const CBlockIndex* start_block = *indexes_start_block;
1975 if (!chainman.
m_blockman.CheckBlockDataAvailability(*index_chain.Tip(), *
Assert(start_block))) {
1976 return InitError(
strprintf(
Untranslated(
"%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));
1981 for (
auto index :
node.indexes)
if (!index->StartBackgroundSync())
return false;
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, Options opts)
std::thread m_thread_load
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
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...
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
static path PathFromString(const std::string &string)
Convert byte string to path object.
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
fs::path FeeestPath(const ArgsManager &argsman)
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
bool ShouldPersistMempool(const ArgsManager &argsman)
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
void Remove(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
void ImportBlocks(ChainstateManager &chainman, std::vector< fs::path > vImportFiles)
bool InitHTTPServer(const util::SignalInterrupt &interrupt)
Initialize HTTP server.
static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
const std::vector< std::string > NET_PERMISSIONS_DOC
std::condition_variable g_best_block_cv
void ReadNotificationArgs(const ArgsManager &args, KernelNotifications ¬ifications)
void InitLogging(const ArgsManager &args)
Initialize global loggers.
SynchronizationState
Current sync state passed to tip changed callbacks.
BCLog::Logger & LogInstance()
ServiceFlags
nServices flags
bool IsPruneMode() const
Whether running in -prune mode.
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. ...
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
CClientUIInterface uiInterface
#define LogPrint(category,...)
int64_t GetBlockTime() const
static const int DEFAULT_HTTP_SERVER_TIMEOUT
static constexpr unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT_KVB
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
static constexpr unsigned int DEFAULT_MEMPOOL_EXPIRY_HOURS
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
#define TRY_LOCK(cs, name)
void SetupServerArgs(ArgsManager &argsman)
Register all arguments with the ArgsManager.
const char *const BITCOIN_SETTINGS_FILENAME
std::atomic_bool fReindex
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
std::unique_ptr< CZMQNotificationInterface > g_zmq_notification_interface
std::string GetChainTypeString() const
Return the chain type string.
void Shutdown(NodeContext &node)
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for -datacarriersize.
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
static constexpr bool DEFAULT_ACCEPT_STALE_FEE_ESTIMATES
static boost::signals2::connection rpc_notify_block_change_connection
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
static const int DEFAULT_HTTP_WORKQUEUE
static void RegisterAllCoreRPCCommands(CRPCTable &t)
An in-memory indexed chain of blocks.
std::vector< bool > DecodeAsmap(fs::path path)
Read asmap from provided binary file.
static const char *const DEFAULT_BLOCKFILTERINDEX
static void OnRPCStarted()
void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
util::Result< void > SetLoggingLevel(const ArgsManager &args)
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...
void StartREST(const std::any &context)
Start HTTP REST subsystem.
static constexpr bool DEFAULT_RPC_DOC_CHECK
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
static constexpr int DEFAULT_CHECKLEVEL
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...
int Height() const
Return the maximal height in the chain.
util::Result< void > SetLoggingCategories(const ArgsManager &args)
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name...
const CChainParams & chainparams
constexpr int DEFAULT_TOR_CONTROL_PORT
Functionality for communicating with Tor.
static constexpr int DEFAULT_STOPATHEIGHT
void StopREST()
Stop HTTP REST subsystem.
Fatal error which should not prompt to reindex.
void OnStopped(std::function< void()> slot)
static constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
static const bool DEFAULT_LISTEN
-listen default
std::atomic< bool > m_reopen_file
static constexpr bool DEFAULT_PROXYRANDOMIZE
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
static void OnRPCStopped()
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
const std::set< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
static constexpr std::chrono::hours FEE_FLUSH_INTERVAL
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
static void RemovePidFile(const ArgsManager &args)
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
const CBlock & GenesisBlock() const
bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
util::Result< void > SanityChecks(const Context &)
Ensure a usable environment with all necessary library support.
static constexpr bool DEFAULT_CHECKPOINTS_ENABLED
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
void StartMapPort(bool use_upnp, bool use_natpmp)
bool DumpMempool(const CTxMemPool &pool, const fs::path &dump_path, FopenFn mockable_fopen_function, bool skip_file_commit)
bool SetProxy(enum Network net, const Proxy &addrProxy)
static const int64_t nMinDbCache
min. -dbcache (MiB)
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
static constexpr bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
static constexpr unsigned int DEFAULT_BYTES_PER_SIGOP
Default for -bytespersigop.
static void HandleSIGHUP(int)
void InitWarning(const bilingual_str &str)
Show warning message.
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
CChain m_chain
The current chain of blockheaders we consult and build on.
ChainType GetChainType() const
Returns the appropriate chain type from the program arguments.
void StartTorControl(CService onion_service_target)
void InterruptHTTPServer()
Interrupt HTTP server threads.
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
virtual void Construct(node::NodeContext &node) const =0
Add wallets that should be opened to list of chain clients.
static constexpr bool DEFAULT_DAEMON
Default value for -daemon option.
bool require_full_verification
Setting require_full_verification to true will require all checks at check_level (below) to succeed f...
std::string ToStringAddrPort() const
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.
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
void Stop()
Stops the instance from staying in sync with blockchain updates.
const util::SignalInterrupt & m_interrupt
static constexpr unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT_KVB
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
bool AppInitBasicSetup(const ArgsManager &args, std::atomic< int > &exit_status)
Initialize bitcoin core: Basic context setup.
util::Result< std::unique_ptr< AddrMan > > LoadAddrman(const NetGroupManager &netgroupman, const ArgsManager &args)
Returns an error string on failure.
static const bool DEFAULT_PEERBLOCKFILTERS
std::string SysErrorString(int err)
Return system error string from errno value.
static constexpr bool DEFAULT_UPNP
Common init functions shared by bitcoin-node, bitcoin-wallet, etc.
uint256 GetBlockHash() const
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
bool InitSignatureCache(size_t max_size_bytes)
void SetRPCWarmupFinished()
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
static const size_t DEFAULT_MAXRECEIVEBUFFER
std::string ToString(const T &t)
Locale-independent version of std::to_string.
NodeContext struct containing references to chain state and connection state.
disallow -foo syntax that doesn't assign any value
bool IsBadPort(uint16_t port)
Determine if a port is "bad" from the perspective of attempting to connect to a node on that port...
static constexpr unsigned int DEFAULT_BLOCKSONLY_MAX_MEMPOOL_SIZE_MB
Default for -maxmempool when blocksonly is set.
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
static constexpr unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
static std::string PathToString(const path &path)
Convert path object to a byte string.
const std::string DEFAULT_TOR_CONTROL
Default control ip and port.
Chainstate stores and provides an API to update our local knowledge of the current best chain...
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
static constexpr bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool, indicating whether the node should attempt to automatically load the mem...
void StopHTTPServer()
Stop HTTP server.
static std::condition_variable g_genesis_wait_cv
void Interrupt(NodeContext &node)
Interrupt threads.
static constexpr unsigned int DEFAULT_MAX_MEMPOOL_SIZE_MB
Default for -maxmempool, maximum megabytes of mempool memory usage.
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
bool InitError(const bilingual_str &str)
Show error message.
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
static bool TryParse(const std::string &str, NetWhitelistPermissions &output, bilingual_str &error)
bilingual_str _(const char *psz)
Translation function.
static constexpr int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
bool AddLocal(const CService &addr_, int nScore)
fs::path GetBlocksDirPath() const
Get blocks directory path.
A combination of a network address (CNetAddr) and a (TCP) port.
A writer stream (for serialization) that computes a 256-bit hash.
kernel::Notifications & GetNotifications() const
bool ParseUInt16(std::string_view str, uint16_t *out)
Convert decimal string to unsigned 16-bit integer with strict parse error feedback.
bool SetNameProxy(const Proxy &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
static constexpr unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
bool StartLogging(const ArgsManager &args)
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const ChainType chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
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].
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
bool AppInitMain(NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
LockResult LockDirectory(const fs::path &directory, const fs::path &lockfile_name, bool probe_only)
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
How often to dump banned addresses/subnets to disk.
const std::string CURRENCY_UNIT
static constexpr bool DEFAULT_FIXEDSEEDS
CMainSignals & GetMainSignals()
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
static const int64_t nDefaultDbCache
-dbcache default (MiB)
static std::unique_ptr< CZMQNotificationInterface > Create(std::function< bool(CBlock &, const CBlockIndex &)> get_block_by_index)
bool InitScriptExecutionCache(size_t max_size_bytes)
Initializes the script-execution cache.
Block and header tip information.
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
#define WAIT_LOCK(cs, name)
static constexpr bool DEFAULT_V2_TRANSPORT
static constexpr bool DEFAULT_DNSSEED
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
static const int64_t nDefaultDbBatchSize
-dbbatchsize default (bytes)
std::string ToString() const
static fs::path GetPidFile(const ArgsManager &args)
static GlobalMutex g_genesis_wait_mutex
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
static constexpr bool DEFAULT_COINSTATSINDEX
const std::string CLIENT_NAME
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
A base class defining functions for notifying about certain kernel events.
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
static const int DEFAULT_NAME_LOOKUP
-dns default
static constexpr auto DEFAULT_MAX_TIP_AGE
void SetLoggingOptions(const ArgsManager &args)
bilingual_str InvalidPortErrMsg(const std::string &optname, const std::string &invalid_value)
static const int DEFAULT_ZMQ_SNDHWM
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
void AddLoggingArgs(ArgsManager &argsman)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
static bool g_generated_pid
True if this process has created a PID file.
virtual void AddWalletOptions(ArgsManager &argsman) const =0
Get wallet help string.
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
static constexpr int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
void StopHTTPRPC()
Stop HTTP RPC subsystem.
std::function< void()> coins_error_cb
enum Network ParseNetwork(const std::string &net_in)
void DumpBanlist() EXCLUSIVE_LOCKS_REQUIRED(!m_banned_mutex)
static constexpr unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
const CChainParams & GetParams() const
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once) ...
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
double verification_progress
static constexpr bool DEFAULT_NATPMP
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.
static const bool DEFAULT_PEERBLOOMFILTERS
void RegisterZMQRPCCommands(CRPCTable &t)
const WalletInitInterface & g_wallet_init_interface
ChainType GetChainType() const
Return the chain type.
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
static constexpr bool DEFAULT_I2P_ACCEPT_INCOMING
const ChainTxData & TxData() const
virtual void fatalError(const std::string &debug_message, const bilingual_str &user_message={})
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
unsigned int nBytesPerSigOp
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
static const char * DEFAULT_ASMAP_FILENAME
static const size_t DEFAULT_MAXSENDBUFFER
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
uint64_t AssumedBlockchainSize() const
Minimum free space (in GB) needed for data directory.
static void new_handler_terminate()
bool error(const char *fmt, const Args &... args)
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
static const uint32_t DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of non-mempool transactions to keep around for block reconstruction.
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
bool ShutdownRequested(node::NodeContext &node)
Return whether node shutdown was requested.
static constexpr bool DEFAULT_TXRECONCILIATION_ENABLE
Whether transaction reconciliation protocol should be enabled by default.
static const signed int DEFAULT_CHECKBLOCKS
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
static constexpr bool DEFAULT_MEMPOOL_FULL_RBF
Default for -mempoolfullrbf, if the transaction replaceability signaling is ignored.
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
fs::path MempoolPath(const ArgsManager &argsman)
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
const MessageStartChars & MessageStart() const
static constexpr bool DEFAULT_REST_ENABLE
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
std::unique_ptr< const CChainParams > CreateChainParams(const ArgsManager &args, const ChainType chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
ServiceFlags nLocalServices
void InterruptREST()
Interrupt RPC REST subsystem.
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Context struct holding the kernel library's logically global state, and passed to external libbitcoin...
static constexpr bool DEFAULT_PERSIST_V1_DAT
Whether to fall back to legacy V1 serialization when writing mempool.dat.
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS
Default for -checkaddrman.
static const int64_t nMaxDbCache
max. -dbcache (MiB)
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
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...
static constexpr bool DEFAULT_TXINDEX
static const uint32_t DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
std::string GetHex() const
Generic failure which reindexing may fix.
void RemoveAll() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
static std::optional< util::SignalInterrupt > g_shutdown
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 bool DEFAULT_ACCEPT_NON_STD_TXN
Default for -acceptnonstdtxn.
static constexpr bool DEFAULT_FORCEDNSSEED
std::string ChainTypeToString(ChainType chain)
const char *const BITCOIN_CONF_FILENAME
CService DefaultOnionServiceTarget()
static constexpr bool DEFAULT_DAEMONWAIT
Default value for -daemonwait option.
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
bilingual_str ErrorString(const Result< T > &result)
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
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...
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
void StartHTTPServer()
Start HTTP server.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static constexpr size_t DEFAULT_MAX_SIG_CACHE_BYTES
static auto quoted(const std::string &s)
void InterruptTorControl()
void OnStarted(std::function< void()> slot)
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Options struct containing options for constructing a CTxMemPool.
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
bool StartIndexBackgroundSync(NodeContext &node)
Validates requirements to run the indexes and spawns each index initial sync thread.
static bool TryParse(const std::string &str, NetWhitebindPermissions &output, bilingual_str &error)
Different type to mark Mutex at global scope.
int nHeight
height of the entry in the chain. The genesis block has height 0
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
This sequence can have 4 types of outcomes:
static void registerSignalHandler(int signal, void(*handler)(int))
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
static bool exists(const path &p)
#define MIN_CORE_FILEDESCRIPTORS
static const bool DEFAULT_PRINTPRIORITY
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
static const bool DEFAULT_LISTEN_ONION
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
static const bool DEFAULT_ACCEPT_DATACARRIER
Default for -datacarrier.
void InitContext(NodeContext &node)
Initialize node context shutdown and args variables.
static bool CreatePidFile(const ArgsManager &args)
static const int DEFAULT_HTTP_THREADS
static bool AppInitServers(NodeContext &node)
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...
CacheSizes CalculateCacheSizes(const ArgsManager &args, size_t n_indexes)
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
#define Assert(val)
Identity function.
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
static bool LockDataDirectory(bool probeOnly)
ReachableNets g_reachable_nets
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
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...
static const std::string DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Addresses from these networks are not publicly routable on the global Internet.