6#if defined(HAVE_CONFIG_H)
86#include <boost/algorithm/string/replace.hpp>
87#include <boost/signals2/signal.hpp>
102#define MIN_CORE_FILEDESCRIPTORS 0
104#define MIN_CORE_FILEDESCRIPTORS 150
168 node.connman->Interrupt();
180 static Mutex g_shutdown_mutex;
181 TRY_LOCK(g_shutdown_mutex, lock_shutdown);
182 if (!lock_shutdown)
return;
183 LogPrintf(
"%s: In progress...\n", __func__);
191 if (
node.mempool)
node.mempool->AddTransactionsUpdated(1);
197 for (
const auto& client :
node.chain_clients) {
205 if (
node.connman)
node.connman->Stop();
211 if (
node.scheduler)
node.scheduler->stop();
212 if (
node.chainman &&
node.chainman->m_load_block.joinable())
node.chainman->m_load_block.join();
217 node.peerman.reset();
218 node.connman.reset();
220 node.addrman.reset();
227 if (
node.fee_estimator)
node.fee_estimator->Flush();
233 if (chainstate->CanFlushToDisk()) {
234 chainstate->ForceFlushStateToDisk();
264 if (chainstate->CanFlushToDisk()) {
265 chainstate->ForceFlushStateToDisk();
266 chainstate->ResetCoinsViews();
270 for (
const auto& client :
node.chain_clients) {
282 node.chain_clients.clear();
286 node.mempool.reset();
287 node.fee_estimator.reset();
288 node.chainman.reset();
289 node.scheduler.reset();
293 LogPrintf(
"%s: Unable to remove PID file: File does not exist\n", __func__);
295 }
catch (
const fs::filesystem_error& e) {
319static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
332 sigemptyset(&sa.sa_mask);
334 sigaction(signal, &sa,
nullptr);
369 std::vector<std::string> hidden_args = {
370 "-dbcrashratio",
"-forcecompactdb",
372 "-choosedatadir",
"-lang=<lang>",
"-min",
"-resetguisettings",
"-splash",
"-uiplatform"};
378 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);
397 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)",
401 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 -coinstatsindex. "
402 "Warning: Reverting this setting requires re-downloading the entire blockchain. "
413 hidden_args.emplace_back(
"-sysperms");
416 argsman.
AddArg(
"-blockfilterindex=<type>",
418 " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
424 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);
442 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_ANY,
OptionsCategory::CONNECTION);
443 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);
447 argsman.
AddArg(
"-port=<port>",
strprintf(
"Listen for connections on <port>. Nodes not using the default ports (default: %u, testnet: %u, signet: %u, regtest: %u) are unlikely to get incoming connections. Not relevant for I2P (see doc/i2p.md).", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()),
ArgsManager::ALLOW_ANY |
ArgsManager::NETWORK_ONLY,
OptionsCategory::CONNECTION);
463 hidden_args.emplace_back(
"-upnp");
468 hidden_args.emplace_back(
"-natpmp");
470 argsman.
AddArg(
"-whitebind=<[permissions@]addr>",
"Bind to the given address and add permission flags to the peers connecting to it. "
474 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 "
475 "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as "
492 hidden_args.emplace_back(
"-zmqpubhashblock=<address>");
493 hidden_args.emplace_back(
"-zmqpubhashtx=<address>");
494 hidden_args.emplace_back(
"-zmqpubrawblock=<address>");
495 hidden_args.emplace_back(
"-zmqpubrawtx=<address>");
496 hidden_args.emplace_back(
"-zmqpubsequence=<n>");
497 hidden_args.emplace_back(
"-zmqpubhashblockhwm=<n>");
498 hidden_args.emplace_back(
"-zmqpubhashtxhwm=<n>");
499 hidden_args.emplace_back(
"-zmqpubrawblockhwm=<n>");
500 hidden_args.emplace_back(
"-zmqpubrawtxhwm=<n>");
501 hidden_args.emplace_back(
"-zmqpubsequencehwm=<n>");
533 argsman.
AddArg(
"-minrelaytxfee=<amt>",
strprintf(
"Fees (in %s/kvB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
544 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);
545 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);
546 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);
549 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);
554 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);
555 argsman.
AddArg(
"-rpcwhitelistdefault",
"Sets default behavior for rpc whitelisting. Unless rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc server acts as if all rpc users are subject to empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault is set to 1 and no -rpcwhitelist is set, rpc server acts as if all rpc users are subject to empty whitelists.",
ArgsManager::ALLOW_ANY,
OptionsCategory::RPC);
563 hidden_args.emplace_back(
"-daemon");
564 hidden_args.emplace_back(
"-daemonwait");
567#if defined(USE_SYSCALL_SANDBOX)
568 argsman.
AddArg(
"-sandbox=<mode>",
"Use the experimental syscall sandbox in the specified mode (-sandbox=log-and-abort or -sandbox=abort). Allow only expected syscalls to be used by bitcoind. Note that this is an experimental new feature that may cause bitcoind to exit or crash unexpectedly: use with caution. In the \"log-and-abort\" mode the invocation of an unexpected syscall results in a debug handler being invoked which will log the incident and terminate the program (without executing the unexpected syscall). In the \"abort\" mode the invocation of an unexpected syscall results in the entire process being killed immediately by the kernel without executing the unexpected syscall.",
ArgsManager::ALLOW_ANY,
OptionsCategory::OPTIONS);
577 const std::string URL_SOURCE_CODE =
"<https://github.com/bitcoin/bitcoin>";
581 strprintf(
_(
"Please contribute if you find %s useful. "
582 "Visit %s for further information about the software.").translated,
585 strprintf(
_(
"The source code is available from %s.").translated,
589 _(
"This is experimental software.").
translated +
"\n" +
590 strprintf(
_(
"Distributed under the MIT software license, see the accompanying file %s or %s").translated,
"COPYING",
"<https://opensource.org/licenses/MIT>") +
600 if (pBlockIndex !=
nullptr) {
612 std::string cmd = args.
GetArg(
"-startupnotify",
"");
614 std::thread t(runCommand, cmd);
643 LogPrintf(
"%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
647 LogPrintf(
"%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
653 LogPrintf(
"%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
655 LogPrintf(
"%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
661 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
665 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
667 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -natpmp=0\n", __func__);
671 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
677 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
679 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -natpmp=0\n", __func__);
682 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
684 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
686 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -i2pacceptincoming=0\n", __func__);
693 LogPrintf(
"%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
699 LogPrintf(
"%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
705 LogPrintf(
"%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
724int nUserMaxConnections;
727int64_t peer_connect_timeout;
728std::set<BlockFilterType> g_enabled_filter_types;
738 std::set_new_handler(std::terminate);
739 LogPrintf(
"Error: Out of memory. Terminating.\n");
750 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
751 _CrtSetReportFile(_CRT_WARN, CreateFileA(
"NUL", GENERIC_WRITE, 0,
nullptr, OPEN_EXISTING, 0, 0));
753 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
757 HeapSetInformation(
nullptr, HeapEnableTerminationOnCorruption,
nullptr, 0);
780 signal(SIGPIPE, SIG_IGN);
782 SetConsoleCtrlHandler(consoleCtrlHandler,
true);
806 errors +=
strprintf(
_(
"Config setting for %s only applied on %s network when in [%s] section.") +
Untranslated(
"\n"), arg, network, network);
809 if (!errors.
empty()) {
819 if (!warnings.
empty()) {
829 if (blockfilterindex_value ==
"" || blockfilterindex_value ==
"1") {
831 }
else if (blockfilterindex_value !=
"0") {
832 const std::vector<std::string> names = args.
GetArgs(
"-blockfilterindex");
833 for (
const auto&
name : names) {
838 g_enabled_filter_types.insert(filter_type);
845 return InitError(
_(
"Cannot set -peerblockfilters without -blockfilterindex."));
854 return InitError(
_(
"Prune mode is incompatible with -txindex."));
856 return InitError(
_(
"Prune mode is incompatible with -coinstatsindex."));
861 return InitError(
_(
"Cannot set -forcednsseed to true when setting -dnsseed to false."));
865 size_t nUserBind = args.
GetArgs(
"-bind").size() + args.
GetArgs(
"-whitebind").size();
876 int nBind = std::max(nUserBind,
size_t(1));
878 nMaxConnections = std::max(nUserMaxConnections, 0);
885 int fd_max = FD_SETSIZE;
891 return InitError(
_(
"Not enough file descriptors available."));
894 if (nMaxConnections < nUserMaxConnections)
895 InitWarning(
strprintf(
_(
"Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
907 LogPrintf(
"Validating signatures for all blocks.\n");
909 if (args.
IsArgSet(
"-minimumchainwork")) {
910 const std::string minChainWorkStr = args.
GetArg(
"-minimumchainwork",
"");
926 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
927 return InitError(
strprintf(
_(
"-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
930 if (args.
IsArgSet(
"-incrementalrelayfee")) {
931 if (std::optional<CAmount> inc_relay_fee =
ParseMoney(args.
GetArg(
"-incrementalrelayfee",
""))) {
939 int64_t nPruneArg = args.
GetIntArg(
"-prune", 0);
941 return InitError(
_(
"Prune cannot be configured with a negative value."));
944 if (nPruneArg == 1) {
945 LogPrintf(
"Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
952 LogPrintf(
"Prune configured to target %u MiB on disk for block and undo files.\n",
nPruneTarget / 1024 / 1024);
962 if (peer_connect_timeout <= 0) {
966 if (args.
IsArgSet(
"-minrelaytxfee")) {
967 if (std::optional<CAmount> min_relay_fee =
ParseMoney(args.
GetArg(
"-minrelaytxfee",
""))) {
981 if (args.
IsArgSet(
"-blockmintxfee")) {
989 if (args.
IsArgSet(
"-dustrelayfee")) {
990 if (std::optional<CAmount> parsed =
ParseMoney(args.
GetArg(
"-dustrelayfee",
""))) {
1023 if (args.
IsArgSet(
"-proxy") && args.
GetArg(
"-proxy",
"").empty()) {
1024 return InitError(
_(
"No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
1027#if defined(USE_SYSCALL_SANDBOX)
1029 const std::string sandbox_arg{args.
GetArg(
"-sandbox",
"")};
1030 bool log_syscall_violation_before_terminating{
false};
1031 if (sandbox_arg ==
"log-and-abort") {
1032 log_syscall_violation_before_terminating =
true;
1033 }
else if (sandbox_arg ==
"abort") {
1036 return InitError(
Untranslated(
"Unknown syscall sandbox mode (-sandbox=<mode>). Available modes are \"log-and-abort\" and \"abort\"."));
1039 const std::vector<std::string> features_using_execve{
1046 for (
const std::string& feature_using_execve : features_using_execve) {
1047 if (!args.
GetArg(feature_using_execve,
"").empty()) {
1048 return InitError(
Untranslated(
strprintf(
"The experimental syscall sandbox feature (-sandbox=<mode>) is incompatible with %s (which uses execve).", feature_using_execve)));
1051 if (!SetupSyscallSandbox(log_syscall_violation_before_terminating)) {
1054 LogPrintf(
"Experimental syscall sandbox enabled (-sandbox=%s): bitcoind will terminate if an unexpected (not allowlisted) syscall is invoked.\n", sandbox_arg);
1104 node.chain =
node.init->makeChain();
1127 LogPrintf(
"Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1131 LogPrintf(
"Warning: relative datadir option '%s' specified, which will be interpreted relative to the "
1132 "current working directory '%s'. This is fragile, because if bitcoin is started in the future "
1133 "from a different location, it will be unable to locate the current data files. There could "
1134 "also be data loss if bitcoin is started while in a temporary directory.\n",
1142 if (script_threads <= 0) {
1149 script_threads = std::max(script_threads - 1, 0);
1154 LogPrintf(
"Script verification uses %d additional threads\n", script_threads);
1155 if (script_threads >= 1) {
1161 node.scheduler = std::make_unique<CScheduler>();
1164 node.scheduler->m_service_thread = std::thread(
util::TraceThread,
"scheduler", [&] {
node.scheduler->serviceQueue(); });
1167 node.scheduler->scheduleEvery([]{
1169 }, std::chrono::minutes{1});
1177 for (
const auto& client :
node.chain_clients) {
1178 client->registerRpcs();
1192 return InitError(
_(
"Unable to start HTTP server. See debug log for details."));
1196 for (
const auto& client :
node.chain_clients) {
1197 if (!client->verify()) {
1217 std::vector<bool> asmap;
1220 if (asmap_path.empty()) {
1223 if (!asmap_path.is_absolute()) {
1231 if (asmap.size() == 0) {
1236 LogPrintf(
"Using asmap version %s for IP bucketing\n", asmap_version.
ToString());
1238 LogPrintf(
"Using /16 prefix for IP bucketing\n");
1241 uiInterface.InitMessage(
_(
"Loading P2P addresses…").translated);
1250 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));
1255 if (!ignores_incoming_txs)
node.fee_estimator = std::make_unique<CBlockPolicyEstimator>();
1259 node.mempool = std::make_unique<CTxMemPool>(
node.fee_estimator.get(), check_ratio);
1262 node.chainman = std::make_unique<ChainstateManager>();
1267 chainman, *
node.mempool, ignores_incoming_txs);
1271 std::vector<std::string> uacomments;
1272 for (
const std::string& cmt : args.
GetArgs(
"-uacomment")) {
1274 return InitError(
strprintf(
_(
"User Agent comment (%s) contains unsafe characters."), cmt));
1275 uacomments.push_back(cmt);
1279 return InitError(
strprintf(
_(
"Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1284 std::set<enum Network> nets;
1285 for (
const std::string& snet : args.
GetArgs(
"-onlynet")) {
1291 for (
int n = 0; n <
NET_MAX; n++) {
1293 if (!nets.count(net))
1298 if (!args.
IsArgSet(
"-cjdnsreachable")) {
1312 std::string proxyArg = args.
GetArg(
"-proxy",
"");
1314 if (proxyArg !=
"" && proxyArg !=
"0") {
1335 std::string onionArg = args.
GetArg(
"-onion",
"");
1336 if (onionArg !=
"") {
1337 if (onionArg ==
"0") {
1352 for (
const std::string& strAddr : args.
GetArgs(
"-externalip")) {
1371 bool fReindexChainState = args.
GetBoolArg(
"-reindex-chainstate",
false);
1375 nTotalCache = std::max(nTotalCache,
nMinDbCache << 20);
1376 nTotalCache = std::min(nTotalCache,
nMaxDbCache << 20);
1377 int64_t nBlockTreeDBCache = std::min(nTotalCache / 8,
nMaxBlockDBCache << 20);
1378 nTotalCache -= nBlockTreeDBCache;
1380 nTotalCache -= nTxIndexCache;
1381 int64_t filter_index_cache = 0;
1382 if (!g_enabled_filter_types.empty()) {
1383 size_t n_indexes = g_enabled_filter_types.size();
1385 filter_index_cache = max_cache / n_indexes;
1386 nTotalCache -= filter_index_cache * n_indexes;
1388 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23));
1390 nTotalCache -= nCoinDBCache;
1391 int64_t nCoinCacheUsage = nTotalCache;
1394 LogPrintf(
"* Using %.1f MiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1396 LogPrintf(
"* Using %.1f MiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
1399 LogPrintf(
"* Using %.1f MiB for %s block filter index database\n",
1402 LogPrintf(
"* Using %.1f MiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1403 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));
1405 bool fLoaded =
false;
1409 return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull();
1416 const int64_t load_block_index_start_time =
GetTimeMillis();
1419 chainman.InitializeChainstate(
Assert(
node.mempool.get()));
1425 auto& pblocktree{chainman.m_blockman.m_block_tree_db};
1429 pblocktree.reset(
new CBlockTreeDB(nBlockTreeDBCache,
false, fReset));
1432 pblocktree->WriteReindexing(
true);
1446 strLoadError =
_(
"Error loading block database");
1454 return InitError(
_(
"Incorrect or no genesis block found. Wrong datadir for network?"));
1460 strLoadError =
_(
"You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1469 strLoadError =
_(
"Error initializing block database");
1476 bool failed_chainstate_init =
false;
1479 chainstate->InitCoinsDB(
1482 fReset || fReindexChainState);
1484 chainstate->CoinsErrorCatcher().AddReadErrCallback([]() {
1486 _(
"Error reading from database, shutting down."),
1492 if (!chainstate->CoinsDB().Upgrade()) {
1493 strLoadError =
_(
"Error upgrading chainstate database");
1494 failed_chainstate_init =
true;
1499 if (!chainstate->ReplayBlocks()) {
1500 strLoadError =
_(
"Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1501 failed_chainstate_init =
true;
1506 chainstate->InitCoinsCache(nCoinCacheUsage);
1507 assert(chainstate->CanFlushToDisk());
1509 if (!is_coinsview_empty(chainstate)) {
1511 if (!chainstate->LoadChainTip()) {
1512 strLoadError =
_(
"Error initializing block database");
1513 failed_chainstate_init =
true;
1516 assert(chainstate->m_chain.Tip() !=
nullptr);
1520 if (failed_chainstate_init) {
1523 }
catch (
const std::exception& e) {
1525 strLoadError =
_(
"Error opening block database");
1531 auto chainstates{chainman.
GetAll()};
1532 if (std::any_of(chainstates.begin(), chainstates.end(),
1534 strLoadError =
strprintf(
_(
"Witness data for blocks after height %d requires validation. Please restart with -reindex."),
1540 bool failed_verification =
false;
1546 if (!is_coinsview_empty(chainstate)) {
1547 uiInterface.InitMessage(
_(
"Verifying blocks…").translated);
1549 LogPrintf(
"Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
1553 const CBlockIndex* tip = chainstate->m_chain.Tip();
1556 strLoadError =
_(
"The block database contains a block which appears to be from the future. "
1557 "This may be due to your computer's date and time being set incorrectly. "
1558 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1559 failed_verification =
true;
1564 *chainstate, chainparams, chainstate->CoinsDB(),
1567 strLoadError =
_(
"Corrupted block database detected");
1568 failed_verification =
true;
1573 }
catch (
const std::exception& e) {
1575 strLoadError =
_(
"Error opening block database");
1576 failed_verification =
true;
1580 if (!failed_verification) {
1590 strLoadError +
Untranslated(
".\n\n") +
_(
"Do you want to rebuild the block database now?"),
1591 strLoadError.
original +
".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1597 LogPrintf(
"Aborted block database rebuild. Exiting.\n");
1610 LogPrintf(
"Shutdown requested. Exiting.\n");
1626 for (
const auto& filter_type : g_enabled_filter_types) {
1641 for (
const auto& client :
node.chain_clients) {
1642 if (!client->load()) {
1652 LogPrintf(
"Unsetting NODE_NETWORK on prune mode\n");
1657 uiInterface.InitMessage(
_(
"Pruning blockstore…").translated);
1658 chainstate->PruneAndFlush();
1676 boost::signals2::connection block_notify_genesis_wait_connection;
1684 const std::string block_notify = args.
GetArg(
"-blocknotify",
"");
1685 if (!block_notify.empty()) {
1688 std::string command = block_notify;
1690 std::thread t(runCommand, command);
1696 std::vector<fs::path> vImportFiles;
1697 for (
const std::string& strFile : args.
GetArgs(
"-loadblock")) {
1714 block_notify_genesis_wait_connection.disconnect();
1723 int chain_active_height;
1740 LogPrintf(
"nBestHeight = %d\n", chain_active_height);
1741 if (
node.peerman)
node.peerman->SetBestHeight(chain_active_height);
1765 for (
const std::string& bind_arg : args.
GetArgs(
"-bind")) {
1767 const size_t index = bind_arg.rfind(
'=');
1768 if (index == std::string::npos) {
1770 connOptions.
vBinds.push_back(bind_addr);
1774 const std::string network_type = bind_arg.substr(index + 1);
1775 if (network_type ==
"onion") {
1776 const std::string truncated_bind_arg = bind_arg.substr(0, index);
1777 if (
Lookup(truncated_bind_arg, bind_addr,
BaseParams().OnionServiceTargetPort(),
false)) {
1786 for (
const std::string& strBind : args.
GetArgs(
"-whitebind")) {
1799 onion_service_target = connOptions.
onion_binds.front();
1802 connOptions.
onion_binds.push_back(onion_service_target);
1808 "for the automatically created Tor onion service."),
1814 for (
const auto& net : args.
GetArgs(
"-whitelist")) {
1826 const auto connect = args.
GetArgs(
"-connect");
1827 if (connect.size() != 1 || connect[0] !=
"0") {
1832 const std::string& i2psam_arg = args.
GetArg(
"-i2psam",
"");
1833 if (!i2psam_arg.empty()) {
1846 if (!
node.connman->Start(*
node.scheduler, connOptions)) {
1855 for (
const auto& client :
node.chain_clients) {
1856 client->start(*
node.scheduler);
1860 node.scheduler->scheduleEvery([banman]{
1864 if (
node.peerman)
node.peerman->StartScheduledTasks(*
node.scheduler);
1867 StartupNotify(args);
std::optional< bilingual_str > LoadAddrman(const std::vector< bool > &asmap, const ArgsManager &args, std::unique_ptr< AddrMan > &addrman)
Returns an error string on failure.
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS
Default for -checkaddrman.
arith_uint256 UintToArith256(const uint256 &a)
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
How often to dump banned addresses/subnets to disk.
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
const std::set< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
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.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
bool fHavePruned
Pruning-related variables and constants.
void ThreadImport(ChainstateManager &chainman, std::vector< fs::path > vImportFiles, const ArgsManager &args)
void CleanupBlockRevFiles()
bool fPruneMode
True if we're running in -prune mode.
std::atomic_bool fReindex
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
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.
const CChainParams & Params()
Return the currently selected parameters.
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
#define Assert(val)
Identity function.
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...
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
@ ALLOW_ANY
disable validation
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
std::atomic< bool > m_reopen_file
void Stop()
Stops the instance from staying in sync with blockchain updates.
bool BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(void Interrupt()
Blocks the current thread until the index is caught up to the current state of the block chain.
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
static const std::string REGTEST
static const std::string TESTNET
static const std::string SIGNET
static const std::string MAIN
Chain name strings.
The block chain is a tree shaped structure starting with the genesis block at the root,...
uint256 GetBlockHash() const
int64_t GetBlockTime() const
int nHeight
height of the entry in the chain. The genesis block has height 0
Access to the block database (blocks/index/)
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
int Height() const
Return the maximal height in the chain.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const CBlock & GenesisBlock() const
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
std::string NetworkIDString() const
Return the network string.
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
const Consensus::Params & GetConsensus() const
bool IsTestChain() const
If this chain is exclusively used for testing.
const CMessageHeader::MessageStartChars & MessageStart() const
CChainState stores and provides an API to update our local knowledge of the current best chain.
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
Fee rate in satoshis per kilobyte: CAmount / kB.
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once)
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToStringIPPort() const
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
static const int DEFAULT_ZMQ_SNDHWM
static CZMQNotificationInterface * Create()
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
CChainState &InitializeChainstate(CTxMemPool *mempool, const std::optional< uint256 > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
CChainState & ActiveChainstate() const
The most-work chain.
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
CChain & ActiveChain() const
static bool TryParse(const std::string &str, NetWhitebindPermissions &output, bilingual_str &error)
static bool TryParse(const std::string &str, NetWhitelistPermissions &output, bilingual_str &error)
static std::unique_ptr< PeerManager > make(const CChainParams &chainparams, CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, bool ignore_incoming_txs)
virtual void AddWalletOptions(ArgsManager &argsman) const =0
Get wallet help string.
virtual void Construct(NodeContext &node) const =0
Add wallets that should be opened to list of chain clients.
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
std::string ToString() const
std::string GetHex() const
std::string GetHex() const
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
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 int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
const std::string CLIENT_NAME
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
const std::string CURRENCY_UNIT
uint256 SerializeHash(const T &obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
Compute the 256-bit hash of an object's serialization.
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
void StopHTTPRPC()
Stop HTTP RPC subsystem.
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
void StartREST(const std::any &context)
Start HTTP REST subsystem.
void StopREST()
Stop HTTP REST subsystem.
void InterruptREST()
Interrupt RPC REST subsystem.
void InterruptHTTPServer()
Interrupt HTTP server threads.
void StartHTTPServer()
Start HTTP server.
bool InitHTTPServer()
Initialize HTTP server.
void StopHTTPServer()
Stop HTTP server.
static const int DEFAULT_HTTP_SERVER_TIMEOUT
static const int DEFAULT_HTTP_WORKQUEUE
static const int DEFAULT_HTTP_THREADS
Common init functions shared by bitcoin-node, bitcoin-wallet, etc.
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
static bool CreatePidFile(const ArgsManager &args)
static const bool DEFAULT_PROXYRANDOMIZE
void Interrupt(NodeContext &node)
Interrupt threads.
void InitLogging(const ArgsManager &args)
Initialize global loggers.
static bool AppInitServers(NodeContext &node)
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
void SetupServerArgs(ArgsManager &argsman)
Register all arguments with the ArgsManager.
#define MIN_CORE_FILEDESCRIPTORS
void Shutdown(NodeContext &node)
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
static void OnRPCStarted()
static Mutex g_genesis_wait_mutex
static void HandleSIGHUP(int)
static fs::path GetPidFile(const ArgsManager &args)
static std::condition_variable g_genesis_wait_cv
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin core: Basic context setup.
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
static const char * DEFAULT_ASMAP_FILENAME
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
static void OnRPCStopped()
static bool LockDataDirectory(bool probeOnly)
static void registerSignalHandler(int signal, void(*handler)(int))
std::string LicenseInfo()
Returns licensing information (for -version)
bool AppInitMain(NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
static const bool DEFAULT_REST_ENABLE
static boost::signals2::connection rpc_notify_block_change_connection
static void new_handler_terminate()
static constexpr bool DEFAULT_DAEMON
Default value for -daemon option.
static constexpr bool DEFAULT_DAEMONWAIT
Default value for -daemonwait option.
BCLog::Logger & LogInstance()
#define LogPrint(category,...)
void StartMapPort(bool use_upnp, bool use_natpmp)
static constexpr bool DEFAULT_NATPMP
static constexpr bool DEFAULT_UPNP
static const bool DEFAULT_PRINTPRIORITY
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
void OnStarted(std::function< void()> slot)
void OnStopped(std::function< void()> slot)
static auto quoted(const std::string &s)
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to byte string.
static path PathFromString(const std::string &string)
Convert byte string to path object.
std::string get_filesystem_error_message(const fs::filesystem_error &e)
void AddLoggingArgs(ArgsManager &argsman)
void SetLoggingCategories(const ArgsManager &args)
bool SanityChecks()
Ensure a usable environment with all necessary library support.
bool StartLogging(const ArgsManager &args)
void SetLoggingOptions(const ArgsManager &args)
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
bool AddLocal(const CService &addr_, int nScore)
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
static const size_t DEFAULT_MAXSENDBUFFER
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
static constexpr bool DEFAULT_FIXEDSEEDS
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
static const size_t DEFAULT_MAXRECEIVEBUFFER
static constexpr bool DEFAULT_FORCEDNSSEED
static constexpr bool DEFAULT_DNSSEED
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
static const bool DEFAULT_LISTEN
-listen default
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
const std::vector< std::string > NET_PERMISSIONS_DOC
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 DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
static const bool DEFAULT_PEERBLOCKFILTERS
static const bool DEFAULT_PEERBLOOMFILTERS
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
@ NET_ONION
TOR (v2 or v3)
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
enum Network ParseNetwork(const std::string &net_in)
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.
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
bool SetProxy(enum Network net, const proxyType &addrProxy)
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
static const int DEFAULT_NAME_LOOKUP
-dns default
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
CFeeRate incrementalRelayFee
unsigned int nBytesPerSigOp
static const unsigned int DUST_RELAY_TX_FEE
Min feerate for defining dust.
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
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 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_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
static const unsigned int DEFAULT_BLOCK_MAX_WEIGHT
Default for -blockmaxweight, which controls the range of block weights the mining code will create.
static const unsigned int DEFAULT_BYTES_PER_SIGOP
Default for -bytespersigop.
ServiceFlags
nServices flags
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
static void RegisterAllCoreRPCCommands(CRPCTable &t)
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
void SetRPCWarmupFinished()
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
static const unsigned int DEFAULT_RPC_SERIALIZE_VERSION
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
bool InitShutdownState()
Initialize shutdown state.
void StartShutdown()
Request shutdown of the application.
void AbortShutdown()
Clear shutdown flag.
void InitSignatureCache()
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
unsigned nMaxDatacarrierBytes
Maximum size of TxoutType::NULL_DATA scripts that this node considers standard.
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
static const bool DEFAULT_ACCEPT_DATACARRIER
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
bool IsHexNumber(const std::string &str)
Return true if the string is a hex number, optionally prefixed with "0x".
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
int m_max_outbound_block_relay
unsigned int nReceiveFloodSize
int m_max_outbound_full_relay
std::vector< NetWhitebindPermissions > vWhiteBinds
uint64_t nMaxOutboundLimit
std::vector< NetWhitelistPermissions > vWhitelistedRange
CClientUIInterface * uiInterface
std::vector< CService > onion_binds
std::vector< std::string > m_specified_outgoing
NetEventsInterface * m_msgproc
ServiceFlags nLocalServices
std::vector< std::string > m_added_nodes
int64_t m_peer_connect_timeout
std::vector< CService > vBinds
unsigned int nSendBufferMaxSize
bool m_i2p_accept_incoming
std::vector< std::string > vSeedNodes
bool m_use_addrman_outgoing
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
uint256 defaultAssumeValid
By default assume that the signatures in ancestors of this block are valid.
int SegwitHeight
Block height at which Segwit (BIP141, BIP143 and BIP147) becomes active.
uint256 nMinimumChainWork
The best chain should have at least this much work.
NodeContext struct containing references to chain state and connection state.
Block and header tip information.
double verification_progress
#define WAIT_LOCK(cs, name)
#define TRY_LOCK(cs, name)
bool error(const char *fmt, const Args &... args)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTimeMillis()
Returns the system time (not mockable)
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
int64_t GetAdjustedTime()
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
CService DefaultOnionServiceTarget()
const std::string DEFAULT_TOR_CONTROL
Default control port.
void InterruptTorControl()
void StartTorControl(CService onion_service_target)
static const bool DEFAULT_LISTEN_ONION
bilingual_str _(const char *psz)
Translation function.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
std::optional< bilingual_str > CheckLegacyTxindex(CBlockTreeDB &block_tree_db)
static const int64_t nMinDbCache
min. -dbcache (MiB)
static const int64_t nDefaultDbBatchSize
-dbbatchsize default (bytes)
static const int64_t nMaxCoinsDBCache
Max memory allocated to coin DB specific cache (MiB)
static const int64_t nMaxBlockDBCache
Max memory allocated to block tree DB specific cache, if no -txindex (MiB)
static const int64_t nMaxTxIndexCache
Max memory allocated to block tree DB specific cache, if -txindex (MiB)
static const int64_t nMaxDbCache
max. -dbcache (MiB)
static const int64_t nDefaultDbCache
-dbcache default (MiB)
static const int64_t max_filter_index_cache
Max memory allocated to all block filter index caches combined in MiB.
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
CClientUIInterface uiInterface
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
uint256 uint256S(const char *str)
std::vector< bool > DecodeAsmap(fs::path path)
Read asmap from provided binary file.
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
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 char *const BITCOIN_SETTINGS_FILENAME
std::string CopyrightHolders(const std::string &strPrefix)
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
bool DirIsWritable(const fs::path &directory)
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
const char *const BITCOIN_CONF_FILENAME
int GetNumCores()
Return the number of cores available on the current system.
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
std::condition_variable g_best_block_cv
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...
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
void InitScriptExecutionCache()
Initializes the script-execution cache.
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
bool DumpMempool(const CTxMemPool &pool, FopenFn mockable_fopen_function, bool skip_file_commit)
Dump the mempool to disk.
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
static const bool DEFAULT_CHECKPOINTS_ENABLED
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
static const unsigned int DEFAULT_CHECKLEVEL
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
SynchronizationState
Current sync state passed to tip changed callbacks.
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
static const char *const DEFAULT_BLOCKFILTERINDEX
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
static constexpr bool DEFAULT_COINSTATSINDEX
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
static const int64_t DEFAULT_MAX_TIP_AGE
static const signed int DEFAULT_CHECKBLOCKS
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
static const bool DEFAULT_TXINDEX
CMainSignals & GetMainSignals()
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
const WalletInitInterface & g_wallet_init_interface
CZMQNotificationInterface * g_zmq_notification_interface
void RegisterZMQRPCCommands(CRPCTable &t)