From b635bc0896294af5afa1b18a35f307dfae441bb8 Mon Sep 17 00:00:00 2001 From: pablomartin4btc Date: Mon, 7 Jul 2025 13:39:25 -0300 Subject: [PATCH] rpc, util: Add EnsureUniqueWalletName MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a new function called EnsureUniqueWalletNamet that returns the selected wallet name across the RPC request endpoint and wallet_name. Supports the case where the wallet_name argument may be omitted—either when using a wallet endpoint, or when not provided at all. In the latter case, if no wallet endpoint is used, an error is raised. Internally reuses the existing implementation to avoid redundant URL decoding and logic duplication. This is a preparatory change for upcoming refactoring of unloadwallet and migratewallet, which will adopt EnsureUniqueWalletName for improved clarity and consistency. --- src/wallet/rpc/util.cpp | 21 +++++++++++++++++++++ src/wallet/rpc/util.h | 5 +++++ 2 files changed, 26 insertions(+) diff --git a/src/wallet/rpc/util.cpp b/src/wallet/rpc/util.cpp index eaca74b6e65..79703985354 100644 --- a/src/wallet/rpc/util.cpp +++ b/src/wallet/rpc/util.cpp @@ -29,6 +29,27 @@ bool GetAvoidReuseFlag(const CWallet& wallet, const UniValue& param) { return avoid_reuse; } +std::string EnsureUniqueWalletName(const JSONRPCRequest& request, const std::string* wallet_name) +{ + std::string endpoint_wallet; + if (GetWalletNameFromJSONRPCRequest(request, endpoint_wallet)) { + // wallet endpoint was used + if (wallet_name && *wallet_name != endpoint_wallet) { + throw JSONRPCError(RPC_INVALID_PARAMETER, + "The RPC endpoint wallet and the wallet name parameter specify different wallets"); + } + return endpoint_wallet; + } + + // Not a wallet endpoint; parameter must be provided + if (!wallet_name) { + throw JSONRPCError(RPC_INVALID_PARAMETER, + "Either the RPC endpoint wallet or the wallet name parameter must be provided"); + } + + return *wallet_name; +} + bool GetWalletNameFromJSONRPCRequest(const JSONRPCRequest& request, std::string& wallet_name) { if (request.URI.starts_with(WALLET_ENDPOINT_BASE)) { diff --git a/src/wallet/rpc/util.h b/src/wallet/rpc/util.h index a73fb177b3e..0c586be4a49 100644 --- a/src/wallet/rpc/util.h +++ b/src/wallet/rpc/util.h @@ -38,6 +38,11 @@ static const RPCResult RESULT_LAST_PROCESSED_BLOCK { RPCResult::Type::OBJ, "last */ std::shared_ptr GetWalletForJSONRPCRequest(const JSONRPCRequest& request); bool GetWalletNameFromJSONRPCRequest(const JSONRPCRequest& request, std::string& wallet_name); +/** + * Ensures that a wallet name is specified across the endpoint and wallet_name. + * Throws `RPC_INVALID_PARAMETER` if none or different wallet names are specified. + */ +std::string EnsureUniqueWalletName(const JSONRPCRequest& request, const std::string* wallet_name); void EnsureWalletIsUnlocked(const CWallet&); WalletContext& EnsureWalletContext(const std::any& context);