xrpld
Loading...
Searching...
No Matches
applySteps.cpp
1#include <xrpl/tx/applySteps.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/basics/base_uint.h>
6#include <xrpl/beast/utility/Zero.h>
7#include <xrpl/beast/utility/instrumentation.h>
8#include <xrpl/ledger/ApplyView.h>
9#include <xrpl/ledger/OpenView.h>
10#include <xrpl/protocol/Rules.h>
11#include <xrpl/protocol/SField.h>
12#include <xrpl/protocol/SeqProxy.h>
13#include <xrpl/protocol/TER.h>
14#include <xrpl/protocol/XRPAmount.h>
15#include <xrpl/tx/ApplyContext.h>
16#include <xrpl/tx/Transactor.h>
17
18#include <cstdint>
19#include <exception>
20#include <expected>
21#include <memory>
22#include <optional>
23#include <utility>
24#pragma push_macro("TRANSACTION")
25#undef TRANSACTION
26
27// Do nothing
28#define TRANSACTION(...)
29#define TRANSACTION_INCLUDE 1
30
31#include <xrpl/protocol/detail/transactions.macro>
32
33#undef TRANSACTION
34#undef TRANSACTION_INCLUDE
35
36#pragma pop_macro("TRANSACTION")
37
38// DO NOT INCLUDE TRANSACTOR HEADER FILES HERE.
39// See the instructions at the top of transactions.macro instead.
40
41#include <xrpl/core/ServiceRegistry.h>
42#include <xrpl/protocol/TxFormats.h>
43
44namespace xrpl {
45
46namespace {
47
48struct UnknownTxnType : std::exception
49{
50 TxType txnType;
51 UnknownTxnType(TxType t) : txnType{t}
52 {
53 }
54};
55
56// Call a lambda with the concrete transaction type as a template parameter
57// throw an "UnknownTxnType" exception on error
58template <class F>
59auto
60withTxnType(Rules const& rules, TxType txnType, F&& f)
61{
62 // These global updates really should have been for every Transaction
63 // step: preflight, preclaim, calculateBaseFee, and doApply. Unfortunately,
64 // they were only included in doApply (via Transactor::operator()). That may
65 // have been sufficient when the changes were only related to operations
66 // that mutated data, but some features will now change how they read data,
67 // so these need to be more global.
68 //
69 // To prevent unintentional side effects on existing checks, they will be
70 // set for every operation only once at least one of the relevant amendments
71 // are enabled.
72 //
73 // See also Transactor::operator().
74 //
75 std::optional<CurrentTransactionRulesGuard> rulesGuard;
76 std::optional<NumberMantissaScaleGuard> mantissaScaleGuard;
77 createGuards(rules, rulesGuard, mantissaScaleGuard);
78
79 switch (txnType)
80 {
81#pragma push_macro("TRANSACTION")
82#undef TRANSACTION
83
84#define TRANSACTION(tag, value, name, ...) \
85 case tag: \
86 return f.template operator()<name>();
87
88#include <xrpl/protocol/detail/transactions.macro>
89
90#undef TRANSACTION
91#pragma pop_macro("TRANSACTION")
92 default:
93 throw UnknownTxnType(txnType);
94 }
95}
96} // namespace
97
98// Templates so preflight does the right thing with T::kConsequencesFactory.
99//
100// This could be done more easily using if constexpr, but Visual Studio
101// 2017 doesn't handle if constexpr correctly. So once we're no longer
102// building with Visual Studio 2017 we can consider replacing the four
103// templates with a single template function that uses if constexpr.
104//
105// For ConsequencesFactoryType::Normal
106//
107
108template <class T>
109 requires(T::kConsequencesFactory == Transactor::ConsequencesFactoryType::Normal)
112{
113 return TxConsequences(ctx.tx);
114};
115
116// For ConsequencesFactoryType::Blocker
117template <class T>
118 requires(T::kConsequencesFactory == Transactor::ConsequencesFactoryType::Blocker)
119TxConsequences
124
125// For ConsequencesFactoryType::Custom
126template <class T>
127 requires(T::kConsequencesFactory == Transactor::ConsequencesFactoryType::Custom)
128TxConsequences
130{
131 return T::makeTxConsequences(ctx);
132};
133
136{
137 try
138 {
139 return withTxnType(ctx.rules, ctx.tx.getTxnType(), [&]<typename T> {
140 auto const tec = Transactor::invokePreflight<T>(ctx);
141 return std::make_pair(
142 tec, isTesSuccess(tec) ? consequencesHelper<T>(ctx) : TxConsequences{tec});
143 });
144 }
145 catch (UnknownTxnType const& e)
146 {
147 // Should never happen
148 // LCOV_EXCL_START
149 JLOG(ctx.j.fatal()) << "Unknown transaction type in preflight: " << e.txnType;
150 UNREACHABLE("xrpl::invokePreflight : unknown transaction type");
151 return {temUNKNOWN, TxConsequences{temUNKNOWN}};
152 // LCOV_EXCL_STOP
153 }
154}
155
156static TER
158{
159 try
160 {
161 // use name hiding to accomplish compile-time polymorphism of static
162 // class functions for Transactor and derived classes.
163 return withTxnType(ctx.view.rules(), ctx.tx.getTxnType(), [&]<typename T> -> TER {
164 // preclaim functionality is divided into two sections:
165 // 1. Up to and including the signature check: returns NotTEC.
166 // All transaction checks before and including checkSign
167 // MUST return NotTEC, or something more restrictive.
168 // Allowing tec results in these steps risks theft or
169 // destruction of funds, as a fee will be charged before the
170 // signature is checked.
171 // 2. After the signature check: returns TER.
172
173 // If the transactor requires a valid account and the
174 // transaction doesn't list one, preflight will have already
175 // a flagged a failure.
176 auto const id = ctx.tx.getAccountID(sfAccount);
177
178 if (id != beast::kZero)
179 {
180 if (NotTEC const preSigResult = [&] -> NotTEC {
181 if (NotTEC const result = T::checkSeqProxy(ctx.view, ctx.tx, ctx.j))
182 return result;
183
184 if (NotTEC const result = T::checkPriorTxAndLastLedger(ctx))
185 return result;
186
187 if (NotTEC const result = T::checkSponsor(ctx.view, ctx.tx))
188 return result;
189
190 if (NotTEC const result =
191 Transactor::invokeCheckPermission<T>(ctx.view, ctx.tx))
192 return result;
193
194 if (NotTEC const result = T::checkSign(ctx))
195 return result;
196
197 return tesSUCCESS;
198 }())
199 return preSigResult;
200
201 // We can't check the fee if we can't compute it, so reject.
202 auto const baseFee = calculateBaseFee(ctx.view, ctx.tx);
203 if (!baseFee)
204 return baseFee.error();
205
206 if (TER const result = T::checkFee(ctx, *baseFee))
207 return result;
208 }
209
210 return T::preclaim(ctx);
211 });
212 }
213 catch (UnknownTxnType const& e)
214 {
215 // Should never happen
216 // LCOV_EXCL_START
217 JLOG(ctx.j.fatal()) << "Unknown transaction type in preclaim: " << e.txnType;
218 UNREACHABLE("xrpl::invokePreclaim : unknown transaction type");
219 return temUNKNOWN;
220 // LCOV_EXCL_STOP
221 }
222}
223
239static std::expected<XRPAmount, TER>
240invokeCalculateBaseFee(ReadView const& view, STTx const& tx)
241{
242 try
243 {
244 return withTxnType(view.rules(), tx.getTxnType(), [&]<typename T> {
245 return T::calculateBaseFee(view, tx);
246 });
247 }
248 catch (UnknownTxnType const&)
249 {
250 // LCOV_EXCL_START
251 UNREACHABLE("xrpl::invoke_calculateBaseFee : unknown transaction type");
253 // LCOV_EXCL_STOP
254 }
255 catch (std::exception const& e)
256 {
257 JLOG(debugLog().error()) << "calculateBaseFee: " << tx.getTransactionID()
258 << " threw an exception: " << e.what();
260 }
261 catch (...)
262 {
263 JLOG(debugLog().error()) << "calculateBaseFee: " << tx.getTransactionID()
264 << " threw an unknown exception";
266 }
267}
268
270 : isBlocker_(false)
271 , fee_(beast::kZero)
272 , potentialSpend_(beast::kZero)
273 , seqProx_(SeqProxy::rawSequence(0))
275{
276 XRPL_ASSERT(
277 !isTesSuccess(pfResult), "xrpl::TxConsequences::TxConsequences : is not tesSUCCESS");
278}
279
281 : isBlocker_(false)
282 , fee_(tx[sfFee].native() && !tx[sfFee].negative() ? tx[sfFee].xrp() : beast::kZero)
283 , potentialSpend_(beast::kZero)
284 , seqProx_(tx.getSeqProxy())
285 , sequencesConsumed_(tx.getSeqProxy().isSeq() ? 1 : 0)
286{
287}
288
293
298
303
304static ApplyResult
306{
307 try
308 {
309 return withTxnType(ctx.view().rules(), ctx.tx.getTxnType(), [&]<typename T> {
310 T p(ctx);
311 return p();
312 });
313 }
314 catch (UnknownTxnType const& e)
315 {
316 // Should never happen
317 // LCOV_EXCL_START
318 JLOG(ctx.journal.fatal()) << "Unknown transaction type in apply: " << e.txnType;
319 UNREACHABLE("xrpl::invokeApply : unknown transaction type");
320 return {temUNKNOWN, false};
321 // LCOV_EXCL_STOP
322 }
323}
324
325// Test-only factory — not part of the public API.
326// The returned Transactor holds a raw reference to ctx; the caller must ensure
327// the ApplyContext outlives the Transactor.
330{
331 return withTxnType(
332 ctx.view().rules(), ctx.tx.getTxnType(), [&]<typename T> -> std::unique_ptr<Transactor> {
333 return std::make_unique<T>(ctx);
334 });
335}
336
337PreflightResult
339 ServiceRegistry& registry,
340 Rules const& rules,
341 STTx const& tx,
342 ApplyFlags flags,
344{
345 PreflightContext const pfCtx(registry, tx, rules, flags, j);
346
347 // XRPL_ASSERT_IF in the PreflightContext constructor only fires in debug
348 // builds; re-check the same invariant here so a release build can't
349 // silently skip a proposed transaction's signature-presence checks
350 // outside of a dry run.
351 if ((flags & TapProposal) != TapNone && (flags & TapDryRun) == TapNone)
352 {
353 // LCOV_EXCL_START
354 JLOG(j.fatal()) << "apply (preflight): TapProposal set without TapDryRun.";
355 return {pfCtx, {tefEXCEPTION, TxConsequences{tx}}};
356 // LCOV_EXCL_STOP
357 }
358
359 try
360 {
361 return {pfCtx, invokePreflight(pfCtx)};
362 }
363 catch (std::exception const& e)
364 {
365 JLOG(j.fatal()) << "apply (preflight): " << e.what();
366 return {pfCtx, {tefEXCEPTION, TxConsequences{tx}}};
367 }
368}
369
370PreflightResult
372 ServiceRegistry& registry,
373 Rules const& rules,
374 UInt256 const& parentBatchId,
375 STTx const& tx,
376 ApplyFlags flags,
378{
379 PreflightContext const pfCtx(registry, tx, parentBatchId, rules, flags, j);
380
381 // See the comment in the other preflight() overload above.
382 if ((flags & TapProposal) != TapNone && (flags & TapDryRun) == TapNone)
383 {
384 // LCOV_EXCL_START
385 JLOG(j.fatal()) << "apply (preflight): TapProposal set without TapDryRun.";
386 return {pfCtx, {tefEXCEPTION, TxConsequences{tx}}};
387 // LCOV_EXCL_STOP
388 }
389
390 try
391 {
392 return {pfCtx, invokePreflight(pfCtx)};
393 }
394 catch (std::exception const& e)
395 {
396 JLOG(j.fatal()) << "apply (preflight): " << e.what();
397 return {pfCtx, {tefEXCEPTION, TxConsequences{tx}}};
398 }
399}
400
401NotTEC
402invokeCheckPermission(ReadView const& view, STTx const& tx)
403{
404 try
405 {
406 return withTxnType(view.rules(), tx.getTxnType(), [&]<typename T> {
407 return Transactor::invokeCheckPermission<T>(view, tx);
408 });
409 }
410 // LCOV_EXCL_START
411 catch (UnknownTxnType const& e)
412 {
413 // Should never happen
414 JLOG(debugLog().fatal()) << "Unknown transaction type in invokeCheckPermission: "
415 << e.txnType;
416 UNREACHABLE("xrpl::invokeCheckPermission : unknown transaction type");
417 return temUNKNOWN;
418 }
419 // LCOV_EXCL_STOP
420}
421
422PreclaimResult
423preclaim(PreflightResult const& preflightResult, ServiceRegistry& registry, OpenView const& view)
424{
426 if (preflightResult.rules != view.rules())
427 {
428 auto const secondFlight = [&] {
429 if (preflightResult.parentBatchId)
430 {
431 return preflight(
432 registry,
433 view.rules(),
434 preflightResult.parentBatchId.value(),
435 preflightResult.tx,
436 preflightResult.flags,
437 preflightResult.j);
438 }
439
440 return preflight(
441 registry,
442 view.rules(),
443 preflightResult.tx,
444 preflightResult.flags,
445 preflightResult.j);
446 }();
447
448 ctx.emplace(
449 registry,
450 view,
451 secondFlight.ter,
452 secondFlight.tx,
453 secondFlight.flags,
454 secondFlight.parentBatchId,
455 secondFlight.j);
456 }
457 else
458 {
459 ctx.emplace(
460 registry,
461 view,
462 preflightResult.ter,
463 preflightResult.tx,
464 preflightResult.flags,
465 preflightResult.parentBatchId,
466 preflightResult.j);
467 }
468
469 try
470 {
471 if (!isTesSuccess(ctx->preflightResult))
472 return {*ctx, ctx->preflightResult};
473 return {*ctx, invokePreclaim(*ctx)};
474 }
475 catch (std::exception const& e)
476 {
477 JLOG(ctx->j.fatal()) << "apply (preclaim): " << e.what();
478 return {*ctx, tefEXCEPTION};
479 }
480}
481
482std::expected<XRPAmount, TER>
483calculateBaseFee(ReadView const& view, STTx const& tx)
484{
485 return invokeCalculateBaseFee(view, tx);
486}
487
488XRPAmount
489calculateDefaultBaseFee(ReadView const& view, STTx const& tx)
490{
491 return Transactor::calculateBaseFee(view, tx);
492}
493
494ApplyResult
495doApply(PreclaimResult const& preclaimResult, ServiceRegistry& registry, OpenView& view)
496{
497 if (preclaimResult.view.seq() != view.seq())
498 {
499 // Logic error from the caller. Don't have enough
500 // info to recover.
501 return {tefEXCEPTION, false};
502 }
503 try
504 {
505 if (!preclaimResult.likelyToClaimFee)
506 return {preclaimResult.ter, false};
507
508 // For any tx with a real account, preclaim already computed this fee
509 // successfully against this same view.
510 auto const baseFee = calculateBaseFee(view, preclaimResult.tx);
511 if (!baseFee)
512 {
513 // LCOV_EXCL_START
514 JLOG(preclaimResult.j.error())
515 << "apply: could not compute base fee: " << transToken(baseFee.error());
516 return {tefINTERNAL, false};
517 // LCOV_EXCL_STOP
518 }
519
520 ApplyContext ctx(
521 registry,
522 view,
523 preclaimResult.parentBatchId,
524 preclaimResult.tx,
525 preclaimResult.ter,
526 *baseFee,
527 preclaimResult.flags,
528 preclaimResult.j);
529 return invokeApply(ctx);
530 }
531 catch (std::exception const& e)
532 {
533 JLOG(preclaimResult.j.fatal()) << "apply: " << e.what();
534 return {tefEXCEPTION, false};
535 }
536}
537
538} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream fatal() const
Definition Journal.h:368
Stream error() const
Definition Journal.h:362
State information when applying a tx.
STTx const & tx
beast::Journal const journal
ApplyView & view()
Writable ledger view that accumulates state and tx changes.
Definition OpenView.h:59
Rules const & rules() const override
Returns the tx processing rules.
Definition OpenView.cpp:151
A view into a ledger.
Definition ReadView.h:41
virtual Rules const & rules() const =0
Returns the tx processing rules.
LedgerIndex seq() const
Returns the sequence number of the base ledger.
Definition ReadView.h:115
Rules controlling protocol behavior.
Definition Rules.h:40
TxType getTxnType() const
Definition STTx.h:250
UInt256 getTransactionID() const
Definition STTx.h:262
A type that represents either a sequence value or a ticket value.
Definition SeqProxy.h:37
Service registry for dependency injection.
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
Class describing the consequences to the account of applying a transaction if the transaction consume...
Definition applySteps.h:53
TxConsequences(NotTEC pfResult)
std::uint32_t sequencesConsumed_
Number of sequences consumed.
Definition applySteps.h:92
Category
Describes how the transaction affects subsequent transactions.
Definition applySteps.h:59
@ Blocker
Affects the ability of subsequent transactions to claim a fee.
Definition applySteps.h:68
XRPAmount potentialSpend_
Does NOT include the fee.
Definition applySteps.h:84
bool isBlocker_
Describes how the transaction affects subsequent transactions.
Definition applySteps.h:76
std::uint32_t sequencesConsumed() const
Sequences consumed.
Definition applySteps.h:169
XRPAmount const & potentialSpend() const
Potential Spend.
Definition applySteps.h:151
SeqProxy seqProx_
SeqProxy of transaction.
Definition applySteps.h:88
XRPAmount fee_
Transaction fee.
Definition applySteps.h:80
T emplace(T... args)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
PreflightResult preflight(ServiceRegistry &registry, Rules const &rules, STTx const &tx, ApplyFlags flags, beast::Journal j)
Gate a transaction based on static information.
TxType
Transaction type identifiers.
Definition TxFormats.h:45
PreclaimResult preclaim(PreflightResult const &preflightResult, ServiceRegistry &registry, OpenView const &view)
Gate a transaction based on static ledger information.
std::expected< XRPAmount, TER > calculateBaseFee(ReadView const &view, STTx const &tx)
Compute only the expected base fee for a transaction.
beast::Journal debugLog()
Returns a debug journal.
Definition Log.cpp:399
static TER invokePreclaim(PreclaimContext const &ctx)
TxConsequences consequencesHelper(PreflightContext const &ctx)
@ tefINTERNAL
Definition TER.h:167
@ tefEXCEPTION
Definition TER.h:166
void createGuards(Rules const &rules, std::optional< CurrentTransactionRulesGuard > &rulesGuard, std::optional< NumberMantissaScaleGuard > &mantissaScaleGuard)
Definition Rules.cpp:93
std::string transToken(TER code)
Definition TER.cpp:259
static std::pair< NotTEC, TxConsequences > invokePreflight(PreflightContext const &ctx)
BaseUInt< 256 > UInt256
Definition base_uint.h:581
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
static std::expected< XRPAmount, TER > invokeCalculateBaseFee(ReadView const &view, STTx const &tx)
Calculates the base fee for a given transaction.
std::unique_ptr< Transactor > makeTransactor(ApplyContext &ctx)
XRPAmount calculateDefaultBaseFee(ReadView const &view, STTx const &tx)
Return the minimum fee that an "ordinary" transaction would pay.
NotTEC invokeCheckPermission(ReadView const &view, STTx const &tx)
Type-erased overload of Transactor::invokeCheckPermission.
ApplyFlags
Definition ApplyView.h:27
@ TapDryRun
Definition ApplyView.h:46
@ TapProposal
Definition ApplyView.h:53
@ TapNone
Definition ApplyView.h:28
@ temUNKNOWN
Definition TER.h:112
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
static ApplyResult invokeApply(ApplyContext &ctx)
ApplyResult doApply(PreclaimResult const &preclaimResult, ServiceRegistry &registry, OpenView &view)
Apply a prechecked transaction to an OpenView.
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:92
ReadView const & view
Definition Transactor.h:95
Describes the results of the preclaim check.
Definition applySteps.h:264
ReadView const & view
From the input - the ledger view.
Definition applySteps.h:269
TER const ter
Intermediate transaction result.
Definition applySteps.h:290
ApplyFlags const flags
From the input - the flags.
Definition applySteps.h:281
STTx const & tx
From the input - the transaction.
Definition applySteps.h:273
std::optional< UInt256 const > const parentBatchId
From the input - the batch identifier, if part of a batch.
Definition applySteps.h:277
beast::Journal const j
From the input - the journal.
Definition applySteps.h:285
bool const likelyToClaimFee
Success flag - whether the transaction is likely to claim a fee.
Definition applySteps.h:296
State information when preflighting a tx.
Definition Transactor.h:39
beast::Journal const j
Definition Transactor.h:46
Describes the results of the preflight check.
Definition applySteps.h:201
beast::Journal const j
From the input - the journal.
Definition applySteps.h:226
ApplyFlags const flags
From the input - the flags.
Definition applySteps.h:222
Rules const rules
From the input - the rules.
Definition applySteps.h:214
NotTEC const ter
Intermediate transaction result.
Definition applySteps.h:231
STTx const & tx
From the input - the transaction.
Definition applySteps.h:206
std::optional< UInt256 const > const parentBatchId
From the input - the batch identifier, if part of a batch.
Definition applySteps.h:210
T unexpected(T... args)
T what(T... args)