rpc, util: Add EnsureUniqueWalletName

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.
This commit is contained in:
pablomartin4btc
2025-07-07 13:39:25 -03:00
parent a8bff38236
commit b635bc0896
2 changed files with 26 additions and 0 deletions

View File

@@ -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)) {

View File

@@ -38,6 +38,11 @@ static const RPCResult RESULT_LAST_PROCESSED_BLOCK { RPCResult::Type::OBJ, "last
*/
std::shared_ptr<CWallet> 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);