1#include <xrpld/app/misc/AMMHelpers.h>
2#include <xrpld/app/misc/AMMUtils.h>
3#include <xrpld/app/tx/detail/InvariantCheck.h>
4#include <xrpld/app/tx/detail/NFTokenUtils.h>
5#include <xrpld/app/tx/detail/PermissionedDomainSet.h>
7#include <xrpl/basics/Log.h>
8#include <xrpl/beast/utility/instrumentation.h>
9#include <xrpl/ledger/CredentialHelpers.h>
10#include <xrpl/ledger/ReadView.h>
11#include <xrpl/ledger/View.h>
12#include <xrpl/protocol/Feature.h>
13#include <xrpl/protocol/Indexes.h>
14#include <xrpl/protocol/LedgerFormats.h>
15#include <xrpl/protocol/MPTIssue.h>
16#include <xrpl/protocol/SField.h>
17#include <xrpl/protocol/STArray.h>
18#include <xrpl/protocol/STNumber.h>
19#include <xrpl/protocol/SystemParameters.h>
20#include <xrpl/protocol/TER.h>
21#include <xrpl/protocol/TxFormats.h>
22#include <xrpl/protocol/Units.h>
23#include <xrpl/protocol/nftPageMask.h>
77 return safe_cast<Privilege>(
82#pragma push_macro("TRANSACTION")
85#define TRANSACTION(tag, value, name, delegatable, amendment, privileges, ...) \
87 return (privileges) & priv; \
95#include <xrpl/protocol/detail/transactions.macro>
103#pragma pop_macro("TRANSACTION")
125 JLOG(j.
fatal()) <<
"Invariant failed: fee paid was negative: "
134 JLOG(j.
fatal()) <<
"Invariant failed: fee paid exceeds system limit: "
143 JLOG(j.
fatal()) <<
"Invariant failed: fee paid is " << fee.
drops()
144 <<
" exceeds fee specified in transaction.";
168 switch (before->getType())
171 drops_ -= (*before)[sfBalance].xrp().drops();
175 ((*before)[sfAmount] - (*before)[sfBalance]).xrp().drops();
178 if (
isXRP((*before)[sfAmount]))
179 drops_ -= (*before)[sfAmount].xrp().drops();
188 switch (
after->getType())
191 drops_ += (*after)[sfBalance].xrp().drops();
195 drops_ += ((*after)[sfAmount] - (*after)[sfBalance])
201 drops_ += (*after)[sfAmount].xrp().drops();
221 JLOG(j.
fatal()) <<
"Invariant failed: XRP net change was positive: "
229 JLOG(j.
fatal()) <<
"Invariant failed: XRP net change of " <<
drops_
230 <<
" doesn't match fee " << fee.
drops();
245 auto isBad = [](
STAmount const& balance) {
246 if (!balance.native())
249 auto const drops = balance.xrp();
263 if (before && before->getType() == ltACCOUNT_ROOT)
264 bad_ |= isBad((*before)[sfBalance]);
266 if (
after &&
after->getType() == ltACCOUNT_ROOT)
280 JLOG(j.
fatal()) <<
"Invariant failed: incorrect account XRP balance";
297 if (pays < beast::zero)
300 if (gets < beast::zero)
304 return pays.
native() && gets.native();
307 if (before && before->getType() == ltOFFER)
308 bad_ |= isBad((*before)[sfTakerPays], (*before)[sfTakerGets]);
311 bad_ |= isBad((*
after)[sfTakerPays], (*after)[sfTakerGets]);
324 JLOG(j.
fatal()) <<
"Invariant failed: offer with a bad amount";
339 auto isBad = [](
STAmount const& amount) {
352 if (amount.holds<
Issue>())
354 if (amount <= beast::zero)
364 if (amount <= beast::zero)
374 if (before && before->getType() == ltESCROW)
375 bad_ |= isBad((*before)[sfAmount]);
385 if (
after &&
after->getType() == ltMPTOKEN_ISSUANCE)
387 auto const outstanding = (*after)[sfOutstandingAmount];
388 checkAmount(outstanding);
389 if (
auto const locked = (*
after)[~sfLockedAmount])
391 checkAmount(*locked);
392 bad_ = outstanding < *locked;
398 auto const mptAmount = (*after)[sfMPTAmount];
399 checkAmount(mptAmount);
400 if (
auto const locked = (*
after)[~sfLockedAmount])
402 checkAmount(*locked);
417 JLOG(j.
fatal()) <<
"Invariant failed: escrow specifies invalid amount";
432 if (isDelete && before && before->getType() == ltACCOUNT_ROOT)
454 JLOG(j.
fatal()) <<
"Invariant failed: account deletion "
455 "succeeded without deleting an account";
457 JLOG(j.
fatal()) <<
"Invariant failed: account deletion "
458 "succeeded but deleted multiple accounts!";
472 JLOG(j.
fatal()) <<
"Invariant failed: an account root was deleted";
484 if (isDelete && before && before->getType() == ltACCOUNT_ROOT)
500 [[maybe_unused]]
bool const enforce =
504 auto const objectExists = [&view, enforce, &j](
auto const& keylet) {
506 if (
auto const sle = view.
read(keylet))
509 auto const typeName = [&sle]() {
514 return item->getName();
519 <<
"Invariant failed: account deletion left behind a "
520 << typeName <<
" object";
525 "ripple::AccountRootsDeletedClean::finalize::objectExists : "
526 "account deletion left no objects behind");
534 auto const accountID = accountSLE->getAccountID(sfAccount);
538 if (objectExists(
std::invoke(keyletfunc, accountID)) && enforce)
553 if (key && objectExists(
Keylet{ltNFTOKEN_PAGE, *key}) && enforce)
561 if (accountSLE->isFieldPresent(*field))
563 auto const key = accountSLE->getFieldH256(*field);
581 if (before &&
after && before->getType() !=
after->getType())
586#pragma push_macro("LEDGER_ENTRY")
589#define LEDGER_ENTRY(tag, ...) case tag:
591 switch (
after->getType())
593#include <xrpl/protocol/detail/ledger_entries.macro>
602#pragma pop_macro("LEDGER_ENTRY")
619 JLOG(j.
fatal()) <<
"Invariant failed: ledger entry type mismatch";
624 JLOG(j.
fatal()) <<
"Invariant failed: invalid ledger entry type added";
638 if (
after &&
after->getType() == ltRIPPLE_STATE)
660 JLOG(j.
fatal()) <<
"Invariant failed: an XRP trust line was created";
672 if (
after &&
after->getType() == ltRIPPLE_STATE)
682 (lowDeepFreeze && !lowFreeze) || (highDeepFreeze && !highFreeze);
697 JLOG(j.
fatal()) <<
"Invariant failed: a trust line with deep freeze flag "
698 "without normal freeze was created";
726 if (balanceChange.signum() == 0)
758 [[maybe_unused]]
bool const enforce =
763 auto const issuerSle =
findIssuer(issue.account, view);
772 "ripple::TransfersNotFrozen::finalize : enforce "
797 after,
"ripple::TransfersNotFrozen::isValidEntry : valid after.");
803 if (
after->getType() == ltACCOUNT_ROOT)
815 return after->getType() == ltRIPPLE_STATE &&
816 (!before || before->getType() == ltRIPPLE_STATE);
825 auto const getBalance = [](
auto const& line,
auto const& other,
bool zero) {
827 line ? line->at(sfBalance) : other->at(sfBalance).zeroed();
828 return zero ? amt.
zeroed() : amt;
836 auto const balanceBefore = getBalance(before,
after,
false);
843 auto const balanceAfter = getBalance(
after, before, isDelete);
845 return balanceAfter - balanceBefore;
853 "ripple::TransfersNotFrozen::recordBalance : valid trustline "
857 changes.senders.emplace_back(std::move(change));
859 changes.receivers.emplace_back(std::move(change));
867 auto const balanceChangeSign = balanceChange.
signum();
868 auto const currency =
after->at(sfBalance).getCurrency();
872 {currency,
after->at(sfHighLimit).getIssuer()},
873 {
after, balanceChangeSign});
877 {currency,
after->at(sfLowLimit).getIssuer()},
878 {
after, -balanceChangeSign});
920 for (
auto const& change : actors)
922 bool const high = change.line->at(sfLowLimit).getIssuer() ==
923 issuer->at(sfAccount);
926 change, high, tx, j, enforce, globalFreeze))
946 bool const deepFreeze =
948 bool const frozen = globalFreeze || deepFreeze || freeze;
960 JLOG(j.
debug()) <<
"Invariant check allowing funds to be moved "
962 <<
" a frozen trustline for AMMClawback "
967 JLOG(j.
fatal()) <<
"Invariant failed: Attempting to move frozen funds for "
972 "ripple::TransfersNotFrozen::validateFrozenState : enforce "
991 if (!before &&
after->getType() == ltACCOUNT_ROOT)
1013 JLOG(j.
fatal()) <<
"Invariant failed: multiple accounts "
1014 "created in a single transaction";
1021 bool const pseudoAccount =
1026 JLOG(j.
fatal()) <<
"Invariant failed: pseudo-account created by a "
1027 "wrong transaction type";
1035 JLOG(j.
fatal()) <<
"Invariant failed: account created with "
1036 "wrong starting sequence number";
1047 <<
"Invariant failed: pseudo-account created with "
1056 JLOG(j.
fatal()) <<
"Invariant failed: account root created illegally";
1069 static constexpr uint256 const accountBits = ~pageBits;
1071 if ((before && before->getType() != ltNFTOKEN_PAGE) ||
1072 (
after &&
after->getType() != ltNFTOKEN_PAGE))
1076 uint256 const account = sle->key() & accountBits;
1077 uint256 const hiLimit = sle->key() & pageBits;
1085 if (account != (*prev & accountBits))
1088 if (hiLimit <= (*prev & pageBits))
1092 if (
auto const next = (*sle)[~sfNextPageMin])
1094 if (account != (*next & accountBits))
1097 if (hiLimit >= (*next & pageBits))
1102 auto const& nftokens = sle->getFieldArray(sfNFTokens);
1105 if (
std::size_t const nftokenCount = nftokens.size();
1106 (!isDelete && nftokenCount == 0) ||
1113 prev ? *prev & pageBits :
uint256(beast::zero);
1117 for (
auto const& obj : nftokens)
1119 uint256 const tokenID = obj[sfNFTokenID];
1126 if (
uint256 const tokenPageBits = tokenID & pageBits;
1127 tokenPageBits < loLimit || tokenPageBits >= hiLimit)
1130 if (
auto uri = obj[~sfURI]; uri && uri->empty())
1144 before->isFieldPresent(sfPreviousPageMin))
1153 if (!isDelete && before &&
after)
1161 before->isFieldPresent(sfNextPageMin) &&
1162 !
after->isFieldPresent(sfNextPageMin))
1179 JLOG(j.
fatal()) <<
"Invariant failed: NFT page is improperly linked.";
1185 JLOG(j.
fatal()) <<
"Invariant failed: NFT found in incorrect page.";
1191 JLOG(j.
fatal()) <<
"Invariant failed: NFTs on page are not sorted.";
1197 JLOG(j.
fatal()) <<
"Invariant failed: NFT contains empty URI.";
1203 JLOG(j.
fatal()) <<
"Invariant failed: NFT page has invalid size.";
1211 JLOG(j.
fatal()) <<
"Invariant failed: Last NFT page deleted with "
1212 "non-empty directory.";
1217 JLOG(j.
fatal()) <<
"Invariant failed: Lost NextMinPage link.";
1232 if (before && before->getType() == ltACCOUNT_ROOT)
1238 if (
after &&
after->getType() == ltACCOUNT_ROOT)
1257 JLOG(j.
fatal()) <<
"Invariant failed: the number of minted tokens "
1258 "changed without a mint transaction!";
1264 JLOG(j.
fatal()) <<
"Invariant failed: the number of burned tokens "
1265 "changed without a burn transaction!";
1277 <<
"Invariant failed: successful minting didn't increase "
1278 "the number of minted tokens.";
1284 JLOG(j.
fatal()) <<
"Invariant failed: failed minting changed the "
1285 "number of minted tokens.";
1292 <<
"Invariant failed: minting changed the number of "
1305 <<
"Invariant failed: successful burning didn't increase "
1306 "the number of burned tokens.";
1313 JLOG(j.
fatal()) <<
"Invariant failed: failed burning changed the "
1314 "number of burned tokens.";
1321 <<
"Invariant failed: burning changed the number of "
1338 if (before && before->getType() == ltRIPPLE_STATE)
1341 if (before && before->getType() == ltMPTOKEN)
1361 <<
"Invariant failed: more than one trustline changed.";
1368 <<
"Invariant failed: more than one mptokens changed.";
1380 if (holderBalance.
signum() < 0)
1383 <<
"Invariant failed: trustline balance is negative";
1392 JLOG(j.
fatal()) <<
"Invariant failed: some trustlines were changed "
1393 "despite failure of the transaction.";
1399 JLOG(j.
fatal()) <<
"Invariant failed: some mptokens were changed "
1400 "despite failure of the transaction.";
1416 if (
after &&
after->getType() == ltMPTOKEN_ISSUANCE)
1447 JLOG(j.
fatal()) <<
"Invariant failed: transaction "
1448 "succeeded without creating a MPT issuance";
1452 JLOG(j.
fatal()) <<
"Invariant failed: transaction "
1453 "succeeded while removing MPT issuances";
1457 JLOG(j.
fatal()) <<
"Invariant failed: transaction "
1458 "succeeded but created multiple issuances";
1468 JLOG(j.
fatal()) <<
"Invariant failed: MPT issuance deletion "
1469 "succeeded without removing a MPT issuance";
1473 JLOG(j.
fatal()) <<
"Invariant failed: MPT issuance deletion "
1474 "succeeded while creating MPT issuances";
1478 JLOG(j.
fatal()) <<
"Invariant failed: MPT issuance deletion "
1479 "succeeded but deleted multiple issuances";
1488 bool const enforceEscrowFinish = (tx.
getTxnType() == ttESCROW_FINISH) &&
1495 enforceEscrowFinish)
1501 JLOG(j.
fatal()) <<
"Invariant failed: MPT authorize "
1502 "succeeded but created MPT issuances";
1507 JLOG(j.
fatal()) <<
"Invariant failed: MPT authorize "
1508 "succeeded but deleted issuances";
1512 submittedByIssuer &&
1516 <<
"Invariant failed: MPT authorize submitted by issuer "
1517 "succeeded but created/deleted mptokens";
1527 <<
"Invariant failed: MPT authorize submitted by holder "
1528 "succeeded but created/deleted bad number of mptokens";
1540 !enforceEscrowFinish,
1541 "ripple::ValidMPTIssuance::finalize",
1542 "not escrow finish tx");
1554 JLOG(j.
fatal()) <<
"Invariant failed: a MPT issuance was created";
1558 JLOG(j.
fatal()) <<
"Invariant failed: a MPT issuance was deleted";
1562 JLOG(j.
fatal()) <<
"Invariant failed: a MPToken was created";
1566 JLOG(j.
fatal()) <<
"Invariant failed: a MPToken was deleted";
1581 if (before && before->getType() != ltPERMISSIONED_DOMAIN)
1583 if (
after &&
after->getType() != ltPERMISSIONED_DOMAIN)
1588 auto const& credentials = sle->getFieldArray(sfAcceptedCredentials);
1599 for (
auto const& cred : sorted)
1601 auto const& credTx = credentials[i++];
1602 sleStatus.
isSorted_ = (cred.first == credTx[sfIssuer]) &&
1603 (cred.second == credTx[sfCredentialType]);
1637 JLOG(j.
fatal()) <<
"Invariant failed: permissioned domain with "
1645 JLOG(j.
fatal()) <<
"Invariant failed: permissioned domain bad "
1654 <<
"Invariant failed: permissioned domain credentials "
1662 <<
"Invariant failed: permissioned domain credentials "
1686 if (
after &&
after->getType() == ltACCOUNT_ROOT)
1688 bool const isPseudo = [&]() {
1695 if (
after->at(sfSequence) == 0)
1716 return after->isFieldPresent(*sf);
1721 error <<
"pseudo-account has " << numFields
1722 <<
" pseudo-account fields set";
1726 if (before && before->at(sfSequence) !=
after->at(sfSequence))
1735 if (
after->isFieldPresent(sfRegularKey))
1751 bool const enforce = view.
rules().
enabled(featureSingleAssetVault);
1756 "ripple::ValidPseudoAccounts::finalize : no bad "
1757 "changes or enforce invariant");
1760 for (
auto const& error :
errors_)
1762 JLOG(j.
fatal()) <<
"Invariant failed: " << error;
1780 if (
after->isFieldPresent(sfDomainID))
1786 if (
after->isFieldPresent(sfDomainID))
1794 (!
after->isFieldPresent(sfDomainID) ||
1795 !
after->isFieldPresent(sfAdditionalBooks) ||
1796 after->getFieldArray(sfAdditionalBooks).size() > 1))
1810 if ((txType != ttPAYMENT && txType != ttOFFER_CREATE) ||
1818 JLOG(j.
fatal()) <<
"Invariant failed: hybrid offer is malformed";
1829 JLOG(j.
fatal()) <<
"Invariant failed: domain doesn't exist";
1839 JLOG(j.
fatal()) <<
"Invariant failed: transaction"
1840 " consumed wrong domains";
1847 JLOG(j.
fatal()) <<
"Invariant failed: domain transaction"
1848 " affected regular offers";
1866 auto const type =
after->getType();
1876 (type == ltACCOUNT_ROOT &&
after->isFieldPresent(sfAMMID)))
1885 if (before->getType() == ltAMM)
1899 bool const positive = amount > beast::zero && amount2 > beast::zero &&
1900 lptAMMBalance > beast::zero;
1903 (amount == beast::zero && amount2 == beast::zero &&
1904 lptAMMBalance == beast::zero);
1915 JLOG(j.
error()) <<
"AMMVote invariant failed: "
1934 JLOG(j.
error()) <<
"AMMBid invariant failed: pool changed";
1967 <<
"AMMCreate invariant failed: AMM object is not created";
1977 tx[sfAmount].get<Issue>(),
1978 tx[sfAmount2].get<Issue>(),
1989 JLOG(j.
error()) <<
"AMMCreate invariant failed: " << amount <<
" "
2006 ?
"AMM object is not deleted on tesSUCCESS"
2007 :
"AMM object is changed on tecINCOMPLETE";
2008 JLOG(j.
error()) <<
"AMMDelete invariant failed: " << msg;
2023 JLOG(j.
error()) <<
"AMM swap invariant failed: AMM object changed";
2042 tx[sfAsset].get<Issue>(),
2043 tx[sfAsset2].get<Issue>(),
2050 auto const poolProductMean =
root2(amount * amount2);
2051 bool const nonNegativeBalances =
2055 auto weakInvariantCheck = [&]() {
2060 if (!nonNegativeBalances ||
2061 (!strongInvariantCheck && !weakInvariantCheck()))
2066 <<
" " << poolProductMean <<
" "
2088 JLOG(j.
error()) <<
"AMMDeposit invariant failed: AMM object is deleted";
2140 case ttAMM_CLAWBACK:
2141 case ttAMM_WITHDRAW:
2150 case ttOFFER_CREATE:
2167 "ValidVault::Vault::make : from Vault object");
2171 self.
asset = from.
at(sfAsset);
2185 from.
getType() == ltMPTOKEN_ISSUANCE,
2186 "ValidVault::Shares::make : from MPTokenIssuance object");
2206 after !=
nullptr && (before !=
nullptr || !isDelete),
2207 "ripple::ValidVault::visitEntry : some object is available");
2218 switch (before->getType())
2223 case ltMPTOKEN_ISSUANCE:
2228 before->getFieldU64(sfOutstandingAmount));
2233 static_cast<std::int64_t>(before->getFieldU64(sfMPTAmount));
2236 case ltACCOUNT_ROOT:
2237 case ltRIPPLE_STATE:
2238 balanceDelta = before->getFieldAmount(sfBalance);
2245 if (!isDelete &&
after)
2247 switch (
after->getType())
2252 case ltMPTOKEN_ISSUANCE:
2257 after->getFieldU64(sfOutstandingAmount)));
2265 case ltACCOUNT_ROOT:
2266 case ltRIPPLE_STATE:
2267 balanceDelta -=
Number(
after->getFieldAmount(sfBalance));
2274 uint256 const key = (before ? before->key() :
after->key());
2292 bool const enforce = view.
rules().
enabled(featureSingleAssetVault);
2302 "Invariant failed: vault operation succeeded without modifying "
2305 enforce,
"ripple::ValidVault::finalize : vault noop invariant");
2314 "Invariant failed: vault updated by a wrong transaction type";
2317 "ripple::ValidVault::finalize : illegal vault transaction "
2325 "Invariant failed: vault operation updated more than single vault";
2327 enforce,
"ripple::ValidVault::finalize : single vault invariant");
2337 if (txnType != ttVAULT_DELETE)
2340 "Invariant failed: vault deleted by a wrong transaction type";
2343 "ripple::ValidVault::finalize : illegal vault deletion "
2358 if (e.share.getMptID() == beforeVault.shareMPTID)
2359 return std::move(e);
2366 JLOG(j.
fatal()) <<
"Invariant failed: deleted vault must also "
2370 "ripple::ValidVault::finalize : shares deletion invariant");
2375 if (deletedShares->sharesTotal != 0)
2377 JLOG(j.
fatal()) <<
"Invariant failed: deleted vault must have no "
2378 "shares outstanding";
2381 if (beforeVault.assetsTotal !=
zero)
2383 JLOG(j.
fatal()) <<
"Invariant failed: deleted vault must have no "
2384 "assets outstanding";
2387 if (beforeVault.assetsAvailable !=
zero)
2389 JLOG(j.
fatal()) <<
"Invariant failed: deleted vault must have no "
2396 else if (txnType == ttVAULT_DELETE)
2398 JLOG(j.
fatal()) <<
"Invariant failed: vault deletion succeeded without "
2401 enforce,
"ripple::ValidVault::finalize : vault deletion invariant");
2409 "ripple::ValidVault::finalize : single vault operation");
2419 if (e.share.getMptID() == afterVault.shareMPTID)
2423 auto const sleShares =
2436 if (afterVault.asset != beforeVault.asset ||
2437 afterVault.pseudoId != beforeVault.pseudoId ||
2438 afterVault.shareMPTID != beforeVault.shareMPTID)
2441 <<
"Invariant failed: violation of vault immutable data";
2448 JLOG(j.
fatal()) <<
"Invariant failed: updated vault must have shares";
2451 "ripple::ValidVault::finalize : vault has shares invariant");
2455 if (updatedShares->sharesTotal == 0)
2457 if (afterVault.assetsTotal !=
zero)
2459 JLOG(j.
fatal()) <<
"Invariant failed: updated zero sized "
2460 "vault must have no assets outstanding";
2463 if (afterVault.assetsAvailable !=
zero)
2465 JLOG(j.
fatal()) <<
"Invariant failed: updated zero sized "
2466 "vault must have no assets available";
2470 else if (updatedShares->sharesTotal > updatedShares->sharesMaximum)
2473 <<
"Invariant failed: updated shares must not exceed maximum "
2474 << updatedShares->sharesMaximum;
2478 if (afterVault.assetsAvailable <
zero)
2481 <<
"Invariant failed: assets available must be positive";
2485 if (afterVault.assetsAvailable > afterVault.assetsTotal)
2487 JLOG(j.
fatal()) <<
"Invariant failed: assets available must "
2488 "not be greater than assets outstanding";
2492 afterVault.lossUnrealized >
2493 afterVault.assetsTotal - afterVault.assetsAvailable)
2496 <<
"Invariant failed: loss unrealized must not exceed "
2497 "the difference between assets outstanding and available";
2501 if (afterVault.assetsTotal <
zero)
2504 <<
"Invariant failed: assets outstanding must be positive";
2508 if (afterVault.assetsMaximum <
zero)
2510 JLOG(j.
fatal()) <<
"Invariant failed: assets maximum must be positive";
2519 "Invariant failed: vault created by a wrong transaction type";
2521 enforce,
"ripple::ValidVault::finalize : vault creation invariant");
2526 afterVault.lossUnrealized !=
beforeVault_[0].lossUnrealized)
2529 "Invariant failed: vault transaction must not change loss "
2541 if (e.share.getMptID() == beforeVault.shareMPTID)
2542 return std::move(e);
2547 if (!beforeShares &&
2552 JLOG(j.
fatal()) <<
"Invariant failed: vault operation succeeded "
2553 "without updating shares";
2555 enforce,
"ripple::ValidVault::finalize : shares noop invariant");
2559 auto const& vaultAsset = afterVault.asset;
2566 return it->second *
sign;
2570 [&]<
typename TIss>(TIss
const& issue) {
2577 id > issue.getIssuer() ? -1 : 1);
2585 vaultAsset.value());
2588 auto ret = deltaAssets(tx[sfAccount]);
2590 if (!ret.has_value() || !vaultAsset.native())
2594 if (
auto const delegate = tx[~sfDelegate];
2595 delegate.has_value() && *delegate != tx[sfAccount])
2598 *ret += fee.
drops();
2605 auto const it = [&]() {
2606 if (
id == afterVault.pseudoId)
2623 case ttVAULT_CREATE: {
2629 <<
"Invariant failed: create operation must not have "
2634 if (afterVault.assetsAvailable !=
zero ||
2635 afterVault.assetsTotal !=
zero ||
2636 afterVault.lossUnrealized !=
zero ||
2637 updatedShares->sharesTotal != 0)
2640 <<
"Invariant failed: created vault must be empty";
2644 if (afterVault.pseudoId != updatedShares->share.getIssuer())
2647 <<
"Invariant failed: shares issuer and vault "
2648 "pseudo-account must be the same";
2652 auto const sleSharesIssuer = view.
read(
2654 if (!sleSharesIssuer)
2657 <<
"Invariant failed: shares issuer must exist";
2664 <<
"Invariant failed: shares issuer must be a "
2669 if (
auto const vaultId = (*sleSharesIssuer)[~sfVaultID];
2670 !vaultId || *vaultId != afterVault.key)
2673 <<
"Invariant failed: shares issuer pseudo-account "
2674 "must point back to the vault";
2685 "ripple::ValidVault::finalize : set updated a vault");
2688 auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId);
2689 if (vaultDeltaAssets)
2692 "Invariant failed: set must not change vault balance";
2696 if (beforeVault.assetsTotal != afterVault.assetsTotal)
2699 "Invariant failed: set must not change assets "
2704 if (afterVault.assetsMaximum >
zero &&
2705 afterVault.assetsTotal > afterVault.assetsMaximum)
2708 "Invariant failed: set assets outstanding must not "
2709 "exceed assets maximum";
2713 if (beforeVault.assetsAvailable != afterVault.assetsAvailable)
2716 "Invariant failed: set must not change assets "
2721 if (beforeShares && updatedShares &&
2722 beforeShares->sharesTotal != updatedShares->sharesTotal)
2725 "Invariant failed: set must not change shares "
2732 case ttVAULT_DEPOSIT: {
2737 "ripple::ValidVault::finalize : deposit updated a vault");
2740 auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId);
2742 if (!vaultDeltaAssets)
2745 "Invariant failed: deposit must change vault balance";
2749 if (*vaultDeltaAssets > tx[sfAmount])
2752 "Invariant failed: deposit must not change vault "
2753 "balance by more than deposited amount";
2757 if (*vaultDeltaAssets <=
zero)
2760 "Invariant failed: deposit must increase vault balance";
2766 bool const issuerDeposit = [&]() ->
bool {
2767 if (vaultAsset.native())
2769 return tx[sfAccount] == vaultAsset.getIssuer();
2774 auto const accountDeltaAssets = deltaAssetsTxAccount();
2775 if (!accountDeltaAssets)
2778 "Invariant failed: deposit must change depositor "
2783 if (*accountDeltaAssets >=
zero)
2786 "Invariant failed: deposit must decrease depositor "
2791 if (*accountDeltaAssets * -1 != *vaultDeltaAssets)
2794 "Invariant failed: deposit must change vault and "
2795 "depositor balance by equal amount";
2800 if (afterVault.assetsMaximum >
zero &&
2801 afterVault.assetsTotal > afterVault.assetsMaximum)
2804 "Invariant failed: deposit assets outstanding must not "
2805 "exceed assets maximum";
2809 auto const accountDeltaShares = deltaShares(tx[sfAccount]);
2810 if (!accountDeltaShares)
2813 "Invariant failed: deposit must change depositor "
2818 if (*accountDeltaShares <=
zero)
2821 "Invariant failed: deposit must increase depositor "
2826 auto const vaultDeltaShares = deltaShares(afterVault.pseudoId);
2827 if (!vaultDeltaShares || *vaultDeltaShares ==
zero)
2830 "Invariant failed: deposit must change vault shares";
2834 if (*vaultDeltaShares * -1 != *accountDeltaShares)
2837 "Invariant failed: deposit must change depositor and "
2838 "vault shares by equal amount";
2842 if (beforeVault.assetsTotal + *vaultDeltaAssets !=
2843 afterVault.assetsTotal)
2845 JLOG(j.
fatal()) <<
"Invariant failed: deposit and assets "
2846 "outstanding must add up";
2849 if (beforeVault.assetsAvailable + *vaultDeltaAssets !=
2850 afterVault.assetsAvailable)
2852 JLOG(j.
fatal()) <<
"Invariant failed: deposit and assets "
2853 "available must add up";
2859 case ttVAULT_WITHDRAW: {
2864 "ripple::ValidVault::finalize : withdrawal updated a "
2868 auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId);
2870 if (!vaultDeltaAssets)
2872 JLOG(j.
fatal()) <<
"Invariant failed: withdrawal must "
2873 "change vault balance";
2877 if (*vaultDeltaAssets >=
zero)
2879 JLOG(j.
fatal()) <<
"Invariant failed: withdrawal must "
2880 "decrease vault balance";
2886 bool const issuerWithdrawal = [&]() ->
bool {
2887 if (vaultAsset.native())
2889 auto const destination =
2890 tx[~sfDestination].value_or(tx[sfAccount]);
2891 return destination == vaultAsset.getIssuer();
2894 if (!issuerWithdrawal)
2896 auto const accountDeltaAssets = deltaAssetsTxAccount();
2897 auto const otherAccountDelta =
2899 if (
auto const destination = tx[~sfDestination];
2900 destination && *destination != tx[sfAccount])
2901 return deltaAssets(*destination);
2905 if (accountDeltaAssets.has_value() ==
2906 otherAccountDelta.has_value())
2909 "Invariant failed: withdrawal must change one "
2910 "destination balance";
2914 auto const destinationDelta =
2915 accountDeltaAssets ? *accountDeltaAssets
2916 : *otherAccountDelta;
2918 if (destinationDelta <=
zero)
2921 "Invariant failed: withdrawal must increase "
2922 "destination balance";
2926 if (*vaultDeltaAssets * -1 != destinationDelta)
2929 "Invariant failed: withdrawal must change vault "
2930 "and destination balance by equal amount";
2935 auto const accountDeltaShares = deltaShares(tx[sfAccount]);
2936 if (!accountDeltaShares)
2939 "Invariant failed: withdrawal must change depositor "
2944 if (*accountDeltaShares >=
zero)
2947 "Invariant failed: withdrawal must decrease depositor "
2952 auto const vaultDeltaShares = deltaShares(afterVault.pseudoId);
2953 if (!vaultDeltaShares || *vaultDeltaShares ==
zero)
2956 "Invariant failed: withdrawal must change vault shares";
2960 if (*vaultDeltaShares * -1 != *accountDeltaShares)
2963 "Invariant failed: withdrawal must change depositor "
2964 "and vault shares by equal amount";
2969 if (beforeVault.assetsTotal + *vaultDeltaAssets !=
2970 afterVault.assetsTotal)
2972 JLOG(j.
fatal()) <<
"Invariant failed: withdrawal and "
2973 "assets outstanding must add up";
2977 if (beforeVault.assetsAvailable + *vaultDeltaAssets !=
2978 afterVault.assetsAvailable)
2980 JLOG(j.
fatal()) <<
"Invariant failed: withdrawal and "
2981 "assets available must add up";
2987 case ttVAULT_CLAWBACK: {
2992 "ripple::ValidVault::finalize : clawback updated a vault");
2995 if (vaultAsset.native() ||
2996 vaultAsset.getIssuer() != tx[sfAccount])
2999 "Invariant failed: clawback may only be performed by "
3004 auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId);
3006 if (!vaultDeltaAssets)
3009 "Invariant failed: clawback must change vault balance";
3013 if (*vaultDeltaAssets >=
zero)
3016 "Invariant failed: clawback must decrease vault "
3021 auto const accountDeltaShares = deltaShares(tx[sfHolder]);
3022 if (!accountDeltaShares)
3025 "Invariant failed: clawback must change holder shares";
3029 if (*accountDeltaShares >=
zero)
3032 "Invariant failed: clawback must decrease holder "
3037 auto const vaultDeltaShares = deltaShares(afterVault.pseudoId);
3038 if (!vaultDeltaShares || *vaultDeltaShares ==
zero)
3041 "Invariant failed: clawback must change vault shares";
3045 if (*vaultDeltaShares * -1 != *accountDeltaShares)
3048 "Invariant failed: clawback must change holder and "
3049 "vault shares by equal amount";
3053 if (beforeVault.assetsTotal + *vaultDeltaAssets !=
3054 afterVault.assetsTotal)
3057 "Invariant failed: clawback and assets outstanding "
3062 if (beforeVault.assetsAvailable + *vaultDeltaAssets !=
3063 afterVault.assetsAvailable)
3066 "Invariant failed: clawback and assets available must "
3077 "ripple::ValidVault::finalize : unknown transaction type");
3087 XRPL_ASSERT(enforce,
"ripple::ValidVault::finalize : vault invariants");
A generic endpoint for log messages.
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
std::vector< std::shared_ptr< SLE const > > accountsDeleted_
std::uint32_t accountsDeleted_
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
A currency issued by an account.
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
std::uint32_t afterMintedTotal
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
std::uint32_t afterBurnedTotal
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
std::uint32_t beforeBurnedTotal
std::uint32_t beforeMintedTotal
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool deepFreezeWithoutFreeze_
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
virtual std::shared_ptr< SLE const > read(Keylet const &k) const =0
Return the state item associated with a key.
virtual std::optional< key_type > succ(key_type const &key, std::optional< key_type > const &last=std::nullopt) const =0
Return the key of the next state item.
virtual bool exists(Keylet const &k) const =0
Determine if a state item exists.
LedgerIndex seq() const
Returns the sequence number of the base ledger.
virtual Rules const & rules() const =0
Returns the tx processing rules.
bool enabled(uint256 const &feature) const
Returns true if a feature is enabled.
Currency const & getCurrency() const
int signum() const noexcept
AccountID const & getIssuer() const
bool native() const noexcept
STAmount zeroed() const
Returns a zero value with the same issuer and currency.
LedgerEntryType getType() const
uint256 const & key() const
Returns the 'key' (or 'index') of this item.
uint192 getFieldH192(SField const &field) const
AccountID getAccountID(SField const &field) const
T::value_type at(TypedField< T > const &f) const
Get the value of a field.
std::uint32_t getFieldU32(SField const &field) const
STAmount const & getFieldAmount(SField const &field) const
uint256 getHash(HashPrefix prefix) const
bool isFieldPresent(SField const &field) const
uint256 getFieldH256(SField const &field) const
TxType getTxnType() const
uint256 getTransactionID() const
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
std::map< AccountID, std::shared_ptr< SLE const > const > possibleIssuers_
bool isValidEntry(std::shared_ptr< SLE const > const &before, std::shared_ptr< SLE const > const &after)
void recordBalance(Issue const &issue, BalanceChange change)
std::shared_ptr< SLE const > findIssuer(AccountID const &issuerID, ReadView const &view)
bool validateIssuerChanges(std::shared_ptr< SLE const > const &issuer, IssuerChanges const &changes, STTx const &tx, beast::Journal const &j, bool enforce)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
STAmount calculateBalanceChange(std::shared_ptr< SLE const > const &before, std::shared_ptr< SLE const > const &after, bool isDelete)
void recordBalanceChanges(std::shared_ptr< SLE const > const &after, STAmount const &balanceChange)
bool validateFrozenState(BalanceChange const &change, bool high, STTx const &tx, beast::Journal const &j, bool enforce, bool globalFreeze)
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
bool finalizeWithdraw(STTx const &, ReadView const &, bool enforce, beast::Journal const &) const
bool finalizeDEX(bool enforce, beast::Journal const &) const
std::optional< STAmount > lptAMMBalanceAfter_
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalizeBid(bool enforce, beast::Journal const &) const
std::optional< AccountID > ammAccount_
bool finalizeDelete(bool enforce, TER res, beast::Journal const &) const
bool finalizeCreate(STTx const &, ReadView const &, bool enforce, beast::Journal const &) const
bool finalizeVote(bool enforce, beast::Journal const &) const
bool finalizeDeposit(STTx const &, ReadView const &, bool enforce, beast::Journal const &) const
bool generalInvariant(STTx const &, ReadView const &, ZeroAllowed zeroAllowed, beast::Journal const &) const
std::optional< STAmount > lptAMMBalanceBefore_
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
std::uint32_t trustlinesChanged
std::uint32_t mptokensChanged
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
std::uint32_t mptIssuancesCreated_
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
std::uint32_t mptokensCreated_
std::uint32_t mptIssuancesDeleted_
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
std::uint32_t mptokensDeleted_
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
std::uint32_t accountsCreated_
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
std::uint32_t accountSeq_
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
hash_set< uint256 > domains_
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
std::optional< SleStatus > sleStatus_[2]
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
std::vector< std::string > errors_
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
std::vector< Shares > beforeMPTs_
std::vector< Vault > beforeVault_
std::unordered_map< uint256, Number > deltas_
static Number constexpr zero
std::vector< Shares > afterMPTs_
std::vector< Vault > afterVault_
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
constexpr value_type drops() const
Returns the number of drops.
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
void visitEntry(bool, std::shared_ptr< SLE const > const &, std::shared_ptr< SLE const > const &)
bool finalize(STTx const &, TER const, XRPAmount const, ReadView const &, beast::Journal const &)
T emplace_back(T... args)
std::set< std::pair< AccountID, Slice > > makeSorted(STArray const &credentials)
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Keylet permissionedDomain(AccountID const &account, std::uint32_t seq) noexcept
Keylet line(AccountID const &id0, AccountID const &id1, Currency const ¤cy) noexcept
The index of a trust line for a given currency.
Keylet mptIssuance(std::uint32_t seq, AccountID const &issuer) noexcept
Keylet account(AccountID const &id) noexcept
AccountID root.
Keylet unchecked(uint256 const &key) noexcept
Any ledger entry.
Keylet nftpage_min(AccountID const &owner)
NFT page keylets.
Keylet nftpage_max(AccountID const &owner)
A keylet for the owner's last possible NFT page.
bool compareTokens(uint256 const &a, uint256 const &b)
uint256 constexpr pageMask(std::string_view("0000000000000000000000000000000000000000ffffffffffffffffffffffff"))
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Currency const & badCurrency()
We deliberately disallow the currency that looks like "XRP" because too many people were using it ins...
bool isXRP(AccountID const &c)
constexpr base_uint< Bits, Tag > operator|(base_uint< Bits, Tag > const &a, base_uint< Bits, Tag > const &b)
static bool validBalances(STAmount const &amount, STAmount const &amount2, STAmount const &lptAMMBalance, ValidAMM::ZeroAllowed zeroAllowed)
std::size_t constexpr maxPermissionedDomainCredentialsArraySize
The maximum number of credentials can be passed in array for permissioned domain.
bool hasPrivilege(STTx const &tx, Privilege priv)
constexpr std::enable_if_t< std::is_integral_v< Dest > &&std::is_integral_v< Src >, Dest > safe_cast(Src s) noexcept
std::uint64_t constexpr maxMPTokenAmount
The maximum amount of MPTokenIssuance.
constexpr XRPAmount INITIAL_XRP
Configure the native currency.
std::size_t constexpr dirMaxTokensPerPage
The maximum number of items in an NFT page.
Buffer sign(PublicKey const &pk, SecretKey const &sk, Slice const &message)
Generate a signature for a message.
std::array< keyletDesc< AccountID const & >, 6 > const directAccountKeylets
std::pair< STAmount, STAmount > ammPoolHolds(ReadView const &view, AccountID const &ammAccountID, Issue const &issue1, Issue const &issue2, FreezeHandling freezeHandling, beast::Journal const j)
Get AMM pool balances.
STAmount accountHolds(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j)
bool isTesSuccess(TER x) noexcept
STAmount ammLPTokens(STAmount const &asset1, STAmount const &asset2, Issue const &lptIssue)
Calculate LP Tokens given AMM pool reserves.
T get(Section const §ion, std::string const &name, T const &defaultValue=T{})
Retrieve a key/value pair from a section.
bool after(NetClock::time_point now, std::uint32_t mark)
Has the specified time passed?
@ transactionID
transaction plus signature to give transaction ID
MPTID makeMptID(std::uint32_t sequence, AccountID const &account)
std::vector< SField const * > const & getPseudoAccountFields()
bool withinRelativeDistance(Quality const &calcQuality, Quality const &reqQuality, Number const &dist)
Check if the relative distance between the qualities is within the requested distance.
bool isPseudoAccount(std::shared_ptr< SLE const > sleAcct)
A pair of SHAMap key and LedgerEntryType.
int const balanceChangeSign
std::shared_ptr< SLE const > const line
std::vector< BalanceChange > receivers
std::vector< BalanceChange > senders
std::size_t credentialsSize_
std::uint64_t sharesMaximum
static Shares make(SLE const &)
std::uint64_t sharesTotal
static Vault make(SLE const &)