xrpld
Loading...
Searching...
No Matches
RPCLedgerHelpers.cpp
1#include <xrpld/rpc/detail/RPCLedgerHelpers.h>
2
3#include <xrpld/app/ledger/InboundLedger.h>
4#include <xrpld/app/ledger/InboundLedgers.h>
5#include <xrpld/app/ledger/LedgerMaster.h>
6#include <xrpld/app/ledger/LedgerToJson.h>
7#include <xrpld/app/main/Application.h>
8#include <xrpld/rpc/Context.h>
9#include <xrpld/rpc/detail/SpecBridge.hpp>
10#include <xrpld/rpc/detail/Tuning.h>
11
12#include <xrpl/basics/base_uint.h>
13#include <xrpl/beast/core/LexicalCast.h>
14#include <xrpl/beast/utility/Zero.h>
15#include <xrpl/beast/utility/instrumentation.h>
16#include <xrpl/json/json_value.h>
17#include <xrpl/ledger/View.h>
18#include <xrpl/protocol/ErrorCodes.h>
19#include <xrpl/protocol/RPCErr.h>
20#include <xrpl/protocol/RippleLedgerHash.h>
21#include <xrpl/protocol/jss.h>
22
23#include <org/xrpl/rpc/v1/get_ledger.pb.h> // IWYU pragma: keep
24#include <org/xrpl/rpc/v1/get_ledger_data.pb.h> // IWYU pragma: keep
25#include <org/xrpl/rpc/v1/get_ledger_entry.pb.h> // IWYU pragma: keep
26#include <org/xrpl/rpc/v1/ledger.pb.h>
27#include <rpcspec/Errors.hpp>
28#include <rpcspec/Ledger.hpp>
29
30#include <cstdint>
31#include <expected>
32#include <memory>
33#include <utility>
34#include <variant>
35
36namespace xrpl::rpc {
37
38namespace {
39
40template <typename... Ts>
41struct Overload : Ts...
42{
43 using Ts::operator()...;
44
45 constexpr Overload(Ts&&... ts) : Ts(std::forward<Ts>(ts))...
46 {
47 }
48};
49
50bool
51isValidatedOld(LedgerMaster& ledgerMaster, bool standalone)
52{
53 if (standalone)
54 return false;
55
56 return ledgerMaster.getValidatedLedgerAge() > tuning::kMaxValidatedLedgerAge;
57}
58
59template <class T>
60::rpc::Status
61ledgerFromHash(
62 T& ledger,
63 json::Value hash,
64 Context const& context,
65 json::StaticString const fieldName)
66{
67 UInt256 ledgerHash;
68 if (!ledgerHash.parseHex(hash.asString()))
69 return {RpcInvalidParams, expectedFieldMessage(fieldName, "hex string")};
70 return getLedger(ledger, ledgerHash, context);
71}
72
73template <class T>
74::rpc::Status
75ledgerFromIndex(
76 T& ledger,
77 json::Value indexValue,
78 Context const& context,
79 json::StaticString const fieldName)
80{
81 auto const index = indexValue.asString();
82
83 if (index == "current" || index.empty())
84 return getLedger(ledger, ::rpc::spec::LedgerShortcut::Current, context);
85
86 if (index == "validated")
87 return getLedger(ledger, ::rpc::spec::LedgerShortcut::Validated, context);
88
89 if (index == "closed")
90 return getLedger(ledger, ::rpc::spec::LedgerShortcut::Closed, context);
91
92 std::uint32_t iVal = 0;
93 if (!beast::lexicalCastChecked(iVal, index))
94 return {RpcInvalidParams, expectedFieldMessage(fieldName, "string or number")};
95
96 return getLedger(ledger, iVal, context);
97}
98
99template <class T>
100::rpc::Status
101ledgerFromRequest(T& ledger, JsonContext const& context)
102{
103 ledger.reset();
104
105 auto& params = context.params;
106 auto const hasLedger = context.params.isMember(jss::ledger);
107 auto const hasHash = context.params.isMember(jss::ledger_hash);
108 auto const hasIndex = context.params.isMember(jss::ledger_index);
109
110 if ((hasLedger + hasHash + hasIndex) > 1)
111 {
112 // while `ledger` is still supported, it is deprecated
113 // and therefore shouldn't be mentioned in the error message
114 if (hasLedger)
115 {
116 return {
118 "Exactly one of 'ledger', 'ledger_hash', or "
119 "'ledger_index' can be specified."};
120 }
121 return {
123 "Exactly one of 'ledger_hash' or "
124 "'ledger_index' can be specified."};
125 }
126
127 // We need to support the legacy "ledger" field.
128 if (hasLedger)
129 {
130 auto& legacyLedger = params[jss::ledger];
131 if (!legacyLedger.isString() && !legacyLedger.isUInt() && !legacyLedger.isInt())
132 {
133 return {RpcInvalidParams, expectedFieldMessage(jss::ledger, "string or number")};
134 }
135 if (legacyLedger.isString() && legacyLedger.asString().size() == 64)
136 {
137 return ledgerFromHash(ledger, legacyLedger, context, jss::ledger);
138 }
139
140 return ledgerFromIndex(ledger, legacyLedger, context, jss::ledger);
141 }
142
143 if (hasHash)
144 {
145 auto const& ledgerHash = params[jss::ledger_hash];
146 if (!ledgerHash.isString())
147 return {RpcInvalidParams, expectedFieldMessage(jss::ledger_hash, "hex string")};
148 return ledgerFromHash(ledger, ledgerHash, context, jss::ledger_hash);
149 }
150
151 if (hasIndex)
152 {
153 auto const& ledgerIndex = params[jss::ledger_index];
154 if (!ledgerIndex.isString() && !ledgerIndex.isUInt() && !ledgerIndex.isInt())
155 {
156 return {RpcInvalidParams, expectedFieldMessage(jss::ledger_index, "string or number")};
157 }
158 return ledgerFromIndex(ledger, ledgerIndex, context, jss::ledger_index);
159 }
160
161 // nothing specified, `index` has a default setting
162 return getLedger(ledger, ::rpc::spec::LedgerShortcut::Current, context);
163}
164} // namespace
165
166template <class T, class R>
167::rpc::Status
168ledgerFromRequest(T& ledger, GRPCContext<R> const& context)
169{
170 R const& request = context.params;
171 return ledgerFromSpecifier(ledger, request.ledger(), context);
172}
173
174// explicit instantiation of above function
175template ::rpc::Status
179
180// explicit instantiation of above function
181template ::rpc::Status
185
186// explicit instantiation of above function
187template ::rpc::Status
191
192template <class T>
193::rpc::Status
195 T& ledger,
196 org::xrpl::rpc::v1::LedgerSpecifier const& specifier,
197 Context const& context)
198{
199 ledger.reset();
200
201 using LedgerCase = org::xrpl::rpc::v1::LedgerSpecifier::LedgerCase;
202 LedgerCase const ledgerCase = specifier.ledger_case();
203 switch (ledgerCase)
204 {
205 case LedgerCase::kHash: {
206 if (auto hash = UInt256::fromVoidChecked(specifier.hash()))
207 {
208 return getLedger(ledger, *hash, context);
209 }
210 return {RpcInvalidParams, "ledgerHashMalformed"};
211 }
212 case LedgerCase::kSequence:
213 return getLedger(ledger, specifier.sequence(), context);
214 case LedgerCase::kShortcut:
215 [[fallthrough]];
216 case LedgerCase::LEDGER_NOT_SET: {
217 auto const shortcut = specifier.shortcut();
218 if (shortcut == org::xrpl::rpc::v1::LedgerSpecifier::SHORTCUT_VALIDATED)
219 {
220 return getLedger(ledger, ::rpc::spec::LedgerShortcut::Validated, context);
221 }
222
223 if (shortcut == org::xrpl::rpc::v1::LedgerSpecifier::SHORTCUT_CURRENT ||
224 shortcut == org::xrpl::rpc::v1::LedgerSpecifier::SHORTCUT_UNSPECIFIED)
225 {
226 return getLedger(ledger, ::rpc::spec::LedgerShortcut::Current, context);
227 }
228 if (shortcut == org::xrpl::rpc::v1::LedgerSpecifier::SHORTCUT_CLOSED)
229 {
230 return getLedger(ledger, ::rpc::spec::LedgerShortcut::Closed, context);
231 }
232 }
233 }
234
235 return ::rpc::Status::kOK;
236}
237
238template <class T>
239::rpc::Status
240getLedger(T& ledger, UInt256 const& ledgerHash, Context const& context)
241{
242 ledger = context.ledgerMaster.getLedgerByHash(ledgerHash);
243 if (ledger == nullptr)
244 return {RpcLgrNotFound, "ledgerNotFound"};
245 return ::rpc::Status::kOK;
246}
247
248template <class T>
249::rpc::Status
250getLedger(T& ledger, uint32_t ledgerIndex, Context const& context)
251{
252 ledger = context.ledgerMaster.getLedgerBySeq(ledgerIndex);
253 if (ledger == nullptr)
254 {
255 auto const cur = context.ledgerMaster.getCurrentLedger();
256 if (cur->header().seq == ledgerIndex)
257 {
258 ledger = cur;
259 }
260 }
261
262 if (ledger == nullptr)
263 return {RpcLgrNotFound, "ledgerNotFound"};
264
265 if (ledger->header().seq > context.ledgerMaster.getValidLedgerIndex() &&
266 isValidatedOld(context.ledgerMaster, context.app.config().standalone()))
267 {
268 ledger.reset();
269 if (context.apiVersion == 1)
270 return {RpcNoNetwork, "InsufficientNetworkMode"};
271 return {RpcNotSynced, "notSynced"};
272 }
273
274 return ::rpc::Status::kOK;
275}
276
277template <class T>
278::rpc::Status
279getLedger(T& ledger, ::rpc::spec::LedgerShortcut shortcut, Context const& context)
280{
281 if (isValidatedOld(context.ledgerMaster, context.app.config().standalone()))
282 {
283 if (context.apiVersion == 1)
284 return {RpcNoNetwork, "InsufficientNetworkMode"};
285 return {RpcNotSynced, "notSynced"};
286 }
287
288 if (shortcut == ::rpc::spec::LedgerShortcut::Validated)
289 {
290 ledger = context.ledgerMaster.getValidatedLedger();
291 if (ledger == nullptr)
292 {
293 if (context.apiVersion == 1)
294 return {RpcNoNetwork, "InsufficientNetworkMode"};
295 return {RpcNotSynced, "notSynced"};
296 }
297
298 XRPL_ASSERT(!ledger->open(), "xrpl::rpc::getLedger : validated is not open");
299 }
300 else
301 {
302 if (shortcut == ::rpc::spec::LedgerShortcut::Current)
303 {
304 ledger = context.ledgerMaster.getCurrentLedger();
305 XRPL_ASSERT(ledger->open(), "xrpl::rpc::getLedger : current is open");
306 }
307 else if (shortcut == ::rpc::spec::LedgerShortcut::Closed)
308 {
309 ledger = context.ledgerMaster.getClosedLedger();
310 XRPL_ASSERT(!ledger->open(), "xrpl::rpc::getLedger : closed is not open");
311 }
312 else
313 {
314 return {RpcInvalidParams, "ledgerIndexMalformed"};
315 }
316
317 if (ledger == nullptr)
318 {
319 if (context.apiVersion == 1)
320 return {RpcNoNetwork, "InsufficientNetworkMode"};
321 return {RpcNotSynced, "notSynced"};
322 }
323
324 static auto const kMinSequenceGap = 10;
325
326 if (ledger->header().seq + kMinSequenceGap < context.ledgerMaster.getValidLedgerIndex())
327 {
328 ledger.reset();
329 if (context.apiVersion == 1)
330 return {RpcNoNetwork, "InsufficientNetworkMode"};
331 return {RpcNotSynced, "notSynced"};
332 }
333 }
334 return ::rpc::Status::kOK;
335}
336
337template <class T>
338::rpc::Status
339getLedger(T& ledger, ::rpc::spec::LedgerSpecifier const& specifier, Context const& context)
340{
341 return std::visit(
342 Overload{
343 [&](std::monostate) {
344 return getLedger(ledger, ::rpc::spec::kDefaultLedgerShortcut, context);
345 },
346 [&](auto const& value) { return getLedger(ledger, value, context); },
347 },
348 specifier.value);
349}
350
351// Explicit instantiation of above four functions
352template ::rpc::Status
354
355template ::rpc::Status
356getLedger<>(std::shared_ptr<ReadView const>&, ::rpc::spec::LedgerShortcut shortcut, Context const&);
357
358template ::rpc::Status
360
361template ::rpc::Status
362getLedger<>(std::shared_ptr<ReadView const>&, ::rpc::spec::LedgerSpecifier const&, Context const&);
363
364// explicit instantiation of ledgerFromSpecifier
365template ::rpc::Status
368 org::xrpl::rpc::v1::LedgerSpecifier const&,
369 Context const&);
370
371// The previous version of the lookupLedger command would accept the
372// "ledger_index" argument as a string and silently treat it as a request to
373// return the current ledger which, while not strictly wrong, could cause a lot
374// of confusion.
375//
376// The code now robustly validates the input and ensures that the only possible
377// values for the "ledger_index" parameter are the index of a ledger passed as
378// an integer or one of the strings "current", "closed" or "validated".
379// Additionally, the code ensures that the value passed in "ledger_hash" is a
380// string and a valid hash. Invalid values will return an appropriate error
381// code.
382//
383// In the absence of the "ledger_hash" or "ledger_index" parameters, the code
384// assumes that "ledger_index" has the value "current".
385//
386// Returns a json::ValueType::Object. If there was an error, it will be in that
387// return value. Otherwise, the object contains the field "validated" and
388// optionally the fields "ledger_hash", "ledger_index" and
389// "ledger_current_index", if they are defined.
390void
391injectLedgerFields(ReadView const& ledger, Context const& context, json::Value& result)
392{
393 auto const& info = ledger.header();
394
395 if (!ledger.open())
396 {
397 result[jss::ledger_hash] = to_string(info.hash);
398 result[jss::ledger_index] = info.seq;
399 }
400 else
401 {
402 result[jss::ledger_current_index] = info.seq;
403 }
404
405 result[jss::validated] = context.ledgerMaster.isValidated(ledger);
406}
407
408::rpc::Status
411 JsonContext const& context,
412 json::Value& result)
413{
414 if (auto status = ledgerFromRequest(ledger, context))
415 return status;
416
417 injectLedgerFields(*ledger, context, result);
418 return ::rpc::Status::kOK;
419}
420
423{
424 json::Value result;
425 if (auto const status = lookupLedger(ledger, context, result))
426 injectSpecError(result, status);
427
428 return result;
429}
430
431std::expected<std::shared_ptr<Ledger const>, json::Value>
433{
434 auto const hasHash = context.params.isMember(jss::ledger_hash);
435 auto const hasIndex = context.params.isMember(jss::ledger_index);
436 std::uint32_t ledgerIndex = 0;
437
438 auto& ledgerMaster = context.app.getLedgerMaster();
439 LedgerHash ledgerHash;
440
441 if ((static_cast<int>(hasHash) + static_cast<int>(hasIndex)) != 1)
442 {
443 return std::unexpected(
445 "Exactly one of 'ledger_hash' or "
446 "'ledger_index' can be specified."));
447 }
448
449 if (hasHash)
450 {
451 auto const& jsonHash = context.params.get(jss::ledger_hash, json::ValueType::Null);
452 if (!jsonHash.isString() || !ledgerHash.parseHex(jsonHash.asString()))
453 return std::unexpected(rpc::expectedFieldError(jss::ledger_hash, "hex string"));
454 }
455 else
456 {
457 auto const& jsonIndex = context.params.get(jss::ledger_index, json::ValueType::Null);
458 if (!jsonIndex.isInt() && !jsonIndex.isUInt())
459 return std::unexpected(rpc::expectedFieldError(jss::ledger_index, "number"));
460
461 // We need a validated ledger to get the hash from the sequence
462 if (ledgerMaster.getValidatedLedgerAge() > rpc::tuning::kMaxValidatedLedgerAge)
463 {
464 if (context.apiVersion == 1)
467 }
468
469 ledgerIndex = jsonIndex.asInt();
470 auto ledger = ledgerMaster.getValidatedLedger();
471
472 if (ledgerIndex >= ledger->header().seq)
473 return std::unexpected(rpc::makeParamError("Ledger index too large"));
474 if (ledgerIndex <= 0)
475 return std::unexpected(rpc::makeParamError("Ledger index too small"));
476
477 auto const j = context.app.getJournal("RPCHandler");
478 // Try to get the hash of the desired ledger from the validated
479 // ledger
480 auto neededHash = hashOfSeq(*ledger, ledgerIndex, j);
481 if (!neededHash)
482 {
483 // Find a ledger more likely to have the hash of the desired
484 // ledger
485 auto const refIndex = getCandidateLedger(ledgerIndex);
486 auto refHash = hashOfSeq(*ledger, refIndex, j);
487 XRPL_ASSERT(refHash, "xrpl::rpc::getOrAcquireLedger : nonzero ledger hash");
488
489 // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above
490 ledger = ledgerMaster.getLedgerByHash(*refHash);
491 if (!ledger)
492 {
493 // We don't have the ledger we need to figure out which
494 // ledger they want. Try to get it.
495
496 if (auto const il = context.app.getInboundLedgers().acquire(
497 *refHash, refIndex, InboundLedger::Reason::GENERIC))
498 {
499 json::Value jvResult = rpc::makeError(
500 RpcLgrNotFound, "acquiring ledger containing requested index");
501 jvResult[jss::acquiring] = getJson(LedgerFill(*il, &context));
502 return std::unexpected(jvResult);
503 }
504
505 if (auto const il = context.app.getInboundLedgers().find(*refHash))
506 // NOLINTEND(bugprone-unchecked-optional-access)
507 {
508 json::Value jvResult = rpc::makeError(
509 RpcLgrNotFound, "acquiring ledger containing requested index");
510 jvResult[jss::acquiring] = il->getJson(0);
511 return std::unexpected(jvResult);
512 }
513
514 // Likely the app is shutting down
516 }
517
518 neededHash = hashOfSeq(*ledger, ledgerIndex, j);
519 }
520 XRPL_ASSERT(neededHash, "xrpl::rpc::getOrAcquireLedger : nonzero needed hash");
521 ledgerHash = neededHash ? *neededHash : beast::kZero; // kludge
522 }
523
524 // Try to get the desired ledger
525 // Verify all nodes even if we think we have it
526 auto ledger = context.app.getInboundLedgers().acquire(
527 ledgerHash, ledgerIndex, InboundLedger::Reason::GENERIC);
528
529 // In standalone mode, accept the ledger from the ledger cache
530 if (!ledger && context.app.config().standalone())
531 ledger = ledgerMaster.getLedgerByHash(ledgerHash);
532
533 if (ledger)
534 return ledger;
535
536 if (auto const il = context.app.getInboundLedgers().find(ledgerHash))
537 return std::unexpected(il->getJson(0));
538
539 return std::unexpected(
540 rpc::makeError(RpcNotReady, "findCreate failed to return an inbound ledger"));
541}
542
543} // namespace xrpl::rpc
Represents a JSON value.
Definition json_value.h:121
Value get(UInt index, Value const &defaultValue) const
If the array contains at least index+1 elements, returns the element value, otherwise returns default...
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.
virtual Config & config()=0
static std::optional< BaseUInt > fromVoidChecked(T const &from)
Definition base_uint.h:347
constexpr bool parseHex(std::string_view sv)
Parse a hex string into a base_uint.
Definition base_uint.h:526
bool standalone() const
virtual std::shared_ptr< Ledger const > acquire(UInt256 const &hash, std::uint32_t seq, InboundLedger::Reason)=0
virtual std::shared_ptr< InboundLedger > find(LedgerHash const &hash)=0
std::shared_ptr< Ledger const > getLedgerBySeq(std::uint32_t index)
Finds a ledger by sequence, preferring the validated chain.
std::shared_ptr< Ledger const > getClosedLedger()
The finalized ledger is the last closed/accepted ledger.
std::shared_ptr< Ledger const > getLedgerByHash(UInt256 const &hash)
std::shared_ptr< Ledger const > getValidatedLedger()
The validated ledger is the last fully validated ledger.
bool isValidated(ReadView const &ledger)
Tests whether a ledger is on the validated chain, using the skip list when the ledger does not alread...
LedgerIndex getValidLedgerIndex()
std::shared_ptr< ReadView const > getCurrentLedger()
The current ledger is the ledger we believe new transactions should go in.
A view into a ledger.
Definition ReadView.h:41
virtual LedgerHeader const & header() const =0
Returns information about the ledger.
virtual bool open() const =0
Returns true if this reflects an open ledger.
virtual beast::Journal getJournal(std::string const &name)=0
virtual InboundLedgers & getInboundLedgers()=0
virtual LedgerMaster & getLedgerMaster()=0
T forward(T... args)
constexpr bool lexicalCastChecked(Out &out, In in)
Intelligently convert from one type to another.
constexpr Zero kZero
Definition Zero.h:30
@ Null
'null' value
Definition json_value.h:26
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
std::expected< std::shared_ptr< Ledger const >, json::Value > getOrAcquireLedger(rpc::JsonContext const &context)
Retrieves or acquires a ledger based on the parameters provided in the given JsonContext.
::rpc::Status ledgerFromRequest(T &ledger, GRPCContext< R > const &context)
Retrieves a ledger from a gRPC request context.
::rpc::Status ledgerFromSpecifier(T &ledger, org::xrpl::rpc::v1::LedgerSpecifier const &specifier, Context const &context)
Retrieves a ledger based on a LedgerSpecifier.
json::Value makeParamError(std::string const &message)
Returns a new json object that indicates invalid parameters.
Definition ErrorCodes.h:231
::rpc::Status getLedger(T &ledger, UInt256 const &ledgerHash, Context const &context)
Retrieves a ledger by its hash.
std::string expectedFieldMessage(std::string const &name, std::string const &type)
Definition ErrorCodes.h:297
::rpc::Status lookupLedger(std::shared_ptr< ReadView const > &ledger, JsonContext const &context, json::Value &result)
Looks up a ledger from a request and fills a json::Value with ledger data.
json::Value makeError(ErrorCodeI code)
Returns a new json object that reflects the error code.
void injectLedgerFields(ReadView const &ledger, Context const &context, json::Value &result)
Writes the fields that identify a ledger into a result.
std::optional< UInt256 > hashOfSeq(ReadView const &ledger, LedgerIndex seq, beast::Journal journal)
Return the hash of a ledger by sequence.
Definition View.cpp:324
@ RpcNoNetwork
Definition ErrorCodes.h:49
@ RpcLgrNotFound
Definition ErrorCodes.h:55
@ RpcNotSynced
Definition ErrorCodes.h:50
@ RpcNotReady
Definition ErrorCodes.h:43
@ RpcInvalidParams
Definition ErrorCodes.h:67
@ RpcNoCurrent
Definition ErrorCodes.h:48
UInt256 LedgerHash
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
LedgerIndex getCandidateLedger(LedgerIndex requested)
Find a ledger index from which we could easily get the requested ledger.
Definition View.h:152
json::Value rpcError(ErrorCodeI iError)
Definition RPCErr.cpp:13
BaseUInt< 256 > UInt256
Definition base_uint.h:581
json::Value getJson(LedgerFill const &fill)
Return a new json::Value representing the ledger with given options.
@ LedgerMaster
ledger master data for signing
Definition HashPrefix.h:59
The context of information needed to call an RPC.
Definition Context.h:27
unsigned int apiVersion
Definition Context.h:37
Application & app
Definition Context.h:29
LedgerMaster & ledgerMaster
Definition Context.h:32
RequestType params
Definition Context.h:59
json::Value params
Definition Context.h:51
T unexpected(T... args)
T visit(T... args)