Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
Tx.hpp
1#pragma once
2
3#include "data/BackendInterface.hpp"
4#include "data/Types.hpp"
5#include "etl/ETLServiceInterface.hpp"
6#include "rpc/JS.hpp"
7#include "rpc/RPCHelpers.hpp"
8#include "rpc/common/SpecBackend.hpp"
9#include "rpc/common/Types.hpp"
10#include "util/Assert.hpp"
11
12#include <boost/asio/spawn.hpp>
13#include <boost/json/conversion.hpp>
14#include <boost/json/object.hpp>
15#include <boost/json/value.hpp>
16#include <boost/json/value_to.hpp>
17#include <fmt/format.h>
18#include <rpcspec/Errors.hpp>
19#include <rpcspec/handlers/tx/Types.hpp>
20#include <xrpl/basics/chrono.h>
21#include <xrpl/basics/strHex.h>
22#include <xrpl/protocol/LedgerHeader.h>
23#include <xrpl/protocol/jss.h>
24
25#include <cstdint>
26#include <memory>
27#include <optional>
28#include <string>
29#include <utility>
30
31namespace rpc {
32
38class TxHandler : public rpc::HandlerFor<rpc::spec::handlers::tx::Input> {
39 std::shared_ptr<BackendInterface> sharedPtrBackend_;
40 std::shared_ptr<etl::ETLServiceInterface const> etl_;
41
42public:
46 struct Output {
47 uint32_t date = 0u;
51 std::string hash = {}; // NOLINT(readability-redundant-member-init)
52 uint32_t ledgerIndex = 0u;
56 std::optional<boost::json::object> meta =
57 std::nullopt; // NOLINT(readability-redundant-member-init)
61 std::optional<boost::json::object> tx =
62 std::nullopt; // NOLINT(readability-redundant-member-init)
66 std::optional<std::string> metaStr =
67 std::nullopt; // NOLINT(readability-redundant-member-init)
71 std::optional<std::string> txStr =
72 std::nullopt; // NOLINT(readability-redundant-member-init)
76 std::optional<std::string> ctid =
77 std::nullopt; // NOLINT(readability-redundant-member-init)
81 std::optional<xrpl::LedgerHeader> ledgerHeader =
82 std::nullopt; // NOLINT(readability-redundant-member-init) ledger hash when apiVersion
83 // >= 2
84 uint32_t apiVersion = 0u;
85 bool validated = true;
86 };
87
92
100 std::shared_ptr<BackendInterface> sharedPtrBackend,
101 std::shared_ptr<etl::ETLServiceInterface const> const& etl
102 )
103 : sharedPtrBackend_(std::move(sharedPtrBackend)), etl_(etl)
104 {
105 }
106
114 [[nodiscard]] Result
115 process(Input const& input, Context const& ctx) const
116 {
117 if (input.ctid && input.transaction) // ambiguous identifier
118 return Error{Status{XrpldError::RpcInvalidParams}};
119
120 if (!input.ctid && !input.transaction) // at least one identifier must be supplied
121 return Error{Status{XrpldError::RpcInvalidParams}};
122
123 static constexpr auto kMaxLedgerRange = 1000u;
124 auto const rangeSupplied = input.minLedger && input.maxLedger;
125
126 if (rangeSupplied) {
127 if (*input.minLedger > *input.maxLedger)
128 return Error{Status{XrpldError::RpcInvalidLgrRange}};
129
130 if (*input.maxLedger - *input.minLedger > kMaxLedgerRange)
131 return Error{Status{XrpldError::RpcExcessiveLgrRange}};
132 }
133
134 std::optional<uint32_t> currentNetId = std::nullopt;
135 if (auto const& etlState = etl_->getETLState(); etlState.has_value())
136 currentNetId = etlState->networkID;
137
138 std::optional<data::TransactionAndMetadata> dbResponse;
139
140 if (input.ctid) {
141 auto const ctid = rpc::decodeCTID(*input.ctid);
142 if (!ctid)
143 return Error{Status{XrpldError::RpcInvalidParams}};
144
145 auto const [lgrSeq, txnIdx, netId] = *ctid;
146 // when current network id is available, let us check the network id from parameter
147 if (currentNetId && netId != *currentNetId) {
148 return Error{Status{
149 XrpldError::RpcWrongNetwork,
150 fmt::format(
151 "Wrong network. You should submit this request to a node running on "
152 "NetworkID: {}",
153 netId
154 )
155 }};
156 }
157
158 dbResponse = fetchTxViaCtid(lgrSeq, txnIdx, ctx.yield);
159 } else {
160 dbResponse = sharedPtrBackend_->fetchTransaction(*input.transaction, ctx.yield);
161 }
162
163 auto output = TxHandler::Output{.apiVersion = ctx.apiVersion};
164
165 if (!dbResponse) {
166 if (rangeSupplied && input.transaction) // ranges not for ctid
167 {
168 auto const range = sharedPtrBackend_->fetchLedgerRange();
169 ASSERT(range.has_value(), "Tx's ledger range must be available");
170
171 // NOLINTBEGIN(bugprone-unchecked-optional-access)
172 auto const searchedAll = range->maxSequence >= *input.maxLedger &&
173 range->minSequence <= *input.minLedger;
174 // NOLINTEND(bugprone-unchecked-optional-access)
175
176 return Error{
177 Status{XrpldError::RpcTxnNotFound, ExtraInfo{{"searched_all", searchedAll}}}
178 };
179 }
180
181 return Error{Status{XrpldError::RpcTxnNotFound}};
182 }
183
184 auto const [txn, meta] =
185 toExpandedJson(*dbResponse, ctx.apiVersion, NFTokenjson::ENABLE, currentNetId);
186
187 if (!input.binary) {
188 output.tx = txn;
189 output.meta = meta;
190 } else {
191 output.txStr = xrpl::strHex(dbResponse->transaction);
192 output.metaStr = xrpl::strHex(dbResponse->metadata);
193
194 // input.transaction might be not available, get hash via tx object
195 if (txn.contains(JS(hash)))
196 output.hash = txn.at(JS(hash)).as_string();
197 }
198
199 // append ctid here to mimic rippled behavior
200 auto const txnIdx = boost::json::value_to<uint64_t>(meta.at("TransactionIndex"));
201 if (txnIdx <= 0xFFFFU && dbResponse->ledgerSequence < 0x0FFF'FFFFUL && currentNetId &&
202 *currentNetId <= 0xFFFFU) {
203 output.ctid = rpc::encodeCTID(
204 dbResponse->ledgerSequence,
205 static_cast<uint16_t>(txnIdx),
206 static_cast<uint16_t>(*currentNetId)
207 );
208 }
209
210 output.date = dbResponse->date;
211 output.ledgerIndex = dbResponse->ledgerSequence;
212
213 // fetch ledger hash
214 if (ctx.apiVersion > 1u) {
215 output.ledgerHeader =
216 sharedPtrBackend_->fetchLedgerBySequence(dbResponse->ledgerSequence, ctx.yield);
217 }
218
219 return output;
220 }
221
222private:
223 [[nodiscard]] std::optional<data::TransactionAndMetadata>
224 fetchTxViaCtid(uint32_t ledgerSeq, uint32_t txId, boost::asio::yield_context yield) const
225 {
226 auto const txs = sharedPtrBackend_->fetchAllTransactionsInLedger(ledgerSeq, yield);
227
228 for (auto const& tx : txs) {
229 auto const [txn, meta] = deserializeTxPlusMeta(tx, ledgerSeq);
230
231 if (meta->getIndex() == txId)
232 return tx;
233 }
234
235 return std::nullopt;
236 }
237
238 friend void
239 tag_invoke(boost::json::value_from_tag, boost::json::value& jv, Output const& output)
240 {
241 auto const getJsonV1 = [&] {
242 auto obj = boost::json::object{};
243
244 if (output.tx) {
245 obj = *output.tx;
246 obj[JS(meta)] = *output.meta;
247 } else {
248 obj[JS(meta)] = *output.metaStr;
249 obj[JS(tx)] = *output.txStr;
250 obj[JS(hash)] = output.hash;
251 }
252
253 obj[JS(validated)] = output.validated;
254 obj[JS(date)] = output.date;
255 obj[JS(ledger_index)] = output.ledgerIndex;
256 obj[JS(inLedger)] = output.ledgerIndex;
257 return obj;
258 };
259
260 auto const getJsonV2 = [&] {
261 auto obj = boost::json::object{};
262
263 if (output.tx) {
264 obj[JS(tx_json)] = *output.tx;
265 obj[JS(tx_json)].as_object()[JS(date)] = output.date;
266 if (output.ctid)
267 obj[JS(tx_json)].as_object()[JS(ctid)] = *output.ctid;
268
269 obj[JS(tx_json)].as_object()[JS(ledger_index)] = output.ledgerIndex;
270 // move hash from tx_json to root
271 if (obj[JS(tx_json)].as_object().contains(JS(hash))) {
272 obj[JS(hash)] = obj[JS(tx_json)].as_object()[JS(hash)];
273 obj[JS(tx_json)].as_object().erase(JS(hash));
274 }
275 obj[JS(meta)] = *output.meta;
276 } else {
277 obj[JS(meta_blob)] = *output.metaStr;
278 obj[JS(tx_blob)] = *output.txStr;
279 obj[JS(hash)] = output.hash;
280 }
281
282 obj[JS(validated)] = output.validated;
283 obj[JS(ledger_index)] = output.ledgerIndex;
284
285 if (output.ledgerHeader) {
286 obj[JS(ledger_hash)] = xrpl::strHex(output.ledgerHeader->hash);
287 obj[JS(close_time_iso)] = xrpl::toStringIso(output.ledgerHeader->closeTime);
288 }
289 return obj;
290 };
291
292 auto obj = output.apiVersion > 1u ? getJsonV2() : getJsonV1();
293
294 if (output.ctid)
295 obj[JS(ctid)] = *output.ctid;
296
297 jv = std::move(obj);
298 }
299};
300
301} // namespace rpc
TxHandler(std::shared_ptr< BackendInterface > sharedPtrBackend, std::shared_ptr< etl::ETLServiceInterface const > const &etl)
Construct a new TxHandler object.
Definition Tx.hpp:99
Result process(Input const &input, Context const &ctx) const
Process the Tx command.
Definition Tx.hpp:115
HandlerReturnType< Output > Result
The result type of the command: either the Output or an error status.
Definition Tx.hpp:91
This namespace contains everything to do with the ETL and ETL sources.
Definition AmendmentBlockHandlerInterface.hpp:6
This namespace contains all the RPC logic and handlers.
Definition AMMHelpers.cpp:17
std::pair< boost::json::object, boost::json::object > toExpandedJson(data::TransactionAndMetadata const &blobs, std::uint32_t const apiVersion, NFTokenjson nftEnabled, std::optional< uint32_t > networkId)
Convert a TransactionAndMetadata to two JSON objects.
Definition RPCHelpers.cpp:235
std::expected< OutputType, Status > HandlerReturnType
Return type for each individual handler.
Definition Types.hpp:63
std::optional< std::tuple< uint32_t, uint16_t, uint16_t > > decodeCTID(T const ctid) noexcept
Decode the CTID from a string or a uint64_t.
Definition RPCHelpers.hpp:799
spec::HandlerFor< InputT, boost::json::value > HandlerFor
The spec-driven base every typed handler inherits.
Definition SpecBackend.hpp:24
std::unexpected< Status > Error
The type that represents just the error part of MaybeError.
Definition Types.hpp:55
std::optional< std::string > encodeCTID(uint32_t ledgerSeq, uint16_t txnIndex, uint32_t networkId) noexcept
Encode CTID as string.
Definition RPCHelpers.cpp:272
@ ENABLE
Insert synthetic NFT fields (e.g. nftoken_id, offer_id) into the metadata.
Definition RPCHelpers.hpp:73
std::pair< std::shared_ptr< xrpl::STTx const >, std::shared_ptr< xrpl::STObject const > > deserializeTxPlusMeta(data::TransactionAndMetadata const &blobs)
Deserialize a TransactionAndMetadata into a pair of STTx and STObject.
Definition RPCHelpers.cpp:186
Context of an RPC call.
Definition Types.hpp:102
uint32_t apiVersion
The API version requested by the client; 0 means invalid/unset.
Definition Types.hpp:126
boost::asio::yield_context yield
The coroutine context the RPC call is executed in.
Definition Types.hpp:106
Result type used to return responses or error statuses to the Webserver subsystem.
Definition Types.hpp:132
A struct to hold the output data of the command.
Definition Tx.hpp:46
std::string hash
Transaction hash, only set when binary was requested.
Definition Tx.hpp:51
std::optional< boost::json::object > meta
Metadata as JSON, unless binary was requested.
Definition Tx.hpp:56
std::optional< std::string > metaStr
Hex-encoded metadata, if binary was requested.
Definition Tx.hpp:66
std::optional< std::string > ctid
Compact transaction ID, if the network ID is known and the CTID can be encoded.
Definition Tx.hpp:76
uint32_t apiVersion
API version of the request.
Definition Tx.hpp:84
uint32_t ledgerIndex
Sequence of the ledger containing the transaction.
Definition Tx.hpp:52
std::optional< std::string > txStr
Hex-encoded transaction, if binary was requested.
Definition Tx.hpp:71
uint32_t date
Close time of the ledger containing the transaction.
Definition Tx.hpp:47
std::optional< xrpl::LedgerHeader > ledgerHeader
Header of the containing ledger (API version 2+).
Definition Tx.hpp:81
bool validated
Whether the ledger is validated.
Definition Tx.hpp:85
std::optional< boost::json::object > tx
Transaction as JSON, unless binary was requested.
Definition Tx.hpp:61