xrpld
Loading...
Searching...
No Matches
AccountTx.cpp
1#include <xrpld/app/ledger/LedgerMaster.h>
2#include <xrpld/app/main/Application.h>
3#include <xrpld/app/misc/DeliverMax.h>
4#include <xrpld/app/misc/Transaction.h>
5#include <xrpld/app/rdb/backend/SQLiteDatabase.h>
6#include <xrpld/rpc/Context.h>
7#include <xrpld/rpc/Role.h>
8#include <xrpld/rpc/detail/RPCHelpers.h>
9#include <xrpld/rpc/detail/RPCLedgerHelpers.h>
10#include <xrpld/rpc/detail/SpecBridge.hpp>
11#include <xrpld/rpc/detail/SyntheticFields.h>
12#include <xrpld/rpc/detail/Tuning.h>
13
14#include <xrpl/basics/Log.h>
15#include <xrpl/basics/base_uint.h>
16#include <xrpl/basics/chrono.h>
17#include <xrpl/basics/strHex.h>
18#include <xrpl/beast/utility/instrumentation.h>
19#include <xrpl/json/json_value.h>
20#include <xrpl/ledger/ReadView.h>
21#include <xrpl/protocol/AccountID.h>
22#include <xrpl/protocol/ErrorCodes.h>
23#include <xrpl/protocol/RPCErr.h>
24#include <xrpl/protocol/RippleLedgerHash.h>
25#include <xrpl/protocol/jss.h>
26#include <xrpl/rdb/RelationalDatabase.h>
27#include <xrpl/resource/Fees.h>
28
29#include <rpcspec/Errors.hpp>
30#include <rpcspec/Ledger.hpp>
31
32#include <cstdint>
33#include <expected>
34#include <memory>
35#include <optional>
36#include <type_traits>
37#include <utility>
38#include <variant>
39
40namespace xrpl {
41
42static std::expected<DelegateFilter, json::Value>
43parseDelegateFilter(json::Value const& delegateNode)
44{
45 if (!delegateNode.isObject())
46 return std::unexpected(rpc::invalidFieldError(jss::delegate));
47
48 if (!delegateNode.isMember(jss::delegate_filter) ||
49 !delegateNode[jss::delegate_filter].isString())
50 return std::unexpected(rpc::invalidFieldError(jss::delegate_filter));
51
52 auto const& delegateFilterStr = delegateNode[jss::delegate_filter].asString();
53
54 auto typeResult = [&] -> std::expected<DelegateType, json::Value> {
55 if (delegateFilterStr == "actor")
57
58 if (delegateFilterStr == "authorizer")
60
61 return std::unexpected(rpc::invalidFieldError(jss::delegate_filter));
62 }();
63
64 if (!typeResult)
65 return std::unexpected(typeResult.error());
66
67 DelegateType const type = *typeResult;
68
69 std::optional<AccountID> counterparty;
70 if (delegateNode.isMember(jss::counter_party))
71 {
72 if (!delegateNode[jss::counter_party].isString())
73 return std::unexpected(rpc::invalidFieldError(jss::counter_party));
74
75 counterparty = parseBase58<AccountID>(delegateNode[jss::counter_party].asString());
76
77 if (!counterparty)
79 }
80
81 return DelegateFilter{.type = type, .counterparty = counterparty};
82}
83
88
89// Moved here from RelationalDatabase, where nothing but this handler used them, so that
90// libxrpl does not depend on the spec for LedgerShortcut. Temporary: the spec's
91// account_tx Input replaces both once account_tx is migrated to the spec.
94
105
106// parses args into a ledger specifier, or returns a Json object on error
108parseLedgerArgs(rpc::Context const& context, json::Value const& params)
109{
110 json::Value response;
111 // if ledger_index_min or max is specified, then ledger_hash or ledger_index
112 // should not be specified. Error out if it is
113 if (context.apiVersion > 1u)
114 {
115 if ((params.isMember(jss::ledger_index_min) || params.isMember(jss::ledger_index_max)) &&
116 (params.isMember(jss::ledger_hash) || params.isMember(jss::ledger_index)))
117 {
118 ::rpc::Status const status{RpcInvalidParams, "invalidParams"};
119 rpc::injectSpecError(response, status);
120 return response;
121 }
122 }
123 if (params.isMember(jss::ledger_index_min) || params.isMember(jss::ledger_index_max))
124 {
125 uint32_t const min =
126 params.isMember(jss::ledger_index_min) && params[jss::ledger_index_min].asInt() >= 0
127 ? params[jss::ledger_index_min].asUInt()
128 : 0;
129 uint32_t const max =
130 params.isMember(jss::ledger_index_max) && params[jss::ledger_index_max].asInt() >= 0
131 ? params[jss::ledger_index_max].asUInt()
132 : UINT32_MAX;
133
134 return LedgerRange{.min = min, .max = max};
135 }
136 if (params.isMember(jss::ledger_hash))
137 {
138 auto& hashValue = params[jss::ledger_hash];
139 if (!hashValue.isString())
140 {
141 ::rpc::Status const status{RpcInvalidParams, "ledgerHashNotString"};
142 rpc::injectSpecError(response, status);
143 return response;
144 }
145
146 LedgerHash hash;
147 if (!hash.parseHex(hashValue.asString()))
148 {
149 ::rpc::Status const status{RpcInvalidParams, "ledgerHashMalformed"};
150 rpc::injectSpecError(response, status);
151 return response;
152 }
153 return hash;
154 }
155 if (params.isMember(jss::ledger_index))
156 {
157 LedgerSpecifier ledger;
158 if (params[jss::ledger_index].isNumeric())
159 {
160 ledger = params[jss::ledger_index].asUInt();
161 }
162 else
163 {
164 std::string const ledgerStr = params[jss::ledger_index].asString();
165
166 if (ledgerStr == "current" || ledgerStr.empty())
167 {
168 ledger = ::rpc::spec::LedgerShortcut::Current;
169 }
170 else if (ledgerStr == "closed")
171 {
172 ledger = ::rpc::spec::LedgerShortcut::Closed;
173 }
174 else if (ledgerStr == "validated")
175 {
176 ledger = ::rpc::spec::LedgerShortcut::Validated;
177 }
178 else
179 {
180 ::rpc::Status const status{RpcInvalidParams, "ledger_index string malformed"};
181 rpc::injectSpecError(response, status);
182 return response;
183 }
184 }
185 return ledger;
186 }
188}
189
192{
193 std::uint32_t uValidatedMin = 0;
194 std::uint32_t uValidatedMax = 0;
195 bool const bValidated = context.ledgerMaster.getValidatedRange(uValidatedMin, uValidatedMax);
196
197 if (!bValidated)
198 {
199 // Don't have a validated ledger range.
200 if (context.apiVersion == 1)
201 return RpcLgrIdxsInvalid;
202 return RpcNotSynced;
203 }
204
205 std::uint32_t uLedgerMin = uValidatedMin;
206 std::uint32_t uLedgerMax = uValidatedMax;
207 // Does request specify a ledger or ledger range?
208 if (ledgerSpecifier)
209 {
210 auto status = std::visit(
211 [&](auto const& ls) -> ::rpc::Status {
212 using T = std::decay_t<decltype(ls)>;
213 if constexpr (std::is_same_v<T, LedgerRange>)
214 {
215 // if ledger_index_min or ledger_index_max is out of
216 // valid ledger range, error out. exclude -1 as
217 // it is a valid input
218 if (context.apiVersion > 1u)
219 {
220 if ((ls.max > uValidatedMax && ls.max != -1) ||
221 (ls.min < uValidatedMin && ls.min != 0))
222 {
223 return RpcLgrIdxMalformed;
224 }
225 }
226 if (ls.min > uValidatedMin)
227 {
228 uLedgerMin = ls.min;
229 }
230 if (ls.max < uValidatedMax)
231 {
232 uLedgerMax = ls.max;
233 }
234 if (uLedgerMax < uLedgerMin)
235 {
236 if (context.apiVersion == 1)
237 return RpcLgrIdxsInvalid;
238 return RpcInvalidLgrRange;
239 }
240 }
241 else
242 {
244 auto status = getLedger(ledgerView, ls, context);
245 if (!ledgerView)
246 {
247 return status;
248 }
249
250 bool const validated = context.ledgerMaster.isValidated(*ledgerView);
251
252 if (!validated || ledgerView->header().seq > uValidatedMax ||
253 ledgerView->header().seq < uValidatedMin)
254 {
255 return RpcLgrNotValidated;
256 }
257 uLedgerMin = uLedgerMax = ledgerView->header().seq;
258 }
259 return ::rpc::Status::kOK;
260 },
261 *ledgerSpecifier);
262
263 if (status)
264 return status;
265 }
266 return LedgerRange{.min = uLedgerMin, .max = uLedgerMax};
267}
268
271{
273
274 AccountTxResult result;
275
276 auto lgrRange = getLedgerRange(context, args.ledger);
277 if (auto stat = std::get_if<::rpc::Status>(&lgrRange))
278 {
279 // An error occurred getting the requested ledger range
280 return {result, *stat};
281 }
282
283 result.ledgerRange = std::get<LedgerRange>(lgrRange);
284
285 result.marker = args.marker;
286
288 .account = args.account,
289 .ledgerRange = result.ledgerRange,
290 .marker = result.marker,
291 .limit = args.limit,
292 .bAdmin = isUnlimited(context.role),
293 .delegate = args.delegate,
294 };
295
296 auto& db = context.app.getRelationalDatabase();
297
298 if (args.binary)
299 {
300 if (args.forward)
301 {
302 auto [tx, marker] = db.oldestAccountTxPageB(options);
303 result.transactions = tx;
304 result.marker = marker;
305 }
306 else
307 {
308 auto [tx, marker] = db.newestAccountTxPageB(options);
309 result.transactions = tx;
310 result.marker = marker;
311 }
312 }
313 else
314 {
315 if (args.forward)
316 {
317 auto [tx, marker] = db.oldestAccountTxPage(options);
318 result.transactions = tx;
319 result.marker = marker;
320 }
321 else
322 {
323 auto [tx, marker] = db.newestAccountTxPage(options);
324 result.transactions = tx;
325 result.marker = marker;
326 }
327 }
328
329 result.limit = args.limit;
330 JLOG(context.j.debug()) << __func__ << " : finished";
331
332 return {result, RpcSuccess};
333}
334
338 AccountTxArgs const& args,
339 rpc::JsonContext const& context)
340{
341 json::Value response;
342 ::rpc::Status const& error = res.second;
343 if (error != RpcSuccess)
344 {
345 rpc::injectSpecError(response, error);
346 }
347 else
348 {
349 AccountTxResult const& result = res.first;
350 response[jss::validated] = true;
351 response[jss::limit] = result.limit;
352 response[jss::account] = context.params[jss::account].asString();
353 response[jss::ledger_index_min] = result.ledgerRange.min;
354 response[jss::ledger_index_max] = result.ledgerRange.max;
355
356 json::Value& jvTxns = (response[jss::transactions] = json::ValueType::Array);
357
358 if (auto txnsData = std::get_if<TxnsData>(&result.transactions))
359 {
360 XRPL_ASSERT(!args.binary, "xrpl::populateJsonResponse : binary is not set");
361
362 for (auto const& [txn, txnMeta] : *txnsData)
363 {
364 if (txn)
365 {
367 jvObj[jss::validated] = true;
368
369 auto const jsonTx = (context.apiVersion > 1 ? jss::tx_json : jss::tx);
370 if (context.apiVersion > 1)
371 {
372 jvObj[jsonTx] = txn->getJson(
373 static_cast<JsonOptions::UnderlyingT>(
375 static_cast<JsonOptions::UnderlyingT>(
377 false);
378 jvObj[jss::hash] = to_string(txn->getID());
379 jvObj[jss::ledger_index] = txn->getLedger();
380 jvObj[jss::ledger_hash] =
381 to_string(context.ledgerMaster.getHashBySeq(txn->getLedger()));
382
383 if (auto closeTime =
384 context.ledgerMaster.getCloseTimeBySeq(txn->getLedger()))
385 jvObj[jss::close_time_iso] = toStringIso(*closeTime);
386 }
387 else
388 {
389 jvObj[jsonTx] = txn->getJson(JsonOptions::Values::IncludeDate);
390 }
391
392 auto const& sttx = txn->getSTransaction();
393 rpc::insertDeliverMax(jvObj[jsonTx], sttx->getTxnType(), context.apiVersion);
394 if (txnMeta)
395 {
396 jvObj[jss::meta] = txnMeta->getJson(JsonOptions::Values::IncludeDate);
397 rpc::insertAllSyntheticInJson(jvObj[jss::meta], context, sttx, *txnMeta);
398 }
399 else
400 {
401 // LCOV_EXCL_START
402 UNREACHABLE(
403 "xrpl::populateJsonResponse : missing "
404 "transaction metadata");
405 // LCOV_EXCL_STOP
406 }
407 }
408 }
409 }
410 else
411 {
412 XRPL_ASSERT(args.binary, "xrpl::populateJsonResponse : binary is set");
413
414 for (auto const& binaryData : std::get<TxnsDataBinary>(result.transactions))
415 {
417
418 jvObj[jss::tx_blob] = strHex(std::get<0>(binaryData));
419 auto const jsonMeta = (context.apiVersion > 1 ? jss::meta_blob : jss::meta);
420 jvObj[jsonMeta] = strHex(std::get<1>(binaryData));
421 jvObj[jss::ledger_index] = std::get<2>(binaryData);
422 jvObj[jss::validated] = true;
423 }
424 }
425
426 if (result.marker)
427 {
428 response[jss::marker] = json::ValueType::Object;
429 response[jss::marker][jss::ledger] = result.marker->ledgerSeq;
430 response[jss::marker][jss::seq] = result.marker->txnSeq;
431
432 if (args.delegate)
433 response[jss::marker][jss::delegate] = true;
434 }
435 }
436
437 JLOG(context.j.debug()) << __func__ << " : finished";
438 return response;
439}
440
441// {
442// account: account,
443// ledger_index_min: ledger_index // optional, defaults to earliest
444// ledger_index_max: ledger_index, // optional, defaults to latest
445// binary: boolean, // optional, defaults to false
446// forward: boolean, // optional, defaults to false
447// limit: integer, // optional
448// marker: object {ledger: ledger_index, seq: txn_sequence} // optional,
449// resume previous query
450// delegate: object { // optional
451// delegate_filter: string, // required; "actor" or "authorizer"
452// counter_party: account // optional
453// }
454// }
455//
456// Pagination note for delegate-filtered queries: the `delegate` object (both
457// `delegate_filter` and `counter_party`) must be supplied unchanged on every
458// paginated request until the query completes. A marker returned by a
459// delegate-filtered query is only valid for a follow-up request that repeats
460// the same `delegate` object
463{
464 if (!context.app.config().useTxTables())
465 return rpcError(RpcNotEnabled);
466
467 auto& params = context.params;
468 AccountTxArgs args;
469 json::Value response;
470
471 // The document[https://xrpl.org/account_tx.html#account_tx] states that
472 // binary and forward params are both boolean values, however, assigning any
473 // string value works. Do not allow this. This check is for api Version 2
474 // onwards only
475 if (context.apiVersion > 1u && params.isMember(jss::binary) && !params[jss::binary].isBool())
476 {
477 return rpc::invalidFieldError(jss::binary);
478 }
479 if (context.apiVersion > 1u && params.isMember(jss::forward) && !params[jss::forward].isBool())
480 {
481 return rpc::invalidFieldError(jss::forward);
482 }
483
484 if (auto const err = rpc::readLimitField(args.limit, rpc::tuning::kAccountTx, context))
485 return *err;
486
487 args.binary = params.isMember(jss::binary) && params[jss::binary].asBool();
488 args.forward = params.isMember(jss::forward) && params[jss::forward].asBool();
489
490 if (!params.isMember(jss::account))
491 return rpc::missingFieldError(jss::account);
492
493 if (!params[jss::account].isString())
494 return rpc::invalidFieldError(jss::account);
495
496 auto const account = parseBase58<AccountID>(params[jss::account].asString());
497 if (!account)
499
500 args.account = *account;
501
502 auto parseRes = parseLedgerArgs(context, params);
503 if (auto jv = std::get_if<json::Value>(&parseRes))
504 {
505 return *jv;
506 }
507
508 args.ledger = std::get<std::optional<LedgerSpecifier>>(parseRes);
509
510 if (params.isMember(jss::marker))
511 {
512 auto& token = params[jss::marker];
513 if (!token.isMember(jss::ledger) || !token.isMember(jss::seq) ||
514 !token[jss::ledger].isConvertibleTo(json::ValueType::UInt) ||
515 !token[jss::seq].isConvertibleTo(json::ValueType::UInt))
516 {
517 ::rpc::Status const status{
519 "invalid marker. Provide ledger index via ledger field, and "
520 "transaction sequence number via seq field"};
521 rpc::injectSpecError(response, status);
522 return response;
523 }
524 args.marker = {
525 .ledgerSeq = token[jss::ledger].asUInt(),
526 .txnSeq = token[jss::seq].asUInt(),
527 };
528 }
529
530 if (params.isMember(jss::delegate))
531 {
532 if (auto const filter = parseDelegateFilter(params[jss::delegate]); filter.has_value())
533 {
534 args.delegate = *filter;
535 }
536 else
537 {
538 return filter.error();
539 }
540 }
541
542 // A marker produced by a delegate-filtered query uses a different
543 // pagination cursor than a normal query, so it is only valid when the same
544 // `delegate` object is supplied again. Reject any mismatch so pagination
545 // cannot silently skip or duplicate results.
546 if (args.marker)
547 {
548 bool const markerFromDelegate = params[jss::marker].isMember(jss::delegate) &&
549 params[jss::marker][jss::delegate].isBool() &&
550 params[jss::marker][jss::delegate].asBool();
551 if (markerFromDelegate != args.delegate.has_value())
552 {
553 ::rpc::Status const status{
555 "Do not mix delegate and non-delegate pagination markers in account_tx; "
556 "repeat the same `delegate` object when using a delegate marker."};
557 rpc::injectSpecError(response, status);
558 return response;
559 }
560 }
561
562 auto const res = doAccountTxHelp(context, args);
563 JLOG(context.j.debug()) << __func__ << " populating response";
564 return populateJsonResponse(res, args, context);
565}
566
567} // namespace xrpl
Stream debug() const
Definition Journal.h:344
Represents a JSON value.
Definition json_value.h:121
bool isObject() const
bool isString() const
Value & append(Value const &value)
Append value to array at the end.
UInt asUInt() const
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.
Int asInt() const
virtual Config & config()=0
constexpr bool parseHex(std::string_view sv)
Parse a hex string into a base_uint.
Definition base_uint.h:526
bool useTxTables() const
bool getValidatedRange(std::uint32_t &minVal, std::uint32_t &maxVal)
Returns Ledgers we have all the nodes for and are indexed: a contiguous part of getFullValidatedRange...
UInt256 getHashBySeq(std::uint32_t index)
Get a ledger's hash by sequence number using the cache.
std::optional< NetClock::time_point > getCloseTimeBySeq(LedgerIndex ledgerIndex)
bool isValidated(ReadView const &ledger)
Tests whether a ledger is on the validated chain, using the skip list when the ledger does not alread...
std::vector< TxnMetaLedgerType > MetaTxsList
std::vector< AccountTx > AccountTxs
std::tuple< Blob, Blob, std::uint32_t > TxnMetaLedgerType
virtual RelationalDatabase & getRelationalDatabase()=0
T empty(T... args)
T get_if(T... args)
T is_same_v
@ UInt
unsigned integer value
Definition json_value.h:28
@ Array
array value (ordered list)
Definition json_value.h:32
@ Object
object value (collection of name/value pairs).
Definition json_value.h:33
Charge const kFeeMediumBurdenRpc
static constexpr LimitRange kAccountTx
Limits for the account_tx command.
void insertDeliverMax(json::Value &txJson, TxType txnType, unsigned int apiVersion)
Copy Amount field to DeliverMax field in transaction output JSON.
Definition DeliverMax.cpp:9
void insertAllSyntheticInJson(json::Value &metadata, ReadView const &ledger, std::shared_ptr< STTx const > const &transaction, TxMeta const &transactionMeta)
Adds all synthetic fields to transaction metadata JSON.
json::Value invalidFieldError(std::string const &name)
Definition ErrorCodes.h:285
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.
json::Value missingFieldError(std::string const &name)
Definition ErrorCodes.h:243
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
RelationalDatabase::AccountTxs TxnsData
Definition AccountTx.cpp:84
@ RpcSuccess
Definition ErrorCodes.h:27
@ RpcActMalformed
Definition ErrorCodes.h:73
@ RpcNotSynced
Definition ErrorCodes.h:50
@ RpcLgrIdxsInvalid
Definition ErrorCodes.h:95
@ RpcNotEnabled
Definition ErrorCodes.h:42
@ RpcInvalidParams
Definition ErrorCodes.h:67
@ RpcLgrNotValidated
Definition ErrorCodes.h:56
@ RpcInvalidLgrRange
Definition ErrorCodes.h:119
@ RpcLgrIdxMalformed
Definition ErrorCodes.h:96
json::Value populateJsonResponse(std::pair< AccountTxResult, ::rpc::Status > const &res, AccountTxArgs const &args, rpc::JsonContext const &context)
json::Value doAccountTx(rpc::JsonContext &context)
RelationalDatabase::AccountTxResult AccountTxResult
Definition AccountTx.cpp:87
std::optional< AccountID > parseBase58(std::string const &s)
Parse AccountID from checked, base58 string.
std::string strHex(FwdIt begin, FwdIt end)
Definition strHex.h:13
static std::expected< DelegateFilter, json::Value > parseDelegateFilter(json::Value const &delegateNode)
Definition AccountTx.cpp:43
std::pair< AccountTxResult, ::rpc::Status > doAccountTxHelp(rpc::Context &context, AccountTxArgs const &args)
RelationalDatabase::MetaTxsList TxnsDataBinary
Definition AccountTx.cpp:85
UInt256 LedgerHash
std::variant< LedgerRange, ::rpc::spec::LedgerShortcut, std::uint32_t, uint256 > LedgerSpecifier
Definition AccountTx.cpp:92
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
std::string toStringIso(date::sys_time< Duration > tp)
Definition chrono.h:70
DelegateType
Enumeration of possible delegate types that can occur during filtering in account_tx.
@ Authorizer
This account signed and submitted transactions on behalf of another account (this account is the sign...
@ Actor
Another account signed and submitted transactions on behalf of this account (this account is the owne...
json::Value rpcError(ErrorCodeI iError)
Definition RPCErr.cpp:13
std::variant< LedgerRange, ::rpc::Status > getLedgerRange(rpc::Context &context, std::optional< LedgerSpecifier > const &ledgerSpecifier)
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
RelationalDatabase::TxnMetaLedgerType TxnDataBinary
Definition AccountTx.cpp:86
std::variant< std::optional< LedgerSpecifier >, json::Value > parseLedgerArgs(rpc::Context const &context, json::Value const &params)
bool isUnlimited(Role const &role)
ADMIN and IDENTIFIED roles shall have unlimited resources.
Definition Role.cpp:115
std::optional< RelationalDatabase::AccountTxMarker > marker
std::optional< DelegateFilter > delegate
std::optional< LedgerSpecifier > ledger
Definition AccountTx.cpp:98
unsigned int UnderlyingT
Definition STBase.h:23
std::variant< AccountTxs, MetaTxsList > transactions
std::optional< AccountTxMarker > marker
The context of information needed to call an RPC.
Definition Context.h:27
resource::Charge & loadType
Definition Context.h:30
beast::Journal const j
Definition Context.h:28
unsigned int apiVersion
Definition Context.h:37
Application & app
Definition Context.h:29
LedgerMaster & ledgerMaster
Definition Context.h:32
json::Value params
Definition Context.h:51
T unexpected(T... args)
T visit(T... args)