 |
Bitcoin Core
21.99.0
P2P Digital Currency
|
Go to the documentation of this file.
6 #if defined(HAVE_CONFIG_H)
81 #include <boost/algorithm/string/replace.hpp>
82 #include <boost/signals2/signal.hpp>
97 #define MIN_CORE_FILEDESCRIPTORS 0
99 #define MIN_CORE_FILEDESCRIPTORS 150
165 node.connman->Interrupt();
174 static Mutex g_shutdown_mutex;
175 TRY_LOCK(g_shutdown_mutex, lock_shutdown);
176 if (!lock_shutdown)
return;
177 LogPrintf(
"%s: In progress...\n", __func__);
185 if (
node.mempool)
node.mempool->AddTransactionsUpdated(1);
191 for (
const auto& client :
node.chain_clients) {
209 node.connman->StopThreads();
211 node.connman->StopNodes();
218 if (
node.scheduler)
node.scheduler->stop();
219 if (
node.chainman &&
node.chainman->m_load_block.joinable())
node.chainman->m_load_block.join();
224 node.peerman.reset();
225 node.connman.reset();
227 node.addrman.reset();
234 if (
node.fee_estimator)
node.fee_estimator->Flush();
240 if (chainstate->CanFlushToDisk()) {
241 chainstate->ForceFlushStateToDisk();
267 if (chainstate->CanFlushToDisk()) {
268 chainstate->ForceFlushStateToDisk();
269 chainstate->ResetCoinsViews();
274 for (
const auto& client :
node.chain_clients) {
286 node.chain_clients.clear();
291 node.mempool.reset();
292 node.fee_estimator.reset();
293 node.chainman =
nullptr;
294 node.scheduler.reset();
298 LogPrintf(
"%s: Unable to remove PID file: File does not exist\n", __func__);
300 }
catch (
const fs::filesystem_error& e) {
324 static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
337 sigemptyset(&sa.sa_mask);
339 sigaction(signal, &sa,
nullptr);
376 std::vector<std::string> hidden_args = {
377 "-dbcrashratio",
"-forcecompactdb",
379 "-choosedatadir",
"-lang=<lang>",
"-min",
"-resetguisettings",
"-splash",
"-uiplatform"};
385 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);
405 argsman.
AddArg(
"-par=<n>",
strprintf(
"Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)",
409 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 and -rescan. "
410 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
421 hidden_args.emplace_back(
"-sysperms");
424 argsman.
AddArg(
"-blockfilterindex=<type>",
426 " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
432 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);
449 argsman.
AddArg(
"-i2pacceptincoming",
"If set and -i2psam is also set then incoming I2P connections are accepted via the SAM proxy. If this is not set but -i2psam is set then only outgoing connections will be made to the I2P network. Ignored if -i2psam is not set. Listening for incoming I2P connections is done through the SAM proxy, not by binding to a local address and port (default: 1)",
ArgsManager::ALLOW_BOOL,
OptionsCategory::CONNECTION);
450 argsman.
AddArg(
"-onlynet=<net>",
"Make outgoing connections only through network <net> (" +
Join(
GetNetworkNames(),
", ") +
"). Incoming connections are not affected by this option. This option can be specified multiple times to allow multiple networks. Warning: if it is used with non-onion networks and the -onion or -proxy option is set, then outbound onion connections will still be made; use -noonion or -onion=0 to disable outbound onion connections in this case.",
ArgsManager::ALLOW_ANY,
OptionsCategory::CONNECTION);
454 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.", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()),
ArgsManager::ALLOW_ANY |
ArgsManager::NETWORK_ONLY,
OptionsCategory::CONNECTION);
470 hidden_args.emplace_back(
"-upnp");
475 hidden_args.emplace_back(
"-natpmp");
477 argsman.
AddArg(
"-whitebind=<[permissions@]addr>",
"Bind to the given address and add permission flags to the peers connecting to it. "
481 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 "
482 "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as "
499 hidden_args.emplace_back(
"-zmqpubhashblock=<address>");
500 hidden_args.emplace_back(
"-zmqpubhashtx=<address>");
501 hidden_args.emplace_back(
"-zmqpubrawblock=<address>");
502 hidden_args.emplace_back(
"-zmqpubrawtx=<address>");
503 hidden_args.emplace_back(
"-zmqpubsequence=<n>");
504 hidden_args.emplace_back(
"-zmqpubhashblockhwm=<n>");
505 hidden_args.emplace_back(
"-zmqpubhashtxhwm=<n>");
506 hidden_args.emplace_back(
"-zmqpubrawblockhwm=<n>");
507 hidden_args.emplace_back(
"-zmqpubrawtxhwm=<n>");
508 hidden_args.emplace_back(
"-zmqpubsequencehwm=<n>");
525 argsman.
AddArg(
"-debug=<category>",
"Output debugging information (default: -nodebug, supplying <category> is optional). "
526 "If <category> is not supplied or if <category> = 1, output all debugging information. <category> can be: " +
LogInstance().LogCategoriesString() +
". This option can be specified multiple times to output multiple categories.",
528 argsman.
AddArg(
"-debugexclude=<category>",
strprintf(
"Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except the specified category. This option can be specified multiple times to exclude multiple categories."),
ArgsManager::ALLOW_ANY,
OptionsCategory::DEBUG_TEST);
531 #ifdef HAVE_THREAD_LOCAL
534 hidden_args.emplace_back(
"-logthreadnames");
554 argsman.
AddArg(
"-minrelaytxfee=<amt>",
strprintf(
"Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
565 argsman.
AddArg(
"-rpcallowip=<ip>",
"Allow JSON-RPC connections from specified source. Valid 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) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times",
ArgsManager::ALLOW_ANY,
OptionsCategory::RPC);
566 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);
567 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 |
ArgsManager::SENSITIVE,
OptionsCategory::RPC);
570 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);
575 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);
576 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_BOOL,
OptionsCategory::RPC);
584 hidden_args.emplace_back(
"-daemon");
585 hidden_args.emplace_back(
"-daemonwait");
594 const std::string URL_SOURCE_CODE =
"<https://github.com/bitcoin/bitcoin>";
598 strprintf(
_(
"Please contribute if you find %s useful. "
599 "Visit %s for further information about the software.").translated,
602 strprintf(
_(
"The source code is available from %s.").translated,
606 _(
"This is experimental software.").
translated +
"\n" +
607 strprintf(
_(
"Distributed under the MIT software license, see the accompanying file %s or %s").translated,
"COPYING",
"<https://opensource.org/licenses/MIT>") +
617 if (pBlockIndex !=
nullptr) {
634 std::map<std::string, fs::path> mapBlockFiles;
639 LogPrintf(
"Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
641 for (fs::directory_iterator
it(blocksdir);
it != fs::directory_iterator();
it++) {
642 if (fs::is_regular_file(*
it) &&
643 it->path().filename().string().length() == 12 &&
644 it->path().filename().string().substr(8,4) ==
".dat")
646 if (
it->path().filename().string().substr(0,3) ==
"blk")
647 mapBlockFiles[
it->path().filename().string().substr(3,5)] =
it->path();
648 else if (
it->path().filename().string().substr(0,3) ==
"rev")
657 int nContigCounter = 0;
658 for (
const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
659 if (
atoi(item.first) == nContigCounter) {
670 std::string cmd = args.
GetArg(
"-startupnotify",
"");
672 std::thread t(runCommand, cmd);
725 LogPrintf(
"%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
729 LogPrintf(
"%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
735 LogPrintf(
"%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
737 LogPrintf(
"%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
743 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
747 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
749 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -natpmp=0\n", __func__);
753 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
759 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
761 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -natpmp=0\n", __func__);
764 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
766 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
768 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -i2pacceptincoming=0\n", __func__);
775 LogPrintf(
"%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
781 LogPrintf(
"%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
787 LogPrintf(
"%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
804 #ifdef HAVE_THREAD_LOCAL
813 version_string +=
" (debug build)";
815 version_string +=
" (release build)";
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);
879 signal(SIGPIPE, SIG_IGN);
881 SetConsoleCtrlHandler(consoleCtrlHandler,
true);
905 errors +=
strprintf(
_(
"Config setting for %s only applied on %s network when in [%s] section.") +
Untranslated(
"\n"), arg, network, network);
908 if (!errors.
empty()) {
918 if (!warnings.
empty()) {
928 if (blockfilterindex_value ==
"" || blockfilterindex_value ==
"1") {
930 }
else if (blockfilterindex_value !=
"0") {
931 const std::vector<std::string> names = args.
GetArgs(
"-blockfilterindex");
932 for (
const auto&
name : names) {
937 g_enabled_filter_types.insert(filter_type);
944 return InitError(
_(
"Cannot set -peerblockfilters without -blockfilterindex."));
951 if (args.
GetArg(
"-prune", 0)) {
953 return InitError(
_(
"Prune mode is incompatible with -txindex."));
957 size_t nUserBind = args.
GetArgs(
"-bind").size() + args.
GetArgs(
"-whitebind").size();
963 int nBind = std::max(nUserBind,
size_t(1));
965 nMaxConnections = std::max(nUserMaxConnections, 0);
974 int fd_max = FD_SETSIZE;
978 return InitError(
_(
"Not enough file descriptors available."));
981 if (nMaxConnections < nUserMaxConnections)
982 InitWarning(
strprintf(
_(
"Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
987 const std::vector<std::string> categories = args.
GetArgs(
"-debug");
989 if (std::none_of(categories.begin(), categories.end(),
990 [](std::string cat){return cat ==
"0" || cat ==
"none";})) {
991 for (
const auto& cat : categories) {
1000 for (
const std::string& cat : args.
GetArgs(
"-debugexclude")) {
1013 LogPrintf(
"Validating signatures for all blocks.\n");
1015 if (args.
IsArgSet(
"-minimumchainwork")) {
1016 const std::string minChainWorkStr = args.
GetArg(
"-minimumchainwork",
"");
1032 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
1033 return InitError(
strprintf(
_(
"-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
1036 if (args.
IsArgSet(
"-incrementalrelayfee")) {
1044 int64_t nPruneArg = args.
GetArg(
"-prune", 0);
1045 if (nPruneArg < 0) {
1046 return InitError(
_(
"Prune cannot be configured with a negative value."));
1049 if (nPruneArg == 1) {
1050 LogPrintf(
"Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1057 LogPrintf(
"Prune configured to target %u MiB on disk for block and undo files.\n",
nPruneTarget / 1024 / 1024);
1067 if (peer_connect_timeout <= 0) {
1071 if (args.
IsArgSet(
"-minrelaytxfee")) {
1086 if (args.
IsArgSet(
"-blockmintxfee")) {
1094 if (args.
IsArgSet(
"-dustrelayfee")) {
1127 if (args.
IsArgSet(
"-proxy") && args.
GetArg(
"-proxy",
"").empty()) {
1128 return InitError(
_(
"No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
1139 return InitError(
strprintf(
_(
"Cannot write to data directory '%s'; check permissions."), datadir.string()));
1153 LogPrintf(
"Using the '%s' SHA256 implementation\n", sha256_algo);
1219 if (fs::exists(config_file_path)) {
1220 LogPrintf(
"Config file: %s\n", config_file_path.string());
1221 }
else if (args.
IsArgSet(
"-conf")) {
1223 InitWarning(
strprintf(
_(
"The specified config file %s does not exist"), config_file_path.string()));
1226 LogPrintf(
"Config file: %s (not found, skipping)\n", config_file_path.string());
1232 LogPrintf(
"Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1235 if (args.
IsArgSet(
"-datadir") && !fs::path(args.
GetArg(
"-datadir",
"")).is_absolute()) {
1236 LogPrintf(
"Warning: relative datadir option '%s' specified, which will be interpreted relative to the "
1237 "current working directory '%s'. This is fragile, because if bitcoin is started in the future "
1238 "from a different location, it will be unable to locate the current data files. There could "
1239 "also be data loss if bitcoin is started while in a temporary directory.\n",
1240 args.
GetArg(
"-datadir",
""), fs::current_path().string());
1247 if (script_threads <= 0) {
1254 script_threads = std::max(script_threads - 1, 0);
1259 LogPrintf(
"Script verification uses %d additional threads\n", script_threads);
1260 if (script_threads >= 1) {
1266 node.scheduler = std::make_unique<CScheduler>();
1269 node.scheduler->m_service_thread = std::thread([&] {
TraceThread(
"scheduler", [&] {
node.scheduler->serviceQueue(); }); });
1272 node.scheduler->scheduleEvery([]{
1274 }, std::chrono::minutes{1});
1282 for (
const auto& client :
node.chain_clients) {
1283 client->registerRpcs();
1297 return InitError(
_(
"Unable to start HTTP server. See debug log for details."));
1301 for (
const auto& client :
node.chain_clients) {
1302 if (!client->verify()) {
1318 node.addrman = std::make_unique<CAddrMan>();
1322 node.connman = std::make_unique<CConnman>(
GetRand(std::numeric_limits<uint64_t>::max()),
GetRand(std::numeric_limits<uint64_t>::max()), *
node.addrman, args.
GetBoolArg(
"-networkactive",
true));
1327 if (!ignores_incoming_txs)
node.fee_estimator = std::make_unique<CBlockPolicyEstimator>();
1331 node.mempool = std::make_unique<CTxMemPool>(
node.fee_estimator.get(), check_ratio);
1339 *
node.scheduler, chainman, *
node.mempool, ignores_incoming_txs);
1343 std::vector<std::string> uacomments;
1344 for (
const std::string& cmt : args.
GetArgs(
"-uacomment")) {
1346 return InitError(
strprintf(
_(
"User Agent comment (%s) contains unsafe characters."), cmt));
1347 uacomments.push_back(cmt);
1351 return InitError(
strprintf(
_(
"Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1356 std::set<enum Network> nets;
1357 for (
const std::string& snet : args.
GetArgs(
"-onlynet")) {
1363 for (
int n = 0; n <
NET_MAX; n++) {
1365 if (!nets.count(net))
1376 std::string proxyArg = args.
GetArg(
"-proxy",
"");
1378 if (proxyArg !=
"" && proxyArg !=
"0") {
1398 std::string onionArg = args.
GetArg(
"-onion",
"");
1399 if (onionArg !=
"") {
1400 if (onionArg ==
"0") {
1415 for (
const std::string& strAddr : args.
GetArgs(
"-externalip")) {
1425 fs::path asmap_path = fs::path(args.
GetArg(
"-asmap",
""));
1426 if (asmap_path.empty()) {
1429 if (!asmap_path.is_absolute()) {
1432 if (!fs::exists(asmap_path)) {
1437 if (asmap.size() == 0) {
1442 node.connman->SetAsmap(std::move(asmap));
1443 LogPrintf(
"Using asmap version %s for IP bucketing\n", asmap_version.
ToString());
1445 LogPrintf(
"Using /16 prefix for IP bucketing\n");
1459 bool fReindexChainState = args.
GetBoolArg(
"-reindex-chainstate",
false);
1463 nTotalCache = std::max(nTotalCache,
nMinDbCache << 20);
1464 nTotalCache = std::min(nTotalCache,
nMaxDbCache << 20);
1465 int64_t nBlockTreeDBCache = std::min(nTotalCache / 8,
nMaxBlockDBCache << 20);
1466 nTotalCache -= nBlockTreeDBCache;
1468 nTotalCache -= nTxIndexCache;
1469 int64_t filter_index_cache = 0;
1470 if (!g_enabled_filter_types.empty()) {
1471 size_t n_indexes = g_enabled_filter_types.size();
1473 filter_index_cache = max_cache / n_indexes;
1474 nTotalCache -= filter_index_cache * n_indexes;
1476 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23));
1478 nTotalCache -= nCoinDBCache;
1479 int64_t nCoinCacheUsage = nTotalCache;
1482 LogPrintf(
"* Using %.1f MiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1484 LogPrintf(
"* Using %.1f MiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
1487 LogPrintf(
"* Using %.1f MiB for %s block filter index database\n",
1490 LogPrintf(
"* Using %.1f MiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1491 LogPrintf(
"* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
1493 bool fLoaded =
false;
1497 return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull();
1504 const int64_t load_block_index_start_time =
GetTimeMillis();
1507 chainman.InitializeChainstate(*
Assert(
node.mempool));
1533 strLoadError =
_(
"Error loading block database");
1541 return InitError(
_(
"Incorrect or no genesis block found. Wrong datadir for network?"));
1547 strLoadError =
_(
"You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1556 strLoadError =
_(
"Error initializing block database");
1563 bool failed_chainstate_init =
false;
1566 chainstate->InitCoinsDB(
1569 fReset || fReindexChainState);
1571 chainstate->CoinsErrorCatcher().AddReadErrCallback([]() {
1573 _(
"Error reading from database, shutting down."),
1579 if (!chainstate->CoinsDB().Upgrade()) {
1580 strLoadError =
_(
"Error upgrading chainstate database");
1581 failed_chainstate_init =
true;
1586 if (!chainstate->ReplayBlocks(chainparams)) {
1587 strLoadError =
_(
"Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1588 failed_chainstate_init =
true;
1593 chainstate->InitCoinsCache(nCoinCacheUsage);
1594 assert(chainstate->CanFlushToDisk());
1596 if (!is_coinsview_empty(chainstate)) {
1598 if (!chainstate->LoadChainTip(chainparams)) {
1599 strLoadError =
_(
"Error initializing block database");
1600 failed_chainstate_init =
true;
1603 assert(chainstate->m_chain.Tip() !=
nullptr);
1607 if (failed_chainstate_init) {
1610 }
catch (
const std::exception& e) {
1612 strLoadError =
_(
"Error opening block database");
1616 bool failed_rewind{
false};
1624 uiInterface.InitMessage(
_(
"Rewinding blocks...").translated);
1625 if (!chainstate->RewindBlockIndex(chainparams)) {
1627 "Unable to rewind the database to a pre-fork state. "
1628 "You will need to redownload the blockchain");
1629 failed_rewind =
true;
1635 if (failed_rewind) {
1639 bool failed_verification =
false;
1645 if (!is_coinsview_empty(chainstate)) {
1646 uiInterface.InitMessage(
_(
"Verifying blocks...").translated);
1648 LogPrintf(
"Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
1652 const CBlockIndex* tip = chainstate->m_chain.Tip();
1655 strLoadError =
_(
"The block database contains a block which appears to be from the future. "
1656 "This may be due to your computer's date and time being set incorrectly. "
1657 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1658 failed_verification =
true;
1666 chainparams, *chainstate, &chainstate->CoinsDB(),
1669 strLoadError =
_(
"Corrupted block database detected");
1670 failed_verification =
true;
1675 }
catch (
const std::exception& e) {
1677 strLoadError =
_(
"Error opening block database");
1678 failed_verification =
true;
1682 if (!failed_verification) {
1692 strLoadError +
Untranslated(
".\n\n") +
_(
"Do you want to rebuild the block database now?"),
1693 strLoadError.
original +
".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1699 LogPrintf(
"Aborted block database rebuild. Exiting.\n");
1712 LogPrintf(
"Shutdown requested. Exiting.\n");
1722 for (
const auto& filter_type : g_enabled_filter_types) {
1728 for (
const auto& client :
node.chain_clients) {
1729 if (!client->load()) {
1739 LogPrintf(
"Unsetting NODE_NETWORK on prune mode\n");
1744 uiInterface.InitMessage(
_(
"Pruning blockstore...").translated);
1745 chainstate->PruneAndFlush();
1769 boost::signals2::connection block_notify_genesis_wait_connection;
1777 const std::string block_notify = args.
GetArg(
"-blocknotify",
"");
1778 if (!block_notify.empty()) {
1781 std::string command = block_notify;
1783 std::thread t(runCommand, command);
1789 std::vector<fs::path> vImportFiles;
1790 for (
const std::string& strFile : args.
GetArgs(
"-loadblock")) {
1791 vImportFiles.push_back(strFile);
1807 block_notify_genesis_wait_connection.disconnect();
1816 int chain_active_height;
1833 LogPrintf(
"nBestHeight = %d\n", chain_active_height);
1834 if (
node.peerman)
node.peerman->SetBestHeight(chain_active_height);
1858 for (
const std::string& bind_arg : args.
GetArgs(
"-bind")) {
1860 const size_t index = bind_arg.rfind(
'=');
1861 if (index == std::string::npos) {
1863 connOptions.
vBinds.push_back(bind_addr);
1867 const std::string network_type = bind_arg.substr(index + 1);
1868 if (network_type ==
"onion") {
1869 const std::string truncated_bind_arg = bind_arg.substr(0, index);
1870 if (
Lookup(truncated_bind_arg, bind_addr,
BaseParams().OnionServiceTargetPort(),
false)) {
1884 const auto bind_addr = connOptions.
onion_binds.front();
1886 InitWarning(
strprintf(
_(
"More than one onion bind address is provided. Using %s for the automatically created Tor onion service."), bind_addr.ToStringIPPort()));
1891 for (
const std::string& strBind : args.
GetArgs(
"-whitebind")) {
1898 for (
const auto& net : args.
GetArgs(
"-whitelist")) {
1910 const auto connect = args.
GetArgs(
"-connect");
1911 if (connect.size() != 1 || connect[0] !=
"0") {
1916 const std::string& i2psam_arg = args.
GetArg(
"-i2psam",
"");
1917 if (!i2psam_arg.empty()) {
1930 if (!
node.connman->Start(*
node.scheduler, connOptions)) {
1939 for (
const auto& client :
node.chain_clients) {
1940 client->start(*
node.scheduler);
1944 node.scheduler->scheduleEvery([banman]{
int64_t GetBlockTime() const
std::string CopyrightHolders(const std::string &strPrefix)
bool InitShutdownState()
Initialize shutdown state.
static bool CreatePidFile(const ArgsManager &args)
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
A combination of a network address (CNetAddr) and a (TCP) port.
void StartREST(const std::any &context)
Start HTTP REST subsystem.
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
static const bool DEFAULT_LOGTIMEMICROS
const WalletInitInterface & g_wallet_init_interface
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
bool DirIsWritable(const fs::path &directory)
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
std::vector< std::string > vSeedNodes
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
uint256 SerializeHash(const T &obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
Compute the 256-bit hash of an object's serialization.
void StartMapPort(bool use_upnp, bool use_natpmp)
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
bilingual_str _(const char *psz)
Translation function.
fs::path GetConfigFile(const std::string &confPath)
const fs::path & GetDataDir(bool fNetSpecific)
static const unsigned int DEFAULT_CHECKLEVEL
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
enum Network ParseNetwork(const std::string &net_in)
fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
static const unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create.
bool IsHexNumber(const std::string &str)
Return true if the string is a hex number, optionally prefixed with "0x".
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
static const int DEFAULT_HTTP_WORKQUEUE
std::vector< CService > vBinds
static void CleanupBlockRevFiles()
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
std::string GetHex() const
static CZMQNotificationInterface * Create()
const std::vector< std::string > NET_PERMISSIONS_DOC
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
CClientUIInterface uiInterface
void InitLogging(const ArgsManager &args)
Initialize global loggers.
CChainState &InitializeChainstate(CTxMemPool &mempool, const uint256 &snapshot_blockhash=uint256()) EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * > GetAll()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
bool m_i2p_accept_incoming
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
unsigned int nBytesPerSigOp
uint64_t nMaxOutboundLimit
bool IsTestChain() const
If this chain is exclusively used for testing.
bool ChronoSanityCheck()
Sanity check epoch match normal Unix epoch.
std::string get_filesystem_error_message(const fs::filesystem_error &e)
int atoi(const std::string &str)
static const int64_t nMaxDbCache
max. -dbcache (MiB)
std::unique_ptr< Chain > MakeChain(NodeContext &node)
Return implementation of Chain interface.
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
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 const bool DEFAULT_LOGIPS
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
int nHeight
height of the entry in the chain. The genesis block has height 0
const std::set< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
virtual void AddWalletOptions(ArgsManager &argsman) const =0
Get wallet help string.
void StartTorControl(CService onion_service_target)
static std::unique_ptr< ECCVerifyHandle > globalVerifyHandle
static const size_t DEFAULT_MAXRECEIVEBUFFER
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
ServiceFlags nLocalServices
static const std::string TESTNET
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
void InterruptTorControl()
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
static void RegisterAllCoreRPCCommands(CRPCTable &t)
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
static void OnRPCStarted()
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
std::vector< std::string > m_added_nodes
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
static void HandleSIGHUP(int)
const Consensus::Params & GetConsensus() const
bool glibcxx_sanity_test()
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
std::string LicenseInfo()
Returns licensing information (for -version)
Block and header tip information.
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
ServiceFlags
nServices flags
static const bool DEFAULT_FIXEDSEEDS
static const int64_t nMaxTxIndexCache
Max memory allocated to block tree DB specific cache, if -txindex (MiB)
static const bool DEFAULT_LOGTIMESTAMPS
void StopREST()
Stop HTTP REST subsystem.
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
#define TRY_LOCK(cs, name)
static const int DEFAULT_ZMQ_SNDHWM
uint256 defaultAssumeValid
By default assume that the signatures in ancestors of this block are valid.
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ChainActive().Tip() will not be pr...
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin core: Basic context setup.
void OnStopped(std::function< void()> slot)
static void OnRPCStopped()
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
void StartHTTPServer()
Start HTTP server.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
const fs::path & GetBlocksDirPath()
Get blocks directory path.
static std::condition_variable g_genesis_wait_cv
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
static const int64_t nDefaultDbCache
-dbcache default (MiB)
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
#define Assert(val)
Identity function.
static boost::signals2::connection rpc_notify_block_change_connection
bool fPruneMode
True if we're running in -prune mode.
Fee rate in satoshis per kilobyte: CAmount / kB.
bool fHavePruned
Pruning-related variables and constants.
static const unsigned int DEFAULT_BLOCK_MIN_TX_FEE
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
static const int64_t nDefaultDbBatchSize
-dbbatchsize default (bytes)
static const bool DEFAULT_FEEFILTER
Default for using fee filter.
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
CMainSignals & GetMainSignals()
CChain & ActiveChain() const
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
static const bool DEFAULT_LISTEN_ONION
static constexpr bool DEFAULT_UPNP
void SetRPCWarmupFinished()
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
static const unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or BIP...
const char *const BITCOIN_SETTINGS_FILENAME
void Stop()
Stops the instance from staying in sync with blockchain updates.
void TraceThread(const char *name, Callable func)
int SegwitHeight
Block height at which Segwit (BIP141, BIP143 and BIP147) becomes active.
const std::string CURRENCY_UNIT
static void StartupNotify(const ArgsManager &args)
static const bool DEFAULT_PEERBLOCKFILTERS
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
static const size_t DEFAULT_MAXSENDBUFFER
void Start()
Start initializes the sync state and registers the instance as a ValidationInterface so that it stays...
const std::string DEFAULT_TOR_CONTROL
Default control port.
void ECC_Stop()
Deinitialize the elliptic curve support.
fs::path GetDefaultDataDir()
static const int64_t nMinDbCache
min. -dbcache (MiB)
std::vector< NetWhitelistPermissions > vWhitelistedRange
const std::string CLIENT_NAME
static const int64_t max_filter_index_cache
Max memory allocated to all block filter index caches combined in MiB.
static const bool DEFAULT_PRINTPRIORITY
CService DefaultOnionServiceTarget()
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
static const bool DEFAULT_PEERBLOOMFILTERS
bool InitError(const bilingual_str &str)
Show error message.
static const bool DEFAULT_CHECKPOINTS_ENABLED
CZMQNotificationInterface * g_zmq_notification_interface
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
bool AppInitMain(NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
void RegisterZMQRPCCommands(CRPCTable &t)
static const std::string REGTEST
void StopHTTPRPC()
Stop HTTP RPC subsystem.
static const int64_t DEFAULT_MAX_TIP_AGE
std::vector< CService > onion_binds
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
static const int64_t nMaxCoinsDBCache
Max memory allocated to coin DB specific cache (MiB)
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
const std::set< std::string > GetUnsuitableSectionOnlyArgs() const
Log warnings for options in m_section_only_args when they are specified in the default section but no...
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Access to the block database (blocks/index/)
int64_t m_peer_connect_timeout
ChainstateManager g_chainman
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
int64_t CAmount
Amount in satoshis (Can be negative)
std::string GetHex() const
static constexpr bool DEFAULT_DAEMONWAIT
Default value for -daemonwait option.
std::string NetworkIDString() const
Return the network string.
bool m_use_addrman_outgoing
static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of orphan+recently-replaced txn to keep around for block reconstruction.
static bool TryParse(const std::string str, NetWhitebindPermissions &output, bilingual_str &error)
void Interrupt(NodeContext &node)
Interrupt threads.
int m_max_outbound_block_relay
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
std::atomic< bool > m_reopen_file
static const bool DEFAULT_LOGSOURCELOCATIONS
static const char * DEFAULT_ASMAP_FILENAME
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once)
static const bool DEFAULT_PROXYRANDOMIZE
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
static const bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
std::string ToString() const
const CBlock & GenesisBlock() const
static const unsigned int DEFAULT_RPC_SERIALIZE_VERSION
unsigned nMaxDatacarrierBytes
Maximum size of TxoutType::NULL_DATA scripts that this node considers standard.
uint256 uint256S(const char *str)
static void new_handler_terminate()
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
std::atomic_bool fReindex
CChainState stores and provides an API to update our local knowledge of the current best chain.
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
#define LogPrint(category,...)
unsigned int nReceiveFloodSize
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
int GetNumCores()
Return the number of cores available on the current system.
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
uint256 GetBlockHash() const
bool m_log_sourcelocations
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
bool ParseMoney(const std::string &money_string, CAmount &nRet)
Parse an amount denoted in full coins.
int Height() const
Return the maximal height in the chain.
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
static const std::string MAIN
Chain name strings.
const CMessageHeader::MessageStartChars & MessageStart() const
unsigned int nSendBufferMaxSize
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
static Mutex g_genesis_wait_mutex
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
double verification_progress
static const bool DEFAULT_DNSSEED
CClientUIInterface * uiInterface
static const bool DEFAULT_LOGTHREADNAMES
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
static const int DEFAULT_NAME_LOOKUP
-dns default
void InitSignatureCache()
void InitWarning(const bilingual_str &str)
Show warning message.
bool SetProxy(enum Network net, const proxyType &addrProxy)
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
void ECC_Start()
Initialize the elliptic curve support.
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
CFeeRate incrementalRelayFee
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
int64_t GetAdjustedTime()
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
static bool InitSanityCheck()
Sanity checks Ensure that Bitcoin is running in a usable environment with all necessary library suppo...
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Users of this module must hold an ECCVerifyHandle.
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
NetEventsInterface * m_msgproc
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
arith_uint256 UintToArith256(const uint256 &a)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
virtual void Construct(NodeContext &node) const =0
Add wallets that should be opened to list of chain clients.
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
static fs::path GetPidFile(const ArgsManager &args)
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
#define MIN_CORE_FILEDESCRIPTORS
void InterruptHTTPServer()
Interrupt HTTP server threads.
@ NET_ONION
TOR (v2 or v3)
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
static bool AppInitServers(NodeContext &node)
bool LoadBlockIndex(const CChainParams &chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
void InitScriptExecutionCache()
Initializes the script-execution cache.
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
BCLog::Logger & LogInstance()
const CChainParams & Params()
Return the currently selected parameters.
bool DumpMempool(const CTxMemPool &pool, FopenFn mockable_fopen_function, bool skip_file_commit)
Dump the mempool to disk.
const char *const DEFAULT_DEBUGLOGFILE
static const char *const DEFAULT_BLOCKFILTERINDEX
std::vector< std::string > m_specified_outgoing
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
void InterruptREST()
Interrupt RPC REST subsystem.
const char *const BITCOIN_CONF_FILENAME
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
bool InitBlockFilterIndex(BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe)
Initialize a block filter index for the given type if one does not already exist.
void OnStarted(std::function< void()> slot)
static bool LockDataDirectory(bool probeOnly)
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
static const unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
static const unsigned int DEFAULT_BYTES_PER_SIGOP
Default for -bytespersigop.
SynchronizationState
Current sync state passed to tip changed callbacks.
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
int m_max_outbound_full_relay
static const bool DEFAULT_TXINDEX
static constexpr bool DEFAULT_NATPMP
uint256 nMinimumChainWork
The best chain should have at least this much work.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
std::string FormatFullVersion()
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
static const bool DEFAULT_REST_ENABLE
bool error(const char *fmt, const Args &... args)
static std::vector< bool > DecodeAsmap(fs::path path)
bool Lookup(const std::string &name, std::vector< CService > &vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
NodeContext struct containing references to chain state and connection state.
static const int64_t nMaxBlockDBCache
Max memory allocated to block tree DB specific cache, if no -txindex (MiB)
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
void ThreadImport(ChainstateManager &chainman, std::vector< fs::path > vImportFiles, const ArgsManager &args)
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
The block chain is a tree shaped structure starting with the genesis block at the root,...
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
void StopHTTPServer()
Stop HTTP server.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
static bool TryParse(const std::string str, NetWhitelistPermissions &output, bilingual_str &error)
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...
assert(std::addressof(::ChainstateActive().CoinsTip())==std::addressof(coins_cache))
static const int DEFAULT_HTTP_THREADS
static constexpr bool DEFAULT_DAEMON
Default value for -daemon option.
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
static std::unique_ptr< PeerManager > make(const CChainParams &chainparams, CConnman &connman, CAddrMan &addrman, BanMan *banman, CScheduler &scheduler, ChainstateManager &chainman, CTxMemPool &pool, bool ignore_incoming_txs)
void StartShutdown()
Request shutdown of the application.
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
RecursiveMutex g_cs_orphans
Guards orphan transactions and extra txs for compact blocks.
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
std::vector< NetWhitebindPermissions > vWhiteBinds
std::unique_ptr< const CChainParams > CreateChainParams(const ArgsManager &args, const std::string &chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
void AbortShutdown()
Clear shutdown flag.
static void registerSignalHandler(int signal, void(*handler)(int))
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
void Shutdown(NodeContext &node)
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
int64_t GetTimeMillis()
Returns the system time (not mockable)
#define WAIT_LOCK(cs, name)
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
bool InitHTTPServer()
Initialize HTTP server.
static const std::string SIGNET
static const int DEFAULT_HTTP_SERVER_TIMEOUT
static const signed int DEFAULT_CHECKBLOCKS
static const bool DEFAULT_FORCEDNSSEED
static const bool DEFAULT_LISTEN
-listen default
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
static const bool DEFAULT_ACCEPT_DATACARRIER
std::condition_variable g_best_block_cv
bool AddLocal(const CService &addr, int nScore)