rippled
Loading...
Searching...
No Matches
RPCHelpers.cpp
1#include <xrpld/app/misc/Transaction.h>
2#include <xrpld/rpc/Context.h>
3#include <xrpld/rpc/DeliveredAmount.h>
4#include <xrpld/rpc/detail/RPCHelpers.h>
5#include <xrpld/rpc/detail/TrustLine.h>
6
7#include <xrpl/ledger/View.h>
8#include <xrpl/protocol/AccountID.h>
9#include <xrpl/protocol/RPCErr.h>
10#include <xrpl/protocol/nftPageMask.h>
11#include <xrpl/rdb/RelationalDatabase.h>
12#include <xrpl/resource/Fees.h>
13#include <xrpl/tx/transactors/nft/NFTokenUtils.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 {
28 return sle->getFieldU64(sfLowNode);
29 }
30 if (sle->getFieldAmount(sfHighLimit).getIssuer() == accountID)
31 {
32 return sle->getFieldU64(sfHighNode);
33 }
34 }
35
36 if (!sle->isFieldPresent(sfOwnerNode))
37 return 0;
38
39 return sle->getFieldU64(sfOwnerNode);
40}
41
42bool
44 ReadView const& ledger,
46 AccountID const& accountID)
47{
48 if (sle->getType() == ltRIPPLE_STATE)
49 {
50 return (sle->getFieldAmount(sfLowLimit).getIssuer() == accountID) ||
51 (sle->getFieldAmount(sfHighLimit).getIssuer() == accountID);
52 }
53 if (sle->isFieldPresent(sfAccount))
54 {
55 // If there's an sfAccount present, also test the sfDestination, if
56 // present. This will match objects such as Escrows (ltESCROW), Payment
57 // Channels (ltPAYCHAN), and Checks (ltCHECK) because those are added to
58 // the Destination account's directory. It intentionally EXCLUDES
59 // NFToken Offers (ltNFTOKEN_OFFER). NFToken Offers are NOT added to the
60 // Destination account's directory.
61 return sle->getAccountID(sfAccount) == accountID ||
62 (sle->isFieldPresent(sfDestination) && sle->getAccountID(sfDestination) == accountID);
63 }
64 if (sle->getType() == ltSIGNER_LIST)
65 {
66 Keylet const accountSignerList = keylet::signers(accountID);
67 return sle->key() == accountSignerList.key;
68 }
69 if (sle->getType() == ltNFTOKEN_OFFER)
70 {
71 // Do not check the sfDestination field. NFToken Offers are NOT added to
72 // the Destination account's directory.
73 return sle->getAccountID(sfOwner) == accountID;
74 }
75
76 return false;
77}
78
81{
83 for (auto const& jv : jvArray)
84 {
85 if (!jv.isString())
86 return hash_set<AccountID>();
87 auto const id = parseBase58<AccountID>(jv.asString());
88 if (!id)
89 return hash_set<AccountID>();
90 result.insert(*id);
91 }
92 return result;
93}
94
96readLimitField(unsigned int& limit, Tuning::LimitRange const& range, JsonContext const& context)
97{
98 limit = range.rDefault;
99 if (!context.params.isMember(jss::limit) || context.params[jss::limit].isNull())
100 return std::nullopt;
101
102 auto const& jvLimit = context.params[jss::limit];
103 if (!jvLimit.isUInt() && (!jvLimit.isInt() || jvLimit.asInt() < 0))
104 return RPC::expected_field_error(jss::limit, "unsigned integer");
105
106 limit = jvLimit.asUInt();
107 if (limit == 0)
108 return RPC::invalid_field_error(jss::limit);
109
110 if (!isUnlimited(context.role))
111 limit = std::max(range.rmin, std::min(range.rmax, limit));
112
113 return std::nullopt;
114}
115
118{
119 // ripple-lib encodes seed used to generate an Ed25519 wallet in a
120 // non-standard way. While rippled never encode seeds that way, we
121 // try to detect such keys to avoid user confusion.
122 if (!value.isString())
123 return std::nullopt;
124
125 auto const result = decodeBase58Token(value.asString(), TokenType::None);
126
127 if (result.size() == 18 && static_cast<std::uint8_t>(result[0]) == std::uint8_t(0xE1) &&
128 static_cast<std::uint8_t>(result[1]) == std::uint8_t(0x4B))
129 return Seed(makeSlice(result.substr(2)));
130
131 return std::nullopt;
132}
133
136{
137 using string_to_seed_t = std::function<std::optional<Seed>(std::string const&)>;
138 using seed_match_t = std::pair<char const*, string_to_seed_t>;
139
140 static seed_match_t const seedTypes[]{
141 {jss::passphrase.c_str(), [](std::string const& s) { return parseGenericSeed(s); }},
142 {jss::seed.c_str(), [](std::string const& s) { return parseBase58<Seed>(s); }},
143 {jss::seed_hex.c_str(), [](std::string const& s) {
144 uint128 i;
145 if (i.parseHex(s))
146 return std::optional<Seed>(Slice(i.data(), i.size()));
147 return std::optional<Seed>{};
148 }}};
149
150 // Identify which seed type is in use.
151 seed_match_t const* seedType = nullptr;
152 int count = 0;
153 for (auto const& t : seedTypes)
154 {
155 if (params.isMember(t.first))
156 {
157 ++count;
158 seedType = &t;
159 }
160 }
161
162 if (count != 1)
163 {
164 error = RPC::make_param_error(
165 "Exactly one of the following must be specified: " + std::string(jss::passphrase) +
166 ", " + std::string(jss::seed) + " or " + std::string(jss::seed_hex));
167 return std::nullopt;
168 }
169
170 // Make sure a string is present
171 auto const& param = params[seedType->first];
172 if (!param.isString())
173 {
174 error = RPC::expected_field_error(seedType->first, "string");
175 return std::nullopt;
176 }
177
178 auto const fieldContents = param.asString();
179
180 // Convert string to seed.
181 std::optional<Seed> seed = seedType->second(fieldContents);
182
183 if (!seed)
184 error = rpcError(rpcBAD_SEED);
185
186 return seed;
187}
188
190keypairForSignature(Json::Value const& params, Json::Value& error, unsigned int apiVersion)
191{
192 bool const has_key_type = params.isMember(jss::key_type);
193
194 // All of the secret types we allow, but only one at a time.
195 static char const* const secretTypes[]{
196 jss::passphrase.c_str(), jss::secret.c_str(), jss::seed.c_str(), jss::seed_hex.c_str()};
197
198 // Identify which secret type is in use.
199 char const* secretType = nullptr;
200 int count = 0;
201 for (auto t : secretTypes)
202 {
203 if (params.isMember(t))
204 {
205 ++count;
206 secretType = t;
207 }
208 }
209
210 if (count == 0 || secretType == nullptr)
211 {
212 error = RPC::missing_field_error(jss::secret);
213 return {};
214 }
215
216 if (count > 1)
217 {
218 error = RPC::make_param_error(
219 "Exactly one of the following must be specified: " + std::string(jss::passphrase) +
220 ", " + std::string(jss::secret) + ", " + std::string(jss::seed) + " or " +
221 std::string(jss::seed_hex));
222 return {};
223 }
224
227
228 if (has_key_type)
229 {
230 if (!params[jss::key_type].isString())
231 {
232 error = RPC::expected_field_error(jss::key_type, "string");
233 return {};
234 }
235
236 keyType = keyTypeFromString(params[jss::key_type].asString());
237
238 if (!keyType)
239 {
240 if (apiVersion > 1u)
241 {
243 }
244 else
245 {
246 error = RPC::invalid_field_error(jss::key_type);
247 }
248 return {};
249 }
250
251 // using strcmp as pointers may not match (see
252 // https://developercommunity.visualstudio.com/t/assigning-constexpr-char--to-static-cha/10021357?entry=problem)
253 if (strcmp(secretType, jss::secret.c_str()) == 0)
254 {
255 error = RPC::make_param_error(
256 "The secret field is not allowed if " + std::string(jss::key_type) + " is used.");
257 return {};
258 }
259 }
260
261 // ripple-lib encodes seed used to generate an Ed25519 wallet in a
262 // non-standard way. While we never encode seeds that way, we try
263 // to detect such keys to avoid user confusion.
264 // using strcmp as pointers may not match (see
265 // https://developercommunity.visualstudio.com/t/assigning-constexpr-char--to-static-cha/10021357?entry=problem)
266 if (strcmp(secretType, jss::seed_hex.c_str()) != 0)
267 {
268 seed = RPC::parseRippleLibSeed(params[secretType]);
269
270 if (seed)
271 {
272 // If the user passed in an Ed25519 seed but *explicitly*
273 // requested another key type, return an error.
275 {
276 error = RPC::make_error(rpcBAD_SEED, "Specified seed is for an Ed25519 wallet.");
277 return {};
278 }
279
280 keyType = KeyType::ed25519;
281 }
282 }
283
284 if (!keyType)
285 keyType = KeyType::secp256k1;
286
287 if (!seed)
288 {
289 if (has_key_type)
290 {
291 seed = getSeedFromRPC(params, error);
292 }
293 else
294 {
295 if (!params[jss::secret].isString())
296 {
297 error = RPC::expected_field_error(jss::secret, "string");
298 return {};
299 }
300
301 seed = parseGenericSeed(params[jss::secret].asString());
302 }
303 }
304
305 if (!seed)
306 {
307 if (!contains_error(error))
308 {
310 }
311
312 return {};
313 }
314
315 if (keyType != KeyType::secp256k1 && keyType != KeyType::ed25519)
316 LogicError("keypairForSignature: invalid key type");
317
318 return generateKeyPair(*keyType, *seed);
319}
320
323{
325 if (params.isMember(jss::type))
326 {
327 static constexpr auto types =
329#pragma push_macro("LEDGER_ENTRY")
330#undef LEDGER_ENTRY
331
332#define LEDGER_ENTRY(tag, value, name, rpcName, ...) {jss::name, jss::rpcName, tag},
333
334#include <xrpl/protocol/detail/ledger_entries.macro>
335
336#undef LEDGER_ENTRY
337#pragma pop_macro("LEDGER_ENTRY")
338 });
339
340 auto const& p = params[jss::type];
341 if (!p.isString())
342 {
343 result.first = RPC::Status{rpcINVALID_PARAMS, "Invalid field 'type', not string."};
344 XRPL_ASSERT(
345 result.first.type() == RPC::Status::Type::error_code_i,
346 "xrpl::RPC::chooseLedgerEntryType : first valid result type");
347 return result;
348 }
349
350 // Use the passed in parameter to find a ledger type based on matching
351 // against the canonical name (case-insensitive) or the RPC name
352 // (case-sensitive).
353 auto const filter = p.asString();
354 auto const iter = std::ranges::find_if(types, [&filter](decltype(types.front())& t) {
355 return boost::iequals(std::get<0>(t), filter) || std::get<1>(t) == filter;
356 });
357 if (iter == types.end())
358 {
359 result.first = RPC::Status{rpcINVALID_PARAMS, "Invalid field 'type'."};
360 XRPL_ASSERT(
361 result.first.type() == RPC::Status::Type::error_code_i,
362 "xrpl::RPC::chooseLedgerEntryType : second valid result "
363 "type");
364 return result;
365 }
366 result.second = std::get<2>(*iter);
367 }
368 return result;
369}
370
371bool
373{
374 switch (type)
375 {
376 case LedgerEntryType::ltAMENDMENTS:
377 case LedgerEntryType::ltDIR_NODE:
378 case LedgerEntryType::ltFEE_SETTINGS:
379 case LedgerEntryType::ltLEDGER_HASHES:
380 case LedgerEntryType::ltNEGATIVE_UNL:
381 return false;
382 default:
383 return true;
384 }
385}
386
387} // namespace RPC
388} // 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:476
pointer data()
Definition base_uint.h:101
static constexpr std::size_t size()
Definition base_uint.h:499
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:273
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:297
Json::Value missing_field_error(std::string const &name)
Definition ErrorCodes.h:231
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:219
std::string invalid_field_message(std::string const &name)
Definition ErrorCodes.h:261
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:295
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:215
bool isUnlimited(Role const &role)
ADMIN and IDENTIFIED roles shall have unlimited resources.
Definition Role.cpp:98
std::string decodeBase58Token(std::string const &s, TokenType type)
Definition tokens.cpp:187
@ 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)