xrpld
Loading...
Searching...
No Matches
RPCHelpers.cpp
1#include <xrpld/rpc/detail/RPCHelpers.h>
2
3#include <xrpld/rpc/Context.h>
4#include <xrpld/rpc/DeliveredAmount.h>
5#include <xrpld/rpc/Role.h>
6#include <xrpld/rpc/detail/Tuning.h>
7
8#include <xrpl/basics/Log.h>
9#include <xrpl/basics/Slice.h>
10#include <xrpl/basics/UnorderedContainers.h>
11#include <xrpl/basics/base_uint.h>
12#include <xrpl/basics/contract.h>
13#include <xrpl/beast/utility/Journal.h>
14#include <xrpl/core/ServiceRegistry.h>
15#include <xrpl/ledger/ReadView.h>
16#include <xrpl/protocol/AccountID.h>
17#include <xrpl/protocol/Asset.h>
18#include <xrpl/protocol/ErrorCodes.h>
19#include <xrpl/protocol/Indexes.h>
20#include <xrpl/protocol/Issue.h>
21#include <xrpl/protocol/KeyType.h>
22#include <xrpl/protocol/LedgerFormats.h>
23#include <xrpl/protocol/PublicKey.h>
24#include <xrpl/protocol/RPCErr.h>
25#include <xrpl/protocol/SField.h>
26#include <xrpl/protocol/SecretKey.h>
27#include <xrpl/protocol/Seed.h>
28#include <xrpl/protocol/UintTypes.h>
29#include <xrpl/protocol/jss.h>
30#include <xrpl/protocol/tokens.h>
31
32#include <boost/algorithm/string/predicate.hpp>
33
34#include <rpcspec/Errors.hpp>
35
36#include <algorithm>
37#include <array>
38#include <charconv>
39#include <cstdint>
40#include <cstring>
41#include <format>
42#include <functional>
43#include <optional>
44#include <string_view>
45#include <system_error>
46#include <tuple>
47#include <utility>
48
49namespace xrpl::rpc {
50
51std::uint64_t
52getStartHint(SLE::ConstRef sle, AccountID const& accountID)
53{
54 if (sle->getType() == ltRIPPLE_STATE)
55 {
56 if (sle->getFieldAmount(sfLowLimit).getIssuer() == accountID)
57 {
58 return sle->getFieldU64(sfLowNode);
59 }
60 if (sle->getFieldAmount(sfHighLimit).getIssuer() == accountID)
61 {
62 return sle->getFieldU64(sfHighNode);
63 }
64 }
65
66 if (!sle->isFieldPresent(sfOwnerNode))
67 return 0;
68
69 return sle->getFieldU64(sfOwnerNode);
70}
71
72namespace {
73
74// UINT64 sf*Node fields that record a page number in an owner directory.
75// Keep in sync with sfields.macro; the xrpl.rpc.RPCHelpers test enforces it.
76constexpr std::array<SField const*, 9> kOwnerDirNodeFields{
77 &sfOwnerNode,
78 &sfLowNode,
79 &sfHighNode,
80 &sfDestinationNode,
81 &sfIssuerNode,
82 &sfSubjectNode,
83 &sfSponseeNode,
84 &sfLoanBrokerNode,
85 &sfVaultNode,
86};
87
88} // namespace
89
90bool
92{
93 return std::ranges::contains(kOwnerDirNodeFields, &field);
94}
95
98{
99 auto const comma = marker.find(',');
100 if (comma == std::string_view::npos)
101 return std::nullopt;
102
103 uint256 startAfter;
104 if (!startAfter.parseHex(marker.substr(0, comma)))
105 return std::nullopt;
106
107 auto hint = marker.substr(comma + 1);
108 hint = hint.substr(0, hint.find(','));
109 if (hint.starts_with('+'))
110 hint.remove_prefix(1);
111
112 std::uint64_t startHint = 0;
113 auto const [end, ec] = std::from_chars(hint.data(), hint.data() + hint.size(), startHint);
114 if (ec != std::errc{} || end != hint.data() + hint.size())
115 return std::nullopt;
116
117 return std::pair{startAfter, startHint};
118}
119
120bool
121isRelatedToAccount(ReadView const& ledger, SLE::ConstRef sle, AccountID const& accountID)
122{
123 // Marker validator for account_lines / account_offers / account_channels
124 // pagination: probes each owner-directory page-hint field on `sle` and
125 // returns true iff `sle`'s key is present on that page in `accountID`'s
126 // owner directory. Bounded by kOwnerDirNodeFields.size() ledger reads.
127 auto const ownerDir = keylet::ownerDir(accountID);
128
129 auto const pageContainsKey = [&](std::uint64_t node) {
130 auto const page = ledger.read(keylet::page(ownerDir, node));
131 return page && std::ranges::contains(page->getFieldV256(sfIndexes), sle->key());
132 };
133
134 return std::ranges::any_of(kOwnerDirNodeFields, [&](SField const* field) {
135 return sle->isFieldPresent(*field) && pageContainsKey(sle->getFieldU64(*field));
136 });
137}
138
141{
142 HashSet<AccountID> result;
143 for (auto const& jv : jvArray)
144 {
145 if (!jv.isString())
146 return HashSet<AccountID>();
147 auto const id = parseBase58<AccountID>(jv.asString());
148 if (!id)
149 return HashSet<AccountID>();
150 result.insert(*id);
151 }
152 return result;
153}
154
157{
158 HashSet<MPTID> result;
159 for (auto const& jv : jvArray)
160 {
161 if (!jv.isString())
162 return HashSet<MPTID>();
163
164 auto const mptIssuanceIdStr = jv.asString();
165 MPTID mptIssuanceID;
166 if (!mptIssuanceID.parseHex(mptIssuanceIdStr))
167 return HashSet<MPTID>();
168
169 result.insert(mptIssuanceID);
170 }
171 return result;
172}
173
174unsigned int
175clampLimit(unsigned int limit, tuning::LimitRange const& range, Role const& role)
176{
177 if (isUnlimited(role))
178 return limit;
179 return std::clamp(limit, range.rmin, range.rmax);
180}
181
183readLimitField(unsigned int& limit, tuning::LimitRange const& range, JsonContext const& context)
184{
185 limit = range.rDefault;
186 if (!context.params.isMember(jss::limit) || context.params[jss::limit].isNull())
187 return std::nullopt;
188
189 auto const& jvLimit = context.params[jss::limit];
190 if (!jvLimit.isUInt() && (!jvLimit.isInt() || jvLimit.asInt() < 0))
191 return rpc::expectedFieldError(jss::limit, "unsigned integer");
192
193 limit = jvLimit.asUInt();
194 if (limit == 0)
195 return rpc::invalidFieldError(jss::limit);
196
197 limit = clampLimit(limit, range, context.role);
198 return std::nullopt;
199}
200
203{
204 // XrplLib encodes seed used to generate an Ed25519 wallet in a
205 // non-standard way. While xrpld never encode seeds that way, we
206 // try to detect such keys to avoid user confusion.
207 if (!value.isString())
208 return std::nullopt;
209
210 auto const result = decodeBase58Token(value.asString(), TokenType::None);
211
212 if (result.size() == 18 && static_cast<std::uint8_t>(result[0]) == std::uint8_t(0xE1) &&
213 static_cast<std::uint8_t>(result[1]) == std::uint8_t(0x4B))
214 return Seed(makeSlice(result.substr(2)));
215
216 return std::nullopt;
217}
218
221{
222 using StringToSeedT = std::function<std::optional<Seed>(std::string const&)>;
223 using SeedMatchT = std::pair<char const*, StringToSeedT>;
224
225 static SeedMatchT const kSeedTypes[]{
226 {jss::passphrase.cStr(), [](std::string const& s) { return parseGenericSeed(s); }},
227 {jss::seed.cStr(), [](std::string const& s) { return parseBase58<Seed>(s); }},
228 {
229 jss::seed_hex.cStr(),
230 [](std::string const& s) {
231 UInt128 i;
232 if (i.parseHex(s))
233 return std::optional<Seed>(Slice(i.data(), i.size()));
234 return std::optional<Seed>{};
235 },
236 },
237 };
238
239 // Identify which seed type is in use.
240 SeedMatchT const* seedType = nullptr;
241 int count = 0;
242 for (auto const& t : kSeedTypes)
243 {
244 if (params.isMember(t.first))
245 {
246 ++count;
247 seedType = &t;
248 }
249 }
250
251 if (count != 1)
252 {
253 error = rpc::makeParamError(
254 "Exactly one of the following must be specified: " + std::string(jss::passphrase) +
255 ", " + std::string(jss::seed) + " or " + std::string(jss::seed_hex));
256 return std::nullopt;
257 }
258
259 // Make sure a string is present
260 auto const& param = params[seedType->first];
261 if (!param.isString())
262 {
263 error = rpc::expectedFieldError(seedType->first, "string");
264 return std::nullopt;
265 }
266
267 auto const fieldContents = param.asString();
268
269 // Convert string to seed.
270 std::optional<Seed> seed = seedType->second(fieldContents);
271
272 if (!seed)
273 error = rpcError(RpcBadSeed);
274
275 return seed;
276}
277
279keypairForSignature(json::Value const& params, json::Value& error, unsigned int apiVersion)
280{
281 bool const hasKeyType = params.isMember(jss::key_type);
282
283 // All of the secret types we allow, but only one at a time.
284 static char const* const kSecretTypes[]{
285 jss::passphrase.cStr(),
286 jss::secret.cStr(),
287 jss::seed.cStr(),
288 jss::seed_hex.cStr(),
289 };
290
291 // Identify which secret type is in use.
292 char const* secretType = nullptr;
293 int count = 0;
294 for (auto t : kSecretTypes)
295 {
296 if (params.isMember(t))
297 {
298 ++count;
299 secretType = t;
300 }
301 }
302
303 if (count == 0 || secretType == nullptr)
304 {
305 error = rpc::missingFieldError(jss::secret);
306 return {};
307 }
308
309 if (count > 1)
310 {
311 error = rpc::makeParamError(
312 "Exactly one of the following must be specified: " + std::string(jss::passphrase) +
313 ", " + std::string(jss::secret) + ", " + std::string(jss::seed) + " or " +
314 std::string(jss::seed_hex));
315 return {};
316 }
317
320
321 if (hasKeyType)
322 {
323 if (!params[jss::key_type].isString())
324 {
325 error = rpc::expectedFieldError(jss::key_type, "string");
326 return {};
327 }
328
329 keyType = keyTypeFromString(params[jss::key_type].asString());
330
331 if (!keyType)
332 {
333 if (apiVersion > 1u)
334 {
336 }
337 else
338 {
339 error = rpc::invalidFieldError(jss::key_type);
340 }
341 return {};
342 }
343
344 // using strcmp as pointers may not match (see
345 // https://developercommunity.visualstudio.com/t/assigning-constexpr-char--to-static-cha/10021357?entry=problem)
346 if (strcmp(secretType, jss::secret.cStr()) == 0)
347 {
348 error = rpc::makeParamError(
349 "The secret field is not allowed if " + std::string(jss::key_type) + " is used.");
350 return {};
351 }
352 }
353
354 // XrplLib encodes seed used to generate an Ed25519 wallet in a
355 // non-standard way. While we never encode seeds that way, we try
356 // to detect such keys to avoid user confusion.
357 // using strcmp as pointers may not match (see
358 // https://developercommunity.visualstudio.com/t/assigning-constexpr-char--to-static-cha/10021357?entry=problem)
359 if (strcmp(secretType, jss::seed_hex.cStr()) != 0)
360 {
361 seed = rpc::parseXrplLibSeed(params[secretType]);
362
363 if (seed)
364 {
365 // If the user passed in an Ed25519 seed but *explicitly*
366 // requested another key type, return an error.
368 {
369 error = rpc::makeError(RpcBadSeed, "Specified seed is for an Ed25519 wallet.");
370 return {};
371 }
372
373 keyType = KeyType::Ed25519;
374 }
375 }
376
377 if (!keyType)
378 keyType = KeyType::Secp256k1;
379
380 if (!seed)
381 {
382 if (hasKeyType)
383 {
384 seed = getSeedFromRPC(params, error);
385 }
386 else
387 {
388 if (!params[jss::secret].isString())
389 {
390 error = rpc::expectedFieldError(jss::secret, "string");
391 return {};
392 }
393
394 seed = parseGenericSeed(params[jss::secret].asString());
395 }
396 }
397
398 if (!seed)
399 {
400 if (!containsError(error))
401 {
403 }
404
405 return {};
406 }
407
408 if (keyType != KeyType::Secp256k1 && keyType != KeyType::Ed25519)
409 logicError("keypairForSignature: invalid key type");
410
411 return generateKeyPair(*keyType, *seed);
412}
413
416{
417 std::pair<::rpc::Status, LedgerEntryType> result{::rpc::Status::kOK, ltANY};
418 if (params.isMember(jss::type))
419 {
420 static constexpr auto kTypes =
421 std::to_array<std::tuple<char const*, char const*, LedgerEntryType>>({
422#pragma push_macro("LEDGER_ENTRY")
423#undef LEDGER_ENTRY
424
425#define LEDGER_ENTRY(tag, value, name, rpcName, ...) {jss::name, jss::rpcName, tag},
426
427#include <xrpl/protocol/detail/ledger_entries.macro>
428
429#undef LEDGER_ENTRY
430#pragma pop_macro("LEDGER_ENTRY")
431 });
432
433 auto const& p = params[jss::type];
434 if (!p.isString())
435 {
436 result.first = ::rpc::Status{RpcInvalidParams, "Invalid field 'type', not string."};
437 return result;
438 }
439
440 // Use the passed in parameter to find a ledger type based on matching
441 // against the canonical name (case-insensitive) or the RPC name
442 // (case-sensitive).
443 auto const filter = p.asString();
444 auto const iter = std::ranges::find_if(kTypes, [&filter](decltype(kTypes.front())& t) {
445 return boost::iequals(std::get<0>(t), filter) || std::get<1>(t) == filter;
446 });
447 if (iter == kTypes.end())
448 {
449 result.first = ::rpc::Status{RpcInvalidParams, "Invalid field 'type'."};
450 return result;
451 }
452 result.second = std::get<2>(*iter);
453 }
454 return result;
455}
456
457bool
459{
460 switch (type)
461 {
462 case LedgerEntryType::ltAMENDMENTS:
463 case LedgerEntryType::ltDIR_NODE:
464 case LedgerEntryType::ltFEE_SETTINGS:
465 case LedgerEntryType::ltLEDGER_HASHES:
466 case LedgerEntryType::ltNEGATIVE_UNL:
467 return false;
468 default:
469 return true;
470 }
471}
472
475 Asset& asset,
476 json::Value const& params,
477 json::StaticString const& name,
479{
480 auto const& jv = params[name];
481 auto const [issuerError, assetError] = [&] {
482 if (name == jss::taker_pays)
485 }();
486
487 if (jv.isMember(jss::mpt_issuance_id) &&
488 (jv.isMember(jss::currency) || jv.isMember(jss::issuer)))
489 {
490 JLOG(j.info()) << std::format("Bad {} currency or MPT.", name.cStr());
491 return RpcInvalidParams;
492 }
493
494 if (jv.isMember(jss::currency))
495 {
496 Issue issue = xrpIssue();
497 // Parse mandatory currency.
498 if (!jv.isMember(jss::currency) ||
499 !toCurrency(issue.currency, jv[jss::currency].asString()))
500 {
501 JLOG(j.info()) << std::format("Bad {} currency.", name.cStr());
502 return assetError;
503 }
504
505 // Parse optional issuer.
506 if ((jv.isMember(jss::issuer) &&
507 (!jv[jss::issuer].isString() || !toIssuer(issue.account, jv[jss::issuer].asString())))
508 // Don't allow illegal issuers.
509 || (!issue.currency != !issue.account) || noAccount() == issue.account)
510 {
511 JLOG(j.info()) << std::format("Bad {} issuer.", name.cStr());
512 return issuerError;
513 }
514 asset = issue;
515 }
516 else if (jv.isMember(jss::mpt_issuance_id))
517 {
518 MPTID mptid;
519 if (!mptid.parseHex(jv[jss::mpt_issuance_id].asString()))
520 return assetError;
521 asset = mptid;
522 }
523 else
524 {
525 JLOG(j.info()) << std::format("Neither {} currency or MPT is present.", name.cStr());
526 return assetError;
527 }
528
529 return RpcSuccess;
530}
531
532} // namespace xrpl::rpc
T any_of(T... args)
T clamp(T... args)
A generic endpoint for log messages.
Definition Journal.h:44
Stream info() const
Definition Journal.h:350
Lightweight wrapper to tag static string.
Definition json_value.h:52
constexpr char const * cStr() const
Definition json_value.h:65
Represents a JSON value.
Definition json_value.h:121
bool isNull() const
isNull() tests to see if this field is null.
std::string asString() const
Returns the unquoted string value.
bool isMember(char const *key) const
Return true if the object has a member named key.
pointer data()
Definition base_uint.h:117
static constexpr std::size_t size()
Definition base_uint.h:549
constexpr bool parseHex(std::string_view sv)
Parse a hex string into a base_uint.
Definition base_uint.h:526
A currency issued by an account.
Definition Issue.h:18
Currency currency
Definition Issue.h:20
AccountID account
Definition Issue.h:21
A view into a ledger.
Definition ReadView.h:41
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
Identifies fields.
Definition SField.h:131
std::shared_ptr< STLedgerEntry const > const & ConstRef
Seeds are used to generate deterministic secret keys.
Definition Seed.h:19
An immutable linear range of bytes.
Definition Slice.h:28
T find(T... args)
T format(T... args)
T from_chars(T... args)
T insert(T... args)
T make_pair(T... args)
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Definition Indexes.cpp:415
Keylet page(UInt256 const &root, std::uint64_t const index=0) noexcept
A page in a directory.
Definition Indexes.cpp:421
The api_version numbers this server serves.
Definition ApiVersion.h:26
json::Value expectedFieldError(std::string const &name, std::string const &type)
Definition ErrorCodes.h:309
bool containsError(json::Value const &json)
Returns true if the json contains an rpc error specification.
unsigned int clampLimit(unsigned int limit, tuning::LimitRange const &range, Role const &role)
Clamps a requested limit to the range a role may use.
bool isOwnerDirNodeField(SField const &field)
Checks whether an SField is a UINT64 sf*Node owner-directory page-hint field probed by isRelatedToAcc...
std::uint64_t getStartHint(SLE::ConstRef sle, AccountID const &accountID)
Gets the start hint for traversing account objects.
std::string invalidFieldMessage(std::string const &name)
Definition ErrorCodes.h:273
json::Value makeParamError(std::string const &message)
Returns a new json object that indicates invalid parameters.
Definition ErrorCodes.h:231
json::Value invalidFieldError(std::string const &name)
Definition ErrorCodes.h:285
HashSet< MPTID > parseMPTIssuanceIDs(json::Value const &jvArray)
Parses an array of MPT issuance IDs from a JSON value.
ErrorCodeI parseSubUnsubJson(Asset &asset, json::Value const &params, json::StaticString const &name, beast::Journal j)
Parse subscribe/unsubscribe 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.
HashSet< AccountID > parseAccountIds(json::Value const &jvArray)
Parses an array of account IDs from a JSON value.
json::Value missingFieldError(std::string const &name)
Definition ErrorCodes.h:243
json::Value makeError(ErrorCodeI code)
Returns a new json object that reflects the error code.
bool isRelatedToAccount(ReadView const &ledger, SLE::ConstRef sle, AccountID const &accountID)
Tests if a ledger entry (SLE) is owned by the specified account.
std::optional< std::pair< uint256, std::uint64_t > > parseAccountMarker(std::string_view marker)
Splits an account marker into the entry to start after and its start hint.
std::optional< Seed > getSeedFromRPC(json::Value const &params, json::Value &error)
Extracts a Seed from RPC parameters.
std::optional< Seed > parseXrplLibSeed(json::Value const &value)
Parses a XrplLib seed from RPC parameters.
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.
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.
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Definition Issue.h:108
ErrorCodeI
Definition ErrorCodes.h:23
@ RpcDstAmtMalformed
Definition ErrorCodes.h:89
@ RpcBadKeyType
Definition ErrorCodes.h:116
@ RpcSuccess
Definition ErrorCodes.h:27
@ RpcSrcCurMalformed
Definition ErrorCodes.h:107
@ RpcInvalidParams
Definition ErrorCodes.h:67
@ RpcBadSeed
Definition ErrorCodes.h:82
@ RpcSrcIsrMalformed
Definition ErrorCodes.h:108
@ RpcDstIsrMalformed
Definition ErrorCodes.h:91
std::optional< KeyType > keyTypeFromString(std::string const &s)
Definition KeyType.h:14
std::optional< AccountID > parseBase58(std::string const &s)
Parse AccountID from checked, base58 string.
ClosedInterval< T > range(T low, T high)
Create a closed range interval.
Definition RangeSet.h:37
BaseUInt< 128 > UInt128
Definition base_uint.h:579
bool toCurrency(Currency &, std::string const &)
Tries to convert a string to a Currency, returns true on success.
Definition UintTypes.cpp:65
std::pair< PublicKey, SecretKey > generateKeyPair(KeyType type, Seed const &seed)
Generate a key pair deterministically.
void logicError(std::string const &how) noexcept
Called when faulty logic causes a broken invariant.
Slice makeSlice(std::array< T, N > const &a)
Definition Slice.h:228
json::Value rpcError(ErrorCodeI iError)
Definition RPCErr.cpp:13
Role
Indicates the level of administrative permission to grant.
Definition Role.h:27
BaseUInt< 192 > MPTID
MPTID is a 192-bit value representing MPT Issuance ID, which is a concatenation of a 32-bit sequence ...
Definition UintTypes.h:54
std::unordered_set< Value, Hash, Pred, Allocator > HashSet
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
AccountID const & noAccount()
A placeholder for empty accounts.
LedgerEntryType
Identifiers for on-ledger objects.
@ ltANY
A special type, matching any ledger entry type.
bool isUnlimited(Role const &role)
ADMIN and IDENTIFIED roles shall have unlimited resources.
Definition Role.cpp:115
std::string decodeBase58Token(std::string const &s, TokenType type)
Definition tokens.cpp:191
bool toIssuer(AccountID &, std::string const &)
Convert hex or base58 string to AccountID.
UInt256 uint256
Definition base_uint.h:587
std::optional< Seed > parseGenericSeed(std::string const &str, bool rfc1751=true)
Attempt to parse a string as a seed.
Definition Seed.cpp:79
json::Value params
Definition Context.h:51
Represents RPC limit parameter values that have a min, default and max.
T substr(T... args)
T value_or(T... args)