6 #include <bitcoin-build-config.h> 96 #include <condition_variable> 100 #include <functional> 109 #include <sys/stat.h> 112 #include <boost/signals2/signal.hpp> 154 #define MIN_LEVELDB_FDS 0 156 #define MIN_LEVELDB_FDS 150 199 if (std::error_code error; !fs::remove(pid_path, error)) {
200 std::string
msg{error ? error.message() :
"File does not exist"};
216 if (!(*
node.shutdown_signal)())
return false;
218 if (
node.notifications)
WITH_LOCK(
node.notifications->m_tip_block_mutex,
node.notifications->m_tip_block_cv.notify_all());
254 std::vector<std::thread> threads;
256 threads.emplace_back(runCommand,
cmd);
258 for (
auto& t : threads) {
267 ShutdownNotify(*
node.args);
276 node.connman->Interrupt();
277 for (
auto* index :
node.indexes) {
284 static Mutex g_shutdown_mutex;
285 TRY_LOCK(g_shutdown_mutex, lock_shutdown);
286 if (!lock_shutdown)
return;
287 LogPrintf(
"%s: In progress...\n", __func__);
295 if (
node.mempool)
node.mempool->AddTransactionsUpdated(1);
301 for (
const auto& client :
node.chain_clients) {
308 if (
node.peerman &&
node.validation_signals)
node.validation_signals->UnregisterValidationInterface(
node.peerman.get());
309 if (
node.connman)
node.connman->Stop();
313 if (
node.background_init_thread.joinable())
node.background_init_thread.join();
317 if (
node.scheduler)
node.scheduler->stop();
321 node.peerman.reset();
322 node.connman.reset();
324 node.addrman.reset();
325 node.netgroupman.reset();
333 if (
node.fee_estimator) {
334 node.fee_estimator->Flush();
335 if (
node.validation_signals) {
336 node.validation_signals->UnregisterValidationInterface(
node.fee_estimator.get());
344 if (chainstate->CanFlushToDisk()) {
345 chainstate->ForceFlushStateToDisk();
352 if (
node.validation_signals)
node.validation_signals->FlushBackgroundCallbacks();
355 for (
auto* index :
node.indexes) index->Stop();
359 node.indexes.clear();
370 if (chainstate->CanFlushToDisk()) {
371 chainstate->ForceFlushStateToDisk();
372 chainstate->ResetCoinsViews();
376 for (
const auto& client :
node.chain_clients) {
387 node.chain_clients.clear();
388 if (
node.validation_signals) {
389 node.validation_signals->UnregisterAllValidationInterfaces();
391 node.mempool.reset();
392 node.fee_estimator.reset();
393 node.chainman.reset();
394 node.validation_signals.reset();
395 node.scheduler.reset();
396 node.ecc_context.reset();
422 static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
425 LogError(
"Failed to send shutdown signal on Ctrl-C\n");
438 sigemptyset(&sa.sa_mask);
440 sigaction(signal, &sa,
nullptr);
463 std::vector<std::string> hidden_args = {
464 "-dbcrashratio",
"-forcecompactdb",
466 "-choosedatadir",
"-lang=<lang>",
"-min",
"-resetguisettings",
"-splash",
"-uiplatform"};
472 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);
474 argsman.
AddArg(
"-blocksxor",
475 strprintf(
"Whether an XOR-key applies to blocksdir *.dat files. " 476 "The created XOR-key will be zeros for an existing blocksdir or when `-blocksxor=0` is " 477 "set, and random for a freshly initialized blocksdir. " 498 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);
499 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)",
502 argsman.
AddArg(
"-persistmempoolv1",
503 strprintf(
"Whether a mempool.dat file created by -persistmempool or the savemempool RPC will be written in the legacy format " 504 "(version 1) or the current format (version 2). This temporary option will be removed in the future. (default: %u)",
508 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. " 509 "Warning: Reverting this setting requires re-downloading the entire blockchain. " 511 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);
512 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);
516 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);
519 argsman.
AddArg(
"-blockfilterindex=<type>",
521 " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
527 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);
542 #ifdef HAVE_SOCKADDR_UN 554 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);
555 #ifdef HAVE_SOCKADDR_UN 561 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);
570 argsman.
AddArg(
"-whitebind=<[permissions@]addr>",
"Bind to the given address and add permission flags to the peers connecting to it. " 574 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 " 575 "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as " 577 "Additional flags \"in\" and \"out\" control whether permissions apply to incoming connections and/or manual (default: incoming only). " 594 hidden_args.emplace_back(
"-zmqpubhashblock=<address>");
595 hidden_args.emplace_back(
"-zmqpubhashtx=<address>");
596 hidden_args.emplace_back(
"-zmqpubrawblock=<address>");
597 hidden_args.emplace_back(
"-zmqpubrawtx=<address>");
598 hidden_args.emplace_back(
"-zmqpubsequence=<n>");
599 hidden_args.emplace_back(
"-zmqpubhashblockhwm=<n>");
600 hidden_args.emplace_back(
"-zmqpubhashtxhwm=<n>");
601 hidden_args.emplace_back(
"-zmqpubrawblockhwm=<n>");
602 hidden_args.emplace_back(
"-zmqpubrawtxhwm=<n>");
603 hidden_args.emplace_back(
"-zmqpubsequencehwm=<n>");
623 argsman.
AddArg(
"-maxtipage=<n>",
624 strprintf(
"Maximum tip age in seconds to consider node in initial block download (default: %u)",
638 argsman.
AddArg(
"-datacarriersize",
639 strprintf(
"Relay and mine transactions whose data-carrying raw scriptPubKey " 640 "is of this size or less (default: %u)",
645 argsman.
AddArg(
"-minrelaytxfee=<amt>",
strprintf(
"Fees (in %s/kvB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
657 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);
658 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);
659 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);
664 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);
668 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);
669 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);
672 if (can_listen_ipc) {
673 argsman.
AddArg(
"-ipcbind=<address>",
"Bind to Unix socket address and listen for incoming connections. Valid address values are \"unix\" to listen on the default path, <datadir>/node.sock, or \"unix:/custom/path\" to specify a custom path. Can be specified multiple times to listen on multiple paths. Default behavior is not to listen on any path. If relative paths are specified, they are interpreted relative to the network data directory. If paths include any parent directory components and the parent directories do not exist, they will be created.",
ArgsManager::ALLOW_ANY,
OptionsCategory::IPC);
680 hidden_args.emplace_back(
"-daemon");
681 hidden_args.emplace_back(
"-daemonwait");
693 std::thread
t(runCommand,
cmd);
721 LogInfo(
"parameter interaction: -bind set -> setting -listen=1\n");
725 LogInfo(
"parameter interaction: -whitebind set -> setting -listen=1\n");
732 LogInfo(
"parameter interaction: -connect or -maxconnections=0 set -> setting -dnsseed=0\n");
734 LogInfo(
"parameter interaction: -connect or -maxconnections=0 set -> setting -listen=0\n");
737 std::string proxy_arg =
args.
GetArg(
"-proxy",
"");
738 if (proxy_arg !=
"" && proxy_arg !=
"0") {
741 LogInfo(
"parameter interaction: -proxy set -> setting -listen=0\n");
745 LogInfo(
"parameter interaction: -proxy set -> setting -natpmp=0\n");
749 LogInfo(
"parameter interaction: -proxy set -> setting -discover=0\n");
755 LogInfo(
"parameter interaction: -listen=0 -> setting -natpmp=0\n");
758 LogInfo(
"parameter interaction: -listen=0 -> setting -discover=0\n");
760 LogInfo(
"parameter interaction: -listen=0 -> setting -listenonion=0\n");
762 LogInfo(
"parameter interaction: -listen=0 -> setting -i2pacceptincoming=0\n");
769 LogInfo(
"parameter interaction: -externalip set -> setting -discover=0\n");
775 LogInfo(
"parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n");
784 LogInfo(
"parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n");
787 if (!onlynets.empty()) {
788 bool clearnet_reachable = std::any_of(onlynets.begin(), onlynets.end(), [](
const auto& net) {
793 LogInfo(
"parameter interaction: -onlynet excludes IPv4 and IPv6 -> setting -dnsseed=0\n");
798 bool settings_changed{
false};
802 LogWarning(R
"(Adding "natpmp": %s to settings.json to replace obsolete "upnp" setting)", upnp->write()); 805 LogWarning(R
"(Removing obsolete "upnp" setting from settings.json)"); 807 settings_changed =
true;
817 message =
strprintf(
" Substituting '-natpmp=%s'.", *arg);
819 LogWarning(
"Option '-upnp=%s' is given but UPnP support was dropped in version 29.0.%s",
841 int64_t peer_connect_timeout;
842 std::set<BlockFilterType> g_enabled_filter_types;
852 std::set_new_handler(std::terminate);
853 LogError(
"Out of memory. Terminating.\n");
864 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
865 _CrtSetReportFile(_CRT_WARN, CreateFileA(
"NUL", GENERIC_WRITE, 0,
nullptr, OPEN_EXISTING, 0, 0));
867 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
871 HeapSetInformation(
nullptr, HeapEnableTerminationOnCorruption,
nullptr, 0);
886 signal(SIGPIPE, SIG_IGN);
888 SetConsoleCtrlHandler(consoleCtrlHandler,
true);
915 if (!errors.
empty()) {
921 LogInfo(
"Warning: Support for testnet3 is deprecated and will be removed in an upcoming release. Consider switching to testnet4.\n");
930 if (!warnings.
empty()) {
940 if (blockfilterindex_value ==
"" || blockfilterindex_value ==
"1") {
942 }
else if (blockfilterindex_value !=
"0") {
943 const std::vector<std::string> names =
args.
GetArgs(
"-blockfilterindex");
944 for (
const auto&
name : names) {
949 g_enabled_filter_types.insert(filter_type);
961 return InitError(
_(
"Cannot set -peerblockfilters without -blockfilterindex."));
969 return InitError(
_(
"Prune mode is incompatible with -txindex."));
971 return InitError(
_(
"Prune mode is incompatible with -reindex-chainstate. Use full -reindex instead."));
977 return InitError(
_(
"Cannot set -forcednsseed to true when setting -dnsseed to false."));
995 int nBind = std::max(nUserBind,
size_t(1));
998 if (user_max_connection < 0) {
1008 available_fds = std::min(FD_SETSIZE, available_fds);
1010 if (available_fds < min_required_fds)
1011 return InitError(
strprintf(
_(
"Not enough file descriptors available. %d available, %d required."), available_fds, min_required_fds));
1014 nMaxConnections = std::min(available_fds - min_required_fds, user_max_connection);
1016 if (nMaxConnections < user_max_connection)
1017 InitWarning(
strprintf(
_(
"Reducing -maxconnections from %d to %d, because of system limitations."), user_max_connection, nMaxConnections));
1029 if (peer_connect_timeout <= 0) {
1068 const std::vector<std::string> test_options =
args.
GetArgs(
"-test");
1069 if (!test_options.empty()) {
1073 for (
const std::string& option : test_options) {
1075 size_t pos = doc_option.find(
" (");
1076 return (pos != std::string::npos) && (doc_option.substr(0, pos) == option);
1090 .notifications = notifications,
1093 if (!chainman_result) {
1096 BlockManager::Options blockman_opts_dummy{
1097 .chainparams = chainman_opts_dummy.chainparams,
1099 .notifications = chainman_opts_dummy.notifications,
1106 if (!blockman_result) {
1111 if (!mempool_result) {
1143 return InitError(
strprintf(
_(
"Initialization sanity check failed. %s is shutting down."), CLIENT_NAME));
1147 return InitError(
strprintf(
_(
"Elliptic curve cryptography sanity check failure. %s is shutting down."), CLIENT_NAME));
1170 node.chain =
node.init->makeChain();
1171 node.mining =
node.init->makeMining();
1176 for (
const std::string port_option : {
1181 const std::string port =
args.
GetArg(port_option,
"");
1189 for ([[maybe_unused]]
const auto& [arg, unix] : std::vector<std::pair<std::string, bool>>{
1194 {
"-rpcbind",
false},
1195 {
"-torcontrol",
false},
1196 {
"-whitebind",
false},
1197 {
"-zmqpubhashblock",
true},
1198 {
"-zmqpubhashtx",
true},
1199 {
"-zmqpubrawblock",
true},
1200 {
"-zmqpubrawtx",
true},
1201 {
"-zmqpubsequence",
true},
1203 for (
const std::string& socket_addr :
args.
GetArgs(arg)) {
1204 std::string host_out;
1205 uint16_t port_out{0};
1207 #ifdef HAVE_SOCKADDR_UN 1227 const bool do_reindex_chainstate,
1234 .signals =
node.validation_signals.get(),
1238 node.mempool = std::make_unique<CTxMemPool>(mempool_opts, mempool_error);
1239 if (!mempool_error.
empty()) {
1240 return {ChainstateLoadStatus::FAILURE_FATAL, mempool_error};
1242 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));
1246 .notifications = *
node.notifications,
1247 .signals =
node.validation_signals.get(),
1251 BlockManager::Options blockman_opts{
1252 .chainparams = chainman_opts.chainparams,
1254 .notifications = chainman_opts.notifications,
1258 .wipe_data = do_reindex,
1267 node.chainman = std::make_unique<ChainstateManager>(*
Assert(
node.shutdown_signal), chainman_opts, blockman_opts);
1270 return {ChainstateLoadStatus::FAILURE,
_(
"Error opening block database")};
1271 }
catch (std::exception& e) {
1272 return {ChainstateLoadStatus::FAILURE_FATAL,
Untranslated(
strprintf(
"Failed to initialize ChainstateManager: %s", e.what()))};
1275 if (chainman.
m_interrupt)
return {ChainstateLoadStatus::INTERRUPTED, {}};
1281 if (!
node.chainman->m_blockman.IsPruneMode()) {
1282 LogPrintf(
"[snapshot] re-enabling NODE_NETWORK services\n");
1285 LogPrintf(
"[snapshot] restarting indexes\n");
1288 Assert(
node.validation_signals)->SyncWithValidationInterfaceQueue();
1289 for (
auto* index :
node.indexes) {
1292 if (!(index->Init() && index->StartBackgroundSync())) {
1293 LogPrintf(
"[snapshot] WARNING failed to restart index %s on snapshot chain\n", index->GetName());
1306 _(
"Error reading from database, shutting down."),
1313 }
catch (
const std::exception& e) {
1318 auto [status, error] = catch_exceptions([&] {
return LoadChainstate(chainman, cache_sizes, options); });
1322 LogWarning(
"pruned datadir may not have more than %d blocks; only checking available blocks\n",
1327 LogInfo(
"Block index and chainstate loaded");
1330 return {status, error};
1339 if (!opt_max_upload) {
1353 LogPrintf(
"Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, available_fds);
1357 LogPrintf(
"Warning: relative datadir option '%s' specified, which will be interpreted relative to the " 1358 "current working directory '%s'. This is fragile, because if bitcoin is started in the future " 1359 "from a different location, it will be unable to locate the current data files. There could " 1360 "also be data loss if bitcoin is started while in a temporary directory.\n",
1365 node.scheduler = std::make_unique<CScheduler>();
1366 auto& scheduler = *
node.scheduler;
1369 scheduler.m_service_thread = std::thread(
util::TraceThread,
"scheduler", [&] { scheduler.serviceQueue(); });
1372 scheduler.scheduleEvery([]{
1374 }, std::chrono::minutes{1});
1377 scheduler.scheduleEvery([&
args, &
node]{
1378 constexpr uint64_t min_disk_space = 50 << 20;
1380 LogError(
"Shutting down due to lack of disk space!\n");
1382 LogError(
"Failed to send shutdown signal after disk space check\n");
1385 }, std::chrono::minutes{5});
1389 [&scheduler](
auto func,
auto window) { scheduler.scheduleEvery(std::move(func), window); },
1393 LogInfo(
"Log rate limiting disabled");
1397 node.validation_signals = std::make_unique<ValidationSignals>(std::make_unique<SerialTaskRunner>(scheduler));
1398 auto& validation_signals = *
node.validation_signals;
1408 for (std::string address :
gArgs.
GetArgs(
"-ipcbind")) {
1410 ipc->listenAddress(address);
1411 }
catch (
const std::exception& e) {
1414 LogPrintf(
"Listening for IPC requests on address %s\n", address);
1422 for (
const auto& client :
node.chain_clients) {
1423 client->registerRpcs();
1440 return InitError(
_(
"Unable to start HTTP server. See debug log for details."));
1444 for (
const auto& client :
node.chain_clients) {
1445 if (!client->verify()) {
1465 std::vector<bool> asmap;
1468 if (!asmap_path.is_absolute()) {
1476 if (asmap.size() == 0) {
1481 LogPrintf(
"Using asmap version %s for IP bucketing\n", asmap_version.
ToString());
1483 LogPrintf(
"Using /16 prefix for IP bucketing\n");
1488 node.netgroupman = std::make_unique<NetGroupManager>(std::move(asmap));
1492 uiInterface.InitMessage(
_(
"Loading P2P addresses…"));
1495 node.addrman = std::move(*addrman);
1502 node.connman = std::make_unique<CConnman>(rng.
rand64(),
1509 if (!peerman_opts.ignore_incoming_txs) {
1514 node.fee_estimator = std::make_unique<CBlockPolicyEstimator>(
FeeestPath(
args), read_stale_estimates);
1518 scheduler.scheduleEvery([fee_estimator] { fee_estimator->FlushFeeEstimates(); },
FEE_FLUSH_INTERVAL);
1519 validation_signals.RegisterValidationInterface(fee_estimator);
1522 for (
const std::string& socket_addr :
args.
GetArgs(
"-bind")) {
1523 std::string host_out;
1524 uint16_t port_out{0};
1525 std::string bind_socket_addr = socket_addr.substr(0, socket_addr.rfind(
'='));
1532 std::vector<std::string> uacomments;
1533 for (
const std::string& cmt :
args.
GetArgs(
"-uacomment")) {
1535 return InitError(
strprintf(
_(
"User Agent comment (%s) contains unsafe characters."), cmt));
1536 uacomments.push_back(cmt);
1540 return InitError(
strprintf(
_(
"Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1545 if (!onlynets.empty()) {
1547 for (
const std::string& snet : onlynets) {
1558 _(
"Outbound connections restricted to CJDNS (-onlynet=cjdns) but " 1559 "-cjdnsreachable is not provided"));
1572 return InitError(
strprintf(
_(
"Incompatible options: -dnsseed=1 was explicitly specified, but -onlynet forbids connections to IPv4/IPv6")));
1583 std::string proxyArg =
args.
GetArg(
"-proxy",
"");
1584 if (proxyArg !=
"" && proxyArg !=
"0") {
1587 addrProxy =
Proxy(proxyArg, proxyRandomize);
1590 if (!proxyAddr.has_value()) {
1594 addrProxy =
Proxy(proxyAddr.value(), proxyRandomize);
1604 onion_proxy = addrProxy;
1612 std::string onionArg =
args.
GetArg(
"-onion",
"");
1613 if (onionArg !=
"") {
1614 if (onionArg ==
"0") {
1615 onion_proxy =
Proxy{};
1616 if (onlynet_used_with_onion) {
1618 _(
"Outbound connections restricted to Tor (-onlynet=onion) but the proxy for " 1619 "reaching the Tor network is explicitly forbidden: -onion=0"));
1623 onion_proxy =
Proxy(onionArg, proxyRandomize);
1626 if (!addr.has_value() || !addr->IsValid()) {
1630 onion_proxy =
Proxy(addr.value(), proxyRandomize);
1641 if (onlynet_used_with_onion && listenonion_disabled) {
1643 _(
"Outbound connections restricted to Tor (-onlynet=onion) but the proxy for " 1644 "reaching the Tor network is not provided: none of -proxy, -onion or " 1645 "-listenonion is given"));
1650 for (
const std::string& strAddr :
args.
GetArgs(
"-externalip")) {
1652 if (addrLocal.has_value() && addrLocal->IsValid())
1660 [&chainman =
node.chainman](std::vector<uint8_t>& block,
const CBlockIndex& index) {
1662 return chainman->m_blockman.ReadRawBlock(block, WITH_LOCK(cs_main, return index.GetBlockPos()));
1673 auto& kernel_notifications{*
node.notifications};
1677 const auto [index_cache_sizes, kernel_cache_sizes] =
CalculateCacheSizes(
args, g_enabled_filter_types.size());
1679 LogInfo(
"Cache configuration:");
1680 LogInfo(
"* Using %.1f MiB for block index database", kernel_cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
1682 LogInfo(
"* Using %.1f MiB for transaction index database", index_cache_sizes.tx_index * (1.0 / 1024 / 1024));
1685 LogInfo(
"* Using %.1f MiB for %s block filter index database",
1688 LogInfo(
"* Using %.1f MiB for chain state database", kernel_cache_sizes.coins_db * (1.0 / 1024 / 1024));
1694 const bool do_reindex_chainstate{
args.
GetBoolArg(
"-reindex-chainstate",
false)};
1700 do_reindex_chainstate,
1706 error +
Untranslated(
".\n\n") +
_(
"Do you want to rebuild the databases now?"),
1707 error.original +
".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1713 if (!
Assert(
node.shutdown_signal)->reset()) {
1714 LogError(
"Internal error: failed to reset shutdown signal.\n");
1719 do_reindex_chainstate,
1723 if (status != ChainstateLoadStatus::SUCCESS && status != ChainstateLoadStatus::INTERRUPTED) {
1730 LogPrintf(
"Shutdown requested. Exiting.\n");
1738 node.banman.get(), chainman,
1741 validation_signals.RegisterValidationInterface(
node.peerman.get());
1750 for (
const auto& filter_type : g_enabled_filter_types) {
1761 for (
auto index :
node.indexes)
if (!index->Init())
return false;
1764 for (
const auto& client :
node.chain_clients) {
1765 if (!client->load()) {
1779 chainstate->PruneAndFlush();
1785 LogPrintf(
"Setting NODE_NETWORK on non-prune mode\n");
1788 LogPrintf(
"Running node in NODE_NETWORK_LIMITED mode until snapshot background sync completes\n");
1806 if (!do_reindex && !do_reindex_chainstate && chain_active_height <= 1) {
1808 uint64_t additional_bytes_needed{
1811 assumed_chain_bytes};
1815 "Disk space for %s may not accommodate the block files. " \
1816 "Approximately %u GB of data will be stored in this directory." 1825 const std::string block_notify =
args.
GetArg(
"-blocknotify",
"");
1826 if (!block_notify.empty()) {
1829 std::string
command = block_notify;
1831 std::thread
t(runCommand,
command);
1837 std::vector<fs::path> vImportFiles;
1838 for (
const std::string& strFile :
args.
GetArgs(
"-loadblock")) {
1847 LogPrintf(
"Stopping after block import\n");
1849 LogError(
"Failed to send shutdown signal after finishing block import\n");
1856 bilingual_str err_str =
_(
"Failed to start indexes, shutting down..");
1879 WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
1880 kernel_notifications.m_tip_block_cv.wait(lock, [&]()
EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
1881 return kernel_notifications.TipBlock() || ShutdownRequested(node);
1891 int64_t best_block_time{};
1896 chain_active_height = tip.nHeight;
1897 best_block_time = tip.GetBlockTime();
1903 if (tip_info && chainman.m_best_header) {
1905 tip_info->
header_time = chainman.m_best_header->GetBlockTime();
1908 LogPrintf(
"nBestHeight = %d\n", chain_active_height);
1909 if (
node.peerman)
node.peerman->SetBestBlock(chain_active_height, std::chrono::seconds{best_block_time});
1916 connOptions.m_max_automatic_connections = nMaxConnections;
1918 connOptions.m_banman =
node.banman.get();
1919 connOptions.m_msgproc =
node.peerman.get();
1922 connOptions.m_added_nodes =
args.
GetArgs(
"-addnode");
1923 connOptions.nMaxOutboundLimit = *opt_max_upload;
1924 connOptions.m_peer_connect_timeout = peer_connect_timeout;
1929 const uint16_t default_bind_port =
1932 const uint16_t default_bind_port_onion = default_bind_port + 1;
1934 const auto BadPortWarning = [](
const char*
prefix, uint16_t port) {
1935 return strprintf(
_(
"%s request to listen on port %u. This port is considered \"bad\" and " 1936 "thus it is unlikely that any peer will connect to it. See " 1937 "doc/p2p-bad-ports.md for details and a full list."),
1942 for (
const std::string& bind_arg :
args.
GetArgs(
"-bind")) {
1943 std::optional<CService> bind_addr;
1944 const size_t index = bind_arg.rfind(
'=');
1945 if (index == std::string::npos) {
1946 bind_addr =
Lookup(bind_arg, default_bind_port,
false);
1947 if (bind_addr.has_value()) {
1948 connOptions.vBinds.push_back(bind_addr.value());
1949 if (
IsBadPort(bind_addr.value().GetPort())) {
1950 InitWarning(BadPortWarning(
"-bind", bind_addr.value().GetPort()));
1955 const std::string network_type = bind_arg.substr(index + 1);
1956 if (network_type ==
"onion") {
1957 const std::string truncated_bind_arg = bind_arg.substr(0, index);
1958 bind_addr =
Lookup(truncated_bind_arg, default_bind_port_onion,
false);
1959 if (bind_addr.has_value()) {
1960 connOptions.onion_binds.push_back(bind_addr.value());
1968 for (
const std::string& strBind :
args.
GetArgs(
"-whitebind")) {
1972 connOptions.vWhiteBinds.push_back(whitebind);
1981 if (connOptions.bind_on_any &&
args.
IsArgSet(
"-port")) {
1989 if (!connOptions.onion_binds.empty()) {
1990 onion_service_target = connOptions.onion_binds.front();
1991 }
else if (!connOptions.vBinds.empty()) {
1992 onion_service_target = connOptions.vBinds.front();
1995 connOptions.onion_binds.push_back(onion_service_target);
1999 if (connOptions.onion_binds.size() > 1) {
2001 "for the automatically created Tor onion service."),
2007 if (connOptions.bind_on_any) {
2013 for (
const auto& net :
args.
GetArgs(
"-whitelist")) {
2019 connOptions.vWhitelistedRangeIncoming.push_back(subnet);
2022 connOptions.vWhitelistedRangeOutgoing.push_back(subnet);
2026 connOptions.vSeedNodes =
args.
GetArgs(
"-seednode");
2032 connOptions.m_use_addrman_outgoing =
false;
2034 if (connect.size() != 1 || connect[0] !=
"0") {
2035 connOptions.m_specified_outgoing = connect;
2037 if (!connOptions.m_specified_outgoing.empty() && !connOptions.vSeedNodes.empty()) {
2038 LogPrintf(
"-seednode is ignored when -connect is used\n");
2042 LogPrintf(
"-dnsseed is ignored when -connect is used and -proxy is specified\n");
2046 const std::string& i2psam_arg =
args.
GetArg(
"-i2psam",
"");
2047 if (!i2psam_arg.empty()) {
2049 if (!addr.has_value() || !addr->IsValid()) {
2056 _(
"Outbound connections restricted to i2p (-onlynet=i2p) but " 2057 "-i2psam is not provided"));
2064 if (!
node.connman->Start(scheduler, connOptions)) {
2078 for (
const auto& client :
node.chain_clients) {
2079 client->start(scheduler);
2083 scheduler.scheduleEvery([banman]{
2087 if (
node.peerman)
node.peerman->StartScheduledTasks(scheduler);
2090 StartupNotify(
args);
2102 std::optional<const CBlockIndex*> indexes_start_block;
2103 std::string older_index_name;
2108 for (
auto index :
node.indexes) {
2110 if (summary.
synced)
continue;
2115 if (!index_chain.Contains(pindex)) {
2116 pindex = index_chain.FindFork(pindex);
2119 if (!indexes_start_block || !pindex || pindex->
nHeight < indexes_start_block.value()->nHeight) {
2120 indexes_start_block = pindex;
2121 older_index_name = summary.
name;
2127 if (indexes_start_block) {
2129 const CBlockIndex* start_block = *indexes_start_block;
2131 if (!chainman.
m_blockman.CheckBlockDataAvailability(*index_chain.Tip(), *
Assert(start_block))) {
2132 return InitError(
Untranslated(
strprintf(
"%s best block of the index goes beyond pruned data. Please disable the index or reindex (which will download the whole blockchain again)", older_index_name)));
2137 for (
auto index :
node.indexes)
if (!index->StartBackgroundSync())
return false;
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
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.
fs::path path
Location in the filesystem where leveldb data will be stored.
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
static const bool DEFAULT_PRINT_MODIFIED_FEE
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)
bool ShouldPersistMempool(const ArgsManager &argsman)
const std::string ADDR_PREFIX_UNIX
Prefix for unix domain socket addresses (which are local filesystem paths)
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
void Remove(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
static constexpr size_t MIN_DB_CACHE
min. -dbcache (bytes)
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
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. ...
bool IsUnixSocketPath(const std::string &name)
Check if a string is a valid UNIX domain socket path.
CClientUIInterface uiInterface
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)
const char *const BITCOIN_SETTINGS_FILENAME
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.
const std::string UA_NAME
static constexpr bool DEFAULT_ACCEPT_STALE_FEE_ESTIMATES
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
constexpr bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
static const int DEFAULT_HTTP_WORKQUEUE
The default value for -rpcworkqueue.
static void RegisterAllCoreRPCCommands(CRPCTable &t)
An in-memory indexed chain of blocks.
static constexpr unsigned int DEFAULT_BLOCK_RESERVED_WEIGHT
Default for -blockreservedweight.
bool CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND, const CBlockIndex &lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, uint32_t status_mask, const CBlockIndex *lower_block=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(boo m_have_pruned)
Check if all blocks in the [upper_block, lower_block] range have data available.
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
std::vector< bool > DecodeAsmap(fs::path path)
Read asmap from provided binary file.
static const char *const DEFAULT_BLOCKFILTERINDEX
void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, node::Warnings &warnings, Options opts)
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
const std::vector< std::string > TEST_OPTIONS_DOC
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)
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.
static constexpr unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
static const bool DEFAULT_LISTEN
-listen default
static constexpr int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
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...
constexpr uint64_t RATELIMIT_MAX_BYTES
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...
bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
ChainstateLoadStatus
Chainstate load status.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
static constexpr size_t DEFAULT_VALIDATION_CACHE_BYTES
util::Result< void > SanityChecks(const Context &)
Ensure a usable environment with all necessary library support.
bool AppInitLockDirectories()
Lock bitcoin core critical directories.
static constexpr bool DEFAULT_CHECKPOINTS_ENABLED
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
bool SetProxy(enum Network net, const Proxy &addrProxy)
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.
double GuessVerificationProgress(const CBlockIndex *pindex) const
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
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.
consteval auto _(util::TranslatedLiteral str)
ChainType GetChainType() const
Returns the appropriate chain type from the program arguments.
void ImportBlocks(ChainstateManager &chainman, std::span< const fs::path > import_paths)
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)
void ThreadRename(const std::string &)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name...
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...
static ChainstateLoadResult InitAndLoadChainstate(NodeContext &node, bool do_reindex, const bool do_reindex_chainstate, const kernel::CacheSizes &cache_sizes, const ArgsManager &args)
std::string ToStringAddrPort() const
virtual void fatalError(const bilingual_str &message)
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
const util::SignalInterrupt & m_interrupt
bool DumpMempool(const CTxMemPool &pool, const fs::path &dump_path, FopenFn mockable_fopen_function, bool skip_file_commit)
void SetupServerArgs(ArgsManager &argsman, bool can_listen_ipc)
Register all arguments with the ArgsManager.
static constexpr unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT_KVB
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
std::function< void()> snapshot_download_completed
Function to restart active indexes; set dynamically to avoid a circular dependency on base/index...
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 unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
static const bool DEFAULT_PEERBLOCKFILTERS
std::string SysErrorString(int err)
Return system error string from errno value.
static constexpr bool DEFAULT_XOR_BLOCKSDIR
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.
Common init functions shared by bitcoin-node, bitcoin-wallet, etc.
uint256 GetBlockHash() const
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
void SetRPCWarmupFinished()
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
static const size_t DEFAULT_MAXRECEIVEBUFFER
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.
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
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...
constexpr bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
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.
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 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.
void StartMapPort(bool enable)
static std::shared_ptr< LogRateLimiter > Create(SchedulerFunction &&scheduler_func, uint64_t max_bytes, std::chrono::seconds reset_window)
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, 48334, 18445) have been chosen arbitra...
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
constexpr bool DEFAULT_LOGRATELIMIT
static constexpr bool DEFAULT_FIXEDSEEDS
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...
Block and header tip information.
std::atomic_bool m_blockfiles_indexed
Whether all blockfiles have been added to the block tree database.
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
static const int64_t nDefaultDbBatchSize
-dbbatchsize default (bytes)
std::string ToString() const
static fs::path GetPidFile(const ArgsManager &args)
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
static constexpr bool DEFAULT_COINSTATSINDEX
static bool LockDirectory(const fs::path &dir, bool probeOnly)
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)
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 LockDirectories(bool probeOnly)
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.
CService DefaultOnionServiceTarget(uint16_t port)
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
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.
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
double verification_progress
static std::unique_ptr< CZMQNotificationInterface > Create(std::function< bool(std::vector< uint8_t > &, const CBlockIndex &)> get_block_by_index)
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.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
static constexpr bool DEFAULT_I2P_ACCEPT_INCOMING
unsigned int nBytesPerSigOp
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr, bool backup=false) const
Write settings file or backup settings file.
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()
static constexpr size_t DEFAULT_DB_CACHE
-dbcache default (bytes)
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.
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
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
static bool TryParse(const std::string &str, NetWhitelistPermissions &output, ConnectionDirection &output_connection_direction, bilingual_str &error)
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.
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.
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.
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.
bool CheckHostPortOptions(const ArgsManager &args)
std::string GetHex() const
Generic failure which reindexing may fix.
void RemoveAll() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
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...
Application-specific storage settings.
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
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...
static constexpr int MIN_CORE_FDS
void StartHTTPServer()
Start HTTP server.
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
std::map< std::string, SettingsValue > rw_settings
Map of setting name to read-write file setting value.
static auto quoted(const std::string &s)
void InterruptTorControl()
ServiceFlags m_local_services
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
std::tuple< ChainstateLoadStatus, bilingual_str > ChainstateLoadResult
Chainstate load status code and optional error string.
bilingual_str InvalidPortErrMsg(const std::string &optname, const std::string &invalid_value)
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)
int nHeight
height of the entry in the chain. The genesis block has height 0
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
void LockSettings(Fn &&fn)
Access settings with lock held.
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.
constexpr auto RATELIMIT_WINDOW
static bool exists(const path &p)
uint64_t rand64() noexcept
Generate a random 64-bit integer.
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
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
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
The default value for -rpcthreads.
static constexpr unsigned int MINIMUM_BLOCK_RESERVED_WEIGHT
This accounts for the block header, var_int encoding of the transaction count and a minimally viable ...
static 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...
Interface providing access to interprocess-communication (IPC) functionality.
CacheSizes CalculateCacheSizes(const ArgsManager &args, size_t n_indexes)
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
#define Assert(val)
Identity function.
void SetRateLimiting(std::shared_ptr< LogRateLimiter > limiter) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
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.
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Addresses from these networks are not publicly routable on the global Internet.