Skip to content

Commit c00000d

Browse files
author
MarcoFalke
committed
rpc: Add MaybeArg() and Arg() default helper
1 parent cd5d2f5 commit c00000d

File tree

5 files changed

+113
-8
lines changed

5 files changed

+113
-8
lines changed

src/rpc/mining.cpp

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ static RPCHelpMan getnetworkhashps()
110110
{
111111
ChainstateManager& chainman = EnsureAnyChainman(request.context);
112112
LOCK(cs_main);
113-
return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].getInt<int>() : 120, !request.params[1].isNull() ? request.params[1].getInt<int>() : -1, chainman.ActiveChain());
113+
return GetNetworkHashPS(self.Arg<int>(0), self.Arg<int>(1), chainman.ActiveChain());
114114
},
115115
};
116116
}
@@ -217,12 +217,12 @@ static RPCHelpMan generatetodescriptor()
217217
"\nGenerate 11 blocks to mydesc\n" + HelpExampleCli("generatetodescriptor", "11 \"mydesc\"")},
218218
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
219219
{
220-
const int num_blocks{request.params[0].getInt<int>()};
221-
const uint64_t max_tries{request.params[2].isNull() ? DEFAULT_MAX_TRIES : request.params[2].getInt<int>()};
220+
const auto num_blocks{self.Arg<int>(0)};
221+
const auto max_tries{self.Arg<uint64_t>(2)};
222222

223223
CScript coinbase_script;
224224
std::string error;
225-
if (!getScriptFromDescriptor(request.params[1].get_str(), coinbase_script, error)) {
225+
if (!getScriptFromDescriptor(self.Arg<std::string>(1), coinbase_script, error)) {
226226
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
227227
}
228228

@@ -468,9 +468,10 @@ static RPCHelpMan prioritisetransaction()
468468
LOCK(cs_main);
469469

470470
uint256 hash(ParseHashV(request.params[0], "txid"));
471+
const auto dummy{self.MaybeArg<double>(1)};
471472
CAmount nAmount = request.params[2].getInt<int64_t>();
472473

473-
if (!(request.params[1].isNull() || request.params[1].get_real() == 0)) {
474+
if (dummy && *dummy != 0) {
474475
throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0.");
475476
}
476477

src/rpc/util.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -609,7 +609,10 @@ UniValue RPCHelpMan::HandleRequest(const JSONRPCRequest& request) const
609609
if (!arg_mismatch.empty()) {
610610
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Wrong type passed:\n%s", arg_mismatch.write(4)));
611611
}
612+
CHECK_NONFATAL(m_req == nullptr);
613+
m_req = &request;
612614
UniValue ret = m_fun(*this, request);
615+
m_req = nullptr;
613616
if (gArgs.GetBoolArg("-rpcdoccheck", DEFAULT_RPC_DOC_CHECK)) {
614617
UniValue mismatch{UniValue::VARR};
615618
for (const auto& res : m_results.m_results) {
@@ -635,6 +638,49 @@ UniValue RPCHelpMan::HandleRequest(const JSONRPCRequest& request) const
635638
return ret;
636639
}
637640

641+
using CheckFn = void(const RPCArg&);
642+
static const UniValue* DetailMaybeArg(CheckFn* check, const std::vector<RPCArg>& params, const JSONRPCRequest* req, size_t i)
643+
{
644+
CHECK_NONFATAL(i < params.size());
645+
const UniValue& arg{CHECK_NONFATAL(req)->params[i]};
646+
const RPCArg& param{params.at(i)};
647+
if (check) check(param);
648+
649+
if (!arg.isNull()) return &arg;
650+
if (!std::holds_alternative<RPCArg::Default>(param.m_fallback)) return nullptr;
651+
return &std::get<RPCArg::Default>(param.m_fallback);
652+
}
653+
654+
static void CheckRequiredOrDefault(const RPCArg& param)
655+
{
656+
// Must use `Arg<Type>(i)` to get the argument or its default value.
657+
const bool required{
658+
std::holds_alternative<RPCArg::Optional>(param.m_fallback) && RPCArg::Optional::NO == std::get<RPCArg::Optional>(param.m_fallback),
659+
};
660+
CHECK_NONFATAL(required || std::holds_alternative<RPCArg::Default>(param.m_fallback));
661+
}
662+
663+
#define TMPL_INST(check_param, ret_type, return_code) \
664+
template <> \
665+
ret_type RPCHelpMan::ArgValue<ret_type>(size_t i) const \
666+
{ \
667+
const UniValue* maybe_arg{ \
668+
DetailMaybeArg(check_param, m_args, m_req, i), \
669+
}; \
670+
return return_code \
671+
} \
672+
void force_semicolon(ret_type)
673+
674+
// Optional arg (without default). Can also be called on required args, if needed.
675+
TMPL_INST(nullptr, std::optional<double>, maybe_arg ? std::optional{maybe_arg->get_real()} : std::nullopt;);
676+
TMPL_INST(nullptr, std::optional<bool>, maybe_arg ? std::optional{maybe_arg->get_bool()} : std::nullopt;);
677+
TMPL_INST(nullptr, const std::string*, maybe_arg ? &maybe_arg->get_str() : nullptr;);
678+
679+
// Required arg or optional arg with default value.
680+
TMPL_INST(CheckRequiredOrDefault, int, CHECK_NONFATAL(maybe_arg)->getInt<int>(););
681+
TMPL_INST(CheckRequiredOrDefault, uint64_t, CHECK_NONFATAL(maybe_arg)->getInt<uint64_t>(););
682+
TMPL_INST(CheckRequiredOrDefault, const std::string&, CHECK_NONFATAL(maybe_arg)->get_str(););
683+
638684
bool RPCHelpMan::IsValidNumArgs(size_t num_args) const
639685
{
640686
size_t num_required_args = 0;

src/rpc/util.h

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#define BITCOIN_RPC_UTIL_H
77

88
#include <addresstype.h>
9+
#include <consensus/amount.h>
910
#include <node/transaction.h>
1011
#include <outputtype.h>
1112
#include <protocol.h>
@@ -14,13 +15,29 @@
1415
#include <rpc/request.h>
1516
#include <script/script.h>
1617
#include <script/sign.h>
18+
#include <uint256.h>
1719
#include <univalue.h>
1820
#include <util/check.h>
1921

22+
#include <cstddef>
23+
#include <cstdint>
24+
#include <functional>
25+
#include <initializer_list>
26+
#include <map>
27+
#include <optional>
2028
#include <string>
29+
#include <type_traits>
30+
#include <utility>
2131
#include <variant>
2232
#include <vector>
2333

34+
class JSONRPCRequest;
35+
enum ServiceFlags : uint64_t;
36+
enum class OutputType;
37+
enum class TransactionError;
38+
struct FlatSigningProvider;
39+
struct bilingual_str;
40+
2441
static constexpr bool DEFAULT_RPC_DOC_CHECK{
2542
#ifdef RPC_DOC_CHECK
2643
true
@@ -383,6 +400,44 @@ class RPCHelpMan
383400
RPCHelpMan(std::string name, std::string description, std::vector<RPCArg> args, RPCResults results, RPCExamples examples, RPCMethodImpl fun);
384401

385402
UniValue HandleRequest(const JSONRPCRequest& request) const;
403+
/**
404+
* Helper to get a request argument.
405+
* This function only works during m_fun(), i.e. it should only be used in
406+
* RPC method implementations. The helper internally checks whether the
407+
* user-passed argument isNull() and parses (from JSON) and returns the
408+
* user-passed argument, or the default value derived from the RPCArg
409+
* documention, or a falsy value if no default was given.
410+
*
411+
* Use Arg<Type>(i) to get the argument or its default value. Otherwise,
412+
* use MaybeArg<Type>(i) to get the optional argument or a falsy value.
413+
*
414+
* The Type passed to this helper must match the corresponding
415+
* RPCArg::Type.
416+
*/
417+
template <typename R>
418+
auto Arg(size_t i) const
419+
{
420+
// Return argument (required or with default value).
421+
if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
422+
// Return numbers by value.
423+
return ArgValue<R>(i);
424+
} else {
425+
// Return everything else by reference.
426+
return ArgValue<const R&>(i);
427+
}
428+
}
429+
template <typename R>
430+
auto MaybeArg(size_t i) const
431+
{
432+
// Return optional argument (without default).
433+
if constexpr (std::is_integral_v<R> || std::is_floating_point_v<R>) {
434+
// Return numbers by value, wrapped in optional.
435+
return ArgValue<std::optional<R>>(i);
436+
} else {
437+
// Return other types by pointer.
438+
return ArgValue<const R*>(i);
439+
}
440+
}
386441
std::string ToString() const;
387442
/** Return the named args that need to be converted from string to another JSON type */
388443
UniValue GetArgMap() const;
@@ -399,6 +454,9 @@ class RPCHelpMan
399454
const std::vector<RPCArg> m_args;
400455
const RPCResults m_results;
401456
const RPCExamples m_examples;
457+
mutable const JSONRPCRequest* m_req{nullptr}; // A pointer to the request for the duration of m_fun()
458+
template <typename R>
459+
R ArgValue(size_t i) const;
402460
};
403461

404462
/**

src/wallet/rpc/coins.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,8 @@ RPCHelpMan getbalance()
194194

195195
LOCK(pwallet->cs_wallet);
196196

197-
const UniValue& dummy_value = request.params[0];
198-
if (!dummy_value.isNull() && dummy_value.get_str() != "*") {
197+
const auto dummy_value{self.MaybeArg<std::string>(0)};
198+
if (dummy_value && *dummy_value != "*") {
199199
throw JSONRPCError(RPC_METHOD_DEPRECATED, "dummy first argument must be excluded or set to \"*\".");
200200
}
201201

src/wallet/rpc/wallet.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -478,7 +478,7 @@ static RPCHelpMan unloadwallet()
478478
// Release the "main" shared pointer and prevent further notifications.
479479
// Note that any attempt to load the same wallet would fail until the wallet
480480
// is destroyed (see CheckUniqueFileid).
481-
std::optional<bool> load_on_start = request.params[1].isNull() ? std::nullopt : std::optional<bool>(request.params[1].get_bool());
481+
std::optional<bool> load_on_start{self.MaybeArg<bool>(1)};
482482
if (!RemoveWallet(context, wallet, load_on_start, warnings)) {
483483
throw JSONRPCError(RPC_MISC_ERROR, "Requested wallet already unloaded");
484484
}

0 commit comments

Comments
 (0)