xrpld
Loading...
Searching...
No Matches
MPTEndpointStep.cpp
1#include <xrpl/basics/Log.h>
2#include <xrpl/basics/Number.h>
3#include <xrpl/basics/base_uint.h>
4#include <xrpl/beast/utility/Journal.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/beast/utility/instrumentation.h>
7#include <xrpl/core/ServiceRegistry.h>
8#include <xrpl/ledger/PaymentSandbox.h>
9#include <xrpl/ledger/View.h>
10#include <xrpl/ledger/helpers/MPTokenHelpers.h>
11#include <xrpl/ledger/helpers/TokenHelpers.h>
12#include <xrpl/protocol/AccountID.h>
13#include <xrpl/protocol/AmountConversions.h>
14#include <xrpl/protocol/Indexes.h>
15#include <xrpl/protocol/MPTAmount.h>
16#include <xrpl/protocol/MPTIssue.h>
17#include <xrpl/protocol/Protocol.h>
18#include <xrpl/protocol/Quality.h>
19#include <xrpl/protocol/STAmount.h>
20#include <xrpl/protocol/TER.h>
21#include <xrpl/protocol/UintTypes.h>
22#include <xrpl/tx/paths/detail/EitherAmount.h>
23#include <xrpl/tx/paths/detail/Steps.h>
24
25#include <boost/container/flat_set.hpp>
26
27#include <algorithm>
28#include <cstdint>
29#include <memory>
30#include <optional>
31#include <sstream>
32#include <string>
33#include <utility>
34
35namespace xrpl {
36
37template <class TDerived>
38class MPTEndpointStep : public StepImp<MPTAmount, MPTAmount, MPTEndpointStep<TDerived>>
39{
40protected:
44
45 // Charge transfer fees when the prev step redeems
46 Step const* const prevStep_ = nullptr;
47 bool const isLast_;
48 // Direct payment between the holders
49 // Used by maxFlow's last step.
50 bool const isDirectBetweenHolders_ = false;
52
69
71
72 // Compute the maximum value that can flow from src->dst at
73 // the best available quality.
74 // return: first element is max amount that can flow,
75 // second is the debt direction of the source w.r.t. the dst
77 maxPaymentFlow(ReadView const& sb) const;
78
79 // Compute srcQOut and dstQIn when the source redeems.
81 qualitiesSrcRedeems(ReadView const& sb) const;
82
83 // Compute srcQOut and dstQIn when the source issues.
85 qualitiesSrcIssues(ReadView const& sb, DebtDirection prevStepDebtDirection) const;
86
87 // Returns srcQOut, dstQIn
89 qualities(ReadView const& sb, DebtDirection srcDebtDir, StrandDirection strandDir) const;
90
91 void
93
94 [[nodiscard]] TER
96 ApplyView& view,
97 AccountID const& src,
98 AccountID const& dst,
99 MPTAmount const& amount);
100
101private:
103 StrandContext const& ctx,
104 AccountID const& src,
105 AccountID const& dst,
106 MPTID const& mpt)
107 : src_(src)
108 , dst_(dst)
109 , mptIssue_(mpt)
110 , prevStep_(ctx.prevStep)
111 , isLast_(ctx.isLast)
113 mptIssue_ == ctx.strandDeliver && ctx.strandSrc != mptIssue_.getIssuer() &&
114 ctx.strandDst != mptIssue_.getIssuer() &&
115 (ctx.isFirst || (ctx.prevStep != nullptr && !ctx.prevStep->bookStepBook())))
116 , j_(ctx.j)
117 {
118 XRPL_ASSERT(
119 src_ == mptIssue_.getIssuer() || dst_ == mptIssue_.getIssuer(),
120 "MPTEndpointStep::MPTEndpointStep src or dst must be an issuer");
121 }
122
123public:
124 [[nodiscard]] AccountID const&
125 src() const
126 {
127 return src_;
128 }
129 [[nodiscard]] AccountID const&
130 dst() const
131 {
132 return dst_;
133 }
134 [[nodiscard]] MPTID const&
135 mptID() const
136 {
137 return mptIssue_.getMptID();
138 }
139
140 [[nodiscard]] std::optional<EitherAmount>
141 cachedIn() const override
142 {
143 if (!cache_)
144 return std::nullopt;
145 return EitherAmount(cache_->in);
146 }
147
148 [[nodiscard]] std::optional<EitherAmount>
149 cachedOut() const override
150 {
151 if (!cache_)
152 return std::nullopt;
153 return EitherAmount(cache_->out);
154 }
155
156 [[nodiscard]] std::optional<AccountID>
157 directStepSrcAcct() const override
158 {
159 return src_;
160 }
161
163 directStepAccts() const override
164 {
165 return std::make_pair(src_, dst_);
166 }
167
168 [[nodiscard]] DebtDirection
169 debtDirection(ReadView const& sb, StrandDirection dir) const override;
170
171 [[nodiscard]] std::uint32_t
172 lineQualityIn(ReadView const& v) const override;
173
175 qualityUpperBound(ReadView const& v, DebtDirection dir) const override;
176
179 PaymentSandbox& sb,
180 ApplyView& afView,
181 boost::container::flat_set<UInt256>& ofrsToRm,
182 MPTAmount const& out);
183
186 PaymentSandbox& sb,
187 ApplyView& afView,
188 boost::container::flat_set<UInt256>& ofrsToRm,
189 MPTAmount const& in);
190
192 validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmount const& in) override;
193
194 // Check for error, existing liquidity, and violations of auth/frozen
195 // constraints.
196 [[nodiscard]] TER
197 check(StrandContext const& ctx) const;
198
199 void
201 MPTAmount const& fwdIn,
202 MPTAmount const& fwdSrcToDst,
203 MPTAmount const& fwdOut,
204 DebtDirection srcDebtDir);
205
206 friend bool
208 {
209 return lhs.src_ == rhs.src_ && lhs.dst_ == rhs.dst_ && lhs.mptIssue_ == rhs.mptIssue_;
210 }
211
212 friend bool
214 {
215 return !(lhs == rhs);
216 }
217
218protected:
220 logStringImpl(char const* name) const
221 {
223 ostr << name << ": "
224 << "\nSrc: " << src_ << "\nDst: " << dst_;
225 return ostr.str();
226 }
227
228private:
229 [[nodiscard]] bool
230 equal(Step const& rhs) const override
231 {
232 if (auto ds = dynamic_cast<MPTEndpointStep const*>(&rhs))
233 {
234 return *this == *ds;
235 }
236 return false;
237 }
238
239 friend TDerived;
240};
241
242//------------------------------------------------------------------------------
243
244// Flow is used in two different circumstances for transferring funds:
245// o Payments, and
246// o Offer crossing.
247// The rules for handling funds in these two cases are almost, but not
248// quite, the same.
249
250// Payment MPTEndpointStep class (not offer crossing).
251class MPTEndpointPaymentStep : public MPTEndpointStep<MPTEndpointPaymentStep>
252{
253public:
256
258 StrandContext const& ctx,
259 AccountID const& src,
260 AccountID const& dst,
261 MPTID const& mpt)
263 {
264 }
265
266 static bool
268 {
269 // A payment doesn't care regardless of prevStepRedeems.
270 return true;
271 }
272
273 // Verify the consistency of the step. These checks are specific to
274 // payments and assume that general checks were already performed.
275 [[nodiscard]] TER
276 check(StrandContext const& ctx, SLE::ConstRef sleSrc) const;
277
278 [[nodiscard]] std::string
279 logString() const override
280 {
281 return logStringImpl("MPTEndpointPaymentStep");
282 }
283
284 // Not applicable for payment
285 static TER
287 {
288 return tesSUCCESS;
289 }
290};
291
292// Offer crossing MPTEndpointStep class (not a payment).
293class MPTEndpointOfferCrossingStep : public MPTEndpointStep<MPTEndpointOfferCrossingStep>
294{
295public:
298
300 StrandContext const& ctx,
301 AccountID const& src,
302 AccountID const& dst,
303 MPTID const& mpt)
305 {
306 }
307
308 static bool
310 {
311 // During offer crossing we rely on the fact that prevStepRedeems
312 // will *always* issue. That's because:
313 // o If there's a prevStep_, it will always be a BookStep.
314 // o BookStep::debtDirection() always returns `issues` when offer
315 // crossing.
316 // An assert based on this return value will tell us if that
317 // behavior changes.
318 return issues(prevStepDir);
319 }
320
321 // Verify the consistency of the step. These checks are specific to
322 // offer crossing and assume that general checks were already performed.
323 static TER
324 check(StrandContext const& ctx, SLE::ConstRef sleSrc);
325
326 [[nodiscard]] std::string
327 logString() const override
328 {
329 return logStringImpl("MPTEndpointOfferCrossingStep");
330 }
331
332 // Can be created in rev or fwd (if limiting step) direction.
333 TER
335};
336
337//------------------------------------------------------------------------------
338
339TER
341{
342 // Since this is a payment, MPToken must be present. Perform all
343 // MPToken related checks.
344
345 // requireAuth checks if MPTIssuance exist. Note that issuer to issuer
346 // payment is invalid
347 auto const& issuer = mptIssue_.getIssuer();
348 if (src_ != issuer)
349 {
350 if (auto const ter = requireAuth(ctx.view, mptIssue_, src_); !isTesSuccess(ter))
351 return ter;
352 }
353
354 if (dst_ != issuer)
355 {
356 if (auto const ter = requireAuth(ctx.view, mptIssue_, dst_); !isTesSuccess(ter))
357 return ter;
358 }
359
360 // Direct MPT payment, no DEX
361 if (mptIssue_ == ctx.strandDeliver &&
362 (ctx.isFirst || (ctx.prevStep != nullptr && !ctx.prevStep->bookStepBook())))
363 {
364 // Between holders
366 {
367 auto const& holder = ctx.isFirst ? src_ : dst_;
368 // Payment between the holders
369 if (isFrozen(ctx.view, holder, mptIssue_))
370 return tecLOCKED;
371
372 if (auto const ter = canTransfer(ctx.view, mptIssue_, holder, ctx.strandDst);
373 !isTesSuccess(ter))
374 return ter;
375 }
376 // Don't need to check if a payment is between issuer and holder
377 // in either direction
378 }
379 // Cross-token MPT payment via DEX
380 else
381 {
382 if (auto const ter = canTrade(ctx.view, mptIssue_); !isTesSuccess(ter))
383 return ter;
384 }
385
386 // Can't check for creditBalance/Limit unless it's the first step.
387 // Otherwise, even if OutstandingAmount is equal to MaximumAmount
388 // a payment can still be successful. For instance, when a balance
389 // is shifted from one holder to another.
390
391 if (prevStep_ == nullptr)
392 {
393 auto const owed = accountFunds(
395 // Already at MaximumAmount
396 if (owed <= beast::kZero)
397 return tecPATH_DRY;
398 }
399
400 return tesSUCCESS;
401}
402
403TER
405{
406 // The standard checks are all we can do because any remaining checks
407 // require the existence of a MPToken. Offer crossing does not
408 // require a pre-existing MPToken.
409 return tesSUCCESS;
410}
411
412TER
414{
415 // TakerPays is the last step if offer crossing
416 if (isLast_)
417 {
418 // Create MPToken for the offer's owner. No need to check
419 // for the reserve since the offer doesn't go on the books
420 // if crossed. Insufficient reserve is allowed if the offer
421 // crossed. See CreateOffer::applyGuts() for reserve check.
422 if (auto const err = xrpl::checkCreateMPT(view, mptIssue_, dst_, j_); !isTesSuccess(err))
423 {
424 // Unreachable: offer-crossing checks reject an offer whose owner
425 // could fail to create the MPToken.
426 // LCOV_EXCL_START
427 UNREACHABLE(
428 "xrpl::MPTEndpointOfferCrossingStep::checkCreateMPT : create MPToken failed");
429 JLOG(j_.trace()) << "MPTEndpointStep::checkCreateMPT: failed create MPT";
430 return err;
431 // LCOV_EXCL_STOP
432 }
433 }
434 return tesSUCCESS;
435}
436
437//------------------------------------------------------------------------------
438
439template <class TDerived>
440TER
442 ApplyView& view,
443 AccountID const& src,
444 AccountID const& dst,
445 MPTAmount const& amount)
446{
447 // Only offer crossing can fail here (payment checkCreateMPT is a no-op),
448 // via the unreachable path excluded in checkCreateMPT() above.
449 if (auto const err = static_cast<TDerived*>(this)->checkCreateMPT(view); !isTesSuccess(err))
450 return err; // LCOV_EXCL_LINE
451
452 return directSendNoFee(
453 view,
454 src,
455 dst,
456 toSTAmount(amount, mptIssue_),
457 /*checkIssuer*/ false,
458 j_);
459}
460
461//------------------------------------------------------------------------------
462
463template <class TDerived>
466{
467 auto const maxFlow = accountFunds(
469
470 // From a holder to an issuer
471 if (src_ != mptIssue_.getIssuer())
473
474 // From an issuer to a holder
475 if (auto const sle = sb.read(keylet::mptokenIssuance(mptIssue_)))
476 {
477 // If issuer is the source account, and it is direct payment then
478 // MPTEndpointStep is the only step. Provide available maxFlow.
479 if (prevStep_ == nullptr)
481
482 // MPTEndpointStep is the last step. It's always issuing in
483 // this case. Can't infer at this point what the maxFlow is, because
484 // the previous step may issue or redeem. Allow OutstandingAmount
485 // to temporarily overflow. Let the previous step figure out how
486 // to limit the flow.
487 std::int64_t const maxAmount = maxMPTAmount(*sle);
488 return {MPTAmount{maxAmount}, DebtDirection::Issues};
489 }
490
491 return {MPTAmount{0}, DebtDirection::Issues};
492}
493
494template <class TDerived>
497{
498 if (dir == StrandDirection::Forward && cache_)
499 return cache_->srcDebtDir;
500
502}
503
504template <class TDerived>
507 PaymentSandbox& sb,
508 ApplyView& /*afView*/,
509 boost::container::flat_set<UInt256>& /*ofrsToRm*/,
510 MPTAmount const& out)
511{
512 cache_.reset();
513
514 auto const [maxSrcToDst, srcDebtDir] = static_cast<TDerived const*>(this)->maxPaymentFlow(sb);
515
516 auto const [srcQOut, dstQIn] = qualities(sb, srcDebtDir, StrandDirection::Reverse);
517 (void)dstQIn;
518
519 JLOG(j_.trace()) << "MPTEndpointStep::rev"
520 << " srcRedeems: " << redeems(srcDebtDir) << " outReq: " << to_string(out)
521 << " maxSrcToDst: " << to_string(maxSrcToDst) << " srcQOut: " << srcQOut
522 << " dstQIn: " << dstQIn;
523
524 if (maxSrcToDst.signum() <= 0)
525 {
526 JLOG(j_.trace()) << "MPTEndpointStep::rev: dry";
527 resetCache(srcDebtDir);
528 return {beast::kZero, beast::kZero};
529 }
530
531 // When a previous step feeds this issuing step, srcQOut is the issuer's
532 // transfer rate and maxPaymentFlow() returns the issuance maximum rather
533 // than a real limit, so srcToDst * srcQOut need not be representable. Cap
534 // srcToDst at the largest amount whose input is; the previous step then
535 // limits the flow to what the source actually holds.
536 MPTAmount const maxRepresentable =
537 mulRatio(MPTAmount(kMaxMpTokenAmount), QUALITY_ONE, srcQOut, /*roundUp*/ false);
538
539 // Don't have to factor in dstQIn since it is always QUALITY_ONE
540 MPTAmount const srcToDst = std::min({out, maxSrcToDst, maxRepresentable});
541
542 // Can't overflow: srcToDst <= kMaxMpTokenAmount * QUALITY_ONE / srcQOut,
543 // so the rounded up product is at most kMaxMpTokenAmount.
544 MPTAmount const in = mulRatio(srcToDst, srcQOut, QUALITY_ONE, /*roundUp*/ true);
545
546 cache_.emplace(in, srcToDst, srcToDst, srcDebtDir);
547
548 auto const ter = sendWithMPTCreate(sb, src_, dst_, srcToDst);
549 if (!isTesSuccess(ter))
550 {
551 // Unreachable: send fails only on funds/auth/overflow, precluded by
552 // maxPaymentFlow, check() requireAuth, and 2*kMaxMpTokenAmount < 2^64.
553 // LCOV_EXCL_START
554 UNREACHABLE("xrpl::MPTEndpointStep::revImp : send failed");
555 JLOG(j_.trace()) << "MPTEndpointStep::rev: error " << ter;
556 resetCache(srcDebtDir);
557 return {beast::kZero, beast::kZero};
558 // LCOV_EXCL_STOP
559 }
560
561 JLOG(j_.trace()) << "MPTEndpointStep::rev: " << (srcToDst < out ? "Limiting" : "Non-limiting")
562 << " srcRedeems: " << redeems(srcDebtDir) << " in: " << to_string(in)
563 << " srcToDst: " << to_string(srcToDst) << " out: " << to_string(out);
564
565 return {in, srcToDst};
566}
567
568// The forward pass should never have more liquidity than the reverse
569// pass. But sometimes rounding differences cause the forward pass to
570// deliver more liquidity. Use the cached values from the reverse pass
571// to prevent this.
572template <class TDerived>
573void
575 MPTAmount const& fwdIn,
576 MPTAmount const& fwdSrcToDst,
577 MPTAmount const& fwdOut,
578 DebtDirection srcDebtDir)
579{
580 // NOLINTBEGIN(bugprone-unchecked-optional-access) cache_ always set before setCacheLimiting is
581 // called
582 if (cache_->in < fwdIn)
583 {
584 MPTAmount const smallDiff(1);
585 auto const diff = fwdIn - cache_->in;
586 if (diff > smallDiff)
587 {
588 if (!cache_->in.value() ||
589 (Number(fwdIn.value()) / Number(cache_->in.value())) > Number(101, -2))
590 {
591 // Detect large diffs on forward pass so they may be
592 // investigated
593 JLOG(j_.warn()) << "MPTEndpointStep::fwd: setCacheLimiting"
594 << " fwdIn: " << to_string(fwdIn)
595 << " cacheIn: " << to_string(cache_->in)
596 << " fwdSrcToDst: " << to_string(fwdSrcToDst)
597 << " cacheSrcToDst: " << to_string(cache_->srcToDst)
598 << " fwdOut: " << to_string(fwdOut)
599 << " cacheOut: " << to_string(cache_->out);
600 cache_.emplace(fwdIn, fwdSrcToDst, fwdOut, srcDebtDir);
601 return;
602 }
603 }
604 }
605 cache_->in = fwdIn;
606 if (fwdSrcToDst < cache_->srcToDst)
607 cache_->srcToDst = fwdSrcToDst;
608 if (fwdOut < cache_->out)
609 cache_->out = fwdOut;
610 cache_->srcDebtDir = srcDebtDir;
611 // NOLINTEND(bugprone-unchecked-optional-access)
612};
613
614template <class TDerived>
617 PaymentSandbox& sb,
618 ApplyView& /*afView*/,
619 boost::container::flat_set<UInt256>& /*ofrsToRm*/,
620 MPTAmount const& in)
621{
622 XRPL_ASSERT(cache_, "MPTEndpointStep<TDerived>::fwdImp : valid cache");
623 // NOLINTBEGIN(bugprone-unchecked-optional-access) assert above
624
625 auto const [maxSrcToDst, srcDebtDir] = static_cast<TDerived const*>(this)->maxPaymentFlow(sb);
626
627 auto const [srcQOut, dstQIn] = qualities(sb, srcDebtDir, StrandDirection::Forward);
628 (void)dstQIn;
629
630 JLOG(j_.trace()) << "MPTEndpointStep::fwd"
631 << " srcRedeems: " << redeems(srcDebtDir) << " inReq: " << to_string(in)
632 << " maxSrcToDst: " << to_string(maxSrcToDst) << " srcQOut: " << srcQOut
633 << " dstQIn: " << dstQIn;
634
635 if (maxSrcToDst.signum() <= 0)
636 {
637 // Unreachable: the reverse pass owns dry detection; every path that
638 // reaches fwdImp (see StrandFlow::flow) has a funded source.
639 // LCOV_EXCL_START
640 UNREACHABLE("xrpl::MPTEndpointStep::fwdImp : dry source");
641 JLOG(j_.trace()) << "MPTEndpointStep::fwd: dry";
642 resetCache(srcDebtDir);
643 return {beast::kZero, beast::kZero};
644 // LCOV_EXCL_STOP
645 }
646
647 auto const maybeSrcToDst = tryMulRatio(in, QUALITY_ONE, srcQOut, /*roundUp*/ false);
648 if (!maybeSrcToDst)
649 {
650 // Unreachable: divides by srcQOut >= QUALITY_ONE, so result <= in <=
651 // maxMPTAmount and can never overflow int64.
652 // LCOV_EXCL_START
653 UNREACHABLE("xrpl::MPTEndpointStep::fwdImp : source to destination overflow");
654 JLOG(j_.trace()) << "MPTEndpointStep::fwd: overflow";
655 resetCache(srcDebtDir);
656 return {beast::kZero, beast::kZero};
657 // LCOV_EXCL_STOP
658 }
659
660 MPTAmount const srcToDst = *maybeSrcToDst;
661
662 if (srcToDst <= maxSrcToDst)
663 {
664 // Don't have to factor in dstQIn since it's always QUALITY_ONE
665 MPTAmount const out = srcToDst;
666 setCacheLimiting(in, srcToDst, out, srcDebtDir);
667
668 JLOG(j_.trace()) << "MPTEndpointStep::fwd: Non-limiting"
669 << " srcRedeems: " << redeems(srcDebtDir) << " in: " << to_string(in)
670 << " srcToDst: " << to_string(srcToDst) << " out: " << to_string(out);
671 }
672 else
673 {
674 // Unreachable: the reverse pass owns all limiting; the forward driver
675 // (StrandFlow::flow) never re-finds a limit, so srcToDst <= maxSrcToDst.
676 // LCOV_EXCL_START
677 UNREACHABLE("xrpl::MPTEndpointStep::fwdImp : forward pass limiting");
678 // limiting node
679 auto const maybeActualIn = tryMulRatio(maxSrcToDst, srcQOut, QUALITY_ONE, /*roundUp*/ true);
680 if (!maybeActualIn)
681 {
682 JLOG(j_.trace()) << "MPTEndpointStep::fwd: overflow";
683 resetCache(srcDebtDir);
684 return {beast::kZero, beast::kZero};
685 }
686
687 MPTAmount const actualIn = *maybeActualIn;
688
689 // Don't have to factor in dstQIn since it's always QUALITY_ONE
690 MPTAmount const out = maxSrcToDst;
691 setCacheLimiting(actualIn, maxSrcToDst, out, srcDebtDir);
692
693 JLOG(j_.trace()) << "MPTEndpointStep::fwd: Limiting"
694 << " srcRedeems: " << redeems(srcDebtDir) << " in: " << to_string(actualIn)
695 << " srcToDst: " << to_string(srcToDst) << " out: " << to_string(out);
696 // LCOV_EXCL_STOP
697 }
698
699 auto const ter = sendWithMPTCreate(sb, src_, dst_, cache_->srcToDst);
700 if (!isTesSuccess(ter))
701 {
702 // Unreachable: send fails only on funds/auth/overflow, precluded by
703 // maxPaymentFlow, check() requireAuth, and 2*kMaxMpTokenAmount < 2^64.
704 // LCOV_EXCL_START
705 UNREACHABLE("xrpl::MPTEndpointStep::fwdImp : send failed");
706 JLOG(j_.trace()) << "MPTEndpointStep::fwd: error " << ter;
707 resetCache(srcDebtDir);
708 return {beast::kZero, beast::kZero};
709 // LCOV_EXCL_STOP
710 }
711
712 return {cache_->in, cache_->out};
713 // NOLINTEND(bugprone-unchecked-optional-access)
714}
715
716template <class TDerived>
719{
720 if (!cache_)
721 {
722 JLOG(j_.trace()) << "Expected valid cache in validFwd";
723 return {false, EitherAmount(MPTAmount(beast::kZero))};
724 }
725
726 auto const savCache = *cache_;
727
728 XRPL_ASSERT(in.holds<MPTAmount>(), "MPTEndpoint<TDerived>::validFwd : is MPT");
729
730 auto const [maxSrcToDst, srcDebtDir] = static_cast<TDerived const*>(this)->maxPaymentFlow(sb);
731 (void)srcDebtDir;
732
733 try
734 {
735 boost::container::flat_set<UInt256> dummy;
736 fwdImp(sb, afView, dummy, in.get<MPTAmount>()); // changes cache
737 }
738 catch (FlowException const&)
739 {
740 return {false, EitherAmount(MPTAmount(beast::kZero))};
741 }
742
743 // NOLINTBEGIN(bugprone-unchecked-optional-access) fwdImp sets cache_ on success
744 if (maxSrcToDst < cache_->srcToDst)
745 {
746 JLOG(j_.warn()) << "MPTEndpointStep: Strand re-execute check failed."
747 << " Exceeded max src->dst limit"
748 << " max src->dst: " << to_string(maxSrcToDst)
749 << " actual src->dst: " << to_string(cache_->srcToDst);
750 return {false, EitherAmount(cache_->out)};
751 }
752
753 if (!(checkNear(savCache.in, cache_->in) && checkNear(savCache.out, cache_->out)))
754 {
755 JLOG(j_.warn()) << "MPTEndpointStep: Strand re-execute check failed."
756 << " ExpectedIn: " << to_string(savCache.in)
757 << " CachedIn: " << to_string(cache_->in)
758 << " ExpectedOut: " << to_string(savCache.out)
759 << " CachedOut: " << to_string(cache_->out);
760 return {false, EitherAmount(cache_->out)};
761 }
762 return {true, EitherAmount(cache_->out)};
763 // NOLINTEND(bugprone-unchecked-optional-access)
764}
765
766// Returns srcQOut, dstQIn
767template <class TDerived>
770{
771 if (prevStep_ == nullptr)
772 return {QUALITY_ONE, QUALITY_ONE};
773
774 auto const prevStepQIn = prevStep_->lineQualityIn(sb);
775 // Unlike trustline MPT doesn't have line quality field
776 auto srcQOut = QUALITY_ONE;
777
778 srcQOut = std::max<std::uint32_t>(prevStepQIn, srcQOut);
779 return {srcQOut, QUALITY_ONE};
780}
781
782// Returns srcQOut, dstQIn
783template <class TDerived>
786 ReadView const& sb,
787 DebtDirection prevStepDebtDirection) const
788{
789 // Charge a transfer rate when issuing and previous step redeems
790
791 XRPL_ASSERT(
792 static_cast<TDerived const*>(this)->verifyPrevStepDebtDirection(prevStepDebtDirection),
793 "MPTEndpointStep<TDerived>::qualitiesSrcIssues : verify prev step debt "
794 "direction");
795
796 std::uint32_t const srcQOut =
797 redeems(prevStepDebtDirection) ? transferRate(sb, mptIssue_.getMptID()).value : QUALITY_ONE;
798
799 // Unlike trustline, MPT doesn't have line quality field
800 return {srcQOut, QUALITY_ONE};
801}
802
803// Returns srcQOut, dstQIn
804template <class TDerived>
807 ReadView const& sb,
808 DebtDirection srcDebtDir,
809 StrandDirection strandDir) const
810{
811 if (redeems(srcDebtDir))
812 {
813 return qualitiesSrcRedeems(sb);
814 }
815
816 auto const prevStepDebtDirection = [&] {
817 if (prevStep_ != nullptr)
818 return prevStep_->debtDirection(sb, strandDir);
820 }();
821 return qualitiesSrcIssues(sb, prevStepDebtDirection);
822}
823
824template <class TDerived>
827{
828 // dst quality in
829 return QUALITY_ONE;
830}
831
832template <class TDerived>
835{
836 auto const dir = this->debtDirection(v, StrandDirection::Forward);
837
838 auto const [srcQOut, dstQIn] =
839 redeems(dir) ? qualitiesSrcRedeems(v) : qualitiesSrcIssues(v, prevStepDir);
840 (void)dstQIn;
841
842 MPTIssue const iss{mptIssue_};
843 // Be careful not to switch the parameters to `getRate`. The
844 // `getRate(offerOut, offerIn)` function is usually used for offers. It
845 // returns offerIn/offerOut. For a direct step, the rate is srcQOut/dstQIn
846 // (Input*dstQIn/srcQOut = Output; So rate = srcQOut/dstQIn). Although the
847 // first parameter is called `offerOut`, it should take the `dstQIn`
848 // variable.
849 return {Quality(getRate(STAmount(iss, QUALITY_ONE), STAmount(iss, srcQOut))), dir};
850}
851
852template <class TDerived>
853TER
855{
856 // The following checks apply for both payments and offer crossing.
857 if (!src_ || !dst_)
858 {
859 JLOG(j_.debug()) << "MPTEndpointStep: specified bad account.";
860 return temBAD_PATH;
861 }
862
863 if (src_ == dst_)
864 {
865 JLOG(j_.debug()) << "MPTEndpointStep: same src and dst.";
866 return temBAD_PATH;
867 }
868
869 auto const sleSrc = ctx.view.read(keylet::account(src_));
870 if (!sleSrc)
871 {
872 JLOG(j_.warn()) << "MPTEndpointStep: can't receive MPT from non-existent issuer: " << src_;
873 return terNO_ACCOUNT;
874 }
875
876 // pure issue/redeem can't be frozen (issuer/holder)
877 // For the first step: check global freeze of the step's own asset.
878 // For the last step: check only the per-holder lock.
879 // Global freeze of the deliver asset is not checked here
880 // because MPT semantics allow issuer<->holder transfers even when globally
881 // locked — only holder-to-holder DEX paths are restricted.
882 // For both steps: a vault share inherits the freeze of the vault's
883 // underlying asset.
884 if (!(ctx.isLast && ctx.isFirst))
885 {
886 auto const& account = ctx.isFirst ? src_ : dst_;
887 bool const frozen = (ctx.isFirst && isGlobalFrozen(ctx.view, mptIssue_)) ||
888 isIndividualFrozen(ctx.view, account, mptIssue_) ||
889 isVaultPseudoAccountFrozen(ctx.view, account, mptIssue_, 0);
890 if (frozen)
891 return terLOCKED;
892 }
893
894 if (ctx.seenBookOuts.count(mptIssue_) > 0)
895 {
896 if (ctx.prevStep == nullptr)
897 {
898 UNREACHABLE(
899 "xrpl::MPTEndpointStep::check : prev seen book without a "
900 "prev step");
901 return temBAD_PATH_LOOP;
902 }
903
904 // This is OK if the previous step is a book step that outputs this
905 // issue
906 if (auto book = ctx.prevStep->bookStepBook())
907 {
908 if (book->out.get<MPTIssue>() != mptIssue_)
909 return temBAD_PATH_LOOP;
910 }
911 }
912
913 if ((ctx.isFirst && !ctx.seenDirectAssets[0].insert(mptIssue_).second) ||
914 (ctx.isLast && !ctx.seenDirectAssets[1].insert(mptIssue_).second))
915 {
916 JLOG(j_.debug()) << "MPTEndpointStep: loop detected: Index: " << ctx.strandSize << ' '
917 << *this;
918 return temBAD_PATH_LOOP;
919 }
920
921 // MPT can only be an endpoint
922 if (!ctx.isLast && !ctx.isFirst)
923 {
924 JLOG(j_.warn()) << "MPTEndpointStep: MPT can only be an endpoint";
925 return temBAD_PATH;
926 }
927
928 auto const& issuer = mptIssue_.getIssuer();
929 if ((src_ != issuer && dst_ != issuer) || (src_ == issuer && dst_ == issuer))
930 {
931 JLOG(j_.warn()) << "MPTEndpointStep: invalid src/dst";
932 return temBAD_PATH;
933 }
934
935 return static_cast<TDerived const*>(this)->check(ctx, sleSrc);
936}
937
938template <class TDerived>
939void
944
945//------------------------------------------------------------------------------
946
949 StrandContext const& ctx,
950 AccountID const& src,
951 AccountID const& dst,
952 MPTID const& mpt)
953{
954 TER ter = tefINTERNAL;
957 {
958 auto offerCrossingStep = std::make_unique<MPTEndpointOfferCrossingStep>(ctx, src, dst, mpt);
959 ter = offerCrossingStep->check(ctx);
960 r = std::move(offerCrossingStep);
961 }
962 else // payment
963 {
964 auto paymentStep = std::make_unique<MPTEndpointPaymentStep>(ctx, src, dst, mpt);
965 ter = paymentStep->check(ctx);
966 r = std::move(paymentStep);
967 }
968 if (!isTesSuccess(ter))
969 return {ter, nullptr};
970
971 return {tesSUCCESS, std::move(r)};
972}
973
974namespace test {
975// Needed for testing
976bool
978 Step const& step,
979 AccountID const& src,
980 AccountID const& dst,
981 MPTID const& mptid)
982{
983 if (auto ds = dynamic_cast<MPTEndpointStep<MPTEndpointPaymentStep> const*>(&step))
984 {
985 return ds->src() == src && ds->dst() == dst && ds->mptID() == mptid;
986 }
987 return false;
988}
989} // namespace test
990
991} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Writeable view to a ledger, for applying a transaction.
Definition ApplyView.h:141
constexpr value_type value() const
Returns the underlying value.
Definition MPTAmount.h:135
static bool verifyPrevStepDebtDirection(DebtDirection prevStepDir)
MPTEndpointOfferCrossingStep(StrandContext const &ctx, AccountID const &src, AccountID const &dst, MPTID const &mpt)
std::string logString() const override
static TER check(StrandContext const &ctx, SLE::ConstRef sleSrc)
MPTEndpointPaymentStep(StrandContext const &ctx, AccountID const &src, AccountID const &dst, MPTID const &mpt)
static TER checkCreateMPT(ApplyView &)
TER check(StrandContext const &ctx, SLE::ConstRef sleSrc) const
static bool verifyPrevStepDebtDirection(DebtDirection)
std::string logString() const override
beast::Journal const j_
std::pair< MPTAmount, MPTAmount > fwdImp(PaymentSandbox &sb, ApplyView &afView, boost::container::flat_set< UInt256 > &ofrsToRm, MPTAmount const &in)
std::optional< std::pair< AccountID, AccountID > > directStepAccts() const override
std::pair< std::uint32_t, std::uint32_t > qualitiesSrcRedeems(ReadView const &sb) const
bool equal(Step const &rhs) const override
TER sendWithMPTCreate(ApplyView &view, AccountID const &src, AccountID const &dst, MPTAmount const &amount)
std::pair< MPTAmount, MPTAmount > revImp(PaymentSandbox &sb, ApplyView &afView, boost::container::flat_set< UInt256 > &ofrsToRm, MPTAmount const &out)
std::string logStringImpl(char const *name) const
DebtDirection debtDirection(ReadView const &sb, StrandDirection dir) const override
MPTEndpointStep(StrandContext const &ctx, AccountID const &src, AccountID const &dst, MPTID const &mpt)
std::pair< std::uint32_t, std::uint32_t > qualities(ReadView const &sb, DebtDirection srcDebtDir, StrandDirection strandDir) const
void setCacheLimiting(MPTAmount const &fwdIn, MPTAmount const &fwdSrcToDst, MPTAmount const &fwdOut, DebtDirection srcDebtDir)
std::uint32_t lineQualityIn(ReadView const &v) const override
std::optional< Cache > cache_
std::optional< EitherAmount > cachedOut() const override
TER check(StrandContext const &ctx) const
std::optional< AccountID > directStepSrcAcct() const override
std::pair< MPTAmount, DebtDirection > maxPaymentFlow(ReadView const &sb) const
MPTID const & mptID() const
friend bool operator==(MPTEndpointStep const &lhs, MPTEndpointStep const &rhs)
void resetCache(DebtDirection dir)
std::pair< bool, EitherAmount > validFwd(PaymentSandbox &sb, ApplyView &afView, EitherAmount const &in) override
std::pair< std::uint32_t, std::uint32_t > qualitiesSrcIssues(ReadView const &sb, DebtDirection prevStepDebtDirection) const
std::optional< EitherAmount > cachedIn() const override
friend bool operator!=(MPTEndpointStep const &lhs, MPTEndpointStep const &rhs)
Step const *const prevStep_
std::pair< std::optional< Quality >, DebtDirection > qualityUpperBound(ReadView const &v, DebtDirection dir) const override
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
A wrapper which makes credits unavailable to balances.
Represents the logical ratio of output currency to input currency.
Definition Quality.h:90
A view into a ledger.
Definition ReadView.h:41
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
std::shared_ptr< STLedgerEntry const > const & ConstRef
A step in a payment path.
Definition Steps.h:83
virtual std::optional< Book > bookStepBook() const
If this step is a BookStep, return the book.
Definition Steps.h:220
T make_pair(T... args)
T make_unique(T... args)
T max(T... args)
T min(T... args)
constexpr Zero kZero
Definition Zero.h:30
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
bool mptEndpointStepEqual(Step const &step, AccountID const &src, AccountID const &dst, MPTID const &mptid)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
@ terLOCKED
Definition TER.h:233
@ terNO_ACCOUNT
Definition TER.h:219
std::int64_t maxMPTAmount(SLE const &sleIssuance)
MaximumAmount doesn't exceed 2**63-1.
TER checkCreateMPT(xrpl::ApplyView &view, xrpl::MPTIssue const &mptIssue, xrpl::AccountID const &holder, SLE::Ref sponsorSle, std::uint32_t flags, beast::Journal j)
bool isIndividualFrozen(ReadView const &view, AccountID const &account, MPTIssue const &mptIssue)
Returns true if account's MPToken for mptIssue carries the individual-lock flag (lsfMPTLocked).
MPTAmount toAmount< MPTAmount >(STAmount const &amt)
bool issues(DebtDirection dir)
Definition Steps.h:50
@ tefINTERNAL
Definition TER.h:167
std::pair< TER, std::unique_ptr< Step > > makeMptEndpointStep(StrandContext const &ctx, AccountID const &src, AccountID const &dst, MPTID const &mpt)
TER canTransfer(ReadView const &view, MPTIssue const &mptIssue, AccountID const &from, AccountID const &to, WaiveMPTCanTransfer waive=WaiveMPTCanTransfer::No, std::uint8_t depth=0)
Check whether to may receive the given MPT from from.
DebtDirection
Definition Steps.h:38
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
TER canTrade(ReadView const &view, Asset const &asset, std::uint8_t depth=0)
Check whether asset may be traded on the DEX.
bool isVaultPseudoAccountFrozen(ReadView const &view, AccountID const &account, MPTIssue const &mptShare, std::uint8_t depth)
Definition View.cpp:160
StrandDirection
Definition Steps.h:40
std::optional< MPTAmount > tryMulRatio(MPTAmount const &amt, std::uint32_t num, std::uint32_t den, bool roundUp)
Definition MPTAmount.h:179
STAmount accountFunds(ReadView const &view, AccountID const &id, STAmount const &saDefault, FreezeHandling freezeHandling, beast::Journal j)
bool isGlobalFrozen(ReadView const &view, AccountID const &issuer)
Check if the issuer has the global freeze flag set.
IOUAmount mulRatio(IOUAmount const &amt, std::uint32_t num, std::uint32_t den, bool roundUp)
Rate transferRate(ReadView const &view, AccountID const &issuer)
Returns IOU issuer transfer fee as Rate.
BaseUInt< 192 > MPTID
MPTID is a 192-bit value representing MPT Issuance ID, which is a concatenation of a 32-bit sequence ...
Definition UintTypes.h:54
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
TER directSendNoFee(ApplyView &view, AccountID const &uSenderID, AccountID const &uReceiverID, STAmount const &saAmount, bool bCheckIssuer, beast::Journal j)
Calls static directSendNoFeeIOU if saAmount represents Issue.
bool checkNear(IOUAmount const &expected, IOUAmount const &actual)
Definition PaySteps.cpp:36
bool isFrozen(ReadView const &view, AccountID const &account, MPTIssue const &mptIssue, std::uint8_t depth=0)
Returns true if account cannot send or receive tokens of mptIssue because a freeze applies.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
@ temBAD_PATH
Definition TER.h:84
@ temBAD_PATH_LOOP
Definition TER.h:85
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
TER requireAuth(ReadView const &view, MPTIssue const &mptIssue, AccountID const &account, AuthType authType=AuthType::Legacy, std::uint8_t depth=0)
Check if the account lacks required authorization for MPT.
@ tecLOCKED
Definition TER.h:369
@ tecPATH_DRY
Definition TER.h:305
bool redeems(DebtDirection dir)
Definition Steps.h:44
constexpr std::uint64_t kMaxMpTokenAmount
The maximum amount of MPTokenIssuance.
Definition Protocol.h:297
@ tesSUCCESS
Definition TER.h:253
STAmount toSTAmount(IOUAmount const &iou, Asset const &asset)
T str(T... args)
bool holds() const
T const & get() const
Cache(MPTAmount const &in, MPTAmount const &srcToDst, MPTAmount const &out, DebtDirection srcDebtDir)
std::uint32_t value
Definition Rate.h:22
Context needed to build Strand Steps and for error checking.
Definition Steps.h:568
Asset const strandDeliver
Asset strand delivers.
Definition Steps.h:572
size_t const strandSize
Length of Strand.
Definition Steps.h:579
ReadView const & view
Current ReadView.
Definition Steps.h:569
bool const isFirst
true if Step is first in Strand
Definition Steps.h:574
std::array< boost::container::flat_set< Asset >, 2 > & seenDirectAssets
A strand may not include the same account node more than once in the same currency.
Definition Steps.h:591
bool const isLast
true if Step is last in Strand
Definition Steps.h:575
boost::container::flat_set< Asset > & seenBookOuts
A strand may not include an offer that output the same issue more than once.
Definition Steps.h:596
AccountID const strandDst
Strand destination account.
Definition Steps.h:571
Step const *const prevStep
The previous step in the strand.
Definition Steps.h:584
OfferCrossing const offerCrossing
Yes/Sell if offer crossing, not payment.
Definition Steps.h:577