rippled
Loading...
Searching...
No Matches
RPCHelpers.cpp
1#include <xrpld/app/misc/Transaction.h>
2#include <xrpld/app/paths/TrustLine.h>
3#include <xrpld/app/rdb/RelationalDatabase.h>
4#include <xrpld/app/tx/detail/NFTokenUtils.h>
5#include <xrpld/rpc/Context.h>
6#include <xrpld/rpc/DeliveredAmount.h>
7#include <xrpld/rpc/detail/RPCHelpers.h>
8
9#include <xrpl/ledger/View.h>
10#include <xrpl/protocol/AccountID.h>
11#include <xrpl/protocol/RPCErr.h>
12#include <xrpl/protocol/nftPageMask.h>
13#include <xrpl/resource/Fees.h>
14
15#include <boost/algorithm/string/case_conv.hpp>
16#include <boost/algorithm/string/predicate.hpp>
17
18namespace xrpl {
19namespace RPC {
20
23{
24 if (sle->getType() == ltRIPPLE_STATE)
25 {
26 if (sle->getFieldAmount(sfLowLimit).getIssuer() == accountID)
27 return sle->getFieldU64(sfLowNode);
28 else if (sle->getFieldAmount(sfHighLimit).getIssuer() == accountID)
29 return sle->getFieldU64(sfHighNode);
30 }
31
32 if (!sle->isFieldPresent(sfOwnerNode))
33 return 0;
34
35 return sle->getFieldU64(sfOwnerNode);
36}
37
38bool
39isRelatedToAccount(ReadView const& ledger, std::shared_ptr<SLE const> const& sle, AccountID const& accountID)
40{
41 if (sle->getType() == ltRIPPLE_STATE)
42 {
43 return (sle->getFieldAmount(sfLowLimit).getIssuer() == accountID) ||
44 (sle->getFieldAmount(sfHighLimit).getIssuer() == accountID);
45 }
46 else if (sle->isFieldPresent(sfAccount))
47 {
48 // If there's an sfAccount present, also test the sfDestination, if
49 // present. This will match objects such as Escrows (ltESCROW), Payment
50 // Channels (ltPAYCHAN), and Checks (ltCHECK) because those are added to
51 // the Destination account's directory. It intentionally EXCLUDES
52 // NFToken Offers (ltNFTOKEN_OFFER). NFToken Offers are NOT added to the
53 // Destination account's directory.
54 return sle->getAccountID(sfAccount) == accountID ||
55 (sle->isFieldPresent(sfDestination) && sle->getAccountID(sfDestination) == accountID);
56 }
57 else if (sle->getType() == ltSIGNER_LIST)
58 {
59 Keylet const accountSignerList = keylet::signers(accountID);
60 return sle->key() == accountSignerList.key;
61 }
62 else if (sle->getType() == ltNFTOKEN_OFFER)
63 {
64 // Do not check the sfDestination field. NFToken Offers are NOT added to
65 // the Destination account's directory.
66 return sle->getAccountID(sfOwner) == accountID;
67 }
68
69 return false;
70}
71
74{
76 for (auto const& jv : jvArray)
77 {
78 if (!jv.isString())
79 return hash_set<AccountID>();
80 auto const id = parseBase58<AccountID>(jv.asString());
81 if (!id)
82 return hash_set<AccountID>();
83 result.insert(*id);
84 }
85 return result;
86}
87
89readLimitField(unsigned int& limit, Tuning::LimitRange const& range, JsonContext const& context)
90{
91 limit = range.rDefault;
92 if (!context.params.isMember(jss::limit) || context.params[jss::limit].isNull())
93 return std::nullopt;
94
95 auto const& jvLimit = context.params[jss::limit];
96 if (!(jvLimit.isUInt() || (jvLimit.isInt() && jvLimit.asInt() >= 0)))
97 return RPC::expected_field_error(jss::limit, "unsigned integer");
98
99 limit = jvLimit.asUInt();
100 if (limit == 0)
101 return RPC::invalid_field_error(jss::limit);
102
103 if (!isUnlimited(context.role))
104 limit = std::max(range.rmin, std::min(range.rmax, limit));
105
106 return std::nullopt;
107}
108
111{
112 // ripple-lib encodes seed used to generate an Ed25519 wallet in a
113 // non-standard way. While rippled never encode seeds that way, we
114 // try to detect such keys to avoid user confusion.
115 if (!value.isString())
116 return std::nullopt;
117
118 auto const result = decodeBase58Token(value.asString(), TokenType::None);
119
120 if (result.size() == 18 && static_cast<std::uint8_t>(result[0]) == std::uint8_t(0xE1) &&
121 static_cast<std::uint8_t>(result[1]) == std::uint8_t(0x4B))
122 return Seed(makeSlice(result.substr(2)));
123
124 return std::nullopt;
125}
126
129{
130 using string_to_seed_t = std::function<std::optional<Seed>(std::string const&)>;
131 using seed_match_t = std::pair<char const*, string_to_seed_t>;
132
133 static seed_match_t const seedTypes[]{
134 {jss::passphrase.c_str(), [](std::string const& s) { return parseGenericSeed(s); }},
135 {jss::seed.c_str(), [](std::string const& s) { return parseBase58<Seed>(s); }},
136 {jss::seed_hex.c_str(), [](std::string const& s) {
137 uint128 i;
138 if (i.parseHex(s))
139 return std::optional<Seed>(Slice(i.data(), i.size()));
140 return std::optional<Seed>{};
141 }}};
142
143 // Identify which seed type is in use.
144 seed_match_t const* seedType = nullptr;
145 int count = 0;
146 for (auto const& t : seedTypes)
147 {
148 if (params.isMember(t.first))
149 {
150 ++count;
151 seedType = &t;
152 }
153 }
154
155 if (count != 1)
156 {
157 error = RPC::make_param_error(
158 "Exactly one of the following must be specified: " + std::string(jss::passphrase) + ", " +
159 std::string(jss::seed) + " or " + std::string(jss::seed_hex));
160 return std::nullopt;
161 }
162
163 // Make sure a string is present
164 auto const& param = params[seedType->first];
165 if (!param.isString())
166 {
167 error = RPC::expected_field_error(seedType->first, "string");
168 return std::nullopt;
169 }
170
171 auto const fieldContents = param.asString();
172
173 // Convert string to seed.
174 std::optional<Seed> seed = seedType->second(fieldContents);
175
176 if (!seed)
177 error = rpcError(rpcBAD_SEED);
178
179 return seed;
180}
181
183keypairForSignature(Json::Value const& params, Json::Value& error, unsigned int apiVersion)
184{
185 bool const has_key_type = params.isMember(jss::key_type);
186
187 // All of the secret types we allow, but only one at a time.
188 static char const* const secretTypes[]{
189 jss::passphrase.c_str(), jss::secret.c_str(), jss::seed.c_str(), jss::seed_hex.c_str()};
190
191 // Identify which secret type is in use.
192 char const* secretType = nullptr;
193 int count = 0;
194 for (auto t : secretTypes)
195 {
196 if (params.isMember(t))
197 {
198 ++count;
199 secretType = t;
200 }
201 }
202
203 if (count == 0 || secretType == nullptr)
204 {
205 error = RPC::missing_field_error(jss::secret);
206 return {};
207 }
208
209 if (count > 1)
210 {
211 error = RPC::make_param_error(
212 "Exactly one of the following must be specified: " + std::string(jss::passphrase) + ", " +
213 std::string(jss::secret) + ", " + std::string(jss::seed) + " or " + std::string(jss::seed_hex));
214 return {};
215 }
216
219
220 if (has_key_type)
221 {
222 if (!params[jss::key_type].isString())
223 {
224 error = RPC::expected_field_error(jss::key_type, "string");
225 return {};
226 }
227
228 keyType = keyTypeFromString(params[jss::key_type].asString());
229
230 if (!keyType)
231 {
232 if (apiVersion > 1u)
234 else
235 error = RPC::invalid_field_error(jss::key_type);
236 return {};
237 }
238
239 // using strcmp as pointers may not match (see
240 // https://developercommunity.visualstudio.com/t/assigning-constexpr-char--to-static-cha/10021357?entry=problem)
241 if (strcmp(secretType, jss::secret.c_str()) == 0)
242 {
243 error =
244 RPC::make_param_error("The secret field is not allowed if " + std::string(jss::key_type) + " is used.");
245 return {};
246 }
247 }
248
249 // ripple-lib encodes seed used to generate an Ed25519 wallet in a
250 // non-standard way. While we never encode seeds that way, we try
251 // to detect such keys to avoid user confusion.
252 // using strcmp as pointers may not match (see
253 // https://developercommunity.visualstudio.com/t/assigning-constexpr-char--to-static-cha/10021357?entry=problem)
254 if (strcmp(secretType, jss::seed_hex.c_str()) != 0)
255 {
256 seed = RPC::parseRippleLibSeed(params[secretType]);
257
258 if (seed)
259 {
260 // If the user passed in an Ed25519 seed but *explicitly*
261 // requested another key type, return an error.
263 {
264 error = RPC::make_error(rpcBAD_SEED, "Specified seed is for an Ed25519 wallet.");
265 return {};
266 }
267
268 keyType = KeyType::ed25519;
269 }
270 }
271
272 if (!keyType)
273 keyType = KeyType::secp256k1;
274
275 if (!seed)
276 {
277 if (has_key_type)
278 seed = getSeedFromRPC(params, error);
279 else
280 {
281 if (!params[jss::secret].isString())
282 {
283 error = RPC::expected_field_error(jss::secret, "string");
284 return {};
285 }
286
287 seed = parseGenericSeed(params[jss::secret].asString());
288 }
289 }
290
291 if (!seed)
292 {
293 if (!contains_error(error))
294 {
296 }
297
298 return {};
299 }
300
301 if (keyType != KeyType::secp256k1 && keyType != KeyType::ed25519)
302 LogicError("keypairForSignature: invalid key type");
303
304 return generateKeyPair(*keyType, *seed);
305}
306
309{
311 if (params.isMember(jss::type))
312 {
314#pragma push_macro("LEDGER_ENTRY")
315#undef LEDGER_ENTRY
316
317#define LEDGER_ENTRY(tag, value, name, rpcName, ...) {jss::name, jss::rpcName, tag},
318
319#include <xrpl/protocol/detail/ledger_entries.macro>
320
321#undef LEDGER_ENTRY
322#pragma pop_macro("LEDGER_ENTRY")
323 });
324
325 auto const& p = params[jss::type];
326 if (!p.isString())
327 {
328 result.first = RPC::Status{rpcINVALID_PARAMS, "Invalid field 'type', not string."};
329 XRPL_ASSERT(
330 result.first.type() == RPC::Status::Type::error_code_i,
331 "xrpl::RPC::chooseLedgerEntryType : first valid result type");
332 return result;
333 }
334
335 // Use the passed in parameter to find a ledger type based on matching
336 // against the canonical name (case-insensitive) or the RPC name
337 // (case-sensitive).
338 auto const filter = p.asString();
339 auto const iter = std::ranges::find_if(types, [&filter](decltype(types.front())& t) {
340 return boost::iequals(std::get<0>(t), filter) || std::get<1>(t) == filter;
341 });
342 if (iter == types.end())
343 {
344 result.first = RPC::Status{rpcINVALID_PARAMS, "Invalid field 'type'."};
345 XRPL_ASSERT(
346 result.first.type() == RPC::Status::Type::error_code_i,
347 "xrpl::RPC::chooseLedgerEntryType : second valid result "
348 "type");
349 return result;
350 }
351 result.second = std::get<2>(*iter);
352 }
353 return result;
354}
355
356bool
358{
359 switch (type)
360 {
361 case LedgerEntryType::ltAMENDMENTS:
362 case LedgerEntryType::ltDIR_NODE:
363 case LedgerEntryType::ltFEE_SETTINGS:
364 case LedgerEntryType::ltLEDGER_HASHES:
365 case LedgerEntryType::ltNEGATIVE_UNL:
366 return false;
367 default:
368 return true;
369 }
370}
371
372} // namespace RPC
373} // namespace xrpl
Represents a JSON value.
Definition json_value.h:130
bool isString() const
std::string asString() const
Returns the unquoted string value.
bool isNull() const
isNull() tests to see if this field is null.
bool isMember(char const *key) const
Return true if the object has a member named key.
A view into a ledger.
Definition ReadView.h:31
Seeds are used to generate deterministic secret keys.
Definition Seed.h:14
An immutable linear range of bytes.
Definition Slice.h:26
constexpr bool parseHex(std::string_view sv)
Parse a hex string into a base_uint.
Definition base_uint.h:471
pointer data()
Definition base_uint.h:101
static constexpr std::size_t size()
Definition base_uint.h:494
T find_if(T... args)
T insert(T... args)
T is_same_v
T max(T... args)
T min(T... args)
Json::Value invalid_field_error(std::string const &name)
Definition ErrorCodes.h:268
bool isRelatedToAccount(ReadView const &ledger, std::shared_ptr< SLE const > const &sle, AccountID const &accountID)
Tests if a ledger entry (SLE) is owned by the specified account.
std::pair< RPC::Status, LedgerEntryType > chooseLedgerEntryType(Json::Value const &params)
Chooses the ledger entry type based on RPC parameters.
bool isAccountObjectsValidType(LedgerEntryType const &type)
Checks if the type is a valid filtering type for the account_objects method.
std::uint64_t getStartHint(std::shared_ptr< SLE const > const &sle, AccountID const &accountID)
Gets the start hint for traversing account objects.
Json::Value expected_field_error(std::string const &name, std::string const &type)
Definition ErrorCodes.h:292
Json::Value missing_field_error(std::string const &name)
Definition ErrorCodes.h:226
std::optional< Seed > parseRippleLibSeed(Json::Value const &value)
Parses a RippleLib seed from RPC parameters.
hash_set< AccountID > parseAccountIds(Json::Value const &jvArray)
Parses an array of account IDs from a JSON value.
static constexpr std::integral_constant< unsigned, Version > apiVersion
Definition ApiVersion.h:38
Json::Value make_param_error(std::string const &message)
Returns a new json object that indicates invalid parameters.
Definition ErrorCodes.h:214
std::string invalid_field_message(std::string const &name)
Definition ErrorCodes.h:256
std::optional< std::pair< PublicKey, SecretKey > > keypairForSignature(Json::Value const &params, Json::Value &error, unsigned int apiVersion)
Generates a keypair for signature from RPC parameters.
Json::Value make_error(error_code_i code)
Returns a new json object that reflects the error code.
std::optional< Seed > getSeedFromRPC(Json::Value const &params, Json::Value &error)
Extracts a Seed from RPC parameters.
std::optional< Json::Value > readLimitField(unsigned int &limit, Tuning::LimitRange const &range, JsonContext const &context)
Retrieves the limit value from a JsonContext or sets a default.
bool contains_error(Json::Value const &json)
Returns true if the json contains an rpc error specification.
Keylet signers(AccountID const &account) noexcept
A SignerList.
Definition Indexes.cpp:287
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
void LogicError(std::string const &how) noexcept
Called when faulty logic causes a broken invariant.
std::optional< KeyType > keyTypeFromString(std::string const &s)
Definition KeyType.h:14
ClosedInterval< T > range(T low, T high)
Create a closed range interval.
Definition RangeSet.h:34
std::pair< PublicKey, SecretKey > generateKeyPair(KeyType type, Seed const &seed)
Generate a key pair deterministically.
Json::Value rpcError(error_code_i iError)
Definition RPCErr.cpp:12
LedgerEntryType
Identifiers for on-ledger objects.
@ ltANY
A special type, matching any ledger entry type.
std::enable_if_t< std::is_same< T, char >::value||std::is_same< T, unsigned char >::value, Slice > makeSlice(std::array< T, N > const &a)
Definition Slice.h:213
bool isUnlimited(Role const &role)
ADMIN and IDENTIFIED roles shall have unlimited resources.
Definition Role.cpp:96
std::string decodeBase58Token(std::string const &s, TokenType type)
Definition tokens.cpp:186
@ rpcBAD_KEY_TYPE
Definition ErrorCodes.h:113
@ rpcBAD_SEED
Definition ErrorCodes.h:79
@ rpcINVALID_PARAMS
Definition ErrorCodes.h:64
std::optional< Seed > parseGenericSeed(std::string const &str, bool rfc1751=true)
Attempt to parse a string as a seed.
Definition Seed.cpp:78
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:19
uint256 key
Definition Keylet.h:20
Json::Value params
Definition Context.h:43
Status represents the results of an operation that might fail.
Definition Status.h:20
static constexpr Code OK
Definition Status.h:26
Represents RPC limit parameter values that have a min, default and max.
T value_or(T... args)