From 756f2279ce3a1602f5ec0d6339784e28e4cc4534 Mon Sep 17 00:00:00 2001 From: Kittywhiskers Van Gogh <63189531+kwvg@users.noreply.github.com> Date: Mon, 27 Jan 2025 12:10:03 +0000 Subject: [PATCH 01/16] refactor: use `GetBoolArg` for `-reindex-chainstate` --- src/test/util/setup_common.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/util/setup_common.cpp b/src/test/util/setup_common.cpp index a1800745f193d..46ab23da0278b 100644 --- a/src/test/util/setup_common.cpp +++ b/src/test/util/setup_common.cpp @@ -313,7 +313,7 @@ TestingSetup::TestingSetup(const std::string& chainName, const std::vector Date: Mon, 27 Jan 2025 11:47:43 +0000 Subject: [PATCH 02/16] merge bitcoin#22976: Rename overloaded int GetArg to GetIntArg --- src/addrdb.cpp | 2 +- src/bench/bench_bitcoin.cpp | 2 +- src/bitcoin-cli.cpp | 6 +-- src/chainparams.cpp | 6 +-- src/coinjoin/options.cpp | 10 ++--- src/evo/mnauth.cpp | 4 +- src/httpserver.cpp | 10 ++--- src/init.cpp | 56 ++++++++++++++-------------- src/llmq/signing.cpp | 2 +- src/net.cpp | 2 +- src/net_processing.cpp | 6 +-- src/node/caches.cpp | 2 +- src/node/interfaces.cpp | 14 +++---- src/node/miner.cpp | 4 +- src/qt/bitcoin.cpp | 6 +-- src/qt/intro.cpp | 6 +-- src/qt/optionsmodel.cpp | 2 +- src/rpc/blockchain.cpp | 2 +- src/rpc/fees.cpp | 2 +- src/rpc/mempool.cpp | 2 +- src/script/sigcache.cpp | 2 +- src/stats/client.cpp | 6 +-- src/test/addrman_tests.cpp | 2 +- src/test/fuzz/addrman.cpp | 2 +- src/test/fuzz/deserialize.cpp | 2 +- src/test/fuzz/net.cpp | 2 +- src/test/fuzz/system.cpp | 2 +- src/test/getarg_tests.cpp | 48 ++++++++++++------------ src/test/util/setup_common.cpp | 6 +-- src/test/util_tests.cpp | 14 +++---- src/timedata.cpp | 2 +- src/txdb.cpp | 4 +- src/util/system.cpp | 2 +- src/util/system.h | 2 +- src/validation.cpp | 32 ++++++++-------- src/wallet/bdb.cpp | 2 +- src/wallet/hdchain.cpp | 2 +- src/wallet/init.cpp | 6 +-- src/wallet/rpcdump.cpp | 2 +- src/wallet/scriptpubkeyman.cpp | 4 +- src/wallet/wallet.cpp | 8 ++-- src/zmq/zmqnotificationinterface.cpp | 2 +- 42 files changed, 150 insertions(+), 150 deletions(-) diff --git a/src/addrdb.cpp b/src/addrdb.cpp index 301b61aa1690c..3683472c6ebb3 100644 --- a/src/addrdb.cpp +++ b/src/addrdb.cpp @@ -185,7 +185,7 @@ void ReadFromStream(AddrMan& addr, CDataStream& ssPeers) std::optional LoadAddrman(const NetGroupManager& netgroupman, const ArgsManager& args, std::unique_ptr& addrman) { - auto check_addrman = std::clamp(args.GetArg("-checkaddrman", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), 0, 1000000); + auto check_addrman = std::clamp(args.GetIntArg("-checkaddrman", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), 0, 1000000); addrman = std::make_unique(netgroupman, /*deterministic=*/false, /*consistency_check_ratio=*/check_addrman); const auto start{SteadyClock::now()}; diff --git a/src/bench/bench_bitcoin.cpp b/src/bench/bench_bitcoin.cpp index aded08c8a5735..565cf39c55576 100644 --- a/src/bench/bench_bitcoin.cpp +++ b/src/bench/bench_bitcoin.cpp @@ -110,7 +110,7 @@ int main(int argc, char** argv) benchmark::Args args; args.asymptote = parseAsymptote(argsman.GetArg("-asymptote", "")); args.is_list_only = argsman.GetBoolArg("-list", false); - args.min_time = std::chrono::milliseconds(argsman.GetArg("-min_time", DEFAULT_MIN_TIME_MS)); + args.min_time = std::chrono::milliseconds(argsman.GetIntArg("-min_time", DEFAULT_MIN_TIME_MS)); args.output_csv = argsman.GetPathArg("-output_csv"); args.output_json = argsman.GetPathArg("-output_json"); args.regex_filter = argsman.GetArg("-filter", DEFAULT_BENCH_FILTER); diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp index 7a1cf38a38bf8..7d1241675fa01 100644 --- a/src/bitcoin-cli.cpp +++ b/src/bitcoin-cli.cpp @@ -753,7 +753,7 @@ static UniValue CallRPC(BaseRequestHandler* rh, const std::string& strMethod, co // 3. default port for chain uint16_t port{BaseParams().RPCPort()}; SplitHostPort(gArgs.GetArg("-rpcconnect", DEFAULT_RPCCONNECT), port, host); - port = static_cast(gArgs.GetArg("-rpcport", port)); + port = static_cast(gArgs.GetIntArg("-rpcport", port)); // Obtain event base raii_event_base base = obtain_event_base(); @@ -763,7 +763,7 @@ static UniValue CallRPC(BaseRequestHandler* rh, const std::string& strMethod, co // Set connection timeout { - const int timeout = gArgs.GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT); + const int timeout = gArgs.GetIntArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT); if (timeout > 0) { evhttp_connection_set_timeout(evcon.get(), timeout); } else { @@ -873,7 +873,7 @@ static UniValue ConnectAndCallRPC(BaseRequestHandler* rh, const std::string& str UniValue response(UniValue::VOBJ); // Execute and handle connection failures with -rpcwait. const bool fWait = gArgs.GetBoolArg("-rpcwait", false); - const int timeout = gArgs.GetArg("-rpcwaittimeout", DEFAULT_WAIT_CLIENT_TIMEOUT); + const int timeout = gArgs.GetIntArg("-rpcwaittimeout", DEFAULT_WAIT_CLIENT_TIMEOUT); const auto deadline{std::chrono::steady_clock::now() + 1s * timeout}; do { diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 5b28f79dec1bc..90b43915583e5 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -1199,9 +1199,9 @@ void CDevNetParams::UpdateDevnetSubsidyAndDiffParametersFromArgs(const ArgsManag { if (!args.IsArgSet("-minimumdifficultyblocks") && !args.IsArgSet("-highsubsidyblocks") && !args.IsArgSet("-highsubsidyfactor")) return; - int nMinimumDifficultyBlocks = gArgs.GetArg("-minimumdifficultyblocks", consensus.nMinimumDifficultyBlocks); - int nHighSubsidyBlocks = gArgs.GetArg("-highsubsidyblocks", consensus.nHighSubsidyBlocks); - int nHighSubsidyFactor = gArgs.GetArg("-highsubsidyfactor", consensus.nHighSubsidyFactor); + int nMinimumDifficultyBlocks = gArgs.GetIntArg("-minimumdifficultyblocks", consensus.nMinimumDifficultyBlocks); + int nHighSubsidyBlocks = gArgs.GetIntArg("-highsubsidyblocks", consensus.nHighSubsidyBlocks); + int nHighSubsidyFactor = gArgs.GetIntArg("-highsubsidyfactor", consensus.nHighSubsidyFactor); LogPrintf("Setting minimumdifficultyblocks=%ld, highsubsidyblocks=%ld, highsubsidyfactor=%ld\n", nMinimumDifficultyBlocks, nHighSubsidyBlocks, nHighSubsidyFactor); UpdateDevnetSubsidyAndDiffParameters(nMinimumDifficultyBlocks, nHighSubsidyBlocks, nHighSubsidyFactor); } diff --git a/src/coinjoin/options.cpp b/src/coinjoin/options.cpp index 7f21e440b6d0d..3ac9234baf208 100644 --- a/src/coinjoin/options.cpp +++ b/src/coinjoin/options.cpp @@ -66,11 +66,11 @@ void CCoinJoinClientOptions::Init() assert(!CCoinJoinClientOptions::_instance); static CCoinJoinClientOptions instance; instance.fCoinJoinMultiSession = gArgs.GetBoolArg("-coinjoinmultisession", DEFAULT_COINJOIN_MULTISESSION); - instance.nCoinJoinSessions = std::min(std::max((int)gArgs.GetArg("-coinjoinsessions", DEFAULT_COINJOIN_SESSIONS), MIN_COINJOIN_SESSIONS), MAX_COINJOIN_SESSIONS); - instance.nCoinJoinRounds = std::min(std::max((int)gArgs.GetArg("-coinjoinrounds", DEFAULT_COINJOIN_ROUNDS), MIN_COINJOIN_ROUNDS), MAX_COINJOIN_ROUNDS); - instance.nCoinJoinAmount = std::min(std::max((int)gArgs.GetArg("-coinjoinamount", DEFAULT_COINJOIN_AMOUNT), MIN_COINJOIN_AMOUNT), MAX_COINJOIN_AMOUNT); - instance.nCoinJoinDenomsGoal = std::min(std::max((int)gArgs.GetArg("-coinjoindenomsgoal", DEFAULT_COINJOIN_DENOMS_GOAL), MIN_COINJOIN_DENOMS_GOAL), MAX_COINJOIN_DENOMS_GOAL); - instance.nCoinJoinDenomsHardCap = std::min(std::max((int)gArgs.GetArg("-coinjoindenomshardcap", DEFAULT_COINJOIN_DENOMS_HARDCAP), MIN_COINJOIN_DENOMS_HARDCAP), MAX_COINJOIN_DENOMS_HARDCAP); + instance.nCoinJoinSessions = std::min(std::max((int)gArgs.GetIntArg("-coinjoinsessions", DEFAULT_COINJOIN_SESSIONS), MIN_COINJOIN_SESSIONS), MAX_COINJOIN_SESSIONS); + instance.nCoinJoinRounds = std::min(std::max((int)gArgs.GetIntArg("-coinjoinrounds", DEFAULT_COINJOIN_ROUNDS), MIN_COINJOIN_ROUNDS), MAX_COINJOIN_ROUNDS); + instance.nCoinJoinAmount = std::min(std::max((int)gArgs.GetIntArg("-coinjoinamount", DEFAULT_COINJOIN_AMOUNT), MIN_COINJOIN_AMOUNT), MAX_COINJOIN_AMOUNT); + instance.nCoinJoinDenomsGoal = std::min(std::max((int)gArgs.GetIntArg("-coinjoindenomsgoal", DEFAULT_COINJOIN_DENOMS_GOAL), MIN_COINJOIN_DENOMS_GOAL), MAX_COINJOIN_DENOMS_GOAL); + instance.nCoinJoinDenomsHardCap = std::min(std::max((int)gArgs.GetIntArg("-coinjoindenomshardcap", DEFAULT_COINJOIN_DENOMS_HARDCAP), MIN_COINJOIN_DENOMS_HARDCAP), MAX_COINJOIN_DENOMS_HARDCAP); CCoinJoinClientOptions::_instance = &instance; } diff --git a/src/evo/mnauth.cpp b/src/evo/mnauth.cpp index 7eb2e18ce5439..eb55888580e5b 100644 --- a/src/evo/mnauth.cpp +++ b/src/evo/mnauth.cpp @@ -37,7 +37,7 @@ void CMNAuth::PushMNAUTH(CNode& peer, CConnman& connman, const CActiveMasternode // This is ok as we only use MNAUTH as a DoS protection and not for sensitive stuff int nOurNodeVersion{PROTOCOL_VERSION}; if (Params().NetworkIDString() != CBaseChainParams::MAIN && gArgs.IsArgSet("-pushversion")) { - nOurNodeVersion = gArgs.GetArg("-pushversion", PROTOCOL_VERSION); + nOurNodeVersion = gArgs.GetIntArg("-pushversion", PROTOCOL_VERSION); } auto pk = mn_activeman.GetPubKey(); const CBLSPublicKey pubKey(pk); @@ -103,7 +103,7 @@ PeerMsgRet CMNAuth::ProcessMessage(CNode& peer, ServiceFlags node_services, CCon uint256 signHash; int nOurNodeVersion{PROTOCOL_VERSION}; if (Params().NetworkIDString() != CBaseChainParams::MAIN && gArgs.IsArgSet("-pushversion")) { - nOurNodeVersion = gArgs.GetArg("-pushversion", PROTOCOL_VERSION); + nOurNodeVersion = gArgs.GetIntArg("-pushversion", PROTOCOL_VERSION); } const CBLSPublicKey pubKey(dmn->pdmnState->pubKeyOperator.Get()); // See comment in PushMNAUTH (fInbound is negated here as we're on the other side of the connection) diff --git a/src/httpserver.cpp b/src/httpserver.cpp index cfa4b17f967c1..75f4846aeff12 100644 --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -322,7 +322,7 @@ static void ThreadHTTP(struct event_base* base) /** Bind HTTP server to specified addresses */ static bool HTTPBindAddresses(struct evhttp* http) { - uint16_t http_port{static_cast(gArgs.GetArg("-rpcport", BaseParams().RPCPort()))}; + uint16_t http_port{static_cast(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))}; std::vector> endpoints; // Determine what addresses to bind to @@ -422,7 +422,7 @@ bool InitHTTPServer() return false; } - evhttp_set_timeout(http, gArgs.GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT)); + evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT)); evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE); evhttp_set_max_body_size(http, MAX_SIZE); evhttp_set_gencb(http, http_request_cb, nullptr); @@ -433,10 +433,10 @@ bool InitHTTPServer() } LogPrint(BCLog::HTTP, "Initialized HTTP server\n"); - int workQueueDepth = std::max((long)gArgs.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L); + int workQueueDepth = std::max((long)gArgs.GetIntArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L); int workQueueDepthExternal = 0; if (const std::string rpc_externaluser{gArgs.GetArg("-rpcexternaluser", "")}; !rpc_externaluser.empty()) { - workQueueDepthExternal = std::max((long)gArgs.GetArg("-rpcexternalworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L); + workQueueDepthExternal = std::max((long)gArgs.GetIntArg("-rpcexternalworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L); g_external_usernames = SplitString(rpc_externaluser, ','); } LogPrintf("HTTP: creating work queue of depth %d external_depth %d\n", workQueueDepth, workQueueDepthExternal); @@ -467,7 +467,7 @@ static std::vector g_thread_http_workers; void StartHTTPServer() { LogPrint(BCLog::HTTP, "Starting HTTP server\n"); - int rpcThreads = std::max((long)gArgs.GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L); + int rpcThreads = std::max((long)gArgs.GetIntArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L); LogPrintf("HTTP: starting %d worker threads\n", rpcThreads); g_thread_http = std::thread(ThreadHTTP, eventBase); diff --git a/src/init.cpp b/src/init.cpp index 62213c68aeba6..37d9bbb49b83d 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -874,7 +874,7 @@ static void PeriodicStats(NodeContext& node) ::g_stats_client->gauge("transactions.mempool.totalTransactions", mempool.size(), 1.0f); ::g_stats_client->gauge("transactions.mempool.totalTxBytes", (int64_t) mempool.GetTotalTxSize(), 1.0f); ::g_stats_client->gauge("transactions.mempool.memoryUsageBytes", (int64_t) mempool.DynamicMemoryUsage(), 1.0f); - ::g_stats_client->gauge("transactions.mempool.minFeePerKb", mempool.GetMinFee(args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK(), 1.0f); + ::g_stats_client->gauge("transactions.mempool.minFeePerKb", mempool.GetMinFee(args.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK(), 1.0f); } } @@ -976,7 +976,7 @@ void InitParameterInteraction(ArgsManager& args) } } - int64_t nPruneArg = args.GetArg("-prune", 0); + int64_t nPruneArg = args.GetIntArg("-prune", 0); if (nPruneArg > 0) { if (args.SoftSetBoolArg("-disablegovernance", true)) { LogPrintf("%s: parameter interaction: -prune=%d -> setting -disablegovernance=true\n", __func__, nPruneArg); @@ -993,7 +993,7 @@ void InitParameterInteraction(ArgsManager& args) args.GetBoolArg("-spentindex", DEFAULT_SPENTINDEX) || args.GetBoolArg("-timestampindex", DEFAULT_TIMESTAMPINDEX); - if (fAdditionalIndexes && args.GetArg("-checklevel", DEFAULT_CHECKLEVEL) < 4) { + if (fAdditionalIndexes && args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL) < 4) { args.ForceSetArg("-checklevel", "4"); LogPrintf("%s: parameter interaction: additional indexes -> setting -checklevel=4\n", __func__); } @@ -1147,7 +1147,7 @@ bool AppInitParameterInteraction(const ArgsManager& args) nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS); } - if (args.GetArg("-prune", 0)) { + if (args.GetIntArg("-prune", 0)) { if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) return InitError(_("Prune mode is incompatible with -txindex.")); if (args.GetBoolArg("-reindex-chainstate", false)) { @@ -1186,7 +1186,7 @@ bool AppInitParameterInteraction(const ArgsManager& args) // Make sure enough file descriptors are available int nBind = std::max(nUserBind, size_t(1)); - nUserMaxConnections = args.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS); + nUserMaxConnections = args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS); nMaxConnections = std::max(nUserMaxConnections, 0); nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS + nBind + NUM_FDS_MESSAGE_CAPTURE); @@ -1234,8 +1234,8 @@ bool AppInitParameterInteraction(const ArgsManager& args) } // mempool limits - int64_t nMempoolSizeMax = args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; - int64_t nMempoolSizeMin = args.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40; + int64_t nMempoolSizeMax = args.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; + int64_t nMempoolSizeMin = args.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40; if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin) return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0))); // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool @@ -1249,7 +1249,7 @@ bool AppInitParameterInteraction(const ArgsManager& args) } // block pruning; get the amount of disk space (in MiB) to allot for block & undo files - int64_t nPruneArg = args.GetArg("-prune", 0); + int64_t nPruneArg = args.GetIntArg("-prune", 0); if (nPruneArg < 0) { return InitError(_("Prune cannot be configured with a negative value.")); } @@ -1273,12 +1273,12 @@ bool AppInitParameterInteraction(const ArgsManager& args) fPruneMode = true; } - nConnectTimeout = args.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT); + nConnectTimeout = args.GetIntArg("-timeout", DEFAULT_CONNECT_TIMEOUT); if (nConnectTimeout <= 0) { nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; } - peer_connect_timeout = args.GetArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT); + peer_connect_timeout = args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT); if (peer_connect_timeout <= 0) { return InitError(Untranslated("peertimeout must be a positive integer.")); } @@ -1318,21 +1318,21 @@ bool AppInitParameterInteraction(const ArgsManager& args) if (!chainparams.IsTestChain() && !fRequireStandard) { return InitError(strprintf(Untranslated("acceptnonstdtxn is not currently supported for %s chain"), chainparams.NetworkIDString())); } - nBytesPerSigOp = args.GetArg("-bytespersigop", nBytesPerSigOp); + nBytesPerSigOp = args.GetIntArg("-bytespersigop", nBytesPerSigOp); if (!g_wallet_init_interface.ParameterInteraction()) return false; fIsBareMultisigStd = args.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG); fAcceptDatacarrier = args.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER); - nMaxDatacarrierBytes = args.GetArg("-datacarriersize", nMaxDatacarrierBytes); + nMaxDatacarrierBytes = args.GetIntArg("-datacarriersize", nMaxDatacarrierBytes); // Option to startup with mocktime set (used for regression testing): - SetMockTime(args.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op + SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM); - nMaxTipAge = args.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE); + nMaxTipAge = args.GetIntArg("-maxtipage", DEFAULT_MAX_TIP_AGE); if (args.GetBoolArg("-reindex-chainstate", false)) { // indexes that must be deactivated to prevent index corruption, see #24630 @@ -1367,10 +1367,10 @@ bool AppInitParameterInteraction(const ArgsManager& args) if (!args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) { return InitError(Untranslated("Masternode must have bloom filters enabled, set -peerbloomfilters=1")); } - if (args.GetArg("-prune", 0) > 0) { + if (args.GetIntArg("-prune", 0) > 0) { return InitError(Untranslated("Masternode must have no pruning enabled, set -prune=0")); } - if (args.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS) < DEFAULT_MAX_PEER_CONNECTIONS) { + if (args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS) < DEFAULT_MAX_PEER_CONNECTIONS) { return InitError(strprintf(Untranslated("Masternode must be able to handle at least %d connections, set -maxconnections=%d"), DEFAULT_MAX_PEER_CONNECTIONS, DEFAULT_MAX_PEER_CONNECTIONS)); } if (args.GetBoolArg("-disablegovernance", !DEFAULT_GOVERNANCE_ENABLE)) { @@ -1469,7 +1469,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) InitSignatureCache(); InitScriptExecutionCache(); - int script_threads = args.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS); + int script_threads = args.GetIntArg("-par", DEFAULT_SCRIPTCHECK_THREADS); if (script_threads <= 0) { // -par=0 means autodetect (number of cores - 1 script threads) // -par=-n means "leave n cores free" (number of cores - n - 1 script threads) @@ -1592,7 +1592,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) } assert(!node.banman); - node.banman = std::make_unique(gArgs.GetDataDirNet() / "banlist", &uiInterface, args.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME)); + node.banman = std::make_unique(gArgs.GetDataDirNet() / "banlist", &uiInterface, args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME)); assert(!node.connman); node.connman = std::make_unique(GetRand(std::numeric_limits::max()), GetRand(std::numeric_limits::max()), @@ -1626,7 +1626,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) } } - int minsporkkeys = args.GetArg("-minsporkkeys", Params().MinSporkKeys()); + int minsporkkeys = args.GetIntArg("-minsporkkeys", Params().MinSporkKeys()); if (!node.sporkman->SetMinSporkKeys(minsporkkeys)) { return InitError(_("Invalid minimum number of spork signers specified with -minsporkkeys")); } @@ -1798,7 +1798,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) // cache size calculations CacheSizes cache_sizes = CalculateCacheSizes(args, g_enabled_filter_types.size()); - int64_t nMempoolSizeMax = args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; + int64_t nMempoolSizeMax = args.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; LogPrintf("Cache configuration:\n"); LogPrintf("* Using %.1f MiB for block index database\n", cache_sizes.block_tree_db * (1.0 / 1024 / 1024)); if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) { @@ -1815,7 +1815,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) assert(!node.chainman); assert(!node.govman); assert(!node.mn_sync); - const int mempool_check_ratio = std::clamp(args.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0, 1000000); + const int mempool_check_ratio = std::clamp(args.GetIntArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0, 1000000); for (bool fLoaded = false; !fLoaded && !ShutdownRequested();) { node.mempool = std::make_unique(node.fee_estimator.get(), mempool_check_ratio); @@ -1940,7 +1940,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) std::optional maybe_verify_error; try { uiInterface.InitMessage(_("Verifying blocks…").translated); - auto check_blocks = args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS); + auto check_blocks = args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS); if (chainman.m_blockman.m_have_pruned && check_blocks > MIN_BLOCKS_TO_KEEP) { LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n", MIN_BLOCKS_TO_KEEP); @@ -1951,7 +1951,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) fReindexChainState, chainparams.GetConsensus(), check_blocks, - args.GetArg("-checklevel", DEFAULT_CHECKLEVEL), + args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL), /*get_unix_time_seconds=*/static_cast(GetTime), [](bool bls_state) { LogPrintf("%s: bls_legacy_scheme=%d\n", __func__, bls_state); @@ -2156,7 +2156,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) } if (::g_stats_client->active()) { - int nStatsPeriod = std::min(std::max((int)args.GetArg("-statsperiod", DEFAULT_STATSD_PERIOD), MIN_STATSD_PERIOD), MAX_STATSD_PERIOD); + int nStatsPeriod = std::min(std::max((int)args.GetIntArg("-statsperiod", DEFAULT_STATSD_PERIOD), MIN_STATSD_PERIOD), MAX_STATSD_PERIOD); node.scheduler->scheduleEvery(std::bind(&PeriodicStats, std::ref(node)), std::chrono::seconds{nStatsPeriod}); } @@ -2267,15 +2267,15 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) connOptions.uiInterface = &uiInterface; connOptions.m_banman = node.banman.get(); connOptions.m_msgproc = node.peerman.get(); - connOptions.nSendBufferMaxSize = 1000 * args.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER); - connOptions.nReceiveFloodSize = 1000 * args.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER); + connOptions.nSendBufferMaxSize = 1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER); + connOptions.nReceiveFloodSize = 1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER); connOptions.m_added_nodes = args.GetArgs("-addnode"); connOptions.nMaxOutboundLimit = *opt_max_upload; connOptions.m_peer_connect_timeout = peer_connect_timeout; // Port to bind to if `-bind=addr` is provided without a `:port` suffix. const uint16_t default_bind_port = - static_cast(args.GetArg("-port", Params().GetDefaultPort())); + static_cast(args.GetIntArg("-port", Params().GetDefaultPort())); const auto BadPortWarning = [](const char* prefix, uint16_t port) { return strprintf(_("%s request to listen on port %u. This port is considered \"bad\" and " @@ -2325,7 +2325,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) // Emit a warning if a bad port is given to -port= but only if -bind and -whitebind are not // given, because if they are, then -port= is ignored. if (connOptions.bind_on_any && args.IsArgSet("-port")) { - const uint16_t port_arg = args.GetArg("-port", 0); + const uint16_t port_arg = args.GetIntArg("-port", 0); if (IsBadPort(port_arg)) { InitWarning(BadPortWarning("-port", port_arg)); } diff --git a/src/llmq/signing.cpp b/src/llmq/signing.cpp index ca4033867d786..675a66fc6cdd0 100644 --- a/src/llmq/signing.cpp +++ b/src/llmq/signing.cpp @@ -665,7 +665,7 @@ void CSigningManager::Cleanup() return; } - int64_t maxAge = gArgs.GetArg("-maxrecsigsage", DEFAULT_MAX_RECOVERED_SIGS_AGE); + int64_t maxAge = gArgs.GetIntArg("-maxrecsigsage", DEFAULT_MAX_RECOVERED_SIGS_AGE); db.CleanupOldRecoveredSigs(maxAge); db.CleanupOldVotes(maxAge); diff --git a/src/net.cpp b/src/net.cpp index 46829633f3e33..b40ec6e812e0a 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -187,7 +187,7 @@ uint16_t GetListenPort() } // Otherwise, if -port= is provided, use that. Otherwise use the default port. - return static_cast(gArgs.GetArg("-port", Params().GetDefaultPort())); + return static_cast(gArgs.GetIntArg("-port", Params().GetDefaultPort())); } // find 'best' local address for a particular peer diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 7e0c768b33c5c..4616a08c7b9f7 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -1453,7 +1453,7 @@ void PeerManagerImpl::PushNodeVersion(CNode& pnode, const Peer& peer) int nProtocolVersion = PROTOCOL_VERSION; if (params.NetworkIDString() != CBaseChainParams::MAIN && gArgs.IsArgSet("-pushversion")) { - nProtocolVersion = gArgs.GetArg("-pushversion", PROTOCOL_VERSION); + nProtocolVersion = gArgs.GetIntArg("-pushversion", PROTOCOL_VERSION); } const bool tx_relay{!RejectIncomingTxs(pnode)}; @@ -1764,7 +1764,7 @@ bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) c void PeerManagerImpl::AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans) { - size_t max_extra_txn = gArgs.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN); + size_t max_extra_txn = gArgs.GetIntArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN); if (max_extra_txn <= 0) return; if (!vExtraTxnForCompact.size()) @@ -4539,7 +4539,7 @@ void PeerManagerImpl::ProcessMessage( } // DoS prevention: do not allow m_orphans to grow unbounded (see CVE-2012-3789) - unsigned int nMaxOrphanTxSize = (unsigned int)std::max((int64_t)0, gArgs.GetArg("-maxorphantxsize", DEFAULT_MAX_ORPHAN_TRANSACTIONS_SIZE)) * 1000000; + unsigned int nMaxOrphanTxSize = (unsigned int)std::max((int64_t)0, gArgs.GetIntArg("-maxorphantxsize", DEFAULT_MAX_ORPHAN_TRANSACTIONS_SIZE)) * 1000000; unsigned int nEvicted = m_orphanage.LimitOrphans(nMaxOrphanTxSize); if (nEvicted > 0) { LogPrint(BCLog::MEMPOOL, "orphanage overflow, removed %u tx\n", nEvicted); diff --git a/src/node/caches.cpp b/src/node/caches.cpp index a257c2f24ac7d..36254dc714199 100644 --- a/src/node/caches.cpp +++ b/src/node/caches.cpp @@ -10,7 +10,7 @@ CacheSizes CalculateCacheSizes(const ArgsManager& args, size_t n_indexes) { - int64_t nTotalCache = (args.GetArg("-dbcache", nDefaultDbCache) << 20); + int64_t nTotalCache = (args.GetIntArg("-dbcache", nDefaultDbCache) << 20); nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache CacheSizes sizes; diff --git a/src/node/interfaces.cpp b/src/node/interfaces.cpp index 94be4f81537c4..802b37557a66e 100644 --- a/src/node/interfaces.cpp +++ b/src/node/interfaces.cpp @@ -902,8 +902,8 @@ class ChainImpl : public Chain } void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) override { - limit_ancestor_count = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); - limit_descendant_count = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); + limit_ancestor_count = gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); + limit_descendant_count = gArgs.GetIntArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); } bool checkChainLimits(const CTransactionRef& tx) override { @@ -911,10 +911,10 @@ class ChainImpl : public Chain LockPoints lp; CTxMemPoolEntry entry(tx, 0, 0, 0, false, 0, lp); CTxMemPool::setEntries ancestors; - auto limit_ancestor_count = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); - auto limit_ancestor_size = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000; - auto limit_descendant_count = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); - auto limit_descendant_size = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000; + auto limit_ancestor_count = gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); + auto limit_ancestor_size = gArgs.GetIntArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000; + auto limit_descendant_count = gArgs.GetIntArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); + auto limit_descendant_size = gArgs.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000; std::string unused_error_string; LOCK(m_node.mempool->cs); return m_node.mempool->CalculateMemPoolAncestors( @@ -934,7 +934,7 @@ class ChainImpl : public Chain CFeeRate mempoolMinFee() override { if (!m_node.mempool) return {}; - return m_node.mempool->GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000); + return m_node.mempool->GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000); } CFeeRate relayMinFee() override { return ::minRelayTxFee; } CFeeRate relayIncrementalFee() override { return ::incrementalRelayFee; } diff --git a/src/node/miner.cpp b/src/node/miner.cpp index 4d6757402fa19..250a88642f334 100644 --- a/src/node/miner.cpp +++ b/src/node/miner.cpp @@ -92,7 +92,7 @@ static BlockAssembler::Options DefaultOptions() BlockAssembler::Options options; options.nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE; if (gArgs.IsArgSet("-blockmaxsize")) { - options.nBlockMaxSize = gArgs.GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); + options.nBlockMaxSize = gArgs.GetIntArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); } if (gArgs.IsArgSet("-blockmintxfee")) { std::optional parsed = ParseMoney(gArgs.GetArg("-blockmintxfee", "")); @@ -155,7 +155,7 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc // Non-mainnet only: allow overriding block.nVersion with // -blockversion=N to test forking scenarios if (Params().NetworkIDString() != CBaseChainParams::MAIN) { - pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion); + pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion); } pblock->nTime = GetAdjustedTime(); diff --git a/src/qt/bitcoin.cpp b/src/qt/bitcoin.cpp index 472fbd7bdd0bb..9d6c5b25dd524 100644 --- a/src/qt/bitcoin.cpp +++ b/src/qt/bitcoin.cpp @@ -652,7 +652,7 @@ int GuiMain(int argc, char* argv[]) // Validate/set normal font weight if (gArgs.IsArgSet("-font-weight-normal")) { QFont::Weight weight; - if (!GUIUtil::weightFromArg(gArgs.GetArg("-font-weight-normal", GUIUtil::weightToArg(GUIUtil::getFontWeightNormal())), weight)) { + if (!GUIUtil::weightFromArg(gArgs.GetIntArg("-font-weight-normal", GUIUtil::weightToArg(GUIUtil::getFontWeightNormal())), weight)) { QMessageBox::critical(0, PACKAGE_NAME, QObject::tr("Error: Specified font-weight-normal invalid. Valid range %1 to %2.").arg(0).arg(8)); return EXIT_FAILURE; @@ -662,7 +662,7 @@ int GuiMain(int argc, char* argv[]) // Validate/set bold font weight if (gArgs.IsArgSet("-font-weight-bold")) { QFont::Weight weight; - if (!GUIUtil::weightFromArg(gArgs.GetArg("-font-weight-bold", GUIUtil::weightToArg(GUIUtil::getFontWeightBold())), weight)) { + if (!GUIUtil::weightFromArg(gArgs.GetIntArg("-font-weight-bold", GUIUtil::weightToArg(GUIUtil::getFontWeightBold())), weight)) { QMessageBox::critical(0, PACKAGE_NAME, QObject::tr("Error: Specified font-weight-bold invalid. Valid range %1 to %2.").arg(0).arg(8)); return EXIT_FAILURE; @@ -672,7 +672,7 @@ int GuiMain(int argc, char* argv[]) // Validate/set font scale if (gArgs.IsArgSet("-font-scale")) { const int nScaleMin = -100, nScaleMax = 100; - int nScale = gArgs.GetArg("-font-scale", GUIUtil::getFontScale()); + int nScale = gArgs.GetIntArg("-font-scale", GUIUtil::getFontScale()); if (nScale < nScaleMin || nScale > nScaleMax) { QMessageBox::critical(0, PACKAGE_NAME, QObject::tr("Error: Specified font-scale invalid. Valid range %1 to %2.").arg(nScaleMin).arg(nScaleMax)); diff --git a/src/qt/intro.cpp b/src/qt/intro.cpp index 581ede260433c..6b01f5d10faf2 100644 --- a/src/qt/intro.cpp +++ b/src/qt/intro.cpp @@ -114,7 +114,7 @@ namespace { //! Return pruning size that will be used if automatic pruning is enabled. int GetPruneTargetGB() { - int64_t prune_target_mib = gArgs.GetArg("-prune", 0); + int64_t prune_target_mib = gArgs.GetIntArg("-prune", 0); // >1 means automatic pruning is enabled by config, 1 means manual pruning, 0 means no pruning. return prune_target_mib > 1 ? PruneMiBtoGB(prune_target_mib) : DEFAULT_PRUNE_TARGET_GB; } @@ -143,7 +143,7 @@ Intro::Intro(QWidget *parent, int64_t blockchain_size_gb, int64_t chain_state_si const int min_prune_target_GB = std::ceil(MIN_DISK_SPACE_FOR_BLOCK_FILES / 1e9); ui->pruneGB->setRange(min_prune_target_GB, std::numeric_limits::max()); - if (gArgs.GetArg("-prune", 0) > 1) { // -prune=1 means enabled, above that it's a size in MiB + if (gArgs.GetIntArg("-prune", 0) > 1) { // -prune=1 means enabled, above that it's a size in MiB ui->prune->setChecked(true); ui->prune->setEnabled(false); } @@ -293,7 +293,7 @@ void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable ui->freeSpace->setText(""); } else { m_bytes_available = bytesAvailable; - if (ui->prune->isEnabled() && !(gArgs.IsArgSet("-prune") && gArgs.GetArg("-prune", 0) == 0)) { + if (ui->prune->isEnabled() && !(gArgs.IsArgSet("-prune") && gArgs.GetIntArg("-prune", 0) == 0)) { ui->prune->setChecked(m_bytes_available < (m_blockchain_size_gb + m_chain_state_size_gb + 10) * GB_BYTES); } UpdateFreeSpaceLabel(); diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp index f818ced681cf1..28c8744924ac2 100644 --- a/src/qt/optionsmodel.cpp +++ b/src/qt/optionsmodel.cpp @@ -419,7 +419,7 @@ void OptionsModel::SetPruneEnabled(bool prune, bool force) if (!gArgs.SoftSetArg("-prune", prune_val)) { addOverriddenOption("-prune"); } - if (gArgs.GetArg("-prune", 0) > 0) { + if (gArgs.GetIntArg("-prune", 0) > 0) { gArgs.SoftSetBoolArg("-disablegovernance", true); gArgs.SoftSetBoolArg("-txindex", false); } diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 41a090bd60f66..76057d0785b09 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -1469,7 +1469,7 @@ RPCHelpMan getblockchaininfo() obj.pushKV("pruneheight", chainman.m_blockman.GetFirstStoredBlock(tip)->nHeight); // if 0, execution bypasses the whole if block. - bool automatic_pruning{args.GetArg("-prune", 0) != 1}; + bool automatic_pruning{args.GetIntArg("-prune", 0) != 1}; obj.pushKV("automatic_pruning", automatic_pruning); if (automatic_pruning) { obj.pushKV("prune_target_size", nPruneTarget); diff --git a/src/rpc/fees.cpp b/src/rpc/fees.cpp index ba541ff9919ae..2e020512889a8 100644 --- a/src/rpc/fees.cpp +++ b/src/rpc/fees.cpp @@ -82,7 +82,7 @@ static RPCHelpMan estimatesmartfee() FeeCalculation feeCalc; CFeeRate feeRate{fee_estimator.estimateSmartFee(conf_target, &feeCalc, conservative)}; if (feeRate != CFeeRate(0)) { - CFeeRate min_mempool_feerate{mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000)}; + CFeeRate min_mempool_feerate{mempool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000)}; CFeeRate min_relay_feerate{::minRelayTxFee}; feeRate = std::max({feeRate, min_mempool_feerate, min_relay_feerate}); result.pushKV("feerate", ValueFromAmount(feeRate.GetFeePerK())); diff --git a/src/rpc/mempool.cpp b/src/rpc/mempool.cpp index 3aa482e42e23d..2a1908be33a05 100644 --- a/src/rpc/mempool.cpp +++ b/src/rpc/mempool.cpp @@ -388,7 +388,7 @@ UniValue MempoolInfoToJSON(const CTxMemPool& pool, const llmq::CInstantSendManag ret.pushKV("bytes", (int64_t)pool.GetTotalTxSize()); ret.pushKV("usage", (int64_t)pool.DynamicMemoryUsage()); ret.pushKV("total_fee", ValueFromAmount(pool.GetTotalFee())); - int64_t maxmempool{gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000}; + int64_t maxmempool{gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000}; ret.pushKV("maxmempool", maxmempool); ret.pushKV("mempoolminfee", ValueFromAmount(std::max(pool.GetMinFee(maxmempool), ::minRelayTxFee).GetFeePerK())); ret.pushKV("minrelaytxfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())); diff --git a/src/script/sigcache.cpp b/src/script/sigcache.cpp index ee40da3e6e116..82344db0aa703 100644 --- a/src/script/sigcache.cpp +++ b/src/script/sigcache.cpp @@ -82,7 +82,7 @@ void InitSignatureCache() { // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero, // setup_bytes creates the minimum possible cache (2 elements). - size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20); + size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetIntArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20); size_t nElems = signatureCache.setup_bytes(nMaxCacheSize); LogPrintf("Using %zu MiB out of %zu/2 requested for signature cache, able to store %zu elements\n", (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems); diff --git a/src/stats/client.cpp b/src/stats/client.cpp index 31b9111f41a96..633dd425caadb 100644 --- a/src/stats/client.cpp +++ b/src/stats/client.cpp @@ -44,9 +44,9 @@ std::unique_ptr InitStatsClient(const ArgsManager& args) }; return std::make_unique(args.GetArg("-statshost", DEFAULT_STATSD_HOST), - args.GetArg("-statsport", DEFAULT_STATSD_PORT), - args.GetArg("-statsbatchsize", DEFAULT_STATSD_BATCH_SIZE), - args.GetArg("-statsduration", DEFAULT_STATSD_DURATION), + args.GetIntArg("-statsport", DEFAULT_STATSD_PORT), + args.GetIntArg("-statsbatchsize", DEFAULT_STATSD_BATCH_SIZE), + args.GetIntArg("-statsduration", DEFAULT_STATSD_DURATION), sanitize_string(args.GetArg("-statsprefix", DEFAULT_STATSD_PREFIX)), sanitize_string(args.GetArg("-statssuffix", DEFAULT_STATSD_SUFFIX))); } diff --git a/src/test/addrman_tests.cpp b/src/test/addrman_tests.cpp index ce9a2bca829ad..33fefd9107943 100644 --- a/src/test/addrman_tests.cpp +++ b/src/test/addrman_tests.cpp @@ -26,7 +26,7 @@ static const bool DETERMINISTIC{true}; static int32_t GetCheckRatio(const NodeContext& node_ctx) { - return std::clamp(node_ctx.args->GetArg("-checkaddrman", 100), 0, 1000000); + return std::clamp(node_ctx.args->GetIntArg("-checkaddrman", 100), 0, 1000000); } static CNetAddr ResolveIP(const std::string& ip) diff --git a/src/test/fuzz/addrman.cpp b/src/test/fuzz/addrman.cpp index 32e578727333d..9baf26a0b2c0e 100644 --- a/src/test/fuzz/addrman.cpp +++ b/src/test/fuzz/addrman.cpp @@ -28,7 +28,7 @@ const BasicTestingSetup* g_setup; int32_t GetCheckRatio() { - return std::clamp(g_setup->m_node.args->GetArg("-checkaddrman", 0), 0, 1000000); + return std::clamp(g_setup->m_node.args->GetIntArg("-checkaddrman", 0), 0, 1000000); } } // namespace diff --git a/src/test/fuzz/deserialize.cpp b/src/test/fuzz/deserialize.cpp index b60abddaf5cdc..bcd7d4d87c056 100644 --- a/src/test/fuzz/deserialize.cpp +++ b/src/test/fuzz/deserialize.cpp @@ -202,7 +202,7 @@ FUZZ_TARGET_DESERIALIZE(addrman_deserialize, { NetGroupManager netgroupman{std::vector()}; AddrMan am(netgroupman, /*deterministic=*/false, - g_setup->m_node.args->GetArg("-checkaddrman", 0)); + g_setup->m_node.args->GetIntArg("-checkaddrman", 0)); DeserializeFromFuzzingInput(buffer, am); }) FUZZ_TARGET_DESERIALIZE(blockheader_deserialize, { diff --git a/src/test/fuzz/net.cpp b/src/test/fuzz/net.cpp index b3c562ee47dca..91face354d247 100644 --- a/src/test/fuzz/net.cpp +++ b/src/test/fuzz/net.cpp @@ -27,7 +27,7 @@ const BasicTestingSetup* g_setup; int32_t GetCheckRatio() { - return std::clamp(g_setup->m_node.args->GetArg("-checkaddrman", 0), 0, 1000000); + return std::clamp(g_setup->m_node.args->GetIntArg("-checkaddrman", 0), 0, 1000000); } } // namespace diff --git a/src/test/fuzz/system.cpp b/src/test/fuzz/system.cpp index a593cfbae31c9..494d25a0d5f48 100644 --- a/src/test/fuzz/system.cpp +++ b/src/test/fuzz/system.cpp @@ -102,7 +102,7 @@ FUZZ_TARGET_INIT(system, initialize_system) const int64_t i64 = fuzzed_data_provider.ConsumeIntegral(); const bool b = fuzzed_data_provider.ConsumeBool(); - (void)args_manager.GetArg(s1, i64); + (void)args_manager.GetIntArg(s1, i64); (void)args_manager.GetArg(s1, s2); (void)args_manager.GetArgFlags(s1); (void)args_manager.GetArgs(s1); diff --git a/src/test/getarg_tests.cpp b/src/test/getarg_tests.cpp index 5a6d17eec14a3..2033551da249b 100644 --- a/src/test/getarg_tests.cpp +++ b/src/test/getarg_tests.cpp @@ -64,91 +64,91 @@ BOOST_AUTO_TEST_CASE(setting_args) set_foo("str"); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "\"str\""); BOOST_CHECK_EQUAL(args.GetArg("foo", "default"), "str"); - BOOST_CHECK_EQUAL(args.GetArg("foo", 100), 0); + BOOST_CHECK_EQUAL(args.GetIntArg("foo", 100), 0); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", true), false); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", false), false); set_foo("99"); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "\"99\""); BOOST_CHECK_EQUAL(args.GetArg("foo", "default"), "99"); - BOOST_CHECK_EQUAL(args.GetArg("foo", 100), 99); + BOOST_CHECK_EQUAL(args.GetIntArg("foo", 100), 99); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", true), true); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", false), true); set_foo("3.25"); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "\"3.25\""); BOOST_CHECK_EQUAL(args.GetArg("foo", "default"), "3.25"); - BOOST_CHECK_EQUAL(args.GetArg("foo", 100), 3); + BOOST_CHECK_EQUAL(args.GetIntArg("foo", 100), 3); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", true), true); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", false), true); set_foo("0"); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "\"0\""); BOOST_CHECK_EQUAL(args.GetArg("foo", "default"), "0"); - BOOST_CHECK_EQUAL(args.GetArg("foo", 100), 0); + BOOST_CHECK_EQUAL(args.GetIntArg("foo", 100), 0); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", true), false); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", false), false); set_foo(""); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "\"\""); BOOST_CHECK_EQUAL(args.GetArg("foo", "default"), ""); - BOOST_CHECK_EQUAL(args.GetArg("foo", 100), 0); + BOOST_CHECK_EQUAL(args.GetIntArg("foo", 100), 0); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", true), true); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", false), true); set_foo(99); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "99"); BOOST_CHECK_EQUAL(args.GetArg("foo", "default"), "99"); - BOOST_CHECK_EQUAL(args.GetArg("foo", 100), 99); + BOOST_CHECK_EQUAL(args.GetIntArg("foo", 100), 99); BOOST_CHECK_THROW(args.GetBoolArg("foo", true), std::runtime_error); BOOST_CHECK_THROW(args.GetBoolArg("foo", false), std::runtime_error); set_foo(3.25); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "3.25"); BOOST_CHECK_EQUAL(args.GetArg("foo", "default"), "3.25"); - BOOST_CHECK_THROW(args.GetArg("foo", 100), std::runtime_error); + BOOST_CHECK_THROW(args.GetIntArg("foo", 100), std::runtime_error); BOOST_CHECK_THROW(args.GetBoolArg("foo", true), std::runtime_error); BOOST_CHECK_THROW(args.GetBoolArg("foo", false), std::runtime_error); set_foo(0); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "0"); BOOST_CHECK_EQUAL(args.GetArg("foo", "default"), "0"); - BOOST_CHECK_EQUAL(args.GetArg("foo", 100), 0); + BOOST_CHECK_EQUAL(args.GetIntArg("foo", 100), 0); BOOST_CHECK_THROW(args.GetBoolArg("foo", true), std::runtime_error); BOOST_CHECK_THROW(args.GetBoolArg("foo", false), std::runtime_error); set_foo(true); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "true"); BOOST_CHECK_EQUAL(args.GetArg("foo", "default"), "1"); - BOOST_CHECK_EQUAL(args.GetArg("foo", 100), 1); + BOOST_CHECK_EQUAL(args.GetIntArg("foo", 100), 1); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", true), true); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", false), true); set_foo(false); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "false"); BOOST_CHECK_EQUAL(args.GetArg("foo", "default"), "0"); - BOOST_CHECK_EQUAL(args.GetArg("foo", 100), 0); + BOOST_CHECK_EQUAL(args.GetIntArg("foo", 100), 0); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", true), false); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", false), false); set_foo(UniValue::VOBJ); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "{}"); BOOST_CHECK_THROW(args.GetArg("foo", "default"), std::runtime_error); - BOOST_CHECK_THROW(args.GetArg("foo", 100), std::runtime_error); + BOOST_CHECK_THROW(args.GetIntArg("foo", 100), std::runtime_error); BOOST_CHECK_THROW(args.GetBoolArg("foo", true), std::runtime_error); BOOST_CHECK_THROW(args.GetBoolArg("foo", false), std::runtime_error); set_foo(UniValue::VARR); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "[]"); BOOST_CHECK_THROW(args.GetArg("foo", "default"), std::runtime_error); - BOOST_CHECK_THROW(args.GetArg("foo", 100), std::runtime_error); + BOOST_CHECK_THROW(args.GetIntArg("foo", 100), std::runtime_error); BOOST_CHECK_THROW(args.GetBoolArg("foo", true), std::runtime_error); BOOST_CHECK_THROW(args.GetBoolArg("foo", false), std::runtime_error); set_foo(UniValue::VNULL); BOOST_CHECK_EQUAL(args.GetSetting("foo").write(), "null"); BOOST_CHECK_EQUAL(args.GetArg("foo", "default"), "default"); - BOOST_CHECK_EQUAL(args.GetArg("foo", 100), 100); + BOOST_CHECK_EQUAL(args.GetIntArg("foo", 100), 100); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", true), true); BOOST_CHECK_EQUAL(args.GetBoolArg("foo", false), false); } @@ -244,25 +244,25 @@ BOOST_AUTO_TEST_CASE(intarg) const auto bar = std::make_pair("-bar", ArgsManager::ALLOW_ANY); SetupArgs(local_args, {foo, bar}); ResetArgs(local_args, ""); - BOOST_CHECK_EQUAL(local_args.GetArg("-foo", 11), 11); - BOOST_CHECK_EQUAL(local_args.GetArg("-foo", 0), 0); + BOOST_CHECK_EQUAL(local_args.GetIntArg("-foo", 11), 11); + BOOST_CHECK_EQUAL(local_args.GetIntArg("-foo", 0), 0); ResetArgs(local_args, "-foo -bar"); - BOOST_CHECK_EQUAL(local_args.GetArg("-foo", 11), 0); - BOOST_CHECK_EQUAL(local_args.GetArg("-bar", 11), 0); + BOOST_CHECK_EQUAL(local_args.GetIntArg("-foo", 11), 0); + BOOST_CHECK_EQUAL(local_args.GetIntArg("-bar", 11), 0); // Check under-/overflow behavior. ResetArgs(local_args, "-foo=-9223372036854775809 -bar=9223372036854775808"); - BOOST_CHECK_EQUAL(local_args.GetArg("-foo", 0), std::numeric_limits::min()); - BOOST_CHECK_EQUAL(local_args.GetArg("-bar", 0), std::numeric_limits::max()); + BOOST_CHECK_EQUAL(local_args.GetIntArg("-foo", 0), std::numeric_limits::min()); + BOOST_CHECK_EQUAL(local_args.GetIntArg("-bar", 0), std::numeric_limits::max()); ResetArgs(local_args, "-foo=11 -bar=12"); - BOOST_CHECK_EQUAL(local_args.GetArg("-foo", 0), 11); - BOOST_CHECK_EQUAL(local_args.GetArg("-bar", 11), 12); + BOOST_CHECK_EQUAL(local_args.GetIntArg("-foo", 0), 11); + BOOST_CHECK_EQUAL(local_args.GetIntArg("-bar", 11), 12); ResetArgs(local_args, "-foo=NaN -bar=NotANumber"); - BOOST_CHECK_EQUAL(local_args.GetArg("-foo", 1), 0); - BOOST_CHECK_EQUAL(local_args.GetArg("-bar", 11), 0); + BOOST_CHECK_EQUAL(local_args.GetIntArg("-foo", 1), 0); + BOOST_CHECK_EQUAL(local_args.GetIntArg("-bar", 11), 0); } BOOST_AUTO_TEST_CASE(patharg) @@ -389,7 +389,7 @@ BOOST_AUTO_TEST_CASE(doubledash) ResetArgs(local_args, "--foo=verbose --bar=1"); BOOST_CHECK_EQUAL(local_args.GetArg("-foo", ""), "verbose"); - BOOST_CHECK_EQUAL(local_args.GetArg("-bar", 0), 1); + BOOST_CHECK_EQUAL(local_args.GetIntArg("-bar", 0), 1); } BOOST_AUTO_TEST_CASE(boolargno) diff --git a/src/test/util/setup_common.cpp b/src/test/util/setup_common.cpp index 46ab23da0278b..99cfc3796c7f4 100644 --- a/src/test/util/setup_common.cpp +++ b/src/test/util/setup_common.cpp @@ -189,7 +189,7 @@ BasicTestingSetup::BasicTestingSetup(const std::string& chainName, const std::ve m_node.netgroupman = std::make_unique(/*asmap=*/std::vector()); m_node.addrman = std::make_unique(*m_node.netgroupman, /*deterministic=*/false, - m_node.args->GetArg("-checkaddrman", 0)); + m_node.args->GetIntArg("-checkaddrman", 0)); m_node.connman = std::make_unique(0x1337, 0x1337, *m_node.addrman, *m_node.netgroupman); // Deterministic randomness for tests. // while g_wallet_init_interface is init here at very early stage @@ -315,8 +315,8 @@ TestingSetup::TestingSetup(const std::string& chainName, const std::vector(GetTime), [](bool bls_state) { LogPrintf("%s: bls_legacy_scheme=%d\n", __func__, bls_state); diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp index 107361b50ded6..a28aee2cc676b 100644 --- a/src/test/util_tests.cpp +++ b/src/test/util_tests.cpp @@ -406,9 +406,9 @@ class CheckValueTest : public TestChain100Setup } if (expect.default_int) { - BOOST_CHECK_EQUAL(test.GetArg("-value", 99999), 99999); + BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99999), 99999); } else if (expect.int_value) { - BOOST_CHECK_EQUAL(test.GetArg("-value", 99999), *expect.int_value); + BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99999), *expect.int_value); } else { BOOST_CHECK(!success); } @@ -538,8 +538,8 @@ static void TestParse(const std::string& str, bool expected_bool, int64_t expect BOOST_CHECK(test.ParseParameters(2, (char**)argv, error)); BOOST_CHECK_EQUAL(test.GetBoolArg("-value", false), expected_bool); BOOST_CHECK_EQUAL(test.GetBoolArg("-value", true), expected_bool); - BOOST_CHECK_EQUAL(test.GetArg("-value", 99998), expected_int); - BOOST_CHECK_EQUAL(test.GetArg("-value", 99999), expected_int); + BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99998), expected_int); + BOOST_CHECK_EQUAL(test.GetIntArg("-value", 99999), expected_int); } // Test bool and int parsing. @@ -890,9 +890,9 @@ BOOST_AUTO_TEST_CASE(util_GetArg) BOOST_CHECK_EQUAL(testArgs.GetArg("strtest1", "default"), "string..."); BOOST_CHECK_EQUAL(testArgs.GetArg("strtest2", "default"), "default"); - BOOST_CHECK_EQUAL(testArgs.GetArg("inttest1", -1), 12345); - BOOST_CHECK_EQUAL(testArgs.GetArg("inttest2", -1), 81985529216486895LL); - BOOST_CHECK_EQUAL(testArgs.GetArg("inttest3", -1), -1); + BOOST_CHECK_EQUAL(testArgs.GetIntArg("inttest1", -1), 12345); + BOOST_CHECK_EQUAL(testArgs.GetIntArg("inttest2", -1), 81985529216486895LL); + BOOST_CHECK_EQUAL(testArgs.GetIntArg("inttest3", -1), -1); BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest1", false), true); BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest2", false), false); BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest3", false), false); diff --git a/src/timedata.cpp b/src/timedata.cpp index 54378a5cf1b5a..0a076291ca5ed 100644 --- a/src/timedata.cpp +++ b/src/timedata.cpp @@ -77,7 +77,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample) int64_t nMedian = g_time_offsets.median(); std::vector vSorted = g_time_offsets.sorted(); // Only let other nodes change our time by so much - int64_t max_adjustment = std::max(0, gArgs.GetArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT)); + int64_t max_adjustment = std::max(0, gArgs.GetIntArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT)); if (nMedian >= -max_adjustment && nMedian <= max_adjustment) { nTimeOffset = nMedian; } else { diff --git a/src/txdb.cpp b/src/txdb.cpp index 90a5a20bba129..6ef8cf5e5c820 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -111,8 +111,8 @@ bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, boo CDBBatch batch(*m_db); size_t count = 0; size_t changed = 0; - size_t batch_size = (size_t)gArgs.GetArg("-dbbatchsize", nDefaultDbBatchSize); - int crash_simulate = gArgs.GetArg("-dbcrashratio", 0); + size_t batch_size = (size_t)gArgs.GetIntArg("-dbbatchsize", nDefaultDbBatchSize); + int crash_simulate = gArgs.GetIntArg("-dbcrashratio", 0); assert(!hashBlock.IsNull()); uint256 old_tip = GetBestBlock(); diff --git a/src/util/system.cpp b/src/util/system.cpp index 2cb4d87328d8c..808fc26a67e43 100644 --- a/src/util/system.cpp +++ b/src/util/system.cpp @@ -630,7 +630,7 @@ std::string ArgsManager::GetArg(const std::string& strArg, const std::string& st return value.isNull() ? strDefault : value.isFalse() ? "0" : value.isTrue() ? "1" : value.isNum() ? value.getValStr() : value.get_str(); } -int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault) const +int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const { const util::SettingsValue value = GetSetting(strArg); return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.get_int64() : LocaleIndependentAtoi(value.get_str()); diff --git a/src/util/system.h b/src/util/system.h index 3fa4ceab53b6f..1fdc003db2629 100644 --- a/src/util/system.h +++ b/src/util/system.h @@ -374,7 +374,7 @@ class ArgsManager * @param nDefault (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ - int64_t GetArg(const std::string& strArg, int64_t nDefault) const; + int64_t GetIntArg(const std::string& strArg, int64_t nDefault) const; /** * Return boolean argument or default value diff --git a/src/validation.cpp b/src/validation.cpp index 01ebc3b2c34b9..b8eef41665f77 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -357,8 +357,8 @@ void CChainState::MaybeUpdateMempoolForReorg( // previously-confirmed transactions back to the mempool. // UpdateTransactionsFromBlock finds descendants of any transactions in // the disconnectpool that were added back and cleans up the mempool state. - const uint64_t ancestor_count_limit = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); - const uint64_t ancestor_size_limit = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000; + const uint64_t ancestor_count_limit = gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); + const uint64_t ancestor_size_limit = gArgs.GetIntArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000; m_mempool->UpdateTransactionsFromBlock(vHashUpdate, ancestor_size_limit, ancestor_count_limit); // Predicate to use for filtering transactions in removeForReorg. @@ -414,8 +414,8 @@ void CChainState::MaybeUpdateMempoolForReorg( LimitMempoolSize( *m_mempool, this->CoinsTip(), - gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, - std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)}); + gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, + std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)}); } /** @@ -471,10 +471,10 @@ class MemPoolAccept m_viewmempool(&active_chainstate.CoinsTip(), m_pool), m_active_chainstate(active_chainstate), m_chain_helper(active_chainstate.ChainHelper()), - m_limit_ancestors(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)), - m_limit_ancestor_size(gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000), - m_limit_descendants(gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)), - m_limit_descendant_size(gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000) { + m_limit_ancestors(gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)), + m_limit_ancestor_size(gArgs.GetIntArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000), + m_limit_descendants(gArgs.GetIntArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)), + m_limit_descendant_size(gArgs.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000) { } // We put the arguments we're handed into a struct, so we can pass them @@ -637,7 +637,7 @@ class MemPoolAccept { AssertLockHeld(::cs_main); AssertLockHeld(m_pool.cs); - CAmount mempoolRejectFee = m_pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(package_size); + CAmount mempoolRejectFee = m_pool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(package_size); if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) { return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee)); } @@ -992,7 +992,7 @@ bool MemPoolAccept::Finalize(const ATMPArgs& args, Workspace& ws) // in the package. LimitMempoolSize() should be called at the very end to make sure the mempool // is still within limits and package submission happens atomically. if (!args.m_package_submission && !bypass_limits) { - LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip(), gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)}); + LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip(), gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)}); if (!m_pool.exists(hash)) return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full"); } @@ -1054,8 +1054,8 @@ bool MemPoolAccept::SubmitPackage(const ATMPArgs& args, std::vector& // It may or may not be the case that all the transactions made it into the mempool. Regardless, // make sure we haven't exceeded max mempool size. LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip(), - gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, - std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)}); + gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, + std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)}); // Find the wtxids of the transactions that made it into the mempool. Allow partial submission, // but don't report success unless they all made it into the mempool. @@ -1707,7 +1707,7 @@ void InitScriptExecutionCache() { g_scriptExecutionCacheHasher.Write(nonce.begin(), 32); // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero, // setup_bytes creates the minimum possible cache (2 elements). - size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20); + size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetIntArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20); size_t nElems = g_scriptExecutionCache.setup_bytes(nMaxCacheSize); LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n", (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems); @@ -2598,7 +2598,7 @@ CoinsCacheSizeState CChainState::GetCoinsCacheSizeState() AssertLockHeld(::cs_main); return this->GetCoinsCacheSizeState( m_coinstip_cache_size_bytes, - gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000); + gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000); } CoinsCacheSizeState CChainState::GetCoinsCacheSizeState( @@ -3307,7 +3307,7 @@ bool CChainState::ActivateBestChain(BlockValidationState& state, std::shared_ptr CBlockIndex *pindexMostWork = nullptr; CBlockIndex *pindexNewTip = nullptr; - int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT); + int nStopAtHeight = gArgs.GetIntArg("-stopatheight", DEFAULT_STOPATHEIGHT); do { // Block until the validation queue drains. This should largely // never happen in normal operation, however may happen during @@ -5309,7 +5309,7 @@ static const uint64_t MEMPOOL_DUMP_VERSION = 1; bool LoadMempool(CTxMemPool& pool, CChainState& active_chainstate, FopenFn mockable_fopen_function) { - int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60; + int64_t nExpiryTimeout = gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60; FILE* filestr{mockable_fopen_function(gArgs.GetDataDirNet() / "mempool.dat", "rb")}; CAutoFile file(filestr, SER_DISK, CLIENT_VERSION); if (file.IsNull()) { diff --git a/src/wallet/bdb.cpp b/src/wallet/bdb.cpp index ef6947a25f949..44da903948fe9 100644 --- a/src/wallet/bdb.cpp +++ b/src/wallet/bdb.cpp @@ -384,7 +384,7 @@ void BerkeleyBatch::Flush() nMinutes = 1; if (env) { // env is nullptr for dummy databases (i.e. in tests). Don't actually flush if env is nullptr so we don't segfault - env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0); + env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetIntArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0); } } diff --git a/src/wallet/hdchain.cpp b/src/wallet/hdchain.cpp index 710784d37f12d..bc00734713077 100644 --- a/src/wallet/hdchain.cpp +++ b/src/wallet/hdchain.cpp @@ -61,7 +61,7 @@ bool CHDChain::SetMnemonic(const SecureString& ssMnemonic, const SecureString& s // empty mnemonic i.e. "generate a new one" if (ssMnemonic.empty()) { - ssMnemonicTmp = CMnemonic::Generate(gArgs.GetArg("-mnemonicbits", DEFAULT_MNEMONIC_BITS)); + ssMnemonicTmp = CMnemonic::Generate(gArgs.GetIntArg("-mnemonicbits", DEFAULT_MNEMONIC_BITS)); } // NOTE: default mnemonic passphrase is an empty string diff --git a/src/wallet/init.cpp b/src/wallet/init.cpp index 8f7a416939261..ee8430395b2ab 100644 --- a/src/wallet/init.cpp +++ b/src/wallet/init.cpp @@ -146,7 +146,7 @@ bool WalletInit::ParameterInteraction() const return InitError(Untranslated("-zapwallettxes has been removed. If you are attempting to remove a stuck transaction from your wallet, please use abandontransaction instead.")); } - int rescan_mode = gArgs.GetArg("-rescan", 0); + int rescan_mode = gArgs.GetIntArg("-rescan", 0); if (rescan_mode < 0 || rescan_mode > 2) { LogPrintf("%s: Warning: incorrect -rescan mode, falling back to default value.\n", __func__); InitWarning(_("Incorrect -rescan mode, falling back to default value")); @@ -169,11 +169,11 @@ bool WalletInit::ParameterInteraction() const gArgs.ForceRemoveArg("mnemonicpassphrase"); } - if (gArgs.GetArg("-coinjoindenomshardcap", DEFAULT_COINJOIN_DENOMS_HARDCAP) < gArgs.GetArg("-coinjoindenomsgoal", DEFAULT_COINJOIN_DENOMS_GOAL)) { + if (gArgs.GetIntArg("-coinjoindenomshardcap", DEFAULT_COINJOIN_DENOMS_HARDCAP) < gArgs.GetIntArg("-coinjoindenomsgoal", DEFAULT_COINJOIN_DENOMS_GOAL)) { return InitError(strprintf(_("%s can't be lower than %s"), "-coinjoindenomshardcap", "-coinjoindenomsgoal")); } - if (CMnemonic::Generate(gArgs.GetArg("-mnemonicbits", CHDChain::DEFAULT_MNEMONIC_BITS)) == SecureString()) { + if (CMnemonic::Generate(gArgs.GetIntArg("-mnemonicbits", CHDChain::DEFAULT_MNEMONIC_BITS)) == SecureString()) { return InitError(strprintf(_("Invalid '%s'. Allowed values: 128, 160, 192, 224, 256."), "-mnemonicbits")); } diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index d829bbab2c4f3..5ea8eb0fc303a 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -1675,7 +1675,7 @@ static UniValue ProcessDescriptorImport(CWallet& wallet, const UniValue& data, c } else { warnings.push_back("Range not given, using default keypool range"); range_start = 0; - range_end = gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE); + range_end = gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE); } next_index = range_start; diff --git a/src/wallet/scriptpubkeyman.cpp b/src/wallet/scriptpubkeyman.cpp index b65a6819ee2bc..01a5ea6016211 100644 --- a/src/wallet/scriptpubkeyman.cpp +++ b/src/wallet/scriptpubkeyman.cpp @@ -1430,7 +1430,7 @@ bool LegacyScriptPubKeyMan::TopUpInner(unsigned int kpSize) if (kpSize > 0) nTargetSize = kpSize; else - nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0); + nTargetSize = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0); // count amount of available keys (internal, external) // make sure the keypool of external and internal keys fits the user selected target (-keypool) @@ -1928,7 +1928,7 @@ bool DescriptorScriptPubKeyMan::TopUp(unsigned int size) if (size > 0) { target_size = size; } else { - target_size = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1); + target_size = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1); } // Calculate the new range_end diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index f030eaeb301ec..ac32c49ae198e 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -3498,7 +3498,7 @@ std::shared_ptr CWallet::Create(interfaces::Chain* chain, interfaces::C warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") + _("The wallet will avoid paying less than the minimum relay fee.")); - walletInstance->m_confirm_target = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET); + walletInstance->m_confirm_target = gArgs.GetIntArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET); walletInstance->m_spend_zero_conf_change = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE); walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n", Ticks(SteadyClock::now() - start)); @@ -3617,7 +3617,7 @@ bool CWallet::AttachChain(const std::shared_ptr& walletInstance, interf // No need to read and scan block if block was created before // our wallet birthday (as adjusted for block time variability) // unless a full rescan was requested - if (gArgs.GetArg("-rescan", 0) != 2) { + if (gArgs.GetIntArg("-rescan", 0) != 2) { std::optional time_first_key; for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) { int64_t time = spk_man->GetTimeFirstKey(); @@ -3731,7 +3731,7 @@ bool CWallet::InitAutoBackup() if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) return true; - nWalletBackups = gArgs.GetArg("-createwalletbackups", 10); + nWalletBackups = gArgs.GetIntArg("-createwalletbackups", 10); nWalletBackups = std::max(0, std::min(10, nWalletBackups)); return true; @@ -4095,7 +4095,7 @@ bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool fForMixingOnl if(nWalletBackups == -2) { TopUpKeyPool(); WalletLogPrintf("Keypool replenished, re-initializing automatic backups.\n"); - nWalletBackups = gArgs.GetArg("-createwalletbackups", 10); + nWalletBackups = gArgs.GetIntArg("-createwalletbackups", 10); } return true; } diff --git a/src/zmq/zmqnotificationinterface.cpp b/src/zmq/zmqnotificationinterface.cpp index eaf83097ea6f0..887c48b5b9bfc 100644 --- a/src/zmq/zmqnotificationinterface.cpp +++ b/src/zmq/zmqnotificationinterface.cpp @@ -61,7 +61,7 @@ std::unique_ptr CZMQNotificationInterface::Create() std::unique_ptr notifier = factory(); notifier->SetType(entry.first); notifier->SetAddress(address); - notifier->SetOutboundMessageHighWaterMark(static_cast(gArgs.GetArg(arg + "hwm", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM))); + notifier->SetOutboundMessageHighWaterMark(static_cast(gArgs.GetIntArg(arg + "hwm", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM))); notifiers.push_back(std::move(notifier)); } } From 3f8593d176251ff6ef18bd8ec6cc7634ba7b583a Mon Sep 17 00:00:00 2001 From: Kittywhiskers Van Gogh <63189531+kwvg@users.noreply.github.com> Date: Mon, 27 Jan 2025 12:24:38 +0000 Subject: [PATCH 03/16] merge bitcoin#23242: Prefix makefile variables with QT_ --- src/Makefile.qt.include | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Makefile.qt.include b/src/Makefile.qt.include index c1ac84cacf6c8..2d3342b1d4de6 100644 --- a/src/Makefile.qt.include +++ b/src/Makefile.qt.include @@ -181,7 +181,7 @@ BITCOIN_QT_H = \ qt/walletview.h \ qt/winshutdownmonitor.h -RES_ICONS = \ +QT_RES_ICONS = \ qt/res/icons/dash.ico \ qt/res/icons/dash_testnet.ico \ qt/res/icons/dash.png \ @@ -286,7 +286,7 @@ if ENABLE_WALLET BITCOIN_QT_CPP += $(BITCOIN_QT_WALLET_CPP) endif # ENABLE_WALLET -RES_IMAGES = \ +QT_RES_IMAGES = \ qt/res/images/arrow_down_dark.png \ qt/res/images/arrow_down_light.png \ qt/res/images/arrow_left_dark.png \ @@ -337,13 +337,13 @@ RES_IMAGES = \ qt/res/images/radio_checked_disabled_light.png \ qt/res/images/splash.png -RES_CSS = \ +QT_RES_CSS = \ qt/res/css/dark.css \ qt/res/css/general.css \ qt/res/css/light.css \ qt/res/css/traditional.css -RES_FONTS = \ +QT_RES_FONTS = \ qt/res/fonts/Montserrat/Montserrat-Black.otf \ qt/res/fonts/Montserrat/Montserrat-BlackItalic.otf \ qt/res/fonts/Montserrat/Montserrat-Bold.otf \ @@ -364,9 +364,9 @@ RES_FONTS = \ qt/res/fonts/Montserrat/Montserrat-ThinItalic.otf \ qt/res/fonts/RobotoMono-Bold.ttf -RES_ANIMATION = $(wildcard $(srcdir)/qt/res/animation/spinner-*.png) +QT_RES_ANIMATION = $(wildcard $(srcdir)/qt/res/animation/spinner-*.png) -BITCOIN_RC = qt/res/dash-qt-res.rc +BITCOIN_QT_RC = qt/res/dash-qt-res.rc BITCOIN_QT_INCLUDES = -DQT_NO_KEYWORDS -DQT_USE_QSTRINGBUILDER @@ -376,7 +376,7 @@ qt_libbitcoinqt_a_CXXFLAGS = $(AM_CXXFLAGS) $(QT_PIE_FLAGS) qt_libbitcoinqt_a_OBJCXXFLAGS = $(AM_OBJCXXFLAGS) $(QT_PIE_FLAGS) qt_libbitcoinqt_a_SOURCES = $(BITCOIN_QT_CPP) $(BITCOIN_QT_H) $(QT_FORMS_UI) \ - $(QT_QRC) $(QT_QRC_LOCALE) $(QT_TS) $(RES_ICONS) $(RES_IMAGES) $(RES_CSS) $(RES_FONTS) $(RES_ANIMATION) + $(QT_QRC) $(QT_QRC_LOCALE) $(QT_TS) $(QT_RES_ICONS) $(QT_RES_IMAGES) $(QT_RES_CSS) $(QT_RES_FONTS) $(QT_RES_ANIMATION) if TARGET_DARWIN qt_libbitcoinqt_a_SOURCES += $(BITCOIN_MM) endif @@ -399,7 +399,7 @@ bitcoin_qt_cxxflags = $(AM_CXXFLAGS) $(QT_PIE_FLAGS) bitcoin_qt_sources = qt/main.cpp if TARGET_WINDOWS - bitcoin_qt_sources += $(BITCOIN_RC) + bitcoin_qt_sources += $(BITCOIN_QT_RC) endif bitcoin_qt_ldadd = qt/libbitcoinqt.a $(LIBBITCOIN_SERVER) if ENABLE_WALLET @@ -449,7 +449,7 @@ $(QT_QRC_LOCALE_CPP): $(QT_QRC_LOCALE) $(QT_QM) $(AM_V_GEN) QT_SELECT=$(QT_SELECT) $(RCC) -name dash_locale --format-version 1 $(@D)/temp_$( $@ @rm $(@D)/temp_$( $@ From b88769e201c37d5a8a285fec5e3d0dd4c2fb87a0 Mon Sep 17 00:00:00 2001 From: Kittywhiskers Van Gogh <63189531+kwvg@users.noreply.github.com> Date: Thu, 25 Apr 2019 11:09:57 -0400 Subject: [PATCH 04/16] merge bitcoin#23155: various fixups for dumptxoutset --- src/rpc/blockchain.cpp | 27 ++++++++++++++++++++++----- src/rpc/blockchain.h | 8 +++++++- src/test/util/chainstate.h | 3 ++- test/functional/rpc_dumptxoutset.py | 4 ++++ 4 files changed, 35 insertions(+), 7 deletions(-) diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 76057d0785b09..1bf709aa7e4aa 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -16,11 +16,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -2577,6 +2579,8 @@ static RPCHelpMan dumptxoutset() {RPCResult::Type::STR_HEX, "base_hash", "the hash of the base of the snapshot"}, {RPCResult::Type::NUM, "base_height", "the height of the base of the snapshot"}, {RPCResult::Type::STR, "path", "the absolute path that the snapshot was written to"}, + {RPCResult::Type::STR_HEX, "txoutset_hash", "the hash of the UTXO set contents"}, + {RPCResult::Type::NUM, "nchaintx", "the number of transactions in the chain up to and including the base block"}, } }, RPCExamples{ @@ -2600,8 +2604,8 @@ static RPCHelpMan dumptxoutset() FILE* file{fsbridge::fopen(temppath, "wb")}; CAutoFile afile{file, SER_DISK, CLIENT_VERSION}; NodeContext& node = EnsureAnyNodeContext(request.context); - const ChainstateManager& chainman = EnsureChainman(node); - UniValue result = CreateUTXOSnapshot(node, chainman.ActiveChainstate(), afile); + UniValue result = CreateUTXOSnapshot( + node, node.chainman->ActiveChainstate(), afile, path, temppath); fs::rename(temppath, path); result.pushKV("path", path.u8string()); @@ -2610,10 +2614,15 @@ static RPCHelpMan dumptxoutset() }; } -UniValue CreateUTXOSnapshot(NodeContext& node, CChainState& chainstate, CAutoFile& afile) +UniValue CreateUTXOSnapshot( + NodeContext& node, + CChainState& chainstate, + CAutoFile& afile, + const fs::path& path, + const fs::path& temppath) { std::unique_ptr pcursor; - CCoinsStats stats{CoinStatsHashType::NONE}; + CCoinsStats stats{CoinStatsHashType::HASH_SERIALIZED}; const CBlockIndex* tip; { @@ -2641,6 +2650,10 @@ UniValue CreateUTXOSnapshot(NodeContext& node, CChainState& chainstate, CAutoFil tip = CHECK_NONFATAL(chainstate.m_blockman.LookupBlockIndex(stats.hashBlock)); } + LOG_TIME_SECONDS(strprintf("writing UTXO snapshot at height %s (%s) to file %s (via %s)", + tip->nHeight, tip->GetBlockHash().ToString(), + fs::PathToString(path), fs::PathToString(temppath))); + SnapshotMetadata metadata{tip->GetBlockHash(), stats.coins_count, tip->nChainTx}; afile << metadata; @@ -2666,7 +2679,11 @@ UniValue CreateUTXOSnapshot(NodeContext& node, CChainState& chainstate, CAutoFil result.pushKV("coins_written", stats.coins_count); result.pushKV("base_hash", tip->GetBlockHash().ToString()); result.pushKV("base_height", tip->nHeight); - + result.pushKV("path", path.u8string()); + result.pushKV("txoutset_hash", stats.hashSerialized.ToString()); + // Cast required because univalue doesn't have serialization specified for + // `unsigned int`, nChainTx's type. + result.pushKV("nchaintx", uint64_t{tip->nChainTx}); return result; } diff --git a/src/rpc/blockchain.h b/src/rpc/blockchain.h index 4cd5c01a4d88b..b282fa28951c0 100644 --- a/src/rpc/blockchain.h +++ b/src/rpc/blockchain.h @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -55,6 +56,11 @@ void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, * Helper to create UTXO snapshots given a chainstate and a file handle. * @return a UniValue map containing metadata about the snapshot. */ -UniValue CreateUTXOSnapshot(NodeContext& node, CChainState& chainstate, CAutoFile& afile); +UniValue CreateUTXOSnapshot( + NodeContext& node, + CChainState& chainstate, + CAutoFile& afile, + const fs::path& path, + const fs::path& tmppath); #endif // BITCOIN_RPC_BLOCKCHAIN_H diff --git a/src/test/util/chainstate.h b/src/test/util/chainstate.h index e95573022c283..e3d2b417c9a22 100644 --- a/src/test/util/chainstate.h +++ b/src/test/util/chainstate.h @@ -34,7 +34,8 @@ CreateAndActivateUTXOSnapshot(NodeContext& node, const fs::path root, F malleati FILE* outfile{fsbridge::fopen(snapshot_path, "wb")}; CAutoFile auto_outfile{outfile, SER_DISK, CLIENT_VERSION}; - UniValue result = CreateUTXOSnapshot(node, node.chainman->ActiveChainstate(), auto_outfile); + UniValue result = CreateUTXOSnapshot( + node, node.chainman->ActiveChainstate(), auto_outfile, snapshot_path, snapshot_path); BOOST_TEST_MESSAGE( "Wrote UTXO snapshot to " << fs::PathToString(snapshot_path.make_preferred()) << ": " << result.write()); diff --git a/test/functional/rpc_dumptxoutset.py b/test/functional/rpc_dumptxoutset.py index c0e5519233f1f..e285bffe1d2c6 100755 --- a/test/functional/rpc_dumptxoutset.py +++ b/test/functional/rpc_dumptxoutset.py @@ -45,6 +45,10 @@ def run_test(self): assert_equal( digest, '32f1d4b7f643c97e88c540f431e8277fdd9332c3dea260b046c93787745e35b0') + assert_equal( + out['txoutset_hash'], '970c1bc05f0d0920cc1eae5854860f90f85453ec815e710f40135ec149345ade') + assert_equal(out['nchaintx'], 101) + # Specifying a path to an existing file will fail. assert_raises_rpc_error( -8, '{} already exists'.format(FILENAME), node.dumptxoutset, FILENAME) From 650ee25809108f793fa40130748e59ce5b5cd1fb Mon Sep 17 00:00:00 2001 From: Kittywhiskers Van Gogh <63189531+kwvg@users.noreply.github.com> Date: Wed, 25 Aug 2021 16:37:14 +0900 Subject: [PATCH 05/16] merge bitcoin#22787: actual immutable pointing --- src/qt/test/addressbooktests.cpp | 2 +- src/qt/test/wallettests.cpp | 2 +- src/rpc/coinjoin.cpp | 8 ++--- src/rpc/evo.cpp | 2 +- src/rpc/governance.cpp | 4 +-- src/rpc/masternode.cpp | 2 +- src/wallet/load.cpp | 2 +- src/wallet/rpcdump.cpp | 2 +- src/wallet/rpcwallet.cpp | 55 +++++++++++++++--------------- src/wallet/test/coinjoin_tests.cpp | 4 +-- src/wallet/test/wallet_tests.cpp | 16 ++++----- src/wallet/wallet.cpp | 6 ++-- src/wallet/wallettool.cpp | 10 +++--- 13 files changed, 57 insertions(+), 58 deletions(-) diff --git a/src/qt/test/addressbooktests.cpp b/src/qt/test/addressbooktests.cpp index fe623b8435eeb..c4a47847aa1c7 100644 --- a/src/qt/test/addressbooktests.cpp +++ b/src/qt/test/addressbooktests.cpp @@ -64,7 +64,7 @@ void TestAddAddressesToSendBook(interfaces::Node& node) { TestChain100Setup test; node.setContext(&test.m_node); - std::shared_ptr wallet = std::make_shared(node.context()->chain.get(), node.context()->coinjoin_loader.get(), "", CreateMockWalletDatabase()); + const std::shared_ptr wallet = std::make_shared(node.context()->chain.get(), node.context()->coinjoin_loader.get(), "", CreateMockWalletDatabase()); wallet->SetupLegacyScriptPubKeyMan(); wallet->LoadWallet(); diff --git a/src/qt/test/wallettests.cpp b/src/qt/test/wallettests.cpp index fe16db6c4e7e7..effb354fd18e1 100644 --- a/src/qt/test/wallettests.cpp +++ b/src/qt/test/wallettests.cpp @@ -109,7 +109,7 @@ void TestGUI(interfaces::Node& node) test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey())); } node.setContext(&test.m_node); - std::shared_ptr wallet = std::make_shared(node.context()->chain.get(), node.context()->coinjoin_loader.get(), "", CreateMockWalletDatabase()); + const std::shared_ptr wallet = std::make_shared(node.context()->chain.get(), node.context()->coinjoin_loader.get(), "", CreateMockWalletDatabase()); AddWallet(wallet); wallet->LoadWallet(); { diff --git a/src/rpc/coinjoin.cpp b/src/rpc/coinjoin.cpp index 81f6c3793346b..6cea9ab6f0195 100644 --- a/src/rpc/coinjoin.cpp +++ b/src/rpc/coinjoin.cpp @@ -73,7 +73,7 @@ static RPCHelpMan coinjoin_reset() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return NullUniValue; const NodeContext& node = EnsureAnyNodeContext(request.context); @@ -107,7 +107,7 @@ static RPCHelpMan coinjoin_start() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return NullUniValue; const NodeContext& node = EnsureAnyNodeContext(request.context); @@ -152,7 +152,7 @@ static RPCHelpMan coinjoin_stop() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return NullUniValue; const NodeContext& node = EnsureAnyNodeContext(request.context); @@ -441,7 +441,7 @@ static RPCHelpMan getcoinjoininfo() obj.pushKV("queue_size", node.cj_ctx->queueman->GetQueueSize()); - std::shared_ptr const wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr wallet = GetWalletForJSONRPCRequest(request); if (!wallet) { return obj; } diff --git a/src/rpc/evo.cpp b/src/rpc/evo.cpp index 1a6868c7b9cf0..b10f6babcd865 100644 --- a/src/rpc/evo.cpp +++ b/src/rpc/evo.cpp @@ -855,7 +855,7 @@ static RPCHelpMan protx_register_submit() CChainstateHelper& chain_helper = *CHECK_NONFATAL(node.chain_helper); - std::shared_ptr const wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return NullUniValue; EnsureWalletIsUnlocked(*wallet); diff --git a/src/rpc/governance.cpp b/src/rpc/governance.cpp index e031721e0a1ca..1dd030e8b4f90 100644 --- a/src/rpc/governance.cpp +++ b/src/rpc/governance.cpp @@ -519,7 +519,7 @@ static RPCHelpMan gobject_vote_many() RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return NullUniValue; const NodeContext& node = EnsureAnyNodeContext(request.context); @@ -572,7 +572,7 @@ static RPCHelpMan gobject_vote_alias() RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return NullUniValue; const NodeContext& node = EnsureAnyNodeContext(request.context); diff --git a/src/rpc/masternode.cpp b/src/rpc/masternode.cpp index 4731ce204dec4..0d4fa60ec377b 100644 --- a/src/rpc/masternode.cpp +++ b/src/rpc/masternode.cpp @@ -190,7 +190,7 @@ static RPCHelpMan masternode_outputs() RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return NullUniValue; // Find possible candidates diff --git a/src/wallet/load.cpp b/src/wallet/load.cpp index 6f5b661efd728..a02802664bfc4 100644 --- a/src/wallet/load.cpp +++ b/src/wallet/load.cpp @@ -116,7 +116,7 @@ bool LoadWallets(interfaces::Chain& chain, interfaces::CoinJoin::Loader& coinjoi continue; } chain.initMessage(_("Loading wallet…").translated); - std::shared_ptr pwallet = database ? CWallet::Create(&chain, &coinjoin_loader, name, std::move(database), options.create_flags, error_string, warnings) : nullptr; + const std::shared_ptr pwallet = database ? CWallet::Create(&chain, &coinjoin_loader, name, std::move(database), options.create_flags, error_string, warnings) : nullptr; if (!warnings.empty()) chain.initWarning(Join(warnings, Untranslated("\n"))); if (!pwallet) { chain.initError(error_string); diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index 5ea8eb0fc303a..2edd2148216b6 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -1968,7 +1968,7 @@ RPCHelpMan listdescriptors() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return NullUniValue; if (!wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) { diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 03c20ffd10746..88250ec9e744b 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -103,7 +103,7 @@ std::shared_ptr GetWalletForJSONRPCRequest(const JSONRPCRequest& reques std::string wallet_name; if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) { - std::shared_ptr pwallet = GetWallet(wallet_name); + const std::shared_ptr pwallet = GetWallet(wallet_name); if (!pwallet) throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Requested wallet does not exist or is not loaded"); return pwallet; } @@ -561,7 +561,7 @@ static RPCHelpMan listaddressgroupings() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block @@ -615,7 +615,7 @@ static RPCHelpMan listaddressbalances() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; LOCK(pwallet->cs_wallet); @@ -662,7 +662,7 @@ static RPCHelpMan signmessage() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; LOCK(pwallet->cs_wallet); @@ -767,7 +767,7 @@ static RPCHelpMan getreceivedbyaddress() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block @@ -806,7 +806,7 @@ static RPCHelpMan getreceivedbylabel() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block @@ -847,7 +847,7 @@ static RPCHelpMan getbalance() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block @@ -891,7 +891,7 @@ static RPCHelpMan getunconfirmedbalance() RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block @@ -1278,7 +1278,7 @@ static RPCHelpMan listreceivedbyaddress() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block @@ -1321,7 +1321,7 @@ static RPCHelpMan listreceivedbylabel() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block @@ -1510,7 +1510,7 @@ static RPCHelpMan listtransactions() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block @@ -1627,7 +1627,7 @@ static RPCHelpMan listsinceblock() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; const CWallet& wallet = *pwallet; @@ -1767,7 +1767,7 @@ static RPCHelpMan gettransaction() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block @@ -1878,7 +1878,7 @@ static RPCHelpMan backupwallet() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block @@ -2366,7 +2366,7 @@ static RPCHelpMan listlockunspent() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; LOCK(pwallet->cs_wallet); @@ -2441,7 +2441,7 @@ static RPCHelpMan setcoinjoinrounds() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return NullUniValue; int nRounds = request.params[0].get_int(); @@ -2472,7 +2472,7 @@ static RPCHelpMan setcoinjoinamount() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return NullUniValue; int nAmount = request.params[0].get_int(); @@ -2517,9 +2517,9 @@ static RPCHelpMan getbalances() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const rpc_wallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr rpc_wallet = GetWalletForJSONRPCRequest(request); if (!rpc_wallet) return NullUniValue; - CWallet& wallet = *rpc_wallet; + const CWallet& wallet = *rpc_wallet; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now @@ -2606,7 +2606,7 @@ static RPCHelpMan getwalletinfo() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block @@ -3060,7 +3060,7 @@ static RPCHelpMan createwallet() options.create_passphrase = passphrase; bilingual_str error; std::optional load_on_start = request.params[6].isNull() ? std::nullopt : std::optional(request.params[6].get_bool()); - std::shared_ptr wallet = CreateWallet(*context.chain, *context.m_coinjoin_loader, request.params[0].get_str(), load_on_start, options, status, error, warnings); + const std::shared_ptr wallet = CreateWallet(*context.chain, *context.m_coinjoin_loader, request.params[0].get_str(), load_on_start, options, status, error, warnings); if (!wallet) { RPCErrorCode code = status == DatabaseStatus::FAILED_ENCRYPT ? RPC_WALLET_ENCRYPTION_FAILED : RPC_WALLET_ERROR; throw JSONRPCError(code, error.original); @@ -3238,7 +3238,7 @@ static RPCHelpMan listunspent() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; int nMinDepth = 1; @@ -3666,10 +3666,9 @@ RPCHelpMan signrawtransactionwithwallet() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VSTR}, true); - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; CMutableTransaction mtx; @@ -3980,7 +3979,7 @@ RPCHelpMan getaddressinfo() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; LOCK(pwallet->cs_wallet); @@ -4090,7 +4089,7 @@ static RPCHelpMan getaddressesbylabel() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; LOCK(pwallet->cs_wallet); @@ -4151,7 +4150,7 @@ static RPCHelpMan listlabels() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; LOCK(pwallet->cs_wallet); @@ -4483,7 +4482,7 @@ RPCHelpMan walletprocesspsbt() { RPCTypeCheck(request.params, {UniValue::VSTR}); - std::shared_ptr const pwallet = GetWalletForJSONRPCRequest(request); + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; const CWallet& wallet{*pwallet}; diff --git a/src/wallet/test/coinjoin_tests.cpp b/src/wallet/test/coinjoin_tests.cpp index 9335ae0098e9b..655262e3bded4 100644 --- a/src/wallet/test/coinjoin_tests.cpp +++ b/src/wallet/test/coinjoin_tests.cpp @@ -129,9 +129,9 @@ class CTransactionBuilderTestSetup : public TestChain100Setup { public: CTransactionBuilderTestSetup() + : wallet{std::make_unique(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateMockWalletDatabase())} { CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); - wallet = std::make_unique(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateMockWalletDatabase()); wallet->SetupLegacyScriptPubKeyMan(); wallet->LoadWallet(); AddWallet(wallet); @@ -151,7 +151,7 @@ class CTransactionBuilderTestSetup : public TestChain100Setup RemoveWallet(wallet, std::nullopt); } - std::shared_ptr wallet; + const std::shared_ptr wallet; CWalletTx& AddTxToChain(uint256 nTxHash) { diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp index b6824bd1e3d2e..54bc114aaa247 100644 --- a/src/wallet/test/wallet_tests.cpp +++ b/src/wallet/test/wallet_tests.cpp @@ -53,7 +53,7 @@ namespace { constexpr CAmount fallbackFee = 1000; } // anonymous namespace -static std::shared_ptr TestLoadWallet(interfaces::Chain* chain, interfaces::CoinJoin::Loader* coinjoin_loader) +static const std::shared_ptr TestLoadWallet(interfaces::Chain* chain, interfaces::CoinJoin::Loader* coinjoin_loader) { DatabaseOptions options; DatabaseStatus status; @@ -223,7 +223,7 @@ BOOST_FIXTURE_TEST_CASE(importmulti_rescan, TestChain100Setup) // before the missing block, and success for a key whose creation time is // after. { - std::shared_ptr wallet = std::make_shared(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateDummyWalletDatabase()); + const std::shared_ptr wallet = std::make_shared(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateDummyWalletDatabase()); wallet->SetupLegacyScriptPubKeyMan(); WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash())); AddWallet(wallet); @@ -284,7 +284,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) // Import key into wallet and call dumpwallet to create backup file. { - std::shared_ptr wallet = std::make_shared(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateDummyWalletDatabase()); + const std::shared_ptr wallet = std::make_shared(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateDummyWalletDatabase()); { auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan(); LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore); @@ -305,7 +305,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME // were scanned, and no prior blocks were scanned. { - std::shared_ptr wallet = std::make_shared(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateDummyWalletDatabase()); + const std::shared_ptr wallet = std::make_shared(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateDummyWalletDatabase()); LOCK(wallet->cs_wallet); wallet->SetupLegacyScriptPubKeyMan(); @@ -330,7 +330,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) // Verify getaddressinfo RPC produces more or less expected results BOOST_FIXTURE_TEST_CASE(rpc_getaddressinfo, TestChain100Setup) { - std::shared_ptr wallet = std::make_shared(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateMockWalletDatabase()); + const std::shared_ptr wallet = std::make_shared(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateMockWalletDatabase()); wallet->SetupLegacyScriptPubKeyMan(); AddWallet(wallet); CoreContext context{m_node}; @@ -708,9 +708,9 @@ class CreateTransactionTestSetup : public TestChain100Setup const std::string strMaxFeeExceeded = "Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)"; CreateTransactionTestSetup() + : wallet{std::make_unique(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateMockWalletDatabase())} { CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); - wallet = std::make_unique(m_node.chain.get(), m_node.coinjoin_loader.get(), "", CreateMockWalletDatabase()); wallet->LoadWallet(); AddWallet(wallet); AddKey(*wallet, coinbaseKey); @@ -729,7 +729,7 @@ class CreateTransactionTestSetup : public TestChain100Setup RemoveWallet(wallet, std::nullopt); } - std::shared_ptr wallet; + const std::shared_ptr wallet; CCoinControl coinControl; template @@ -1195,7 +1195,7 @@ BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup) node.fee_estimator = std::make_unique(); node.mempool = std::make_unique(node.fee_estimator.get()); auto chain = interfaces::MakeChain(node); - std::shared_ptr wallet = std::make_shared(chain.get(), m_node.coinjoin_loader.get(), "", CreateDummyWalletDatabase()); + const std::shared_ptr wallet = std::make_shared(chain.get(), m_node.coinjoin_loader.get(), "", CreateDummyWalletDatabase()); wallet->SetupLegacyScriptPubKeyMan(); wallet->SetMinVersion(FEATURE_LATEST); wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index ac32c49ae198e..0ad8540e146c7 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -239,7 +239,7 @@ std::shared_ptr LoadWalletInternal(interfaces::Chain& chain, interfaces } chain.initMessage(_("Loading wallet…").translated); - std::shared_ptr wallet = CWallet::Create(&chain, &coinjoin_loader, name, std::move(database), options.create_flags, error, warnings); + const std::shared_ptr wallet = CWallet::Create(&chain, &coinjoin_loader, name, std::move(database), options.create_flags, error, warnings); if (!wallet) { error = Untranslated("Wallet loading failed.") + Untranslated(" ") + error; status = DatabaseStatus::FAILED_LOAD; @@ -305,7 +305,7 @@ std::shared_ptr CreateWallet(interfaces::Chain& chain, interfaces::Coin // Make the wallet chain.initMessage(_("Loading wallet…").translated); - std::shared_ptr wallet = CWallet::Create(&chain, &coinjoin_loader, name, std::move(database), wallet_creation_flags, error, warnings); + const std::shared_ptr wallet = CWallet::Create(&chain, &coinjoin_loader, name, std::move(database), wallet_creation_flags, error, warnings); if (!wallet) { error = Untranslated("Wallet creation failed.") + Untranslated(" ") + error; status = DatabaseStatus::FAILED_CREATE; @@ -3258,7 +3258,7 @@ std::shared_ptr CWallet::Create(interfaces::Chain* chain, interfaces::C const auto start{SteadyClock::now()}; // TODO: Can't use std::make_shared because we need a custom deleter but // should be possible to use std::allocate_shared. - std::shared_ptr walletInstance(new CWallet(chain, coinjoin_loader, name, std::move(database)), ReleaseWallet); + const std::shared_ptr walletInstance(new CWallet(chain, coinjoin_loader, name, std::move(database)), ReleaseWallet); // TODO: refactor this condition: validation of error looks like workaround if (!walletInstance->AutoBackupWallet(fs::PathFromString(walletFile), error, warnings) && !error.original.empty()) { return nullptr; diff --git a/src/wallet/wallettool.cpp b/src/wallet/wallettool.cpp index 98271775c527b..1c183c9ed9c64 100644 --- a/src/wallet/wallettool.cpp +++ b/src/wallet/wallettool.cpp @@ -56,7 +56,7 @@ static void WalletCreate(CWallet* wallet_instance, uint64_t wallet_creation_flag wallet_instance->TopUpKeyPool(); } -static std::shared_ptr MakeWallet(const std::string& name, const fs::path& path, DatabaseOptions options) +static const std::shared_ptr MakeWallet(const std::string& name, const fs::path& path, DatabaseOptions options) { DatabaseStatus status; bilingual_str error; @@ -149,7 +149,7 @@ bool ExecuteWalletToolFunc(const ArgsManager& args, const std::string& command) options.require_format = DatabaseFormat::SQLITE; } - std::shared_ptr wallet_instance = MakeWallet(name, path, options); + const std::shared_ptr wallet_instance = MakeWallet(name, path, options); if (wallet_instance) { WalletShowInfo(wallet_instance.get()); wallet_instance->Close(); @@ -157,7 +157,7 @@ bool ExecuteWalletToolFunc(const ArgsManager& args, const std::string& command) } else if (command == "info") { DatabaseOptions options; options.require_existing = true; - std::shared_ptr wallet_instance = MakeWallet(name, path, options); + const std::shared_ptr wallet_instance = MakeWallet(name, path, options); if (!wallet_instance) return false; WalletShowInfo(wallet_instance.get()); wallet_instance->Close(); @@ -183,7 +183,7 @@ bool ExecuteWalletToolFunc(const ArgsManager& args, const std::string& command) #ifdef USE_BDB DatabaseOptions options; options.require_existing = true; - std::shared_ptr wallet_instance = MakeWallet(name, path, options); + const std::shared_ptr wallet_instance = MakeWallet(name, path, options); if (wallet_instance == nullptr) return false; std::vector vHash; @@ -210,7 +210,7 @@ bool ExecuteWalletToolFunc(const ArgsManager& args, const std::string& command) } else if (command == "dump") { DatabaseOptions options; options.require_existing = true; - std::shared_ptr wallet_instance = MakeWallet(name, path, options); + const std::shared_ptr wallet_instance = MakeWallet(name, path, options); if (!wallet_instance) return false; bilingual_str error; bool ret = DumpWallet(*wallet_instance, error); From 98d21f124967cacc3d1bfdc28fb89710b5a88892 Mon Sep 17 00:00:00 2001 From: Kittywhiskers Van Gogh <63189531+kwvg@users.noreply.github.com> Date: Tue, 28 Jan 2025 03:25:01 +0000 Subject: [PATCH 06/16] merge bitcoin#23602: Split stuff from rpcwallet --- src/Makefile.am | 1 + src/wallet/rpc/signmessage.cpp | 68 ++++++++++++++++++++++++++++++++++ src/wallet/rpcwallet.cpp | 59 +---------------------------- src/wallet/rpcwallet.h | 2 +- 4 files changed, 72 insertions(+), 58 deletions(-) create mode 100644 src/wallet/rpc/signmessage.cpp diff --git a/src/Makefile.am b/src/Makefile.am index 090b8924fe419..37b95333f1135 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -600,6 +600,7 @@ libbitcoin_wallet_a_SOURCES = \ wallet/interfaces.cpp \ wallet/load.cpp \ wallet/receive.cpp \ + wallet/rpc/signmessage.cpp \ wallet/rpcdump.cpp \ wallet/rpcwallet.cpp \ wallet/scriptpubkeyman.cpp \ diff --git a/src/wallet/rpc/signmessage.cpp b/src/wallet/rpc/signmessage.cpp new file mode 100644 index 0000000000000..a9ebf4c33f7b2 --- /dev/null +++ b/src/wallet/rpc/signmessage.cpp @@ -0,0 +1,68 @@ +// Copyright (c) 2011-2021 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include +#include +#include +#include +#include + +#include + +RPCHelpMan signmessage() +{ + return RPCHelpMan{"signmessage", + "\nSign a message with the private key of an address" + + HELP_REQUIRING_PASSPHRASE, + { + {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The Dash address to use for the private key."}, + {"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message to create a signature of."}, + }, + RPCResult{ + RPCResult::Type::STR, "signature", "The signature of the message encoded in base 64" + }, + RPCExamples{ + "\nUnlock the wallet for 30 seconds\n" + + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + + "\nCreate the signature\n" + + HelpExampleCli("signmessage", "\"" + EXAMPLE_ADDRESS[0] + "\" \"my message\"") + + "\nVerify the signature\n" + + HelpExampleCli("verifymessage", "\"" + EXAMPLE_ADDRESS[0] + "\" \"signature\" \"my message\"") + + "\nAs a JSON-RPC call\n" + + HelpExampleRpc("signmessage", "\"" + EXAMPLE_ADDRESS[0] + "\", \"my message\"") + }, + [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue + { + const std::shared_ptr pwallet = GetWalletForJSONRPCRequest(request); + if (!pwallet) return NullUniValue; + + LOCK(pwallet->cs_wallet); + + EnsureWalletIsUnlocked(*pwallet); + + std::string strAddress = request.params[0].get_str(); + std::string strMessage = request.params[1].get_str(); + + CTxDestination dest = DecodeDestination(strAddress); + if (!IsValidDestination(dest)) { + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address"); + } + + const PKHash* pkhash = std::get_if(&dest); + if (!pkhash) { + throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); + } + + std::string signature; + SigningResult err = pwallet->SignMessage(strMessage, *pkhash, signature); + if (err == SigningResult::SIGNING_FAILED) { + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, SigningResultString(err)); + } else if (err != SigningResult::OK) { + throw JSONRPCError(RPC_WALLET_ERROR, SigningResultString(err)); + } + + return signature; + }, + }; +} diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 88250ec9e744b..82bfaec6defc4 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -20,7 +20,6 @@ #include