Skip to content

Commit b63428a

Browse files
committed
rpc: refactor: use more (Maybe)Arg<std::string_view>
Use the {Arg,MaybeArg}<std::string_view> helper in all places where it is a trivial change. In many places, this simplifies the logic and reduces duplication of default values.
1 parent 037830c commit b63428a

File tree

9 files changed

+69
-79
lines changed

9 files changed

+69
-79
lines changed

src/rpc/blockchain.cpp

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
#include <serialize.h>
4141
#include <streams.h>
4242
#include <sync.h>
43+
#include <tinyformat.h>
4344
#include <txdb.h>
4445
#include <txmempool.h>
4546
#include <undo.h>
@@ -60,6 +61,7 @@
6061
#include <memory>
6162
#include <mutex>
6263
#include <optional>
64+
#include <string>
6365
#include <string_view>
6466
#include <vector>
6567

@@ -937,7 +939,7 @@ static RPCHelpMan pruneblockchain()
937939
};
938940
}
939941

940-
CoinStatsHashType ParseHashType(const std::string& hash_type_input)
942+
CoinStatsHashType ParseHashType(std::string_view hash_type_input)
941943
{
942944
if (hash_type_input == "hash_serialized_3") {
943945
return CoinStatsHashType::HASH_SERIALIZED;
@@ -1039,7 +1041,7 @@ static RPCHelpMan gettxoutsetinfo()
10391041
UniValue ret(UniValue::VOBJ);
10401042

10411043
const CBlockIndex* pindex{nullptr};
1042-
const CoinStatsHashType hash_type{request.params[0].isNull() ? CoinStatsHashType::HASH_SERIALIZED : ParseHashType(request.params[0].get_str())};
1044+
const CoinStatsHashType hash_type{ParseHashType(self.Arg<std::string_view>("hash_type"))};
10431045
bool index_requested = request.params[2].isNull() || request.params[2].get_bool();
10441046

10451047
NodeContext& node = EnsureAnyNodeContext(request.context);
@@ -2516,7 +2518,8 @@ static RPCHelpMan scanblocks()
25162518
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
25172519
{
25182520
UniValue ret(UniValue::VOBJ);
2519-
if (request.params[0].get_str() == "status") {
2521+
auto action{self.Arg<std::string_view>("action")};
2522+
if (action == "status") {
25202523
BlockFiltersScanReserver reserver;
25212524
if (reserver.reserve()) {
25222525
// no scan in progress
@@ -2525,7 +2528,7 @@ static RPCHelpMan scanblocks()
25252528
ret.pushKV("progress", g_scanfilter_progress.load());
25262529
ret.pushKV("current_height", g_scanfilter_progress_height.load());
25272530
return ret;
2528-
} else if (request.params[0].get_str() == "abort") {
2531+
} else if (action == "abort") {
25292532
BlockFiltersScanReserver reserver;
25302533
if (reserver.reserve()) {
25312534
// reserve was possible which means no scan was running
@@ -2534,12 +2537,12 @@ static RPCHelpMan scanblocks()
25342537
// set the abort flag
25352538
g_scanfilter_should_abort_scan = true;
25362539
return true;
2537-
} else if (request.params[0].get_str() == "start") {
2540+
} else if (action == "start") {
25382541
BlockFiltersScanReserver reserver;
25392542
if (!reserver.reserve()) {
25402543
throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan already in progress, use action \"abort\" or \"status\"");
25412544
}
2542-
const std::string filtertype_name{request.params[4].isNull() ? "basic" : request.params[4].get_str()};
2545+
auto filtertype_name{self.Arg<std::string_view>("filtertype")};
25432546

25442547
BlockFilterType filtertype;
25452548
if (!BlockFilterTypeByName(filtertype_name, filtertype)) {
@@ -2551,7 +2554,7 @@ static RPCHelpMan scanblocks()
25512554

25522555
BlockFilterIndex* index = GetBlockFilterIndex(filtertype);
25532556
if (!index) {
2554-
throw JSONRPCError(RPC_MISC_ERROR, "Index is not enabled for filtertype " + filtertype_name);
2557+
throw JSONRPCError(RPC_MISC_ERROR, tfm::format("Index is not enabled for filtertype %s", filtertype_name));
25552558
}
25562559

25572560
NodeContext& node = EnsureAnyNodeContext(request.context);
@@ -2650,9 +2653,8 @@ static RPCHelpMan scanblocks()
26502653
ret.pushKV("to_height", start_index->nHeight); // start_index is always the last scanned block here
26512654
ret.pushKV("relevant_blocks", std::move(blocks));
26522655
ret.pushKV("completed", completed);
2653-
}
2654-
else {
2655-
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid action '%s'", request.params[0].get_str()));
2656+
} else {
2657+
throw JSONRPCError(RPC_INVALID_PARAMETER, tfm::format("Invalid action '%s'", action));
26562658
}
26572659
return ret;
26582660
},
@@ -2917,10 +2919,7 @@ static RPCHelpMan getblockfilter()
29172919
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
29182920
{
29192921
uint256 block_hash = ParseHashV(request.params[0], "blockhash");
2920-
std::string filtertype_name = BlockFilterTypeName(BlockFilterType::BASIC);
2921-
if (!request.params[1].isNull()) {
2922-
filtertype_name = request.params[1].get_str();
2923-
}
2922+
auto filtertype_name{self.Arg<std::string_view>("filtertype")};
29242923

29252924
BlockFilterType filtertype;
29262925
if (!BlockFilterTypeByName(filtertype_name, filtertype)) {
@@ -2929,7 +2928,7 @@ static RPCHelpMan getblockfilter()
29292928

29302929
BlockFilterIndex* index = GetBlockFilterIndex(filtertype);
29312930
if (!index) {
2932-
throw JSONRPCError(RPC_MISC_ERROR, "Index is not enabled for filtertype " + filtertype_name);
2931+
throw JSONRPCError(RPC_MISC_ERROR, tfm::format("Index is not enabled for filtertype %s", filtertype_name));
29332932
}
29342933

29352934
const CBlockIndex* block_index;
@@ -3075,10 +3074,10 @@ static RPCHelpMan dumptxoutset()
30753074
}
30763075

30773076
const ArgsManager& args{EnsureAnyArgsman(request.context)};
3078-
const fs::path path = fsbridge::AbsPathJoin(args.GetDataDirNet(), fs::u8path(request.params[0].get_str()));
3077+
const fs::path path = fsbridge::AbsPathJoin(args.GetDataDirNet(), fs::u8path(self.Arg<std::string_view>("path")));
30793078
// Write to a temporary path and then move into `path` on completion
30803079
// to avoid confusion due to an interruption.
3081-
const fs::path temppath = fsbridge::AbsPathJoin(args.GetDataDirNet(), fs::u8path(request.params[0].get_str() + ".incomplete"));
3080+
const fs::path temppath = path + ".incomplete";
30823081

30833082
if (fs::exists(path)) {
30843083
throw JSONRPCError(

src/rpc/fees.cpp

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#include <array>
2222
#include <cmath>
2323
#include <string>
24+
#include <string_view>
2425

2526
using common::FeeModeFromString;
2627
using common::FeeModesDetail;
@@ -67,18 +68,15 @@ static RPCHelpMan estimatesmartfee()
6768
CHECK_NONFATAL(mempool.m_opts.signals)->SyncWithValidationInterfaceQueue();
6869
unsigned int max_target = fee_estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
6970
unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target);
70-
bool conservative = false;
71-
if (!request.params[1].isNull()) {
72-
FeeEstimateMode fee_mode;
73-
if (!FeeModeFromString(request.params[1].get_str(), fee_mode)) {
74-
throw JSONRPCError(RPC_INVALID_PARAMETER, InvalidEstimateModeErrorMessage());
75-
}
76-
if (fee_mode == FeeEstimateMode::CONSERVATIVE) conservative = true;
71+
FeeEstimateMode fee_mode;
72+
if (!FeeModeFromString(self.Arg<std::string_view>("estimate_mode"), fee_mode)) {
73+
throw JSONRPCError(RPC_INVALID_PARAMETER, InvalidEstimateModeErrorMessage());
7774
}
7875

7976
UniValue result(UniValue::VOBJ);
8077
UniValue errors(UniValue::VARR);
8178
FeeCalculation feeCalc;
79+
bool conservative{fee_mode == FeeEstimateMode::CONSERVATIVE};
8280
CFeeRate feeRate{fee_estimator.estimateSmartFee(conf_target, &feeCalc, conservative)};
8381
if (feeRate != CFeeRate(0)) {
8482
CFeeRate min_mempool_feerate{mempool.GetMinFee()};

src/rpc/mempool.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#include <util/time.h>
2929
#include <util/vector.h>
3030

31+
#include <string_view>
3132
#include <utility>
3233

3334
using node::DumpMempool;
@@ -768,7 +769,7 @@ static RPCHelpMan importmempool()
768769
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Can only import the mempool after the block download and sync is done.");
769770
}
770771

771-
const fs::path load_path{fs::u8path(request.params[0].get_str())};
772+
const fs::path load_path{fs::u8path(self.Arg<std::string_view>("filepath"))};
772773
const UniValue& use_current_time{request.params[1]["use_current_time"]};
773774
const UniValue& apply_fee_delta{request.params[1]["apply_fee_delta_priority"]};
774775
const UniValue& apply_unbroadcast{request.params[1]["apply_unbroadcast_set"]};

src/rpc/net.cpp

Lines changed: 23 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@
3636
#include <optional>
3737
#include <stdexcept>
3838
#include <string>
39+
#include <string_view>
3940
#include <vector>
4041

4142
using node::NodeContext;
4243
using util::Join;
43-
using util::TrimString;
4444

4545
const std::vector<std::string> CONNECTION_TYPE_DOC{
4646
"outbound-full-relay (default automatic connections)",
@@ -402,7 +402,7 @@ static RPCHelpMan addconnection()
402402
}
403403

404404
const std::string address = request.params[0].get_str();
405-
const std::string conn_type_in{TrimString(request.params[1].get_str())};
405+
auto conn_type_in{util::TrimStringView(self.Arg<std::string_view>("connection_type"))};
406406
ConnectionType conn_type{};
407407
if (conn_type_in == "outbound-full-relay") {
408408
conn_type = ConnectionType::OUTBOUND_FULL_RELAY;
@@ -462,16 +462,15 @@ static RPCHelpMan disconnectnode()
462462
CConnman& connman = EnsureConnman(node);
463463

464464
bool success;
465-
const UniValue &address_arg = request.params[0];
466-
const UniValue &id_arg = request.params[1];
465+
auto address{self.MaybeArg<std::string_view>("address")};
466+
auto node_id{self.MaybeArg<int64_t>("nodeid")};
467467

468-
if (!address_arg.isNull() && id_arg.isNull()) {
468+
if (address && !node_id) {
469469
/* handle disconnect-by-address */
470-
success = connman.DisconnectNode(address_arg.get_str());
471-
} else if (!id_arg.isNull() && (address_arg.isNull() || (address_arg.isStr() && address_arg.get_str().empty()))) {
470+
success = connman.DisconnectNode(*address);
471+
} else if (node_id && (!address || address->empty())) {
472472
/* handle disconnect-by-id */
473-
NodeId nodeid = (NodeId) id_arg.getInt<int64_t>();
474-
success = connman.DisconnectNode(nodeid);
473+
success = connman.DisconnectNode(*node_id);
475474
} else {
476475
throw JSONRPCError(RPC_INVALID_PARAMS, "Only one of address and nodeid should be provided.");
477476
}
@@ -523,10 +522,10 @@ static RPCHelpMan getaddednodeinfo()
523522

524523
std::vector<AddedNodeInfo> vInfo = connman.GetAddedNodeInfo(/*include_connected=*/true);
525524

526-
if (!request.params[0].isNull()) {
525+
if (auto node{self.MaybeArg<std::string_view>("node")}) {
527526
bool found = false;
528527
for (const AddedNodeInfo& info : vInfo) {
529-
if (info.m_params.m_added_node == request.params[0].get_str()) {
528+
if (info.m_params.m_added_node == *node) {
530529
vInfo.assign(1, info);
531530
found = true;
532531
break;
@@ -754,36 +753,32 @@ static RPCHelpMan setban()
754753
},
755754
[&](const RPCHelpMan& help, const JSONRPCRequest& request) -> UniValue
756755
{
757-
std::string strCommand;
758-
if (!request.params[1].isNull())
759-
strCommand = request.params[1].get_str();
760-
if (strCommand != "add" && strCommand != "remove") {
756+
auto command{help.Arg<std::string_view>("command")};
757+
if (command != "add" && command != "remove") {
761758
throw std::runtime_error(help.ToString());
762759
}
763760
NodeContext& node = EnsureAnyNodeContext(request.context);
764761
BanMan& banman = EnsureBanman(node);
765762

766763
CSubNet subNet;
767764
CNetAddr netAddr;
768-
bool isSubnet = false;
769-
770-
if (request.params[0].get_str().find('/') != std::string::npos)
771-
isSubnet = true;
765+
std::string subnet_arg{help.Arg<std::string_view>("subnet")};
766+
const bool isSubnet{subnet_arg.find('/') != subnet_arg.npos};
772767

773768
if (!isSubnet) {
774-
const std::optional<CNetAddr> addr{LookupHost(request.params[0].get_str(), false)};
769+
const std::optional<CNetAddr> addr{LookupHost(subnet_arg, false)};
775770
if (addr.has_value()) {
776771
netAddr = static_cast<CNetAddr>(MaybeFlipIPv6toCJDNS(CService{addr.value(), /*port=*/0}));
777772
}
773+
} else {
774+
subNet = LookupSubNet(subnet_arg);
778775
}
779-
else
780-
subNet = LookupSubNet(request.params[0].get_str());
781776

782-
if (! (isSubnet ? subNet.IsValid() : netAddr.IsValid()) )
777+
if (! (isSubnet ? subNet.IsValid() : netAddr.IsValid()) ) {
783778
throw JSONRPCError(RPC_CLIENT_INVALID_IP_OR_SUBNET, "Error: Invalid IP/Subnet");
779+
}
784780

785-
if (strCommand == "add")
786-
{
781+
if (command == "add") {
787782
if (isSubnet ? banman.IsBanned(subNet) : banman.IsBanned(netAddr)) {
788783
throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: IP/Subnet already banned");
789784
}
@@ -809,9 +804,7 @@ static RPCHelpMan setban()
809804
node.connman->DisconnectNode(netAddr);
810805
}
811806
}
812-
}
813-
else if(strCommand == "remove")
814-
{
807+
} else if(command == "remove") {
815808
if (!( isSubnet ? banman.Unban(subNet) : banman.Unban(netAddr) )) {
816809
throw JSONRPCError(RPC_CLIENT_INVALID_IP_OR_SUBNET, "Error: Unban failed. Requested address/subnet was not previously manually banned.");
817810
}
@@ -1051,11 +1044,11 @@ static RPCHelpMan sendmsgtopeer()
10511044
HelpExampleCli("sendmsgtopeer", "0 \"addr\" \"ffffff\"") + HelpExampleRpc("sendmsgtopeer", "0 \"addr\" \"ffffff\"")},
10521045
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
10531046
const NodeId peer_id{request.params[0].getInt<int64_t>()};
1054-
const std::string& msg_type{request.params[1].get_str()};
1047+
const auto msg_type{self.Arg<std::string_view>("msg_type")};
10551048
if (msg_type.size() > CMessageHeader::MESSAGE_TYPE_SIZE) {
10561049
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Error: msg_type too long, max length is %i", CMessageHeader::MESSAGE_TYPE_SIZE));
10571050
}
1058-
auto msg{TryParseHex<unsigned char>(request.params[2].get_str())};
1051+
auto msg{TryParseHex<unsigned char>(self.Arg<std::string_view>("msg"))};
10591052
if (!msg.has_value()) {
10601053
throw JSONRPCError(RPC_INVALID_PARAMETER, "Error parsing input for msg");
10611054
}

src/rpc/node.cpp

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#include <rpc/server_util.h>
2222
#include <rpc/util.h>
2323
#include <scheduler.h>
24+
#include <tinyformat.h>
2425
#include <univalue.h>
2526
#include <util/any.h>
2627
#include <util/check.h>
@@ -30,6 +31,7 @@
3031
#ifdef HAVE_MALLOC_INFO
3132
#include <malloc.h>
3233
#endif
34+
#include <string_view>
3335

3436
using node::NodeContext;
3537

@@ -176,7 +178,7 @@ static RPCHelpMan getmemoryinfo()
176178
},
177179
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
178180
{
179-
std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str();
181+
auto mode{self.Arg<std::string_view>("mode")};
180182
if (mode == "stats") {
181183
UniValue obj(UniValue::VOBJ);
182184
obj.pushKV("locked", RPCLockedMemoryInfo());
@@ -188,7 +190,7 @@ static RPCHelpMan getmemoryinfo()
188190
throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo mode not available");
189191
#endif
190192
} else {
191-
throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
193+
throw JSONRPCError(RPC_INVALID_PARAMETER, tfm::format("unknown mode %s", mode));
192194
}
193195
},
194196
};
@@ -385,7 +387,7 @@ static RPCHelpMan getindexinfo()
385387
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
386388
{
387389
UniValue result(UniValue::VOBJ);
388-
const std::string index_name = request.params[0].isNull() ? "" : request.params[0].get_str();
390+
const std::string index_name{self.MaybeArg<std::string_view>("index_name").value_or("")};
389391

390392
if (g_txindex) {
391393
result.pushKVs(SummaryToJSON(g_txindex->GetSummary(), index_name));

0 commit comments

Comments
 (0)