6 #if defined(HAVE_CONFIG_H) 57 #include <boost/algorithm/string/classification.hpp> 58 #include <boost/algorithm/string/replace.hpp> 59 #include <boost/algorithm/string/split.hpp> 60 #include <boost/bind.hpp> 61 #include <boost/thread.hpp> 62 #include <openssl/crypto.h> 70 static const bool DEFAULT_PROXYRANDOMIZE =
true;
71 static const bool DEFAULT_REST_ENABLE =
false;
72 static const bool DEFAULT_STOPAFTERBLOCKIMPORT =
false;
81 #define MIN_CORE_FILEDESCRIPTORS 0 83 #define MIN_CORE_FILEDESCRIPTORS 150 86 static const char* FEE_ESTIMATES_FILENAME=
"fee_estimates.dat";
125 }
catch(
const std::runtime_error& e) {
127 LogPrintf(
"Error reading from database: %s\n", e.what());
138 static std::unique_ptr<CCoinsViewErrorCatcher> pcoinscatcher;
139 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
141 static boost::thread_group threadGroup;
161 LogPrintf(
"%s: In progress...\n", __func__);
163 TRY_LOCK(cs_Shutdown, lockShutdown);
191 threadGroup.interrupt_all();
192 threadGroup.join_all();
207 fs::path est_path =
GetDataDir() / FEE_ESTIMATES_FILENAME;
209 if (!est_fileout.
IsNull())
212 LogPrintf(
"%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
237 pcoinscatcher.reset();
254 }
catch (
const fs::filesystem_error& e) {
255 LogPrintf(
"%s: Unable to remove pidfile: %s\n", __func__, e.what());
262 globalVerifyHandle.reset();
264 LogPrintf(
"%s: done\n", __func__);
273 static void HandleSIGTERM(
int)
278 static void HandleSIGHUP(
int)
283 static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
292 static void registerSignalHandler(
int signal,
void(*
handler)(
int))
296 sigemptyset(&sa.sa_mask);
298 sigaction(signal, &sa,
nullptr);
302 static void OnRPCStarted()
307 static void OnRPCStopped()
325 std::vector<std::string> hidden_args = {
"-h",
"-help",
326 "-dbcrashratio",
"-forcecompactdb",
328 "-allowselfsignedrootcertificates",
"-choosedatadir",
"-lang=<lang>",
"-min",
"-resetguisettings",
"-rootcertificates=<file>",
"-splash",
"-uiplatform"};
334 gArgs.
AddArg(
"-alertnotify=<cmd>",
"Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)",
false,
OptionsCategory::OPTIONS);
335 gArgs.
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)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()),
false,
OptionsCategory::OPTIONS);
338 gArgs.
AddArg(
"-blockreconstructionextratxn=<n>",
strprintf(
"Extra transactions to keep in memory for compact block reconstructions (default: %u)", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN),
false,
OptionsCategory::OPTIONS);
346 gArgs.
AddArg(
"-includeconf=<file>",
"Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)",
false,
OptionsCategory::OPTIONS);
351 gArgs.
AddArg(
"-minimumchainwork=<hex>",
strprintf(
"Minimum work assumed to exist on a valid chain in hex (default: %s, testnet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()),
true,
OptionsCategory::OPTIONS);
352 gArgs.
AddArg(
"-par=<n>",
strprintf(
"Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)",
358 hidden_args.emplace_back(
"-pid");
360 gArgs.
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. " 361 "Warning: Reverting this setting requires re-downloading the entire blockchain. " 362 "(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024),
false,
OptionsCategory::OPTIONS);
364 gArgs.
AddArg(
"-reindex-chainstate",
"Rebuild chain state from the currently indexed blocks. When in pruning mode or if blocks on disk might be corrupted, use full -reindex instead.",
false,
OptionsCategory::OPTIONS);
366 gArgs.
AddArg(
"-sysperms",
"Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)",
false,
OptionsCategory::OPTIONS);
368 hidden_args.emplace_back(
"-sysperms");
372 gArgs.
AddArg(
"-addnode=<ip>",
"Add a node to connect to and attempt to keep the connection open (see the `addnode` RPC command help for more info). This option can be specified multiple times to add multiple nodes.",
false,
OptionsCategory::CONNECTION);
376 gArgs.
AddArg(
"-connect=<ip>",
"Connect only to the specified node; -noconnect disables automatic connections (the rules for this peer are the same as for -addnode). This option can be specified multiple times to connect to multiple nodes.",
false,
OptionsCategory::CONNECTION);
388 gArgs.
AddArg(
"-maxtimeadjustment",
strprintf(
"Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)", DEFAULT_MAX_TIME_ADJUSTMENT),
false,
OptionsCategory::CONNECTION);
391 gArgs.
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.",
false,
OptionsCategory::CONNECTION);
394 gArgs.
AddArg(
"-port=<port>",
strprintf(
"Listen for connections on <port> (default: %u, testnet: %u, regtest: %u)", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()),
false,
OptionsCategory::CONNECTION);
397 gArgs.
AddArg(
"-seednode=<ip>",
"Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes.",
false,
OptionsCategory::CONNECTION);
408 hidden_args.emplace_back(
"-upnp");
411 gArgs.
AddArg(
"-whitelist=<IP address or network>",
"Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR notated network (e.g. 1.2.3.0/24). Can be specified multiple times." 412 " Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway",
false,
OptionsCategory::CONNECTION);
422 hidden_args.emplace_back(
"-zmqpubhashblock=<address>");
423 hidden_args.emplace_back(
"-zmqpubhashtx=<address>");
424 hidden_args.emplace_back(
"-zmqpubrawblock=<address>");
425 hidden_args.emplace_back(
"-zmqpubrawtx=<address>");
429 gArgs.
AddArg(
"-checklevel=<n>",
strprintf(
"How thorough the block verification of -checkblocks is: " 430 "level 0 reads the blocks from disk, " 431 "level 1 verifies block validity, " 432 "level 2 verifies undo data, " 433 "level 3 checks disconnection of tip blocks, " 434 "and level 4 tries to reconnect the blocks, " 435 "each level includes the checks of the previous levels " 437 gArgs.
AddArg(
"-checkblockindex",
strprintf(
"Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()),
true,
OptionsCategory::DEBUG_TEST);
438 gArgs.
AddArg(
"-checkmempool=<n>",
strprintf(
"Run checks every <n> transactions (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()),
true,
OptionsCategory::DEBUG_TEST);
447 gArgs.
AddArg(
"-limitdescendantsize=<n>",
strprintf(
"Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT),
true,
OptionsCategory::DEBUG_TEST);
449 gArgs.
AddArg(
"-debug=<category>",
"Output debugging information (default: -nodebug, supplying <category> is optional). " 451 gArgs.
AddArg(
"-debugexclude=<category>",
strprintf(
"Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except one or more specified categories."),
false,
OptionsCategory::DEBUG_TEST);
459 gArgs.
AddArg(
"-maxtxfee=<amt>",
strprintf(
"Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)",
475 gArgs.
AddArg(
"-minrelaytxfee=<amt>",
strprintf(
"Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
486 gArgs.
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",
false,
OptionsCategory::RPC);
487 gArgs.
AddArg(
"-rpcauth=<userpw>",
"Username and 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",
false,
OptionsCategory::RPC);
488 gArgs.
AddArg(
"-rpcbind=<addr>[:port]",
"Bind to given address to listen for JSON-RPC connections. 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, or if -rpcallowip has been specified, 0.0.0.0 and :: i.e., all addresses)",
false,
OptionsCategory::RPC);
489 gArgs.
AddArg(
"-rpccookiefile=<loc>",
"Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)",
false,
OptionsCategory::RPC);
491 gArgs.
AddArg(
"-rpcport=<port>",
strprintf(
"Listen for JSON-RPC connections on <port> (default: %u, testnet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), regtestBaseParams->RPCPort()),
false,
OptionsCategory::RPC);
492 gArgs.
AddArg(
"-rpcserialversion",
strprintf(
"Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)", DEFAULT_RPC_SERIALIZE_VERSION),
false,
OptionsCategory::RPC);
502 hidden_args.emplace_back(
"-daemon");
511 const std::string URL_SOURCE_CODE =
"<https://github.com/bsha3/bsha3>";
512 const std::string URL_WEBSITE =
"<https://bsha3.org>";
516 strprintf(
_(
"Please contribute if you find %s useful. " 517 "Visit %s for further information about the software."),
520 strprintf(
_(
"The source code is available from %s."),
524 _(
"This is experimental software.") +
"\n" +
525 strprintf(
_(
"Distributed under the MIT software license, see the accompanying file %s or %s"),
"COPYING",
"<https://opensource.org/licenses/MIT>") +
"\n" +
527 strprintf(
_(
"This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard."),
"<https://www.openssl.org>") +
531 static void BlockNotifyCallback(
bool initialSync,
const CBlockIndex *pBlockIndex)
533 if (initialSync || !pBlockIndex)
536 std::string strCmd =
gArgs.
GetArg(
"-blocknotify",
"");
537 if (!strCmd.empty()) {
544 static bool fHaveGenesis =
false;
545 static Mutex g_genesis_wait_mutex;
546 static std::condition_variable g_genesis_wait_cv;
548 static void BlockNotifyGenesisWait(
bool,
const CBlockIndex *pBlockIndex)
550 if (pBlockIndex !=
nullptr) {
552 LOCK(g_genesis_wait_mutex);
555 g_genesis_wait_cv.notify_all();
579 static void CleanupBlockRevFiles()
581 std::map<std::string, fs::path> mapBlockFiles;
586 LogPrintf(
"Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
588 for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
589 if (fs::is_regular_file(*it) &&
590 it->path().filename().string().length() == 12 &&
591 it->path().filename().string().substr(8,4) ==
".dat")
593 if (it->path().filename().string().substr(0,3) ==
"blk")
594 mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
595 else if (it->path().filename().string().substr(0,3) ==
"rev")
604 int nContigCounter = 0;
605 for (
const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
606 if (
atoi(item.first) == nContigCounter) {
614 static void ThreadImport(std::vector<fs::path> vImportFiles)
633 LogPrintf(
"Reindexing block file blk%05u.dat...\n", (
unsigned int)nFile);
639 LogPrintf(
"Reindexing finished\n");
645 fs::path pathBootstrap =
GetDataDir() /
"bootstrap.dat";
646 if (fs::exists(pathBootstrap)) {
649 fs::path pathBootstrapOld =
GetDataDir() /
"bootstrap.dat.old";
650 LogPrintf(
"Importing bootstrap.dat...\n");
654 LogPrintf(
"Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
659 for (
const fs::path& path : vImportFiles) {
662 LogPrintf(
"Importing blocks file %s...\n", path.string());
665 LogPrintf(
"Warning: Could not open blocks file %s\n", path.string());
677 if (
gArgs.
GetBoolArg(
"-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
678 LogPrintf(
"Stopping after block import\n");
683 if (
gArgs.
GetArg(
"-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
693 static bool InitSanityCheck()
696 InitError(
"Elliptic curve cryptography sanity check failure. Aborting.");
704 InitError(
"OS cryptographic RNG sanity check failure. Aborting.");
711 static bool AppInitServers()
732 LogPrintf(
"%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
736 LogPrintf(
"%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
742 LogPrintf(
"%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
744 LogPrintf(
"%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
750 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
754 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
757 LogPrintf(
"%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
763 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
765 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
767 LogPrintf(
"%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
773 LogPrintf(
"%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
779 LogPrintf(
"%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
783 if (
gArgs.
GetBoolArg(
"-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
785 LogPrintf(
"%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
794 static std::string ResolveErrMsg(
const char *
const optname,
const std::string& strBind)
796 return strprintf(
_(
"Cannot resolve -%s address: '%s'"), optname, strBind);
813 LogPrintf(
"\n\n\n\n\n");
823 version_string +=
" (debug build)";
825 version_string +=
" (release build)";
827 LogPrintf(
PACKAGE_NAME " version %s\n", version_string);
833 int nUserMaxConnections;
839 [[noreturn]]
static void new_handler_terminate()
845 std::set_new_handler(std::terminate);
846 LogPrintf(
"Error: Out of memory. Terminating.\n");
857 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
858 _CrtSetReportFile(_CRT_WARN, CreateFileA(
"NUL", GENERIC_WRITE, 0,
nullptr, OPEN_EXISTING, 0, 0));
860 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
866 #ifndef PROCESS_DEP_ENABLE 869 #define PROCESS_DEP_ENABLE 0x00000001 871 typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
872 PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA(
"Kernel32.dll"),
"SetProcessDEPPolicy");
873 if (setProcDEPPol !=
nullptr) setProcDEPPol(PROCESS_DEP_ENABLE);
877 return InitError(
"Initializing networking failed");
885 registerSignalHandler(SIGTERM, HandleSIGTERM);
886 registerSignalHandler(SIGINT, HandleSIGTERM);
889 registerSignalHandler(SIGHUP, HandleSIGHUP);
892 signal(SIGPIPE, SIG_IGN);
894 SetConsoleCtrlHandler(consoleCtrlHandler,
true);
897 std::set_new_handler(new_handler_terminate);
916 return InitError(
_(
"Prune mode is incompatible with -txindex."));
922 return InitError(
"Cannot set -bind or -whitebind together with -listen=0");
926 int nBind = std::max(nUserBind,
size_t(1));
927 nUserMaxConnections =
gArgs.
GetArg(
"-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
928 nMaxConnections = std::max(nUserMaxConnections, 0);
932 nMaxConnections = std::max(std::min<int>(nMaxConnections, FD_SETSIZE - nBind -
MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS), 0);
935 return InitError(
_(
"Not enough file descriptors available."));
938 if (nMaxConnections < nUserMaxConnections)
939 InitWarning(
strprintf(
_(
"Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
944 const std::vector<std::string> categories =
gArgs.
GetArgs(
"-debug");
946 if (std::none_of(categories.begin(), categories.end(),
947 [](std::string cat){
return cat ==
"0" || cat ==
"none";})) {
948 for (
const auto& cat : categories) {
957 for (
const std::string& cat :
gArgs.
GetArgs(
"-debugexclude")) {
975 LogPrintf(
"Validating signatures for all blocks.\n");
978 const std::string minChainWorkStr =
gArgs.
GetArg(
"-minimumchainwork",
"");
980 return InitError(
strprintf(
"Invalid non-hex (%s) minimum chain work value specified", minChainWorkStr));
992 int64_t nMempoolSizeMax =
gArgs.
GetArg(
"-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
993 int64_t nMempoolSizeMin =
gArgs.
GetArg(
"-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
994 if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
995 return InitError(
strprintf(
_(
"-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
1017 if (nPruneArg < 0) {
1018 return InitError(
_(
"Prune cannot be configured with a negative value."));
1021 if (nPruneArg == 1) {
1022 LogPrintf(
"Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
1027 return InitError(
strprintf(
_(
"Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1029 LogPrintf(
"Prune configured to target %uMiB on disk for block and undo files.\n",
nPruneTarget / 1024 / 1024);
1047 LogPrintf(
"Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::
minRelayTxFee.
ToString());
1086 if (
gArgs.
GetArg(
"-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
1087 return InitError(
"rpcserialversion must be non-negative.");
1089 if (
gArgs.
GetArg(
"-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
1090 return InitError(
"unknown rpcserialversion requested.");
1097 std::string strReplacementModeList =
gArgs.
GetArg(
"-mempoolreplacement",
"");
1098 std::vector<std::string> vstrReplacementModes;
1099 boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(
","));
1100 fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(),
"fee") != vstrReplacementModes.end());
1106 static bool LockDataDirectory(
bool probeOnly)
1111 return InitError(
strprintf(
_(
"Cannot write to data directory '%s'; check permissions."), datadir.string()));
1125 LogPrintf(
"Using the '%s' SHA256 implementation\n", sha256_algo);
1131 if (!InitSanityCheck())
1137 return LockDataDirectory(
true);
1145 if (!LockDataDirectory(
false)) {
1174 LogPrintf(
"Using data directory %s\n",
GetDataDir().
string());
1178 if (fs::exists(config_file_path)) {
1179 LogPrintf(
"Config file: %s\n", config_file_path.string());
1182 InitWarning(
strprintf(
_(
"The specified config file %s does not exist\n"), config_file_path.string()));
1185 LogPrintf(
"Config file: %s (not found, skipping)\n", config_file_path.string());
1188 LogPrintf(
"Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
1192 LogPrintf(
"Warning: relative datadir option '%s' specified, which will be interpreted relative to the " 1193 "current working directory '%s'. This is fragile, because if bitcoin is started in the future " 1194 "from a different location, it will be unable to locate the current data files. There could " 1195 "also be data loss if bitcoin is started while in a temporary directory.\n",
1196 gArgs.
GetArg(
"-datadir",
""), fs::current_path().string());
1210 threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>,
"scheduler", serviceLoop));
1218 RegisterAllCoreRPCCommands(
tableRPC);
1232 if (!AppInitServers())
1233 return InitError(
_(
"Unable to start HTTP server. See debug log for details."));
1253 std::vector<std::string> uacomments;
1254 for (
const std::string& cmt :
gArgs.
GetArgs(
"-uacomment")) {
1256 return InitError(
strprintf(
_(
"User Agent comment (%s) contains unsafe characters."), cmt));
1257 uacomments.push_back(cmt);
1261 return InitError(
strprintf(
_(
"Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1266 std::set<enum Network> nets;
1267 for (
const std::string& snet :
gArgs.
GetArgs(
"-onlynet")) {
1273 for (
int n = 0; n <
NET_MAX; n++) {
1275 if (!nets.count(net))
1283 bool proxyRandomize =
gArgs.
GetBoolArg(
"-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1286 std::string proxyArg =
gArgs.
GetArg(
"-proxy",
"");
1288 if (proxyArg !=
"" && proxyArg !=
"0") {
1308 std::string onionArg =
gArgs.
GetArg(
"-onion",
"");
1309 if (onionArg !=
"") {
1310 if (onionArg ==
"0") {
1330 for (
const std::string& strAddr :
gArgs.
GetArgs(
"-externalip")) {
1335 return InitError(ResolveErrMsg(
"externalip", strAddr));
1345 uint64_t nMaxOutboundLimit = 0;
1346 uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
1349 nMaxOutboundLimit =
gArgs.
GetArg(
"-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
1355 bool fReindexChainState =
gArgs.
GetBoolArg(
"-reindex-chainstate",
false);
1358 int64_t nTotalCache = (
gArgs.
GetArg(
"-dbcache", nDefaultDbCache) << 20);
1359 nTotalCache = std::max(nTotalCache, nMinDbCache << 20);
1360 nTotalCache = std::min(nTotalCache, nMaxDbCache << 20);
1361 int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20);
1362 nTotalCache -= nBlockTreeDBCache;
1363 int64_t nTxIndexCache = std::min(nTotalCache / 8,
gArgs.
GetBoolArg(
"-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0);
1364 nTotalCache -= nTxIndexCache;
1365 int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23));
1366 nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20);
1367 nTotalCache -= nCoinDBCache;
1369 int64_t nMempoolSizeMax =
gArgs.
GetArg(
"-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1370 LogPrintf(
"Cache configuration:\n");
1371 LogPrintf(
"* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
1373 LogPrintf(
"* Using %.1fMiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
1375 LogPrintf(
"* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
1376 LogPrintf(
"* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of unused mempool space)\n",
nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
1378 bool fLoaded =
false;
1381 std::string strLoadError;
1388 const int64_t load_block_index_start_time =
GetTimeMillis();
1393 pcoinscatcher.reset();
1403 CleanupBlockRevFiles();
1413 strLoadError =
_(
"Error loading block database");
1420 return InitError(
_(
"Incorrect or no genesis block found. Wrong datadir for network?"));
1426 strLoadError =
_(
"You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
1435 strLoadError =
_(
"Error initializing block database");
1448 strLoadError =
_(
"Error upgrading chainstate database");
1454 strLoadError =
_(
"Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
1461 bool is_coinsview_empty = fReset || fReindexChainState ||
pcoinsTip->GetBestBlock().IsNull();
1462 if (!is_coinsview_empty) {
1465 strLoadError =
_(
"Error initializing block database");
1477 strLoadError =
_(
"Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain");
1482 if (!is_coinsview_empty) {
1485 LogPrintf(
"Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
1486 MIN_BLOCKS_TO_KEEP);
1492 strLoadError =
_(
"The block database contains a block which appears to be from the future. " 1493 "This may be due to your computer's date and time being set incorrectly. " 1494 "Only rebuild the block database if you are sure that your computer's date and time are correct");
1499 gArgs.
GetArg(
"-checkblocks", DEFAULT_CHECKBLOCKS))) {
1500 strLoadError =
_(
"Corrupted block database detected");
1504 }
catch (
const std::exception& e) {
1505 LogPrintf(
"%s\n", e.what());
1506 strLoadError =
_(
"Error opening block database");
1511 LogPrintf(
" block index %15dms\n",
GetTimeMillis() - load_block_index_start_time);
1518 strLoadError +
".\n\n" +
_(
"Do you want to rebuild the block database now?"),
1519 strLoadError +
".\nPlease restart with -reindex or -reindex-chainstate to recover.",
1525 LogPrintf(
"Aborted block database rebuild. Exiting.\n");
1538 LogPrintf(
"Shutdown requested. Exiting.\n");
1542 fs::path est_path =
GetDataDir() / FEE_ESTIMATES_FILENAME;
1545 if (!est_filein.
IsNull())
1563 LogPrintf(
"Unsetting NODE_NETWORK on prune mode\n");
1583 uiInterface.NotifyBlockTip_connect(BlockNotifyGenesisWait);
1585 fHaveGenesis =
true;
1589 uiInterface.NotifyBlockTip_connect(BlockNotifyCallback);
1591 std::vector<fs::path> vImportFiles;
1592 for (
const std::string& strFile :
gArgs.
GetArgs(
"-loadblock")) {
1593 vImportFiles.push_back(strFile);
1596 threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
1605 g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
1607 uiInterface.NotifyBlockTip_disconnect(BlockNotifyGenesisWait);
1616 int chain_active_height;
1621 LogPrintf(
"mapBlockIndex.size() = %u\n",
mapBlockIndex.size());
1624 LogPrintf(
"nBestHeight = %d\n", chain_active_height);
1640 connOptions.
nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
1652 for (
const std::string& strBind :
gArgs.
GetArgs(
"-bind")) {
1655 return InitError(ResolveErrMsg(
"bind", strBind));
1657 connOptions.
vBinds.push_back(addrBind);
1659 for (
const std::string& strBind :
gArgs.
GetArgs(
"-whitebind")) {
1661 if (!
Lookup(strBind.c_str(), addrBind, 0,
false)) {
1662 return InitError(ResolveErrMsg(
"whitebind", strBind));
1664 if (addrBind.
GetPort() == 0) {
1684 if (connect.size() != 1 || connect[0] !=
"0") {
1688 if (!connman.Start(scheduler, connOptions)) {
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
std::vector< CService > vBinds
std::unique_ptr< const CChainParams > CreateChainParams(const std::string &chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
void EnableCategory(LogFlags flag)
void RandomInit()
Initialize the RNG.
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
bool(* handler)(HTTPRequest *req, const std::string &strReq)
void ECC_Start()
Initialize the elliptic curve support.
unsigned short GetPort() const
std::vector< CSubNet > vWhitelistedRange
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Creates and returns a std::unique_ptr<CBaseChainParams> of the chosen chain.
bool IsHexNumber(const std::string &str)
Return true if the string is a hex number, optionally prefixed with "0x".
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
bool fPruneMode
True if we're running in -prune mode.
std::condition_variable g_best_block_cv
ServiceFlags
nServices flags
void UnloadBlockIndex()
Unload database information.
void InitLogging()
Initialize global loggers.
bool AddLocal(const CService &addr, int nScore)
FILE * fopen(const fs::path &p, const char *mode)
#define TRY_LOCK(cs, name)
const char *const BITCOIN_CONF_FILENAME
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
static const std::string REGTEST
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
bool AppInitMain()
Bitcoin core main initialization.
const char *const BITCOIN_PID_FILENAME
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
virtual void RegisterRPC(CRPCTable &) const =0
Register wallet RPC.
bool fHavePruned
Pruning-related variables and constants.
virtual void Start(CScheduler &scheduler) const =0
Start wallets.
std::string ListLogCategories()
Returns a string with the log categories.
bool Write(CAutoFile &fileout) const
Write estimation data to a file.
void FlushUnconfirmed()
Empty mempool transactions on shutdown to record failure to confirm for txs still in mempool...
unsigned int nReceiveFloodSize
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
CClientUIInterface * uiInterface
bool LoadMempool()
Load the mempool from disk.
void WarnForSectionOnlyArgs()
Log warnings for options in m_section_only_args when they are specified in the default section but no...
int Height() const
Return the maximal height in the chain.
void SetMockTime(int64_t nMockTimeIn)
bool StartHTTPRPC()
Start HTTP RPC subsystem.
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
void StopREST()
Stop HTTP REST subsystem.
void OnStopped(std::function< void()> slot)
void SetLimited(enum Network net, bool fLimited)
Make a particular network entirely off-limits (no automatic connects to it)
std::atomic< bool > m_reopen_file
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
void Interrupt()
Interrupt threads.
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
const std::string CURRENCY_UNIT
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
void UnregisterAllValidationInterfaces()
Unregister all wallets from core.
std::function< void()> Function
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
unsigned short GetListenPort()
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
void StartREST()
Start HTTP REST subsystem.
std::vector< CService > vWhiteBinds
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
bool AppInitBasicSetup()
Initialize bitcoin core: Basic context setup.
unsigned int nBytesPerSigOp
std::string LicenseInfo()
Returns licensing information (for -version)
void InterruptHTTPServer()
Interrupt HTTP server threads.
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...
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
bool SetNameProxy(const proxyType &addrProxy)
void RenameThread(const char *name)
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Find the best known block, and make it the tip of the block chain.
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
arith_uint256 UintToArith256(const uint256 &a)
CCoinsViewErrorCatcher(CCoinsView *view)
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
int64_t CAmount
Amount in satoshis (Can be negative)
bool CheckDiskSpace(uint64_t nAdditionalBytes, bool blocks_dir)
Check whether enough disk space is available for an incoming block.
void InitParameterInteraction()
Parameter interaction: change current parameters depending on various rules.
uint256 GetBlockHash() const
void SetRPCWarmupFinished()
CBlockPolicyEstimator feeEstimator
int ScheduleBatchPriority(void)
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
void setSanityCheck(double dFrequency=1.0)
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 ReplayBlocks(const CChainParams ¶ms, CCoinsView *view)
Replay blocks that aren't fully applied to the database.
enum Network ParseNetwork(std::string net)
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
static CZMQNotificationInterface * Create()
const std::string DEFAULT_TOR_CONTROL
Default control port.
Access to the block database (blocks/index/)
void StopHTTPServer()
Stop HTTP server.
Abstract view on the open txout dataset.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
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::unique_ptr< CCoinsViewDB > pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
NetEventsInterface * m_msgproc
A combination of a network address (CNetAddr) and a (TCP) port.
virtual void Close() const =0
Close wallets.
std::vector< std::string > vSeedNodes
uint256 uint256S(const char *str)
std::vector< std::string > m_specified_outgoing
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
void RegisterWithMempoolSignals(CTxMemPool &pool)
Register with mempool to call TransactionRemovedFromMempool callbacks.
void InitSignatureCache()
virtual bool Verify() const =0
Verify wallets.
CMainSignals & GetMainSignals()
void DisableCategory(LogFlags flag)
void UnregisterWithMempoolSignals(CTxMemPool &pool)
Unregister with mempool.
bool ParseMoney(const std::string &str, CAmount &nRet)
#define WAIT_LOCK(cs, name)
std::atomic_bool fImporting
void ThreadScriptCheck()
Run an instance of the script checking thread.
An outpoint - a combination of a transaction hash and an index n into its vout.
const std::string CLIENT_NAME
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
void AddTransactionsUpdated(unsigned int n)
bool RenameOver(fs::path src, fs::path dest)
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
bool DumpMempool()
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...
std::string FormatFullVersion()
std::string CopyrightHolders(const std::string &strPrefix)
virtual bool Open() const =0
Open wallets.
fs::path GetDefaultDataDir()
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
bool LookupSubNet(const char *pszName, CSubNet &ret)
bool SetProxy(enum Network net, const proxyType &addrProxy)
const fs::path & GetBlocksDir(bool fNetSpecific)
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
bool LoadBlockIndex(const CChainParams &chainparams)
Load the block tree and coins database from disk, initializing state if we're running with -reindex...
void StopHTTPRPC()
Stop HTTP RPC subsystem.
bool AppInitParameterInteraction()
Initialization: parameter interaction.
uint64_t nMaxOutboundTimeframe
std::atomic_bool fReindex
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once) ...
Capture information about block/transaction validation.
bool glibcxx_sanity_test()
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
bool fFeeEstimatesInitialized
void RegisterZMQRPCCommands(CRPCTable &t)
uint256 nMinimumChainWork
std::atomic_bool g_is_mempool_loaded
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
const WalletInitInterface & g_wallet_init_interface
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
void SetupChainParamsBaseOptions()
Set the arguments for chainparams.
void SetupServerArgs()
Setup the arguments for gArgs.
bool InitError(const std::string &str)
Show error message.
uint256 defaultAssumeValid
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
fs::path GetConfigFile(const std::string &confPath)
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
CCoinsView backed by the coin database (chainstate/)
void InitScriptExecutionCache()
Initializes the script-execution cache.
void AddArg(const std::string &name, const std::string &help, const bool debug_only, const OptionsCategory &cat)
Add argument.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool Read(CAutoFile &filein)
Read estimation data from a file.
ServiceFlags nLocalServices
void InterruptREST()
Interrupt RPC REST subsystem.
int64_t GetAdjustedTime()
bool DirIsWritable(const fs::path &directory)
uint64_t nMaxOutboundLimit
void runCommand(const std::string &strCommand)
std::vector< std::string > m_added_nodes
bool Lookup(const char *pszName, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
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...
std::string GetHex() const
Fee rate in satoshis per kilobyte: CAmount / kB.
std::unique_ptr< CConnman > g_connman
virtual void Flush() const =0
Flush Wallets.
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
std::unique_ptr< PeerLogicValidation > peerLogic
static const std::string TESTNET
unsigned int nSendBufferMaxSize
void StartHTTPServer()
Start HTTP server.
void RPCNotifyBlockChange(bool ibd, const CBlockIndex *pindex)
Callback for when block tip changed.
const fs::path & GetDataDir(bool fNetSpecific)
void CreatePidFile(const fs::path &path, pid_t pid)
void InterruptTorControl()
void OnStarted(std::function< void()> slot)
std::string GetHex() const
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
std::string ToString() const
void InitWarning(const std::string &str)
Show warning message.
CClientUIInterface uiInterface
CCoinsView backed by another CCoinsView.
int GetNumCores()
Return the number of cores available on the current system.
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
const Consensus::Params & GetConsensus() const
virtual void Stop() const =0
Stop Wallets.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
void PruneAndFlush()
Prune block files and flush state to disk.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
#define MIN_CORE_FILEDESCRIPTORS
std::string AmountErrMsg(const char *const optname, const std::string &strValue)
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
const char *const DEFAULT_DEBUGLOGFILE
fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
bool m_use_addrman_outgoing
bool RewindBlockIndex(const CChainParams ¶ms)
When there are blocks in the active chain with missing data, rewind the chainstate and remove them fr...
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
CFeeRate incrementalRelayFee
unsigned nMaxDatacarrierBytes
Maximum size of TX_NULL_DATA scripts that this node considers standard.
BCLog::Logger *const g_logger
NOTE: the logger instances is leaked on exit.
bool LoadChainTip(const CChainParams &chainparams)
Update the chain tip based on database information.
Non-refcounted RAII wrapper for FILE*.
std::string _(const char *psz)
Translation function.
int atoi(const std::string &str)
uint64_t GetRand(uint64_t nMax)
CZMQNotificationInterface * g_zmq_notification_interface
CBlockIndex * LookupBlockIndex(const uint256 &hash)
bool DefaultShrinkDebugFile() const
virtual void AddWalletOptions() const =0
Get wallet help string.