xrpld
Loading...
Searching...
No Matches
VaultInvariant.cpp
1#include <xrpl/tx/invariants/VaultInvariant.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Journal.h>
6#include <xrpl/beast/utility/Zero.h>
7#include <xrpl/beast/utility/instrumentation.h>
8#include <xrpl/ledger/ReadView.h>
9#include <xrpl/ledger/helpers/AccountRootHelpers.h>
10#include <xrpl/ledger/helpers/TokenHelpers.h>
11#include <xrpl/ledger/helpers/VaultHelpers.h>
12#include <xrpl/protocol/Feature.h>
13#include <xrpl/protocol/Indexes.h>
14#include <xrpl/protocol/Issue.h>
15#include <xrpl/protocol/LedgerFormats.h>
16#include <xrpl/protocol/Protocol.h>
17#include <xrpl/protocol/Rate.h>
18#include <xrpl/protocol/SField.h>
19#include <xrpl/protocol/STAmount.h>
20#include <xrpl/protocol/STLedgerEntry.h>
21#include <xrpl/protocol/STNumber.h> // IWYU pragma: keep
22#include <xrpl/protocol/STTx.h>
23#include <xrpl/protocol/TER.h>
24#include <xrpl/protocol/TxFormats.h>
25#include <xrpl/protocol/XRPAmount.h>
26#include <xrpl/tx/Transactor.h>
27#include <xrpl/tx/invariants/InvariantCheckPrivilege.h>
28
29#include <algorithm>
30#include <cstdint>
31#include <optional>
32#include <utility>
33#include <variant>
34#include <vector>
35
36namespace xrpl {
37
38namespace {
39
40/*
41 * True iff the recorded sfVaultKind identifies a closed-ended vault.
42 * Centralizes the presence + enum-value check used by the phase-gate
43 * invariants below.
44 */
45[[nodiscard]] bool
46isClosedEnded(std::optional<std::uint8_t> const& vaultKind)
47{
48 return vaultKind && *vaultKind == std::to_underlying(VaultKind::ClosedEnded);
49}
50
51} // namespace
52
55{
56 XRPL_ASSERT(from.getType() == ltVAULT, "ValidVault::Vault::make : from Vault object");
57
59 self.key = from.key();
60 self.asset = from.at(sfAsset);
61 self.pseudoId = from.getAccountID(sfAccount);
62 self.owner = from.at(sfOwner);
63 self.shareMPTID = from.getFieldH192(sfShareMPTID);
64 self.assetsTotal = from.at(sfAssetsTotal);
65 self.assetsAvailable = from.at(sfAssetsAvailable);
66 self.assetsMaximum = from.at(sfAssetsMaximum);
67 self.lossUnrealized = from.at(sfLossUnrealized);
68 self.assetsDeployed = from[~sfAssetsDeployed].value_or(Number{0});
69 self.yieldUnrealized = from[~sfYieldUnrealized].value_or(Number{0});
70 self.version = decodeVaultVersion(from[~sfLEVersion]);
71 self.vaultKind = from[~sfVaultKind];
72 self.subscriptionDate = from[~sfSubscriptionDate];
73 self.redemptionDate = from[~sfRedemptionDate];
74 return self;
75}
76
79{
80 XRPL_ASSERT(
81 from.getType() == ltMPTOKEN_ISSUANCE,
82 "ValidVault::Shares::make : from MPTokenIssuance object");
83
85 self.share = MPTIssue(makeMptID(from.getFieldU32(sfSequence), from.getAccountID(sfIssuer)));
86 self.sharesTotal = from.at(sfOutstandingAmount);
87 self.sharesMaximum = from[~sfMaximumAmount].value_or(kMaxMpTokenAmount);
88 return self;
89}
90
91void
93{
94 // If `before` is empty, this means an object is being created, in which
95 // case `isDelete` must be false. Otherwise `before` and `after` are set and
96 // `isDelete` indicates whether an object is being deleted or modified.
97 XRPL_ASSERT(
98 after != nullptr && (before != nullptr || !isDelete),
99 "xrpl::ValidVault::visitEntry : some object is available");
100
101 // Number balanceDelta will capture the difference (delta) between "before"
102 // state (zero if created) and "after" state (zero if destroyed), and
103 // preserves value scale (exponent) to round values to the same scale during
104 // validation. It is used to validate that the change in account
105 // balances matches the change in vault balances, stored to deltas_ at the
106 // end of this function.
107 DeltaInfo balanceDelta{.delta = kNumZero, .scale = std::nullopt};
108
109 std::int8_t sign = 0;
110 if (before)
111 {
112 switch (before->getType())
113 {
114 case ltVAULT:
115 beforeVault_.push_back(Vault::make(*before));
116 break;
117 case ltMPTOKEN_ISSUANCE:
118 // At this moment we have no way of telling if this object holds
119 // vault shares or something else. Save it for finalize.
120 beforeMPTs_.push_back(Shares::make(*before));
121 balanceDelta.delta =
122 static_cast<std::int64_t>(before->getFieldU64(sfOutstandingAmount));
123 // MPTs are ints, so the scale is always 0.
124 balanceDelta.scale = 0;
125 sign = 1;
126 break;
127 case ltMPTOKEN:
128 balanceDelta.delta = static_cast<std::int64_t>(before->getFieldU64(sfMPTAmount));
129 // MPTs are ints, so the scale is always 0.
130 balanceDelta.scale = 0;
131 sign = -1;
132 break;
133 case ltACCOUNT_ROOT:
134 balanceDelta.delta = before->getFieldAmount(sfBalance);
135 // Account balance is XRP, which is an int, so the scale is
136 // always 0.
137 balanceDelta.scale = 0;
138 sign = -1;
139 break;
140 case ltRIPPLE_STATE: {
141 auto const amount = before->getFieldAmount(sfBalance);
142 balanceDelta.delta = amount;
143 // Trust Line balances are STAmounts, so we can use the exponent
144 // directly to get the scale.
145 balanceDelta.scale = amount.exponent();
146 sign = -1;
147 break;
148 }
149 default:;
150 }
151 }
152
153 if (!isDelete && after)
154 {
155 switch (after->getType())
156 {
157 case ltVAULT:
158 afterVault_.push_back(Vault::make(*after));
159 break;
160 case ltMPTOKEN_ISSUANCE:
161 // At this moment we have no way of telling if this object holds
162 // vault shares or something else. Save it for finalize.
163 afterMPTs_.push_back(Shares::make(*after));
164 balanceDelta.delta -=
165 Number(static_cast<std::int64_t>(after->getFieldU64(sfOutstandingAmount)));
166 // MPTs are ints, so the scale is always 0.
167 balanceDelta.scale = 0;
168 sign = 1;
169 break;
170 case ltMPTOKEN:
171 balanceDelta.delta -=
172 Number(static_cast<std::int64_t>(after->getFieldU64(sfMPTAmount)));
173 // MPTs are ints, so the scale is always 0.
174 balanceDelta.scale = 0;
175 sign = -1;
176 break;
177 case ltACCOUNT_ROOT:
178 balanceDelta.delta -= Number(after->getFieldAmount(sfBalance));
179 // Account balance is XRP, which is an int, so the scale is
180 // always 0.
181 balanceDelta.scale = 0;
182 sign = -1;
183 break;
184 case ltRIPPLE_STATE: {
185 auto const amount = after->getFieldAmount(sfBalance);
186 balanceDelta.delta -= Number(amount);
187 // Trust Line balances are STAmounts, so we can use the exponent
188 // directly to get the scale.
189 if (amount.exponent() > balanceDelta.scale)
190 balanceDelta.scale = amount.exponent();
191 sign = -1;
192 break;
193 }
194 default:;
195 }
196 }
197
198 UInt256 const key = (before ? before->key() : after->key());
199 // Append to deltas if sign is non-zero, i.e. an object of an interesting
200 // type has been updated. A transaction may update an object even when
201 // its balance has not changed, e.g. transaction fee equals the amount
202 // transferred to the account. We intentionally do not compare balanceDelta
203 // against zero, to avoid missing such updates.
204 if (sign != 0)
205 {
206 XRPL_ASSERT_PARTS(balanceDelta.scale, "xrpl::ValidVault::visitEntry", "scale initialized");
207 balanceDelta.delta *= sign;
208 deltas_[key] = balanceDelta;
209 }
210}
211
214{
215 auto const& vaultAsset = afterVault_[0].asset;
216 auto const lookup = [&](UInt256 const& key) -> std::optional<DeltaInfo> {
217 auto const it = deltas_.find(key);
218 if (it == deltas_.end())
219 return std::nullopt;
220 return it->second;
221 };
222
223 return std::visit(
224 [&]<typename TIss>(TIss const& issue) -> std::optional<DeltaInfo> {
225 if constexpr (std::is_same_v<TIss, Issue>)
226 {
227 if (isXRP(issue))
228 return lookup(keylet::account(id).key);
229 auto result = lookup(keylet::trustLine(id, issue).key);
230 // Trust-line balance is stored from the low-account's perspective;
231 // negate if id is the high account so the delta is in id's terms.
232 if (result && id > issue.getIssuer())
233 result->delta = -result->delta;
234 return result;
235 }
236 else if constexpr (std::is_same_v<TIss, MPTIssue>)
237 {
238 return lookup(keylet::mptoken(issue.getMptID(), id).key);
239 }
240 },
241 vaultAsset.value());
242}
243
246{
247 auto const feePayer = Transactor::getFeePayer(view, tx);
248 if (feePayer.type == FeePayerType::SponsorPreFunded)
249 return std::nullopt;
250 return feePayer.id;
251}
252
255 ReadView const& view,
256 AccountID const& id,
257 STTx const& tx,
258 XRPAmount fee,
259 bool fix340Enabled) const
260{
261 auto const& vaultAsset = afterVault_[0].asset;
262 auto ret = deltaAssets(id);
263 if (!ret.has_value() || !vaultAsset.native())
264 return ret;
265
266 if (!fix340Enabled)
267 {
268 // Legacy behaviour: only tx[sfAccount] was ever considered for a fee
269 // correction, and only when STTx::getFeePayerID identified it as the
270 // fee payer (which is never true for a sponsor, since
271 // self-sponsorship is disallowed). After that sender-only correction
272 // a zero delta is collapsed to absence; if the correction does not
273 // apply, a present-zero is returned as-is.
274 if (id != tx[sfAccount] || tx.getFeePayerID() != id)
275 return ret;
276
277 ret->delta += fee.drops();
278 if (ret->delta == kZero)
279 return std::nullopt;
280
281 return ret;
282 }
283
284 // Add the fee back only onto the AccountRoot that actually paid it: an
285 // ordinary sender, a delegate, or a co-signed fee sponsor -- but never a
286 // pre-funded sponsorship, whose fee is drawn from the ltSponsorship
287 // object rather than the sponsor's own XRP balance.
288 if (auto const payer = feePayerAccountRoot(view, tx); payer && *payer == id)
289 ret->delta += fee.drops();
290
291 // Normalize an economically zero delta to absence regardless of who (if
292 // anyone) paid the fee, so a touched-but-unchanged AccountRoot (e.g. the
293 // sender in a third-party withdrawal, touched only for sequence/ticket
294 // processing) is never misread as a second payout recipient.
295 if (ret->delta == kZero)
296 return std::nullopt;
297
298 return ret;
299}
300
303{
304 auto const& afterVault = afterVault_[0];
305 auto const it = [&] {
306 if (id == afterVault.pseudoId)
307 return deltas_.find(keylet::mptokenIssuance(afterVault.shareMPTID).key);
308 return deltas_.find(keylet::mptoken(afterVault.shareMPTID, id).key);
309 }();
310
311 return it != deltas_.end() ? std::optional<DeltaInfo>(it->second) : std::nullopt;
312}
313
314bool
316{
317 return vault.assetsAvailable == 0 && vault.assetsTotal == 0;
318}
319
320bool
322{
323 if (afterVault_.empty())
324 {
325 // LCOV_EXCL_START
326 UNREACHABLE("xrpl::ValidVault::finalizeLoanSet : vault exists");
327 return false;
328 // LCOV_EXCL_STOP
329 }
330
331 auto const& afterVault = afterVault_[0];
332
333 // Loan origination against a closed-ended vault is only permitted while the vault is in the
334 // Investment phase - strictly past SubscriptionDate and before RedemptionDate. Open-ended
335 // vaults have NoPhase and are unaffected.
336 auto const phase = getVaultPhase(
337 view, afterVault.vaultKind, afterVault.subscriptionDate, afterVault.redemptionDate);
338 if (phase == VaultPhase::NoPhase)
339 return true;
340
341 if (phase != VaultPhase::Investment)
342 {
343 JLOG(j.fatal()) << //
344 "Invariant failed: loan origination only allowed in Investment phase";
345 return false;
346 }
347
348 return true;
349}
350
351namespace {
352
353// sfAssetsTotal, sfAssetsAvailable and sfLossUnrealized are STNumber fields
354// with kSmdNeedsAsset, so IOU writes go through associateAsset -> roundToAsset
355// -> STAmount quantization. Since assetsTotal is the largest number, it lands
356// on the coarsest decimal grid, and strict equality on the deltas can fire on
357// a single unit of quantization noise even when the underlying flow is
358// correct. Absorb one unit at the coarsest scale.
359//
360// XRP and MPT are integer-domain assets (Asset::integral() is true) with no
361// sub-ULP quantization; treating a whole drop / MPT unit as "noise" would
362// hide real accounting bugs. Keep the strict comparison there. Note that
363// gating on the sign of `scale` would be wrong: IOU amounts >= 1e15 have a
364// non-negative STAmount exponent but still quantize.
365[[nodiscard]] bool
366agreesWithinOneUnit(Number const& lhs, Number const& rhs, Asset const& asset, std::int32_t scale)
367{
368 if (asset.integral())
369 return lhs == rhs;
370 auto const diff = lhs - rhs;
371 Number const tolerance{1, scale};
372 return (diff < beast::kZero ? -diff : diff) <= tolerance;
373}
374
375// L, T and A are each independently quantized; the strict L <= T - A check
376// can fire on residual noise even when the true relationship holds. Tolerate
377// one unit at scale(assetsTotal) - the coarsest of the three grids. As with
378// the delta check above, the tolerance is meaningful only for IOU
379// (Asset::integral() is false); XRP and MPT keep the strict comparison.
380[[nodiscard]] bool
381lessOrEqualPlusOneUnit(Number const& lhs, Number const& rhs, Asset const& asset, std::int32_t scale)
382{
383 if (asset.integral())
384 return lhs <= rhs;
385 return lhs <= rhs + Number{1, scale};
386}
387
388} // namespace
389
390std::int32_t
391ValidVault::computeVaultMinScale(DeltaInfo const& vaultDelta, Rules const& rules) const
392{
393 // Returns the posterior `assetsTotal` scale.
394 //
395 // 1. Because STAmounts are normalized, `assetsTotal` (being >= `assetsAvailable`)
396 // safely represents the coarsest exponent needed for both fields.
397 //
398 // 2. The scale may decrease (withdraw/clawback) or increase (deposit). In both cases
399 // we ensure the vault is in a legitimate state in the post-transaction scale.
400 auto const& afterVault = afterVault_[0];
401 auto const& vaultAsset = afterVault.asset;
402 if (rules.enabled(fixCleanup3_2_0))
403 {
405 return scale(afterVault.assetsTotal, vaultAsset);
406 }
407
408 auto const& beforeVault = beforeVault_[0];
409 auto const totalDelta =
410 DeltaInfo::makeDelta(beforeVault.assetsTotal, afterVault.assetsTotal, vaultAsset);
411 auto const availableDelta =
412 DeltaInfo::makeDelta(beforeVault.assetsAvailable, afterVault.assetsAvailable, vaultAsset);
413 return computeCoarsestScale({vaultDelta, totalDelta, availableDelta});
414}
415
416bool
418 Vault const& afterVault,
419 Vault const& beforeVault,
420 Asset const& vaultAsset,
421 bool fix340Enabled,
422 std::int32_t minScale,
423 Number const& roundedVaultDelta,
424 Number const& exactVaultDelta,
425 char const* verb,
426 beast::Journal const& j)
427{
428 bool result = true;
429
430 // FixedPrecision: the stored AssetsTotal is a Downward-floored cache
431 // (AA + AD), not an exact running total, so comparing its delta against
432 // the real transfer can be off by more than one unit purely from
433 // independent floor-rounding of the two snapshots -- not an accounting
434 // bug. The stored-cache-equals-derived-total check elsewhere in finalize,
435 // plus the AssetsDeployed-only-changed-by-lending-transactors check,
436 // already cover AssetsTotal; only compare it here on Legacy/CashBasis,
437 // where AssetsTotal is written exactly alongside AA.
438 if (afterVault.version != VaultVersion::FixedPrecision)
439 {
440 auto const assetTotalDelta =
441 roundToAsset(vaultAsset, afterVault.assetsTotal - beforeVault.assetsTotal, minScale);
442 bool const totalAddsUp = fix340Enabled
443 ? agreesWithinOneUnit(assetTotalDelta, roundedVaultDelta, vaultAsset, minScale)
444 : assetTotalDelta == roundedVaultDelta;
445 if (!totalAddsUp)
446 {
447 JLOG(j.fatal()) << "Invariant failed: " << verb
448 << " and assets outstanding must add up";
449 result = false;
450 }
451 }
452
453 auto const assetAvailableDelta = roundToAsset(
454 vaultAsset, afterVault.assetsAvailable - beforeVault.assetsAvailable, minScale);
455 // FixedPrecision: AssetsAvailable is the exact, single writer
456 // (adjustVaultBalances)-managed balance, so its delta must match the real
457 // transfer exactly, with no rounding tolerance -- compare the exact
458 // deltas, not the values rounded to the posterior AssetsTotal scale.
459 bool const availableAddsUp = [&] {
460 if (afterVault.version == VaultVersion::FixedPrecision)
461 {
462 return (afterVault.assetsAvailable - beforeVault.assetsAvailable) == exactVaultDelta;
463 }
464 if (fix340Enabled)
465 {
466 return agreesWithinOneUnit(
467 assetAvailableDelta, roundedVaultDelta, vaultAsset, minScale);
468 }
469 return assetAvailableDelta == roundedVaultDelta;
470 }();
471 if (!availableAddsUp)
472 {
473 JLOG(j.fatal()) << "Invariant failed: " << verb << " and assets available must add up";
474 result = false;
475 }
476
477 return result;
478}
479
480bool
482 STTx const& tx,
483 TER const ret,
484 XRPAmount const fee,
485 ReadView const& view,
486 beast::Journal const& j)
487{
488 bool const enforce = view.rules().enabled(featureSingleAssetVault);
489 bool const fix340Enabled = view.rules().enabled(fixCleanup3_4_0);
490 bool const fix350Enabled = view.rules().enabled(fixCleanup3_5_0);
491
492 if (!isTesSuccess(ret))
493 return true; // Do not perform checks
494
495 if (afterVault_.empty() && beforeVault_.empty())
496 {
498 {
499 JLOG(j.fatal()) << //
500 "Invariant failed: vault operation succeeded without modifying "
501 "a vault";
502 XRPL_ASSERT(enforce, "xrpl::ValidVault::finalize : vault noop invariant");
503 return !enforce;
504 }
505
506 return true; // Not a vault operation
507 }
510 {
511 JLOG(j.fatal()) << //
512 "Invariant failed: vault updated by a wrong transaction type";
513 XRPL_ASSERT(
514 enforce,
515 "xrpl::ValidVault::finalize : illegal vault transaction "
516 "invariant");
517 return !enforce; // Also not a vault operation
518 }
519
520 if (beforeVault_.size() > 1 || afterVault_.size() > 1)
521 {
522 JLOG(j.fatal()) << //
523 "Invariant failed: vault operation updated more than single vault";
524 XRPL_ASSERT(enforce, "xrpl::ValidVault::finalize : single vault invariant");
525 return !enforce; // That's all we can do here
526 }
527
528 auto const txnType = tx.getTxnType();
529
530 // We do special handling for ttVAULT_DELETE first, because it's the only
531 // vault-modifying transaction without an "after" state of the vault
532 if (afterVault_.empty())
533 {
534 if (txnType != ttVAULT_DELETE)
535 {
536 JLOG(j.fatal()) << //
537 "Invariant failed: vault deleted by a wrong transaction type";
538 XRPL_ASSERT(
539 enforce,
540 "xrpl::ValidVault::finalize : illegal vault deletion "
541 "invariant");
542 return !enforce; // That's all we can do here
543 }
544
545 // Note, if afterVault_ is empty then we know that beforeVault_ is not
546 // empty, as enforced at the top of this function
547 auto const& beforeVault = beforeVault_[0];
548
549 // At this moment we only know a vault is being deleted and there
550 // might be some MPTokenIssuance objects which are deleted in the
551 // same transaction. Find the one matching this vault.
552 auto const deletedShares = [&] -> std::optional<Shares> {
553 for (auto const& e : beforeMPTs_)
554 {
555 if (e.share.getMptID() == beforeVault.shareMPTID)
556 return e;
557 }
558 return std::nullopt;
559 }();
560
561 if (!deletedShares)
562 {
563 JLOG(j.fatal()) << "Invariant failed: deleted vault must also "
564 "delete shares";
565 XRPL_ASSERT(enforce, "xrpl::ValidVault::finalize : shares deletion invariant");
566 return !enforce; // That's all we can do here
567 }
568
569 bool result = true;
570 if (deletedShares->sharesTotal != 0)
571 {
572 JLOG(j.fatal()) << "Invariant failed: deleted vault must have no "
573 "shares outstanding";
574 result = false;
575 }
576 if (beforeVault.assetsTotal != kZero)
577 {
578 JLOG(j.fatal()) << "Invariant failed: deleted vault must have no "
579 "assets outstanding";
580 result = false;
581 }
582 if (beforeVault.assetsAvailable != kZero)
583 {
584 JLOG(j.fatal()) << "Invariant failed: deleted vault must have no "
585 "assets available";
586 result = false;
587 }
588
589 return result;
590 }
591 if (txnType == ttVAULT_DELETE)
592 {
593 JLOG(j.fatal()) << "Invariant failed: vault deletion succeeded without "
594 "deleting a vault";
595 XRPL_ASSERT(enforce, "xrpl::ValidVault::finalize : vault deletion invariant");
596 return !enforce; // That's all we can do here
597 }
598
599 // Note, `afterVault_.empty()` is handled above
600 auto const& afterVault = afterVault_[0];
601 XRPL_ASSERT(
602 beforeVault_.empty() || beforeVault_[0].key == afterVault.key,
603 "xrpl::ValidVault::finalize : single vault operation");
604
605 auto const updatedShares = [&] -> std::optional<Shares> {
606 // At this moment we only know that a vault is being updated and there
607 // might be some MPTokenIssuance objects which are also updated in the
608 // same transaction. Find the one matching the shares to this vault.
609 // Note, we expect updatedMPTs collection to be extremely small. For
610 // such collections linear search is faster than lookup.
611 for (auto const& e : afterMPTs_)
612 {
613 if (e.share.getMptID() == afterVault.shareMPTID)
614 return e;
615 }
616
617 auto const sleShares = view.read(keylet::mptokenIssuance(afterVault.shareMPTID));
618
619 return sleShares ? std::optional<Shares>(Shares::make(*sleShares)) : std::nullopt;
620 }();
621
622 bool result = true;
623
624 // Universal transaction checks
625 // From LendingProtocolV1_1 onwards, vault immutability check is moved to InvariantCheck.cpp
626 if (!beforeVault_.empty() && !view.rules().enabled(featureLendingProtocolV1_1))
627 {
628 auto const& beforeVault = beforeVault_[0];
629 if (afterVault.asset != beforeVault.asset || afterVault.pseudoId != beforeVault.pseudoId ||
630 afterVault.shareMPTID != beforeVault.shareMPTID)
631 {
632 JLOG(j.fatal()) << "Invariant failed: violation of vault immutable data";
633 result = false;
634 }
635 }
636
637 if (!updatedShares)
638 {
639 JLOG(j.fatal()) << "Invariant failed: updated vault must have shares";
640 XRPL_ASSERT(enforce, "xrpl::ValidVault::finalize : vault has shares invariant");
641 return !enforce; // That's all we can do here
642 }
643
644 if (updatedShares->sharesTotal == 0)
645 {
646 if (afterVault.assetsTotal != kZero)
647 {
648 JLOG(j.fatal()) << "Invariant failed: updated zero sized "
649 "vault must have no assets outstanding";
650 result = false;
651 }
652 if (afterVault.assetsAvailable != kZero)
653 {
654 JLOG(j.fatal()) << "Invariant failed: updated zero sized "
655 "vault must have no assets available";
656 result = false;
657 }
658 if (afterVault.version == VaultVersion::FixedPrecision &&
659 afterVault.assetsDeployed != kZero)
660 {
661 JLOG(j.fatal()) << "Invariant failed: updated zero sized "
662 "vault must have no AssetsDeployed";
663 result = false;
664 }
665 }
666 else if (updatedShares->sharesTotal > updatedShares->sharesMaximum)
667 {
668 JLOG(j.fatal()) //
669 << "Invariant failed: updated shares must not exceed maximum "
670 << updatedShares->sharesMaximum;
671 result = false;
672 }
673
674 if (afterVault.assetsAvailable < kZero)
675 {
676 JLOG(j.fatal()) << "Invariant failed: assets available must not be negative";
677 result = false;
678 }
679
680 if (afterVault.assetsAvailable > afterVault.assetsTotal)
681 {
682 JLOG(j.fatal()) << "Invariant failed: assets available must "
683 "not be greater than assets outstanding";
684 result = false;
685 }
686 else
687 {
688 bool const gapExceeded = [&] {
689 if (afterVault.version == VaultVersion::FixedPrecision)
690 {
691 // FixedPrecision: both LossUnrealized and AssetsDeployed are exact
692 // (never rounded), so compare them directly. AssetsTotal is
693 // just a rounded cache of AssetsAvailable + AssetsDeployed and
694 // is not the reference this check needs.
695 return afterVault.lossUnrealized > afterVault.assetsDeployed;
696 }
697 if (!fix340Enabled)
698 {
699 return afterVault.lossUnrealized >
700 afterVault.assetsTotal - afterVault.assetsAvailable;
701 }
702
703 auto const s = scale(afterVault.assetsTotal, afterVault.asset);
704 return !lessOrEqualPlusOneUnit(
705 afterVault.lossUnrealized,
706 afterVault.assetsTotal - afterVault.assetsAvailable,
707 afterVault.asset,
708 s);
709 }();
710 if (gapExceeded)
711 {
712 JLOG(j.fatal()) //
713 << "Invariant failed: loss unrealized must not exceed "
714 "the difference between assets outstanding and available";
715 result = false;
716 }
717 }
718
719 if (afterVault.version == VaultVersion::FixedPrecision)
720 {
721 if (afterVault.assetsDeployed < kZero)
722 {
723 JLOG(j.fatal()) << "Invariant failed: AssetsDeployed must not be negative";
724 result = false;
725 }
726 else if (
727 Number(STAmount{afterVault.asset, afterVault.assetsDeployed}) !=
728 afterVault.assetsDeployed)
729 {
730 JLOG(j.fatal()) //
731 << "Invariant failed: AssetsDeployed must be exactly representable "
732 "at the vault asset's precision";
733 result = false;
734 }
735
736 Number const expectedAssetsTotal = [&] {
738 return Number(
739 STAmount{afterVault.asset, afterVault.assetsAvailable + afterVault.assetsDeployed});
740 }();
741 if (afterVault.assetsTotal != expectedAssetsTotal)
742 {
743 JLOG(j.fatal()) //
744 << "Invariant failed: stored AssetsTotal must equal AssetsAvailable "
745 "plus AssetsDeployed, rounded Downward";
746 result = false;
747 }
748
749 if (afterVault.yieldUnrealized < kZero)
750 {
751 JLOG(j.fatal()) << "Invariant failed: YieldUnrealized must not be negative";
752 result = false;
753 }
754 }
755
756 if (fix340Enabled && afterVault.lossUnrealized < kZero)
757 {
758 JLOG(j.fatal()) << "Invariant failed: loss unrealized must not be negative";
759 result = false;
760 }
761
762 if (afterVault.assetsTotal < kZero)
763 {
764 JLOG(j.fatal()) << "Invariant failed: assets outstanding must not be negative";
765 result = false;
766 }
767
768 if (afterVault.assetsMaximum < kZero)
769 {
770 JLOG(j.fatal()) << "Invariant failed: assets maximum must not be negative";
771 result = false;
772 }
773
774 // Thanks to this check we can simply do `assert(!beforeVault_.empty()` when
775 // enforcing invariants on transaction types other than ttVAULT_CREATE
776 if (beforeVault_.empty() && txnType != ttVAULT_CREATE)
777 {
778 JLOG(j.fatal()) << //
779 "Invariant failed: vault created by a wrong transaction type";
780 XRPL_ASSERT(enforce, "xrpl::ValidVault::finalize : vault creation invariant");
781 return !enforce; // That's all we can do here
782 }
783
784 // ttLOAN_SET, ttLOAN_PAY and ttLOAN_MANAGE are the only transactors allowed to
785 // write AssetsDeployed and YieldUnrealized; any new transactor that writes
786 // either field must be added to both allow-lists below.
787 if (afterVault.version == VaultVersion::FixedPrecision && !beforeVault_.empty() &&
788 afterVault.assetsDeployed != beforeVault_[0].assetsDeployed && txnType != ttLOAN_SET &&
789 txnType != ttLOAN_PAY && txnType != ttLOAN_MANAGE)
790 {
791 JLOG(j.fatal()) << //
792 "Invariant failed: vault transaction must not change AssetsDeployed";
793 result = false;
794 }
795
796 if (!beforeVault_.empty() && afterVault.lossUnrealized != beforeVault_[0].lossUnrealized &&
797 txnType != ttLOAN_MANAGE && txnType != ttLOAN_PAY)
798 {
799 JLOG(j.fatal()) << //
800 "Invariant failed: vault transaction must not change loss "
801 "unrealized";
802 result = false;
803 }
804
805 if (afterVault.version == VaultVersion::FixedPrecision && !beforeVault_.empty() &&
806 afterVault.yieldUnrealized != beforeVault_[0].yieldUnrealized && txnType != ttLOAN_SET &&
807 txnType != ttLOAN_PAY && txnType != ttLOAN_MANAGE)
808 {
809 JLOG(j.fatal()) << //
810 "Invariant failed: vault transaction must not change yield "
811 "unrealized";
812 result = false;
813 }
814
815 // Immutability of VaultKind, SubscriptionDate and RedemptionDate is enforced by
816 // NoModifiedUnmodifiableFields in InvariantCheck.cpp.
817
818 auto const beforeShares = [&] -> std::optional<Shares> {
819 if (beforeVault_.empty())
820 return std::nullopt;
821 auto const& beforeVault = beforeVault_[0];
822
823 for (auto const& e : beforeMPTs_)
824 {
825 if (e.share.getMptID() == beforeVault.shareMPTID)
826 return e;
827 }
828 return std::nullopt;
829 }();
830
831 if (!beforeShares &&
832 (tx.getTxnType() == ttVAULT_DEPOSIT || //
833 tx.getTxnType() == ttVAULT_WITHDRAW || //
834 tx.getTxnType() == ttVAULT_CLAWBACK))
835 {
836 JLOG(j.fatal()) << "Invariant failed: vault operation succeeded "
837 "without updating shares";
838 XRPL_ASSERT(enforce, "xrpl::ValidVault::finalize : shares noop invariant");
839 return !enforce; // That's all we can do here
840 }
841
842 auto const& vaultAsset = afterVault.asset;
843
844 // Technically this does not need to be a lambda, but it's more
845 // convenient thanks to early "return false"; the not-so-nice
846 // alternatives are several layers of nested if/else or more complex
847 // (i.e. brittle) if statements.
848 result &= [&] {
849 switch (txnType)
850 {
851 case ttVAULT_CREATE: {
852 bool result = true;
853
854 if (!beforeVault_.empty())
855 {
856 JLOG(j.fatal()) //
857 << "Invariant failed: create operation must not have "
858 "updated a vault";
859 result = false;
860 }
861
862 if (afterVault.assetsAvailable != kZero || afterVault.assetsTotal != kZero ||
863 afterVault.lossUnrealized != kZero || updatedShares->sharesTotal != 0 ||
864 (afterVault.version == VaultVersion::FixedPrecision &&
865 (afterVault.assetsDeployed != kZero || afterVault.yieldUnrealized != kZero)))
866 {
867 JLOG(j.fatal()) //
868 << "Invariant failed: created vault must be empty";
869 result = false;
870 }
871
872 if (afterVault.pseudoId != updatedShares->share.getIssuer())
873 {
874 JLOG(j.fatal()) //
875 << "Invariant failed: shares issuer and vault "
876 "pseudo-account must be the same";
877 result = false;
878 }
879
880 auto const sleSharesIssuer =
881 view.read(keylet::account(updatedShares->share.getIssuer()));
882 if (!sleSharesIssuer)
883 {
884 JLOG(j.fatal()) //
885 << "Invariant failed: shares issuer must exist";
886 return false;
887 }
888
889 if (!isPseudoAccount(sleSharesIssuer))
890 {
891 JLOG(j.fatal()) //
892 << "Invariant failed: shares issuer must be a "
893 "pseudo-account";
894 result = false;
895 }
896
897 if (auto const vaultId = (*sleSharesIssuer)[~sfVaultID];
898 !vaultId || *vaultId != afterVault.key)
899 {
900 JLOG(j.fatal()) //
901 << "Invariant failed: shares issuer pseudo-account "
902 "must point back to the vault";
903 result = false;
904 }
905
906 if (isClosedEnded(afterVault.vaultKind))
907 {
908 if (!afterVault.subscriptionDate || !afterVault.redemptionDate)
909 {
910 JLOG(j.fatal()) //
911 << "Invariant failed: closed-ended vault must have SubscriptionDate "
912 "and RedemptionDate";
913 result = false;
914 }
915 else if (!isValidClosedEndedGap(
916 *afterVault.subscriptionDate, *afterVault.redemptionDate))
917 {
918 JLOG(j.fatal()) //
919 << "Invariant failed: closed-ended vault RedemptionDate - "
920 "SubscriptionDate must be within [MIN_INVESTMENT_PERIOD, "
921 "MAX_INVESTMENT_PERIOD)";
922 result = false;
923 }
924 }
925
926 return result;
927 }
928 case ttVAULT_SET: {
929 bool result = true;
930
931 XRPL_ASSERT(
932 !beforeVault_.empty(), "xrpl::ValidVault::finalize : set updated a vault");
933 auto const& beforeVault = beforeVault_[0];
934
935 auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId);
936 if (vaultDeltaAssets)
937 {
938 JLOG(j.fatal()) << //
939 "Invariant failed: set must not change vault balance";
940 result = false;
941 }
942
943 if (beforeVault.assetsTotal != afterVault.assetsTotal)
944 {
945 JLOG(j.fatal()) << //
946 "Invariant failed: set must not change assets "
947 "outstanding";
948 result = false;
949 }
950
951 // AssetsTotal may exceed AssetsMaximum when the excess is interest. After
952 // fixCleanup3_4_0, only reject a VaultSet that supplies sfAssetsMaximum or
953 // otherwise changes the cap to a nonzero value still below AssetsTotal.
954 if (afterVault.assetsMaximum > kZero &&
955 afterVault.assetsTotal > afterVault.assetsMaximum &&
956 (!fix340Enabled || tx.isFieldPresent(sfAssetsMaximum) ||
957 beforeVault.assetsMaximum != afterVault.assetsMaximum))
958 {
959 JLOG(j.fatal()) << //
960 "Invariant failed: set assets outstanding must not "
961 "exceed assets maximum";
962 result = false;
963 }
964
965 if (beforeVault.assetsAvailable != afterVault.assetsAvailable)
966 {
967 JLOG(j.fatal()) << //
968 "Invariant failed: set must not change assets "
969 "available";
970 result = false;
971 }
972
973 if (beforeShares && updatedShares &&
974 beforeShares->sharesTotal != updatedShares->sharesTotal)
975 {
976 JLOG(j.fatal()) << //
977 "Invariant failed: set must not change shares "
978 "outstanding";
979 result = false;
980 }
981
982 return result;
983 }
984 case ttVAULT_DEPOSIT: {
985 bool result = true;
986
987 XRPL_ASSERT(
988 !beforeVault_.empty(), "xrpl::ValidVault::finalize : deposit updated a vault");
989 auto const& beforeVault = beforeVault_[0];
990
991 // Deposit is only allowed while the vault is in NoPhase or
992 // Subscription.
993 auto const depositPhase = getVaultPhase(
994 view,
995 afterVault.vaultKind,
996 afterVault.subscriptionDate,
997 afterVault.redemptionDate);
998 if (depositPhase != VaultPhase::NoPhase && depositPhase != VaultPhase::Subscription)
999 {
1000 JLOG(j.fatal()) << //
1001 "Invariant failed: deposit only allowed in "
1002 "Subscription or NoPhase";
1003 result = false;
1004 }
1005
1006 auto const maybeVaultDeltaAssets = deltaAssets(afterVault.pseudoId);
1007 if (!maybeVaultDeltaAssets)
1008 {
1009 JLOG(j.fatal()) << //
1010 "Invariant failed: deposit must change vault balance";
1011 return false; // That's all we can do
1012 }
1013
1014 // Get the posterior scale to round calculations to
1015 auto const minScale = computeVaultMinScale(*maybeVaultDeltaAssets, view.rules());
1016
1017 auto const vaultDeltaAssets =
1018 roundToAsset(vaultAsset, maybeVaultDeltaAssets->delta, minScale);
1019 auto const txAmount = roundToAsset(vaultAsset, tx[sfAmount], minScale);
1020
1021 if (vaultDeltaAssets > txAmount)
1022 {
1023 JLOG(j.fatal()) << //
1024 "Invariant failed: deposit must not change vault "
1025 "balance by more than deposited amount";
1026 result = false;
1027 }
1028
1029 // FixedPrecision: AssetsAvailable is exact and the pseudo-account
1030 // delta is exact; rounding either one down to the posterior
1031 // AssetsTotal scale before the sign check can turn a legitimate
1032 // sub-unit deposit into a false zero. Compare the exact deltas
1033 // instead; Legacy/CashBasis keep the rounded comparison.
1034 bool const isFixedPrecision = afterVault.version == VaultVersion::FixedPrecision;
1035 Number const exactVaultDeltaAssets = maybeVaultDeltaAssets->delta;
1036 Number const signCheckDeltaAssets =
1037 isFixedPrecision ? exactVaultDeltaAssets : vaultDeltaAssets;
1038
1039 if (signCheckDeltaAssets <= kZero)
1040 {
1041 JLOG(j.fatal()) << //
1042 "Invariant failed: deposit must increase vault balance";
1043 result = false;
1044 }
1045
1046 // Any payments (including deposits) made by the issuer
1047 // do not change their balance, but create funds instead.
1048 bool const issuerDeposit = [&] -> bool {
1049 if (vaultAsset.native())
1050 return false;
1051 return tx[sfAccount] == vaultAsset.getIssuer();
1052 }();
1053
1054 if (!issuerDeposit)
1055 {
1056 auto const maybeAccDeltaAssets =
1057 deltaAssetsForParty(view, tx[sfAccount], tx, fee, fix340Enabled);
1058 if (!maybeAccDeltaAssets)
1059 {
1060 JLOG(j.fatal())
1061 << "Invariant failed: deposit must change depositor balance";
1062 return false;
1063 }
1064 auto const localMinScale =
1065 std::max(minScale, computeCoarsestScale({*maybeAccDeltaAssets}));
1066
1067 auto const accountDeltaAssets =
1068 roundToAsset(vaultAsset, maybeAccDeltaAssets->delta, localMinScale);
1069 auto const localVaultDeltaAssets =
1070 roundToAsset(vaultAsset, vaultDeltaAssets, localMinScale);
1071
1072 // For IOUs, if the deposit amount is not-representable at depositor trustline
1073 // scale deposit amount could round to zero, giving depositor shares for no
1074 // assets. Unlike withdrawal, we do not allow that.
1075 if (accountDeltaAssets >= kZero)
1076 {
1077 JLOG(j.fatal())
1078 << "Invariant failed: deposit must decrease depositor balance";
1079 result = false;
1080 }
1081
1082 bool const acctVaultAddsUp = fix340Enabled
1083 ? agreesWithinOneUnit(
1084 localVaultDeltaAssets * -1,
1085 accountDeltaAssets,
1086 vaultAsset,
1087 localMinScale)
1088 : localVaultDeltaAssets * -1 == accountDeltaAssets;
1089 if (!acctVaultAddsUp)
1090 {
1091 JLOG(j.fatal()) << "Invariant failed: " << //
1092 "deposit must change vault and depositor balance by equal amount";
1093 result = false;
1094 }
1095 }
1096
1097 if (afterVault.assetsMaximum > kZero &&
1098 afterVault.assetsTotal > afterVault.assetsMaximum)
1099 {
1100 JLOG(j.fatal()) << "Invariant failed: " << //
1101 "deposit assets outstanding must not exceed assets maximum";
1102 result = false;
1103 }
1104
1105 auto const maybeAccDeltaShares = deltaShares(tx[sfAccount]);
1106 if (!maybeAccDeltaShares)
1107 {
1108 JLOG(j.fatal()) << "Invariant failed: deposit must change depositor shares";
1109 return false; // That's all we can do
1110 }
1111 // We don't round shares, they are integral MPT
1112 auto const& accountDeltaShares = *maybeAccDeltaShares;
1113 if (accountDeltaShares.delta <= kZero)
1114 {
1115 JLOG(j.fatal()) << "Invariant failed: deposit must increase depositor shares";
1116 result = false;
1117 }
1118
1119 auto const maybeVaultDeltaShares = deltaShares(afterVault.pseudoId);
1120 if (!maybeVaultDeltaShares || maybeVaultDeltaShares->delta == kZero)
1121 {
1122 JLOG(j.fatal()) << "Invariant failed: deposit must change vault shares";
1123 return false; // That's all we can do
1124 }
1125
1126 // We don't round shares, they are integral MPT
1127 auto const& vaultDeltaShares = *maybeVaultDeltaShares;
1128 if (vaultDeltaShares.delta * -1 != accountDeltaShares.delta)
1129 {
1130 JLOG(j.fatal()) << "Invariant failed: " << //
1131 "deposit must change depositor and vault shares by equal amount";
1132 result = false;
1133 }
1134
1135 if (!checkTotalsAddUp(
1136 afterVault,
1137 beforeVault,
1138 vaultAsset,
1139 fix340Enabled,
1140 minScale,
1141 vaultDeltaAssets,
1142 exactVaultDeltaAssets,
1143 "deposit",
1144 j))
1145 result = false;
1146
1147 return result;
1148 }
1149 case ttVAULT_WITHDRAW: {
1150 bool result = true;
1151
1152 XRPL_ASSERT(
1153 !beforeVault_.empty(),
1154 "xrpl::ValidVault::finalize : withdrawal updated a vault");
1155 auto const& beforeVault = beforeVault_[0];
1156
1157 // Withdrawal from a closed-ended vault is not allowed during the Investment phase
1158 // (strictly past SubscriptionDate, before RedemptionDate).
1159 if (getVaultPhase(
1160 view,
1161 afterVault.vaultKind,
1162 afterVault.subscriptionDate,
1163 afterVault.redemptionDate) == VaultPhase::Investment)
1164 {
1165 JLOG(j.fatal()) << //
1166 "Invariant failed: withdrawal not allowed during "
1167 "Investment phase";
1168 result = false;
1169 }
1170
1171 auto const maybeVaultDeltaAssets = deltaAssets(afterVault.pseudoId);
1172
1173 // Post-fixCleanup3_4_0: a withdrawal that redeems shares from a
1174 // pool with no effective value left to back them (e.g. fully
1175 // impaired/insolvent) legitimately moves zero assets on both
1176 // sides — VaultWithdraw::doApply does not touch either
1177 // balance-holding entry for a zero-value transfer, so no delta
1178 // is recorded. VaultWithdraw::doApply separately rejects
1179 // (tecPRECISION_LOSS) the case where a *positive* per-share
1180 // value merely rounds down to zero, so a missing delta while
1181 // the pool still held positive effective value indicates a
1182 // real accounting bug, not this exception.
1183 bool const zeroDeltaIsLegitimate = fix340Enabled && !maybeVaultDeltaAssets &&
1184 beforeVault.assetsTotal == beforeVault.lossUnrealized;
1185
1186 if (!maybeVaultDeltaAssets && !zeroDeltaIsLegitimate)
1187 {
1188 JLOG(j.fatal()) << "Invariant failed: withdrawal must change vault balance";
1189 return false; // That's all we can do
1190 }
1191
1192 DeltaInfo const vaultDeltaAssets = maybeVaultDeltaAssets.value_or(
1193 DeltaInfo{.delta = kNumZero, .scale = std::nullopt});
1194
1195 // Get the posterior scale to round calculations to
1196 auto const minScale = computeVaultMinScale(vaultDeltaAssets, view.rules());
1197
1198 auto const vaultPseudoDeltaAssets =
1199 roundToAsset(vaultAsset, vaultDeltaAssets.delta, minScale);
1200
1201 // FixedPrecision: AssetsAvailable is exact and the pseudo-account
1202 // delta is exact; rounding either one down to the posterior
1203 // AssetsTotal scale before the sign check can turn a legitimate
1204 // sub-unit withdrawal into a false zero and reject it. Compare
1205 // the exact deltas instead; Legacy/CashBasis keep the rounded
1206 // comparison.
1207 bool const isFixedPrecision = afterVault.version == VaultVersion::FixedPrecision;
1208 Number const signCheckDeltaAssets =
1209 isFixedPrecision ? vaultDeltaAssets.delta : vaultPseudoDeltaAssets;
1210
1211 if (!zeroDeltaIsLegitimate && signCheckDeltaAssets >= kZero)
1212 {
1213 JLOG(j.fatal()) << "Invariant failed: withdrawal must decrease vault balance";
1214 result = false;
1215 }
1216
1217 // Any payments (including withdrawal) going to the issuer
1218 // do not change their balance, but destroy funds instead.
1219 bool const issuerWithdrawal = [&] -> bool {
1220 if (vaultAsset.native())
1221 return false;
1222 auto const destination = tx[~sfDestination].value_or(tx[sfAccount]);
1223 return destination == vaultAsset.getIssuer();
1224 }();
1225
1226 if (!issuerWithdrawal)
1227 {
1228 // Identify the intended recipient explicitly from
1229 // sfDestination (falling back to sfAccount for a
1230 // self-withdrawal), rather than inferring it from which
1231 // side happens to show a delta. When a distinct
1232 // destination is named, the sending account must not
1233 // also show a real economic delta -- that would mean two
1234 // accounts were paid, which is always a bug, regardless
1235 // of what (if anything) the named destination received.
1236 auto const destinationField = tx[~sfDestination];
1237 AccountID const recipient = destinationField.value_or(tx[sfAccount]);
1238 bool const distinctDestination =
1239 destinationField.has_value() && *destinationField != tx[sfAccount];
1240
1241 // Intentionally ungated: `fix340Enabled &&` here would let the
1242 // pre-amendment sponsored case succeed and change consensus.
1243 if (distinctDestination &&
1244 deltaAssetsForParty(view, tx[sfAccount], tx, fee, fix340Enabled)
1245 .has_value())
1246 {
1247 JLOG(j.fatal()) << //
1248 "Invariant failed: withdrawal must change one destination balance";
1249 return false;
1250 }
1251
1252 auto const maybeRecipientDelta =
1253 deltaAssetsForParty(view, recipient, tx, fee, fix340Enabled);
1254
1255 if (!maybeRecipientDelta.has_value())
1256 {
1257 // A legitimate zero-value withdrawal moves nothing to
1258 // the recipient either; there is nothing left to
1259 // cross-check.
1260 if (!zeroDeltaIsLegitimate)
1261 {
1262 JLOG(j.fatal()) << //
1263 "Invariant failed: withdrawal must change one destination balance";
1264 return false;
1265 }
1266 }
1267 else
1268 {
1269 // A one-sided change is cross-checked even for a
1270 // legitimate zero vault delta: the destination must
1271 // then have moved by (rounded) zero as well.
1272 auto const destinationDelta = *maybeRecipientDelta;
1273
1274 // the scale of destinationDelta can be coarser than
1275 // minScale, so we take that into account when rounding
1276 auto const destinationScale = computeCoarsestScale({destinationDelta});
1277 auto const localMinScale = std::max(minScale, destinationScale);
1278
1279 auto const roundedDestinationDelta =
1280 roundToAsset(vaultAsset, destinationDelta.delta, localMinScale);
1281
1282 // Post-fixCleanup3_2_0: Tolerate zero-rounded destination deltas for IOUs
1283 // only. If the receiver's trust line sits at a coarser scale, the inflow
1284 // may safely round down to zero.
1285 //
1286 // XRP and MPT remain strict for rounding artifacts.
1287 bool const tolerateZeroDelta =
1288 view.rules().enabled(fixCleanup3_2_0) && !vaultAsset.integral();
1289 auto const invalidBalanceChange = tolerateZeroDelta
1290 ? roundedDestinationDelta < kZero
1291 : roundedDestinationDelta <= kZero;
1292 if (invalidBalanceChange)
1293 {
1294 JLOG(j.fatal()) << //
1295 "Invariant failed: withdrawal must increase destination balance";
1296 result = false;
1297 }
1298
1299 auto const localPseudoDeltaAssets =
1300 roundToAsset(vaultAsset, vaultPseudoDeltaAssets, localMinScale);
1301 auto const rate = transferRate(view, vaultAsset);
1302 bool const feeAdjustedWithdrawal = fix350Enabled && distinctDestination &&
1303 !vaultAsset.native() && tx[sfAccount] != vaultAsset.getIssuer() &&
1304 rate != kParityRate;
1305 auto expectedDestinationDelta = localPseudoDeltaAssets * -1;
1306 if (feeAdjustedWithdrawal)
1307 {
1308 expectedDestinationDelta =
1310 STAmount{vaultAsset, expectedDestinationDelta}, rate)
1311 .value();
1312 }
1313 // For IOU assets near a precision boundary the destination's STAmount
1314 // exponent can shift, making part of the sent value unrepresentable at
1315 // the receiver's new scale — that portion is irreversibly absorbed by the
1316 // IOU rail. Tolerate the mismatch only when the destroyed amount (vault
1317 // outflow minus destination inflow, in Number space) is itself sub-ULP at
1318 // the destination's scale. Floor rounding is used so that values exactly
1319 // at the step boundary are not mistakenly dismissed. Any representable
1320 // discrepancy indicates a real accounting bug and must be caught.
1321 auto const destroyedIsSubUlp = !feeAdjustedWithdrawal &&
1322 tolerateZeroDelta &&
1324 vaultAsset,
1325 vaultDeltaAssets.delta * -1 - destinationDelta.delta,
1326 destinationScale,
1328 bool const withdrawAddsUp = fix340Enabled
1329 ? agreesWithinOneUnit(
1330 expectedDestinationDelta,
1331 roundedDestinationDelta,
1332 vaultAsset,
1333 localMinScale)
1334 : expectedDestinationDelta == roundedDestinationDelta;
1335 if (!destroyedIsSubUlp && !withdrawAddsUp)
1336 {
1337 JLOG(j.fatal()) << "Invariant failed: " << //
1338 "withdrawal must change vault and destination balance by equal "
1339 "amount";
1340 result = false;
1341 }
1342 }
1343 }
1344
1345 // We don't round shares, they are integral MPT
1346 auto const accountDeltaShares = deltaShares(tx[sfAccount]);
1347 if (!accountDeltaShares)
1348 {
1349 JLOG(j.fatal()) << "Invariant failed: withdrawal must change depositor shares";
1350 return false;
1351 }
1352
1353 if (accountDeltaShares->delta >= kZero)
1354 {
1355 JLOG(j.fatal())
1356 << "Invariant failed: withdrawal must decrease depositor shares";
1357 result = false;
1358 }
1359
1360 // We don't round shares, they are integral MPT
1361 auto const vaultDeltaShares = deltaShares(afterVault.pseudoId);
1362 if (!vaultDeltaShares || vaultDeltaShares->delta == kZero)
1363 {
1364 JLOG(j.fatal()) << "Invariant failed: withdrawal must change vault shares";
1365 return false; // That's all we can do
1366 }
1367
1368 if (vaultDeltaShares->delta * -1 != accountDeltaShares->delta)
1369 {
1370 JLOG(j.fatal()) << "Invariant failed: " << //
1371 "withdrawal must change depositor and vault shares by equal amount";
1372 result = false;
1373 }
1374
1375 if (!checkTotalsAddUp(
1376 afterVault,
1377 beforeVault,
1378 vaultAsset,
1379 fix340Enabled,
1380 minScale,
1381 vaultPseudoDeltaAssets,
1382 vaultDeltaAssets.delta,
1383 "withdrawal",
1384 j))
1385 result = false;
1386
1387 return result;
1388 }
1389 case ttVAULT_CLAWBACK: {
1390 bool result = true;
1391
1392 XRPL_ASSERT(
1393 !beforeVault_.empty(), "xrpl::ValidVault::finalize : clawback updated a vault");
1394 auto const& beforeVault = beforeVault_[0];
1395
1396 if (vaultAsset.native() || vaultAsset.getIssuer() != tx[sfAccount])
1397 {
1398 // The owner can use clawback to force-burn shares when the
1399 // vault is empty but there are outstanding shares
1400 if (!(beforeShares && beforeShares->sharesTotal > 0 &&
1401 isVaultEmpty(beforeVault) && beforeVault.owner == tx[sfAccount]))
1402 {
1403 JLOG(j.fatal()) << "Invariant failed: " << //
1404 "clawback may only be performed by the asset issuer, or by the vault "
1405 "owner of an empty vault";
1406 return false; // That's all we can do
1407 }
1408 }
1409
1410 auto const maybeVaultDeltaAssets = deltaAssets(afterVault.pseudoId);
1411 if (maybeVaultDeltaAssets)
1412 {
1413 auto const minScale =
1414 computeVaultMinScale(*maybeVaultDeltaAssets, view.rules());
1415 auto const vaultDeltaAssets =
1416 roundToAsset(vaultAsset, maybeVaultDeltaAssets->delta, minScale);
1417 // FixedPrecision: AssetsAvailable is exact and the
1418 // pseudo-account delta is exact; rounding either one down
1419 // to the posterior AssetsTotal scale before the sign
1420 // check can turn a legitimate sub-unit clawback into a
1421 // false zero and reject it. Compare the exact deltas
1422 // instead; Legacy/CashBasis keep the rounded comparison.
1423 bool const isFixedPrecision =
1424 afterVault.version == VaultVersion::FixedPrecision;
1425 Number const signCheckDeltaAssets =
1426 isFixedPrecision ? maybeVaultDeltaAssets->delta : vaultDeltaAssets;
1427 if (signCheckDeltaAssets >= kZero)
1428 {
1429 JLOG(j.fatal()) << "Invariant failed: clawback must decrease vault balance";
1430 result = false;
1431 }
1432
1433 if (!checkTotalsAddUp(
1434 afterVault,
1435 beforeVault,
1436 vaultAsset,
1437 fix340Enabled,
1438 minScale,
1439 vaultDeltaAssets,
1440 maybeVaultDeltaAssets->delta,
1441 "clawback",
1442 j))
1443 result = false;
1444 }
1445 else if (!isVaultEmpty(beforeVault))
1446 {
1447 JLOG(j.fatal()) << //
1448 "Invariant failed: clawback must change vault balance";
1449 return false; // That's all we can do
1450 }
1451
1452 // We don't need to round shares, they are integral MPT
1453 auto const maybeAccountDeltaShares = deltaShares(tx[sfHolder]);
1454 if (!maybeAccountDeltaShares)
1455 {
1456 JLOG(j.fatal()) << //
1457 "Invariant failed: clawback must change holder shares";
1458 return false; // That's all we can do
1459 }
1460 if (maybeAccountDeltaShares->delta >= kZero)
1461 {
1462 JLOG(j.fatal()) << //
1463 "Invariant failed: clawback must decrease holder shares";
1464 result = false;
1465 }
1466
1467 // We don't need to round shares, they are integral MPT
1468 auto const vaultDeltaShares = deltaShares(afterVault.pseudoId);
1469 if (!vaultDeltaShares || vaultDeltaShares->delta == kZero)
1470 {
1471 JLOG(j.fatal()) << //
1472 "Invariant failed: clawback must change vault shares";
1473 return false; // That's all we can do
1474 }
1475
1476 if (vaultDeltaShares->delta * -1 != maybeAccountDeltaShares->delta)
1477 {
1478 JLOG(j.fatal()) << "Invariant failed: " << //
1479 "clawback must change holder and vault shares by equal amount";
1480 result = false;
1481 }
1482
1483 return result;
1484 }
1485
1486 case ttLOAN_SET:
1487 return finalizeLoanSet(view, j);
1488 case ttLOAN_MANAGE:
1489 case ttLOAN_PAY:
1490 return true;
1491
1492 default:
1493 // LCOV_EXCL_START
1494 UNREACHABLE("xrpl::ValidVault::finalize : unknown transaction type");
1495 return false;
1496 // LCOV_EXCL_STOP
1497 }
1498 }();
1499
1500 if (!result)
1501 {
1502 // The comment at the top of this file starting with "assert(enforce)"
1503 // explains this assert.
1504 XRPL_ASSERT(enforce, "xrpl::ValidVault::finalize : vault invariants");
1505 return !enforce;
1506 }
1507
1508 return true;
1509}
1510
1511[[nodiscard]] ValidVault::DeltaInfo
1512ValidVault::DeltaInfo::makeDelta(Number const& before, Number const& after, Asset const& asset)
1513{
1514 return {
1515 .delta = after - before,
1516 .scale = std::max(xrpl::scale(after, asset), xrpl::scale(before, asset)),
1517 };
1518}
1519
1520[[nodiscard]] std::int32_t
1522{
1523 if (numbers.empty())
1524 return 0;
1525
1526 auto const max = std::ranges::max_element(
1527 numbers, [](auto const& a, auto const& b) -> bool { return a.scale < b.scale; });
1528 XRPL_ASSERT_PARTS(
1529 max->scale, "xrpl::ValidVault::computeCoarsestScale", "scale set for destinationDelta");
1530 return max->scale.value_or(STAmount::kMaxOffset);
1531}
1532
1533} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream fatal() const
Definition Journal.h:368
bool integral() const
Definition Asset.h:133
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
A view into a ledger.
Definition ReadView.h:41
virtual Rules const & rules() const =0
Returns the tx processing rules.
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
Rules controlling protocol behavior.
Definition Rules.h:40
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
static constexpr int kMaxOffset
Definition STAmount.h:62
UInt256 const & key() const
Returns the 'key' (or 'index') of this item.
LedgerEntryType getType() const
std::shared_ptr< STLedgerEntry const > const & ConstRef
T::value_type at(TypedField< T > const &f) const
Get the value of a field.
Definition STObject.h:1077
std::uint32_t getFieldU32(SField const &field) const
Definition STObject.cpp:601
UInt192 getFieldH192(SField const &field) const
Definition STObject.cpp:625
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
AccountID getAccountID(SField const &field) const
Definition STObject.cpp:643
TxType getTxnType() const
Definition STTx.h:250
AccountID getFeePayerID() const
Definition STTx.cpp:673
static FeePayer getFeePayer(ReadView const &view, STTx const &tx)
static std::optional< AccountID > feePayerAccountRoot(ReadView const &view, STTx const &tx)
Return the AccountRoot whose XRP balance actually absorbed a transaction's fee, if any.
std::unordered_map< UInt256, DeltaInfo > deltas_
std::vector< Shares > afterMPTs_
std::optional< DeltaInfo > deltaAssetsForParty(ReadView const &view, AccountID const &id, STTx const &tx, XRPAmount fee, bool fix340Enabled) const
Return the vault-asset delta for a party inspected as a withdrawal/deposit counterparty,...
static bool isVaultEmpty(Vault const &vault)
Check whether a vault holds no assets.
static bool checkTotalsAddUp(Vault const &afterVault, Vault const &beforeVault, Asset const &vaultAsset, bool fix340Enabled, std::int32_t minScale, Number const &roundedVaultDelta, Number const &exactVaultDelta, char const *verb, beast::Journal const &j)
Check that a vault's AssetsTotal and AssetsAvailable deltas add up against the real transfer,...
std::vector< Vault > afterVault_
std::optional< DeltaInfo > deltaShares(AccountID const &id) const
Return the vault-share balance-change delta for an account.
void visitEntry(bool, SLE::ConstRef, SLE::ConstRef)
std::vector< Shares > beforeMPTs_
static std::int32_t computeCoarsestScale(std::vector< DeltaInfo > const &numbers)
bool finalizeLoanSet(ReadView const &view, beast::Journal const &j) const
Invariant check for ttLOAN_SET.
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
std::vector< Vault > beforeVault_
static constexpr Number kZero
std::optional< DeltaInfo > deltaAssets(AccountID const &id) const
Return the vault-asset balance-change delta for an account.
std::int32_t computeVaultMinScale(DeltaInfo const &vaultDelta, Rules const &rules) const
Compute the minimum STAmount scale for rounding invariant calculations.
constexpr value_type drops() const
Returns the number of drops.
Definition XRPAmount.h:163
T empty(T... args)
T is_same_v
T max_element(T... args)
T max(T... args)
constexpr Zero kZero
Definition Zero.h:30
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:547
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
Keylet trustLine(AccountID const &id0, AccountID const &id1, Currency const &currency) noexcept
The index of a trust line for a given currency.
Definition Indexes.cpp:287
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
static constexpr Number kNumZero
Definition Number.h:667
STAmount subtractTransferFee(STAmount const &amount, Rate const &rate)
Returns the amount a receiver gets when amount leaves the sender and the issuer takes the transfer fe...
bool isXRP(AccountID const &c)
Definition AccountID.h:84
bool isValidClosedEndedGap(std::uint32_t sub, std::uint32_t red)
Returns true iff the (SubscriptionDate, RedemptionDate) gap of a closed-ended vault satisfies kMinInv...
int scale(Number const &number, Asset const &asset)
Get the scale of a Number for a given asset.
Definition STAmount.h:819
STLedgerEntry SLE
BaseUInt< 256 > UInt256
Definition base_uint.h:581
bool hasPrivilege(STTx const &tx, Privilege priv)
Rate transferRate(ReadView const &view, AccountID const &issuer)
Returns IOU issuer transfer fee as Rate.
bool after(NetClock::time_point now, std::uint32_t mark)
Has the specified time passed?
Definition View.cpp:668
Rate const kParityRate
A transfer rate signifying a 1:1 exchange.
VaultPhase getVaultPhase(ReadView const &view, SLE::ConstRef vault)
Returns the current lifecycle phase of a vault.
MPTID makeMptID(std::uint32_t const sequence, AccountID const &account)
Definition Indexes.cpp:219
void roundToAsset(A const &asset, Number &value)
Round an arbitrary precision Number IN PLACE to the precision of a given Asset.
Definition STAmount.h:745
bool isPseudoAccount(SLE::const_pointer sleAcct)
Returns true if and only if sleAcct is a pseudo-account of any kind (i.e.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
Buffer sign(PublicKey const &pk, SecretKey const &sk, Slice const &message)
Generate a signature for a message.
TERSubset< CanCvtToTER > TER
Definition TER.h:657
constexpr std::uint64_t kMaxMpTokenAmount
The maximum amount of MPTokenIssuance.
Definition Protocol.h:297
VaultVersion decodeVaultVersion(std::optional< std::uint8_t > leVersion)
Decodes an already-extracted sfLEVersion value with the same range check as getVaultVersion.
static DeltaInfo makeDelta(Number const &before, Number const &after, Asset const &asset)
std::optional< int > scale
static Shares make(SLE const &)
std::optional< std::uint8_t > vaultKind
std::optional< std::uint32_t > subscriptionDate
std::optional< std::uint32_t > redemptionDate
static Vault make(SLE const &)
T value(T... args)
T visit(T... args)