6 #if defined(HAVE_CONFIG_H) 79 #include <boost/algorithm/string/replace.hpp> 80 #include <boost/signals2/signal.hpp> 81 #include <boost/thread/thread.hpp> 97 #define MIN_CORE_FILEDESCRIPTORS 0 99 #define MIN_CORE_FILEDESCRIPTORS 150 178 static Mutex g_shutdown_mutex;
179 TRY_LOCK(g_shutdown_mutex, lock_shutdown);
180 if (!lock_shutdown)
return;
181 LogPrintf(
"%s: In progress...\n", __func__);
244 if (chainstate->CanFlushToDisk()) {
245 chainstate->ForceFlushStateToDisk();
271 if (chainstate->CanFlushToDisk()) {
272 chainstate->ForceFlushStateToDisk();
273 chainstate->ResetCoinsViews();
302 LogPrintf(
"%s: Unable to remove PID file: File does not exist\n", __func__);
304 }
catch (
const fs::filesystem_error& e) {
328 static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
341 sigemptyset(&sa.sa_mask);
343 sigaction(signal, &sa,
nullptr);
355 rpc_notify_block_change_connection.disconnect();
380 std::vector<std::string> hidden_args = {
381 "-dbcrashratio",
"-forcecompactdb",
383 "-choosedatadir",
"-lang=<lang>",
"-min",
"-resetguisettings",
"-splash",
"-uiplatform"};
389 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);
408 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)",
412 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. " 413 "Warning: Reverting this setting requires re-downloading the entire blockchain. " 424 hidden_args.emplace_back(
"-sysperms");
427 argsman.
AddArg(
"-blockfilterindex=<type>",
429 " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
435 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);
450 argsman.
AddArg(
"-onlynet=<net>",
"Make outgoing connections only through network <net> (ipv4, ipv6 or onion). Incoming connections are not affected by this option. This option can be specified multiple times to allow multiple networks.",
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>");
524 argsman.
AddArg(
"-debug=<category>",
"Output debugging information (default: -nodebug, supplying <category> is optional). " 525 "If <category> is not supplied or if <category> = 1, output all debugging information. <category> can be: " +
LogInstance().LogCategoriesString() +
".",
530 #ifdef HAVE_THREAD_LOCAL 533 hidden_args.emplace_back(
"-logthreadnames");
552 argsman.
AddArg(
"-minrelaytxfee=<amt>",
strprintf(
"Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
563 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);
564 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);
565 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);
568 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);
573 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);
574 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);
581 hidden_args.emplace_back(
"-daemon");
590 const std::string URL_SOURCE_CODE =
"<https://github.com/bitcoin/bitcoin>";
594 strprintf(
_(
"Please contribute if you find %s useful. " 595 "Visit %s for further information about the software.").translated,
598 strprintf(
_(
"The source code is available from %s.").translated,
602 _(
"This is experimental software.").
translated +
"\n" +
603 strprintf(
_(
"Distributed under the MIT software license, see the accompanying file %s or %s").translated,
"COPYING",
"<https://opensource.org/licenses/MIT>") +
613 if (pBlockIndex !=
nullptr) {
615 LOCK(g_genesis_wait_mutex);
618 g_genesis_wait_cv.notify_all();
644 std::map<std::string, fs::path> mapBlockFiles;
649 LogPrintf(
"Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
651 for (fs::directory_iterator
it(blocksdir);
it != fs::directory_iterator();
it++) {
652 if (fs::is_regular_file(*
it) &&
653 it->path().filename().string().length() == 12 &&
654 it->path().filename().string().substr(8,4) ==
".dat")
656 if (
it->path().filename().string().substr(0,3) ==
"blk")
657 mapBlockFiles[
it->path().filename().string().substr(3,5)] =
it->path();
658 else if (
it->path().filename().string().substr(0,3) ==
"rev")
667 int nContigCounter = 0;
668 for (
const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
669 if (
atoi(item.first) == nContigCounter) {
680 std::string cmd = args.
GetArg(
"-startupnotify",
"");
682 std::thread t(runCommand, cmd);
706 LogPrintf(
"Reindexing block file blk%05u.dat...\n", (
unsigned int)nFile);
709 LogPrintf(
"Shutdown requested. Exit %s\n", __func__);
722 for (
const fs::path& path : vImportFiles) {
725 LogPrintf(
"Importing blocks file %s...\n", path.string());
728 LogPrintf(
"Shutdown requested. Exit %s\n", __func__);
732 LogPrintf(
"Warning: Could not open blocks file %s\n", path.string());
743 if (!chainstate->ActivateBestChain(state, chainparams,
nullptr)) {
751 LogPrintf(
"Stopping after block import\n");
802 LogPrintf(
"%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
806 LogPrintf(
"%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
812 LogPrintf(
"%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
814 LogPrintf(
"%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
820 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
824 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
826 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -natpmp=0\n", __func__);
830 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
836 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
838 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -natpmp=0\n", __func__);
841 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
843 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
849 LogPrintf(
"%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
855 LogPrintf(
"%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
861 LogPrintf(
"%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
878 #ifdef HAVE_THREAD_LOCAL 886 version_string +=
" (debug build)";
888 version_string +=
" (release build)";
896 int nUserMaxConnections;
899 int64_t peer_connect_timeout;
900 std::set<BlockFilterType> g_enabled_filter_types;
910 std::set_new_handler(std::terminate);
911 LogPrintf(
"Error: Out of memory. Terminating.\n");
922 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
923 _CrtSetReportFile(_CRT_WARN, CreateFileA(
"NUL", GENERIC_WRITE, 0,
nullptr, OPEN_EXISTING, 0, 0));
925 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
929 HeapSetInformation(
nullptr, HeapEnableTerminationOnCorruption,
nullptr, 0);
952 signal(SIGPIPE, SIG_IGN);
954 SetConsoleCtrlHandler(consoleCtrlHandler,
true);
978 errors +=
strprintf(
_(
"Config setting for %s only applied on %s network when in [%s] section.") +
Untranslated(
"\n"), arg, network, network);
981 if (!errors.
empty()) {
991 if (!warnings.
empty()) {
1001 if (blockfilterindex_value ==
"" || blockfilterindex_value ==
"1") {
1003 }
else if (blockfilterindex_value !=
"0") {
1004 const std::vector<std::string> names = args.
GetArgs(
"-blockfilterindex");
1005 for (
const auto&
name : names) {
1010 g_enabled_filter_types.insert(filter_type);
1017 return InitError(
_(
"Cannot set -peerblockfilters without -blockfilterindex."));
1024 if (args.
GetArg(
"-prune", 0)) {
1026 return InitError(
_(
"Prune mode is incompatible with -txindex."));
1027 if (!g_enabled_filter_types.empty()) {
1028 return InitError(
_(
"Prune mode is incompatible with -blockfilterindex."));
1033 size_t nUserBind = args.
GetArgs(
"-bind").size() + args.
GetArgs(
"-whitebind").size();
1039 int nBind = std::max(nUserBind,
size_t(1));
1041 nMaxConnections = std::max(nUserMaxConnections, 0);
1049 int fd_max = FD_SETSIZE;
1053 return InitError(
_(
"Not enough file descriptors available."));
1056 if (nMaxConnections < nUserMaxConnections)
1057 InitWarning(
strprintf(
_(
"Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
1062 const std::vector<std::string> categories = args.
GetArgs(
"-debug");
1064 if (std::none_of(categories.begin(), categories.end(),
1065 [](std::string cat){
return cat ==
"0" || cat ==
"none";})) {
1066 for (
const auto& cat : categories) {
1075 for (
const std::string& cat : args.
GetArgs(
"-debugexclude")) {
1088 LogPrintf(
"Validating signatures for all blocks.\n");
1090 if (args.
IsArgSet(
"-minimumchainwork")) {
1091 const std::string minChainWorkStr = args.
GetArg(
"-minimumchainwork",
"");
1107 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
1108 return InitError(
strprintf(
_(
"-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
1111 if (args.
IsArgSet(
"-incrementalrelayfee")) {
1119 int64_t nPruneArg = args.
GetArg(
"-prune", 0);
1120 if (nPruneArg < 0) {
1121 return InitError(
_(
"Prune cannot be configured with a negative value."));
1124 if (nPruneArg == 1) {
1125 LogPrintf(
"Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1132 LogPrintf(
"Prune configured to target %u MiB on disk for block and undo files.\n",
nPruneTarget / 1024 / 1024);
1142 if (peer_connect_timeout <= 0) {
1146 if (args.
IsArgSet(
"-minrelaytxfee")) {
1161 if (args.
IsArgSet(
"-blockmintxfee")) {
1169 if (args.
IsArgSet(
"-dustrelayfee")) {
1202 if (args.
IsArgSet(
"-proxy") && args.
GetArg(
"-proxy",
"").empty()) {
1203 return InitError(
_(
"No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
1214 return InitError(
strprintf(
_(
"Cannot write to data directory '%s'; check permissions."), datadir.string()));
1228 LogPrintf(
"Using the '%s' SHA256 implementation\n", sha256_algo);
1294 if (fs::exists(config_file_path)) {
1295 LogPrintf(
"Config file: %s\n", config_file_path.string());
1296 }
else if (args.
IsArgSet(
"-conf")) {
1298 InitWarning(
strprintf(
_(
"The specified config file %s does not exist\n"), config_file_path.string()));
1301 LogPrintf(
"Config file: %s (not found, skipping)\n", config_file_path.string());
1307 LogPrintf(
"Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1310 if (args.
IsArgSet(
"-datadir") && !fs::path(args.
GetArg(
"-datadir",
"")).is_absolute()) {
1311 LogPrintf(
"Warning: relative datadir option '%s' specified, which will be interpreted relative to the " 1312 "current working directory '%s'. This is fragile, because if bitcoin is started in the future " 1313 "from a different location, it will be unable to locate the current data files. There could " 1314 "also be data loss if bitcoin is started while in a temporary directory.\n",
1315 args.
GetArg(
"-datadir",
""), fs::current_path().string());
1322 if (script_threads <= 0) {
1329 script_threads = std::max(script_threads - 1, 0);
1334 LogPrintf(
"Script verification uses %d additional threads\n", script_threads);
1335 if (script_threads >= 1) {
1337 for (
int i = 0; i < script_threads; ++i) {
1343 node.
scheduler = MakeUnique<CScheduler>();
1351 }, std::chrono::minutes{1});
1360 client->registerRpcs();
1374 return InitError(
_(
"Unable to start HTTP server. See debug log for details."));
1379 if (!client->verify()) {
1397 node.
connman = MakeUnique<CConnman>(
GetRand(std::numeric_limits<uint64_t>::max()),
GetRand(std::numeric_limits<uint64_t>::max()), args.
GetBoolArg(
"-networkactive",
true));
1402 if (!ignores_incoming_txs) node.
fee_estimator = std::make_unique<CBlockPolicyEstimator>();
1418 std::vector<std::string> uacomments;
1419 for (
const std::string& cmt : args.
GetArgs(
"-uacomment")) {
1421 return InitError(
strprintf(
_(
"User Agent comment (%s) contains unsafe characters."), cmt));
1422 uacomments.push_back(cmt);
1426 return InitError(
strprintf(
_(
"Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1431 std::set<enum Network> nets;
1432 for (
const std::string& snet : args.
GetArgs(
"-onlynet")) {
1438 for (
int n = 0; n <
NET_MAX; n++) {
1440 if (!nets.count(net))
1451 std::string proxyArg = args.
GetArg(
"-proxy",
"");
1453 if (proxyArg !=
"" && proxyArg !=
"0") {
1473 std::string onionArg = args.
GetArg(
"-onion",
"");
1474 if (onionArg !=
"") {
1475 if (onionArg ==
"0") {
1490 for (
const std::string& strAddr : args.
GetArgs(
"-externalip")) {
1500 fs::path asmap_path = fs::path(args.
GetArg(
"-asmap",
""));
1501 if (asmap_path.empty()) {
1504 if (!asmap_path.is_absolute()) {
1507 if (!fs::exists(asmap_path)) {
1512 if (asmap.size() == 0) {
1517 node.
connman->SetAsmap(std::move(asmap));
1518 LogPrintf(
"Using asmap version %s for IP bucketing\n", asmap_version.
ToString());
1520 LogPrintf(
"Using /16 prefix for IP bucketing\n");
1534 bool fReindexChainState = args.
GetBoolArg(
"-reindex-chainstate",
false);
1538 nTotalCache = std::max(nTotalCache,
nMinDbCache << 20);
1539 nTotalCache = std::min(nTotalCache,
nMaxDbCache << 20);
1540 int64_t nBlockTreeDBCache = std::min(nTotalCache / 8,
nMaxBlockDBCache << 20);
1541 nTotalCache -= nBlockTreeDBCache;
1543 nTotalCache -= nTxIndexCache;
1544 int64_t filter_index_cache = 0;
1545 if (!g_enabled_filter_types.empty()) {
1546 size_t n_indexes = g_enabled_filter_types.size();
1548 filter_index_cache = max_cache / n_indexes;
1549 nTotalCache -= filter_index_cache * n_indexes;
1551 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23));
1553 nTotalCache -= nCoinDBCache;
1554 int64_t nCoinCacheUsage = nTotalCache;
1557 LogPrintf(
"* Using %.1f MiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1559 LogPrintf(
"* Using %.1f MiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
1562 LogPrintf(
"* Using %.1f MiB for %s block filter index database\n",
1565 LogPrintf(
"* Using %.1f MiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1566 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));
1568 bool fLoaded =
false;
1572 return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull();
1576 uiInterface.InitMessage(
_(
"Loading block index...").translated);
1579 const int64_t load_block_index_start_time =
GetTimeMillis();
1608 strLoadError =
_(
"Error loading block database");
1616 return InitError(
_(
"Incorrect or no genesis block found. Wrong datadir for network?"));
1622 strLoadError =
_(
"You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1631 strLoadError =
_(
"Error initializing block database");
1638 bool failed_chainstate_init =
false;
1641 chainstate->InitCoinsDB(
1644 fReset || fReindexChainState);
1646 chainstate->CoinsErrorCatcher().AddReadErrCallback([]() {
1648 _(
"Error reading from database, shutting down."),
1654 if (!chainstate->CoinsDB().Upgrade()) {
1655 strLoadError =
_(
"Error upgrading chainstate database");
1656 failed_chainstate_init =
true;
1661 if (!chainstate->ReplayBlocks(chainparams)) {
1662 strLoadError =
_(
"Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1663 failed_chainstate_init =
true;
1668 chainstate->InitCoinsCache(nCoinCacheUsage);
1669 assert(chainstate->CanFlushToDisk());
1671 if (!is_coinsview_empty(chainstate)) {
1673 if (!chainstate->LoadChainTip(chainparams)) {
1674 strLoadError =
_(
"Error initializing block database");
1675 failed_chainstate_init =
true;
1678 assert(chainstate->m_chain.Tip() !=
nullptr);
1682 if (failed_chainstate_init) {
1685 }
catch (
const std::exception& e) {
1687 strLoadError =
_(
"Error opening block database");
1691 bool failed_rewind{
false};
1699 uiInterface.InitMessage(
_(
"Rewinding blocks...").translated);
1700 if (!chainstate->RewindBlockIndex(chainparams)) {
1702 "Unable to rewind the database to a pre-fork state. " 1703 "You will need to redownload the blockchain");
1704 failed_rewind =
true;
1710 if (failed_rewind) {
1714 bool failed_verification =
false;
1720 if (!is_coinsview_empty(chainstate)) {
1721 uiInterface.InitMessage(
_(
"Verifying blocks...").translated);
1723 LogPrintf(
"Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
1727 const CBlockIndex* tip = chainstate->m_chain.Tip();
1730 strLoadError =
_(
"The block database contains a block which appears to be from the future. " 1731 "This may be due to your computer's date and time being set incorrectly. " 1732 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1733 failed_verification =
true;
1741 chainparams, &chainstate->CoinsDB(),
1744 strLoadError =
_(
"Corrupted block database detected");
1745 failed_verification =
true;
1750 }
catch (
const std::exception& e) {
1752 strLoadError =
_(
"Error opening block database");
1753 failed_verification =
true;
1757 if (!failed_verification) {
1767 strLoadError +
Untranslated(
".\n\n") +
_(
"Do you want to rebuild the block database now?"),
1768 strLoadError.
original +
".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1774 LogPrintf(
"Aborted block database rebuild. Exiting.\n");
1787 LogPrintf(
"Shutdown requested. Exiting.\n");
1797 for (
const auto& filter_type : g_enabled_filter_types) {
1804 if (!client->load()) {
1814 LogPrintf(
"Unsetting NODE_NETWORK on prune mode\n");
1819 uiInterface.InitMessage(
_(
"Pruning blockstore...").translated);
1820 chainstate->PruneAndFlush();
1844 boost::signals2::connection block_notify_genesis_wait_connection;
1848 fHaveGenesis =
true;
1852 const std::string block_notify = args.
GetArg(
"-blocknotify",
"");
1853 if (!block_notify.empty()) {
1856 std::string command = block_notify;
1858 std::thread t(runCommand, command);
1864 std::vector<fs::path> vImportFiles;
1865 for (
const std::string& strFile : args.
GetArgs(
"-loadblock")) {
1866 vImportFiles.push_back(strFile);
1880 g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
1882 block_notify_genesis_wait_connection.disconnect();
1891 int chain_active_height;
1908 LogPrintf(
"nBestHeight = %d\n", chain_active_height);
1909 if (node.
peerman) node.
peerman->SetBestHeight(chain_active_height);
1918 connOptions.nMaxConnections = nMaxConnections;
1924 connOptions.m_banman = node.
banman.get();
1925 connOptions.m_msgproc = node.
peerman.get();
1928 connOptions.m_added_nodes = args.
GetArgs(
"-addnode");
1931 connOptions.m_peer_connect_timeout = peer_connect_timeout;
1933 for (
const std::string& bind_arg : args.
GetArgs(
"-bind")) {
1935 const size_t index = bind_arg.rfind(
'=');
1936 if (index == std::string::npos) {
1938 connOptions.vBinds.push_back(bind_addr);
1942 const std::string network_type = bind_arg.substr(index + 1);
1943 if (network_type ==
"onion") {
1944 const std::string truncated_bind_arg = bind_arg.substr(0, index);
1945 if (
Lookup(truncated_bind_arg, bind_addr,
BaseParams().OnionServiceTargetPort(),
false)) {
1946 connOptions.onion_binds.push_back(bind_addr);
1954 if (connOptions.onion_binds.empty()) {
1959 const auto bind_addr = connOptions.onion_binds.front();
1960 if (connOptions.onion_binds.size() > 1) {
1961 InitWarning(
strprintf(
_(
"More than one onion bind address is provided. Using %s for the automatically created Tor onion service."), bind_addr.ToStringIPPort()));
1966 for (
const std::string& strBind : args.
GetArgs(
"-whitebind")) {
1970 connOptions.vWhiteBinds.push_back(whitebind);
1973 for (
const auto& net : args.
GetArgs(
"-whitelist")) {
1977 connOptions.vWhitelistedRange.push_back(subnet);
1980 connOptions.vSeedNodes = args.
GetArgs(
"-seednode");
1983 connOptions.m_use_addrman_outgoing = !args.
IsArgSet(
"-connect");
1984 if (!connOptions.m_use_addrman_outgoing) {
1985 const auto connect = args.
GetArgs(
"-connect");
1986 if (connect.size() != 1 || connect[0] !=
"0") {
1987 connOptions.m_specified_outgoing = connect;
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
void EnableCategory(LogFlags flag)
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
std::string NetworkIDString() const
Return the network string.
void ECC_Start()
Initialize the elliptic curve support.
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
bool(* handler)(const util::Ref &context, HTTPRequest *req, const std::string &strReq)
std::vector< std::unique_ptr< interfaces::ChainClient > > chain_clients
List of all chain clients (wallet processes or other client) connected to node.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
bool fPruneMode
True if we're running in -prune mode.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
std::deque< CInv >::iterator it
static void CleanupBlockRevFiles()
const std::vector< std::string > NET_PERMISSIONS_DOC
std::condition_variable g_best_block_cv
void InitLogging(const ArgsManager &args)
Initialize global loggers.
SynchronizationState
Current sync state passed to tip changed callbacks.
BCLog::Logger & LogInstance()
ServiceFlags
nServices flags
const char *const BITCOIN_SETTINGS_FILENAME
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
#define LogPrint(category,...)
int64_t GetBlockTime() const
bool DirIsWritable(const fs::path &directory)
bool AddLocal(const CService &addr, int nScore)
FILE * fopen(const fs::path &p, const char *mode)
fs::path GetDefaultDataDir()
static const int DEFAULT_HTTP_SERVER_TIMEOUT
static const int64_t nMaxTxIndexCache
Max memory allocated to block tree DB specific cache, if -txindex (MiB)
#define TRY_LOCK(cs, name)
Dummy value to indicate the number of NET_* constants.
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
void Shutdown(NodeContext &node)
static const std::string REGTEST
RecursiveMutex g_cs_orphans
Guards orphan transactions and extra txs for compact blocks.
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
static const unsigned int DEFAULT_RPC_SERIALIZE_VERSION
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
int64_t GetTimeMillis()
Returns the system time (not mockable)
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
int GetNumCores()
Return the number of cores available on the current system.
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
static boost::signals2::connection rpc_notify_block_change_connection
std::unique_ptr< BanMan > banman
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
static const bool DEFAULT_FORCEDNSSEED
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
std::unique_ptr< CTxMemPool > mempool
static const int DEFAULT_HTTP_WORKQUEUE
static void RegisterAllCoreRPCCommands(CRPCTable &t)
bool fHavePruned
Pruning-related variables and constants.
static void OnRPCStarted()
static const int64_t DEFAULT_MAX_TIP_AGE
void InitWarning(const bilingual_str &str)
Show warning message.
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.
static const bool DEFAULT_ACCEPT_DATACARRIER
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
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...
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
static const bool DEFAULT_LOGTHREADNAMES
int Height() const
Return the maximal height in the chain.
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name...
std::unique_ptr< interfaces::Chain > chain
void StopREST()
Stop HTTP REST subsystem.
void OnStopped(std::function< void()> slot)
static const unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or BIP...
static const bool DEFAULT_LISTEN
-listen default
static const bool DEFAULT_LOGTIMEMICROS
std::atomic< bool > m_reopen_file
CChainState stores and provides an API to update our local knowledge of the current best chain...
std::string CopyrightHolders(const std::string &strPrefix)
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
static void OnRPCStopped()
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
static void LogPrintf(const char *fmt, const Args &... args)
const std::set< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
const CBlock & GenesisBlock() const
static std::unique_ptr< ECCVerifyHandle > globalVerifyHandle
const fs::path & GetBlocksDir()
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
bool InitShutdownState()
Initialize shutdown state.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
void StartMapPort(bool use_upnp, bool use_natpmp)
static const int64_t nMinDbCache
min. -dbcache (MiB)
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
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. ...
static const int64_t max_filter_index_cache
Max memory allocated to all block filter index caches combined in MiB.
virtual void Construct(NodeContext &node) const =0
Add wallets that should be opened to list of chain clients.
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
bool ParseMoney(const std::string &money_string, CAmount &nRet)
Parse an amount denoted in full coins.
static void HandleSIGHUP(int)
static const bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
static boost::thread_group threadGroup
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
const char *const BITCOIN_CONF_FILENAME
std::string LicenseInfo()
Returns licensing information (for -version)
void StartTorControl(CService onion_service_target)
void InterruptHTTPServer()
Interrupt HTTP server threads.
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
void ThreadScriptCheck(int worker_num)
Run an instance of the script checking thread.
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
static const bool DEFAULT_STOPAFTERBLOCKIMPORT
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
void Stop()
Stops the instance from staying in sync with blockchain updates.
std::unique_ptr< Chain > MakeChain(NodeContext &node)
Return implementation of Chain interface.
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
arith_uint256 UintToArith256(const uint256 &a)
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin core: Basic context setup.
std::function< void()> rpc_interruption_point
static const std::string MAIN
Chain name strings.
static const bool DEFAULT_PEERBLOCKFILTERS
void LoadMempool(const ArgsManager &args)
Load the persisted mempool from disk.
bool Lookup(const std::string &name, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Resolve a service string to its corresponding service.
int64_t CAmount
Amount in satoshis (Can be negative)
static constexpr bool DEFAULT_UPNP
uint256 GetBlockHash() const
void SetMockTime(int64_t nMockTimeIn)
For testing.
void SetRPCWarmupFinished()
uint256 SerializeHash(const T &obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
Compute the 256-bit hash of an object's serialization.
static const size_t DEFAULT_MAXRECEIVEBUFFER
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
bool InitHTTPServer()
Initialize HTTP server.
Users of this module must hold an ECCVerifyHandle.
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
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...
ChainstateManager * chainman
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.
static CZMQNotificationInterface * Create()
NodeContext struct containing references to chain state and connection state.
const std::string DEFAULT_TOR_CONTROL
Default control port.
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
std::unique_ptr< CConnman > connman
Access to the block database (blocks/index/)
void StopHTTPServer()
Stop HTTP server.
static std::condition_variable g_genesis_wait_cv
void Interrupt(NodeContext &node)
Interrupt threads.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
void ECC_Stop()
Deinitialize the elliptic curve support.
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
std::string ToString() const
bilingual_str _(const char *psz)
Translation function.
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...
static bool AppInitServers(const util::Ref &context, NodeContext &node)
int atoi(const std::string &str)
A combination of a network address (CNetAddr) and a (TCP) port.
uint256 uint256S(const char *str)
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
const fs::path & GetDataDir(bool fNetSpecific)
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
void InitSignatureCache()
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
const std::string CURRENCY_UNIT
CMainSignals & GetMainSignals()
static const int64_t nDefaultDbCache
-dbcache default (MiB)
void DisableCategory(LogFlags flag)
void Start()
Start initializes the sync state and registers the instance as a ValidationInterface so that it stays...
static std::unique_ptr< PeerManager > make(const CChainParams &chainparams, CConnman &connman, BanMan *banman, CScheduler &scheduler, ChainstateManager &chainman, CTxMemPool &pool, bool ignore_incoming_txs)
static const bool DEFAULT_FEEFILTER
Default for using fee filter.
Block and header tip information.
const CMessageHeader::MessageStartChars & MessageStart() const
static void StartupNotify(const ArgsManager &args)
bool InitError(const bilingual_str &str)
Show error message.
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
ChainstateManager g_chainman
#define WAIT_LOCK(cs, name)
std::atomic_bool fImporting
static const int64_t nDefaultDbBatchSize
-dbbatchsize default (bytes)
std::string ToString() const
static fs::path GetPidFile(const ArgsManager &args)
const std::string CLIENT_NAME
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
static const int DEFAULT_NAME_LOOKUP
-dns default
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...
void TraceThread(const char *name, Callable func)
static const char *const DEFAULT_BLOCKFILTERINDEX
static const int DEFAULT_ZMQ_SNDHWM
static const bool DEFAULT_PROXYRANDOMIZE
bool IsHexNumber(const std::string &str)
Return true if the string is a hex number, optionally prefixed with "0x".
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download...
std::string FormatFullVersion()
std::unique_ptr< PeerManager > peerman
CFeeRate incrementalRelayFee
virtual void AddWalletOptions(ArgsManager &argsman) const =0
Get wallet help string.
Type-safe dynamic reference.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
static const int64_t nMaxBlockDBCache
Max memory allocated to block tree DB specific cache, if no -txindex (MiB)
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
static void ThreadImport(ChainstateManager &chainman, std::vector< fs::path > vImportFiles, const ArgsManager &args)
bool SetProxy(enum Network net, const proxyType &addrProxy)
void StopHTTPRPC()
Stop HTTP RPC subsystem.
enum Network ParseNetwork(const std::string &net_in)
void StartREST(const util::Ref &context)
Start HTTP REST subsystem.
void LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, FlatFilePos *dbp)
Import blocks from an external file.
std::atomic_bool fReindex
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
CBlockIndex * LookupBlockIndex(const uint256 &hash)
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once) ...
std::string get_filesystem_error_message(const fs::filesystem_error &e)
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
bool glibcxx_sanity_test()
double verification_progress
static constexpr bool DEFAULT_NATPMP
bool StartHTTPRPC(const util::Ref &context)
Start HTTP RPC subsystem.
static const bool DEFAULT_PEERBLOOMFILTERS
void RegisterZMQRPCCommands(CRPCTable &t)
uint256 nMinimumChainWork
The best chain should have at least this much work.
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
static const bool DEFAULT_CHECKPOINTS_ENABLED
const WalletInitInterface & g_wallet_init_interface
#define EXCLUSIVE_LOCKS_REQUIRED(...)
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
bool IsTestChain() const
If this chain is exclusively used for testing.
unsigned int nBytesPerSigOp
static const unsigned int DEFAULT_BYTES_PER_SIGOP
Default for -bytespersigop.
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
static const char * DEFAULT_ASMAP_FILENAME
uint256 defaultAssumeValid
By default assume that the signatures in ancestors of this block are valid.
static const size_t DEFAULT_MAXSENDBUFFER
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
static void new_handler_terminate()
fs::path GetConfigFile(const std::string &confPath)
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 bool TryParse(const std::string str, NetWhitebindPermissions &output, bilingual_str &error)
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
static const signed int DEFAULT_CHECKBLOCKS
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
static const int64_t nMaxCoinsDBCache
Max memory allocated to coin DB specific cache (MiB)
void InitScriptExecutionCache()
Initializes the script-execution cache.
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...
static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of orphan+recently-replaced txn to keep around for block reconstruction.
static const unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
ServiceFlags nLocalServices
void InterruptREST()
Interrupt RPC REST subsystem.
int64_t GetAdjustedTime()
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
static const int64_t nMaxDbCache
max. -dbcache (MiB)
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
std::string FormatSubVersion(const std::string &name, int nClientVersion, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip...
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.
std::string GetHex() const
void AbortShutdown()
Clear shutdown flag.
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
static Mutex g_genesis_wait_mutex
Fee rate in satoshis per kilobyte: CAmount / kB.
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
CService DefaultOnionServiceTarget()
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
void StartShutdown()
Request shutdown of the application.
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
std::unique_ptr< CBlockPolicyEstimator > fee_estimator
static const std::string TESTNET
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
static std::vector< bool > DecodeAsmap(fs::path path)
void StartHTTPServer()
Start HTTP server.
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
static std::thread g_load_block
CChainState & ActiveChainstate() const
The most-work chain.
void InterruptTorControl()
int SegwitHeight
Block height at which Segwit (BIP141, BIP143 and BIP147) becomes active.
void OnStarted(std::function< void()> slot)
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
std::string GetHex() const
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
static bool InitSanityCheck()
Sanity checks Ensure that Bitcoin is running in a usable environment with all necessary library suppo...
bool AppInitMain(const util::Ref &context, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks, tx, addrs, etc)
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
static const bool DEFAULT_LOGIPS
CClientUIInterface uiInterface
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.
const Consensus::Params & GetConsensus() const
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
static const bool DEFAULT_PRINTPRIORITY
static void registerSignalHandler(int signal, void(*handler)(int))
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
static const unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create...
#define MIN_CORE_FILEDESCRIPTORS
int64_t GetTime()
Return system time (or mocked time, if set)
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
const char *const DEFAULT_DEBUGLOGFILE
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
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 error(const char *fmt, const Args &... args)
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
static const bool DEFAULT_LOGTIMESTAMPS
static bool CreatePidFile(const ArgsManager &args)
static const std::string SIGNET
static const bool DEFAULT_TXINDEX
static const int DEFAULT_HTTP_THREADS
static const bool DEFAULT_REST_ENABLE
static bool TryParse(const std::string str, NetWhitelistPermissions &output, bilingual_str &error)
unsigned nMaxDatacarrierBytes
Maximum size of TxoutType::NULL_DATA scripts that this node considers standard.
CChain & ActiveChain() const
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
static const unsigned int DEFAULT_CHECKLEVEL
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
#define Assert(val)
Identity function.
CZMQNotificationInterface * g_zmq_notification_interface
static bool LockDataDirectory(bool probeOnly)
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
std::unique_ptr< CScheduler > scheduler
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.
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Addresses from these networks are not publicly routable on the global Internet.