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";
1040 JLOG(j.
fatal()) <<
"Invariant failed: account created with "
1041 "wrong starting sequence number";
1052 <<
"Invariant failed: pseudo-account created with "
1061 JLOG(j.
fatal()) <<
"Invariant failed: account root created illegally";
1074 static constexpr uint256 const accountBits = ~pageBits;
1076 if ((before && before->getType() != ltNFTOKEN_PAGE) ||
1077 (
after &&
after->getType() != ltNFTOKEN_PAGE))
1081 uint256 const account = sle->key() & accountBits;
1082 uint256 const hiLimit = sle->key() & pageBits;
1090 if (account != (*prev & accountBits))
1093 if (hiLimit <= (*prev & pageBits))
1097 if (
auto const next = (*sle)[~sfNextPageMin])
1099 if (account != (*next & accountBits))
1102 if (hiLimit >= (*next & pageBits))
1107 auto const& nftokens = sle->getFieldArray(sfNFTokens);
1110 if (
std::size_t const nftokenCount = nftokens.size();
1111 (!isDelete && nftokenCount == 0) ||
1118 prev ? *prev & pageBits :
uint256(beast::zero);
1122 for (
auto const& obj : nftokens)
1124 uint256 const tokenID = obj[sfNFTokenID];
1131 if (
uint256 const tokenPageBits = tokenID & pageBits;
1132 tokenPageBits < loLimit || tokenPageBits >= hiLimit)
1135 if (
auto uri = obj[~sfURI]; uri && uri->empty())
1149 before->isFieldPresent(sfPreviousPageMin))
1158 if (!isDelete && before &&
after)
1166 before->isFieldPresent(sfNextPageMin) &&
1167 !
after->isFieldPresent(sfNextPageMin))
1184 JLOG(j.
fatal()) <<
"Invariant failed: NFT page is improperly linked.";
1190 JLOG(j.
fatal()) <<
"Invariant failed: NFT found in incorrect page.";
1196 JLOG(j.
fatal()) <<
"Invariant failed: NFTs on page are not sorted.";
1202 JLOG(j.
fatal()) <<
"Invariant failed: NFT contains empty URI.";
1208 JLOG(j.
fatal()) <<
"Invariant failed: NFT page has invalid size.";
1216 JLOG(j.
fatal()) <<
"Invariant failed: Last NFT page deleted with "
1217 "non-empty directory.";
1222 JLOG(j.
fatal()) <<
"Invariant failed: Lost NextMinPage link.";
1237 if (before && before->getType() == ltACCOUNT_ROOT)
1243 if (
after &&
after->getType() == ltACCOUNT_ROOT)
1262 JLOG(j.
fatal()) <<
"Invariant failed: the number of minted tokens "
1263 "changed without a mint transaction!";
1269 JLOG(j.
fatal()) <<
"Invariant failed: the number of burned tokens "
1270 "changed without a burn transaction!";
1282 <<
"Invariant failed: successful minting didn't increase "
1283 "the number of minted tokens.";
1289 JLOG(j.
fatal()) <<
"Invariant failed: failed minting changed the "
1290 "number of minted tokens.";
1297 <<
"Invariant failed: minting changed the number of "
1310 <<
"Invariant failed: successful burning didn't increase "
1311 "the number of burned tokens.";
1318 JLOG(j.
fatal()) <<
"Invariant failed: failed burning changed the "
1319 "number of burned tokens.";
1326 <<
"Invariant failed: burning changed the number of "
1343 if (before && before->getType() == ltRIPPLE_STATE)
1346 if (before && before->getType() == ltMPTOKEN)
1366 <<
"Invariant failed: more than one trustline changed.";
1373 <<
"Invariant failed: more than one mptokens changed.";
1385 if (holderBalance.
signum() < 0)
1388 <<
"Invariant failed: trustline balance is negative";
1397 JLOG(j.
fatal()) <<
"Invariant failed: some trustlines were changed "
1398 "despite failure of the transaction.";
1404 JLOG(j.
fatal()) <<
"Invariant failed: some mptokens were changed "
1405 "despite failure of the transaction.";
1421 if (
after &&
after->getType() == ltMPTOKEN_ISSUANCE)
1452 JLOG(j.
fatal()) <<
"Invariant failed: transaction "
1453 "succeeded without creating a MPT issuance";
1457 JLOG(j.
fatal()) <<
"Invariant failed: transaction "
1458 "succeeded while removing MPT issuances";
1462 JLOG(j.
fatal()) <<
"Invariant failed: transaction "
1463 "succeeded but created multiple issuances";
1473 JLOG(j.
fatal()) <<
"Invariant failed: MPT issuance deletion "
1474 "succeeded without removing a MPT issuance";
1478 JLOG(j.
fatal()) <<
"Invariant failed: MPT issuance deletion "
1479 "succeeded while creating MPT issuances";
1483 JLOG(j.
fatal()) <<
"Invariant failed: MPT issuance deletion "
1484 "succeeded but deleted multiple issuances";
1493 bool const enforceEscrowFinish = (tx.
getTxnType() == ttESCROW_FINISH) &&
1500 enforceEscrowFinish)
1506 JLOG(j.
fatal()) <<
"Invariant failed: MPT authorize "
1507 "succeeded but created MPT issuances";
1512 JLOG(j.
fatal()) <<
"Invariant failed: MPT authorize "
1513 "succeeded but deleted issuances";
1517 submittedByIssuer &&
1521 <<
"Invariant failed: MPT authorize submitted by issuer "
1522 "succeeded but created/deleted mptokens";
1532 <<
"Invariant failed: MPT authorize submitted by holder "
1533 "succeeded but created/deleted bad number of mptokens";
1545 !enforceEscrowFinish,
1546 "ripple::ValidMPTIssuance::finalize",
1547 "not escrow finish tx");
1559 JLOG(j.
fatal()) <<
"Invariant failed: a MPT issuance was created";
1563 JLOG(j.
fatal()) <<
"Invariant failed: a MPT issuance was deleted";
1567 JLOG(j.
fatal()) <<
"Invariant failed: a MPToken was created";
1571 JLOG(j.
fatal()) <<
"Invariant failed: a MPToken was deleted";
1586 if (before && before->getType() != ltPERMISSIONED_DOMAIN)
1588 if (
after &&
after->getType() != ltPERMISSIONED_DOMAIN)
1593 auto const& credentials = sle->getFieldArray(sfAcceptedCredentials);
1604 for (
auto const& cred : sorted)
1606 auto const& credTx = credentials[i++];
1607 sleStatus.
isSorted_ = (cred.first == credTx[sfIssuer]) &&
1608 (cred.second == credTx[sfCredentialType]);
1642 JLOG(j.
fatal()) <<
"Invariant failed: permissioned domain with "
1650 JLOG(j.
fatal()) <<
"Invariant failed: permissioned domain bad "
1659 <<
"Invariant failed: permissioned domain credentials "
1667 <<
"Invariant failed: permissioned domain credentials "
1691 if (
after &&
after->getType() == ltACCOUNT_ROOT)
1693 bool const isPseudo = [&]() {
1700 if (
after->at(sfSequence) == 0)
1721 return after->isFieldPresent(*sf);
1726 error <<
"pseudo-account has " << numFields
1727 <<
" pseudo-account fields set";
1731 if (before && before->at(sfSequence) !=
after->at(sfSequence))
1740 if (
after->isFieldPresent(sfRegularKey))
1756 bool const enforce = view.
rules().
enabled(featureSingleAssetVault);
1761 "ripple::ValidPseudoAccounts::finalize : no bad "
1762 "changes or enforce invariant");
1765 for (
auto const& error :
errors_)
1767 JLOG(j.
fatal()) <<
"Invariant failed: " << error;
1785 if (
after->isFieldPresent(sfDomainID))
1791 if (
after->isFieldPresent(sfDomainID))
1799 (!
after->isFieldPresent(sfDomainID) ||
1800 !
after->isFieldPresent(sfAdditionalBooks) ||
1801 after->getFieldArray(sfAdditionalBooks).size() > 1))
1815 if ((txType != ttPAYMENT && txType != ttOFFER_CREATE) ||
1823 JLOG(j.
fatal()) <<
"Invariant failed: hybrid offer is malformed";
1834 JLOG(j.
fatal()) <<
"Invariant failed: domain doesn't exist";
1844 JLOG(j.
fatal()) <<
"Invariant failed: transaction"
1845 " consumed wrong domains";
1852 JLOG(j.
fatal()) <<
"Invariant failed: domain transaction"
1853 " affected regular offers";
1871 auto const type =
after->getType();
1881 (type == ltACCOUNT_ROOT &&
after->isFieldPresent(sfAMMID)))
1890 if (before->getType() == ltAMM)
1904 bool const positive = amount > beast::zero && amount2 > beast::zero &&
1905 lptAMMBalance > beast::zero;
1908 (amount == beast::zero && amount2 == beast::zero &&
1909 lptAMMBalance == beast::zero);
1920 JLOG(j.
error()) <<
"AMMVote invariant failed: "
1939 JLOG(j.
error()) <<
"AMMBid invariant failed: pool changed";
1972 <<
"AMMCreate invariant failed: AMM object is not created";
1982 tx[sfAmount].get<Issue>(),
1983 tx[sfAmount2].get<Issue>(),
1994 JLOG(j.
error()) <<
"AMMCreate invariant failed: " << amount <<
" "
2011 ?
"AMM object is not deleted on tesSUCCESS"
2012 :
"AMM object is changed on tecINCOMPLETE";
2013 JLOG(j.
error()) <<
"AMMDelete invariant failed: " << msg;
2028 JLOG(j.
error()) <<
"AMM swap invariant failed: AMM object changed";
2047 tx[sfAsset].get<Issue>(),
2048 tx[sfAsset2].get<Issue>(),
2055 auto const poolProductMean =
root2(amount * amount2);
2056 bool const nonNegativeBalances =
2060 auto weakInvariantCheck = [&]() {
2065 if (!nonNegativeBalances ||
2066 (!strongInvariantCheck && !weakInvariantCheck()))
2071 <<
" " << poolProductMean <<
" "
2093 JLOG(j.
error()) <<
"AMMDeposit invariant failed: AMM object is deleted";
2145 case ttAMM_CLAWBACK:
2146 case ttAMM_WITHDRAW:
2155 case ttOFFER_CREATE:
2172 "ValidVault::Vault::make : from Vault object");
2176 self.
asset = from.
at(sfAsset);
2190 from.
getType() == ltMPTOKEN_ISSUANCE,
2191 "ValidVault::Shares::make : from MPTokenIssuance object");
2211 after !=
nullptr && (before !=
nullptr || !isDelete),
2212 "ripple::ValidVault::visitEntry : some object is available");
2223 switch (before->getType())
2228 case ltMPTOKEN_ISSUANCE:
2233 before->getFieldU64(sfOutstandingAmount));
2238 static_cast<std::int64_t>(before->getFieldU64(sfMPTAmount));
2241 case ltACCOUNT_ROOT:
2242 case ltRIPPLE_STATE:
2243 balanceDelta = before->getFieldAmount(sfBalance);
2250 if (!isDelete &&
after)
2252 switch (
after->getType())
2257 case ltMPTOKEN_ISSUANCE:
2262 after->getFieldU64(sfOutstandingAmount)));
2270 case ltACCOUNT_ROOT:
2271 case ltRIPPLE_STATE:
2272 balanceDelta -=
Number(
after->getFieldAmount(sfBalance));
2279 uint256 const key = (before ? before->key() :
after->key());
2297 bool const enforce = view.
rules().
enabled(featureSingleAssetVault);
2307 "Invariant failed: vault operation succeeded without modifying "
2310 enforce,
"ripple::ValidVault::finalize : vault noop invariant");
2319 "Invariant failed: vault updated by a wrong transaction type";
2322 "ripple::ValidVault::finalize : illegal vault transaction "
2330 "Invariant failed: vault operation updated more than single vault";
2332 enforce,
"ripple::ValidVault::finalize : single vault invariant");
2342 if (txnType != ttVAULT_DELETE)
2345 "Invariant failed: vault deleted by a wrong transaction type";
2348 "ripple::ValidVault::finalize : illegal vault deletion "
2363 if (e.share.getMptID() == beforeVault.shareMPTID)
2364 return std::move(e);
2371 JLOG(j.
fatal()) <<
"Invariant failed: deleted vault must also "
2375 "ripple::ValidVault::finalize : shares deletion invariant");
2380 if (deletedShares->sharesTotal != 0)
2382 JLOG(j.
fatal()) <<
"Invariant failed: deleted vault must have no "
2383 "shares outstanding";
2386 if (beforeVault.assetsTotal !=
zero)
2388 JLOG(j.
fatal()) <<
"Invariant failed: deleted vault must have no "
2389 "assets outstanding";
2392 if (beforeVault.assetsAvailable !=
zero)
2394 JLOG(j.
fatal()) <<
"Invariant failed: deleted vault must have no "
2401 else if (txnType == ttVAULT_DELETE)
2403 JLOG(j.
fatal()) <<
"Invariant failed: vault deletion succeeded without "
2406 enforce,
"ripple::ValidVault::finalize : vault deletion invariant");
2414 "ripple::ValidVault::finalize : single vault operation");
2424 if (e.share.getMptID() == afterVault.shareMPTID)
2428 auto const sleShares =
2441 if (afterVault.asset != beforeVault.asset ||
2442 afterVault.pseudoId != beforeVault.pseudoId ||
2443 afterVault.shareMPTID != beforeVault.shareMPTID)
2446 <<
"Invariant failed: violation of vault immutable data";
2453 JLOG(j.
fatal()) <<
"Invariant failed: updated vault must have shares";
2456 "ripple::ValidVault::finalize : vault has shares invariant");
2460 if (updatedShares->sharesTotal == 0)
2462 if (afterVault.assetsTotal !=
zero)
2464 JLOG(j.
fatal()) <<
"Invariant failed: updated zero sized "
2465 "vault must have no assets outstanding";
2468 if (afterVault.assetsAvailable !=
zero)
2470 JLOG(j.
fatal()) <<
"Invariant failed: updated zero sized "
2471 "vault must have no assets available";
2475 else if (updatedShares->sharesTotal > updatedShares->sharesMaximum)
2478 <<
"Invariant failed: updated shares must not exceed maximum "
2479 << updatedShares->sharesMaximum;
2483 if (afterVault.assetsAvailable <
zero)
2486 <<
"Invariant failed: assets available must be positive";
2490 if (afterVault.assetsAvailable > afterVault.assetsTotal)
2492 JLOG(j.
fatal()) <<
"Invariant failed: assets available must "
2493 "not be greater than assets outstanding";
2497 afterVault.lossUnrealized >
2498 afterVault.assetsTotal - afterVault.assetsAvailable)
2501 <<
"Invariant failed: loss unrealized must not exceed "
2502 "the difference between assets outstanding and available";
2506 if (afterVault.assetsTotal <
zero)
2509 <<
"Invariant failed: assets outstanding must be positive";
2513 if (afterVault.assetsMaximum <
zero)
2515 JLOG(j.
fatal()) <<
"Invariant failed: assets maximum must be positive";
2524 "Invariant failed: vault created by a wrong transaction type";
2526 enforce,
"ripple::ValidVault::finalize : vault creation invariant");
2531 afterVault.lossUnrealized !=
beforeVault_[0].lossUnrealized)
2534 "Invariant failed: vault transaction must not change loss "
2546 if (e.share.getMptID() == beforeVault.shareMPTID)
2547 return std::move(e);
2552 if (!beforeShares &&
2557 JLOG(j.
fatal()) <<
"Invariant failed: vault operation succeeded "
2558 "without updating shares";
2560 enforce,
"ripple::ValidVault::finalize : shares noop invariant");
2564 auto const& vaultAsset = afterVault.asset;
2571 return it->second *
sign;
2575 [&]<
typename TIss>(TIss
const& issue) {
2582 id > issue.getIssuer() ? -1 : 1);
2590 vaultAsset.value());
2593 auto ret = deltaAssets(tx[sfAccount]);
2595 if (!ret.has_value() || !vaultAsset.native())
2599 if (
auto const delegate = tx[~sfDelegate];
2600 delegate.has_value() && *delegate != tx[sfAccount])
2603 *ret += fee.
drops();
2610 auto const it = [&]() {
2611 if (
id == afterVault.pseudoId)
2628 case ttVAULT_CREATE: {
2634 <<
"Invariant failed: create operation must not have "
2639 if (afterVault.assetsAvailable !=
zero ||
2640 afterVault.assetsTotal !=
zero ||
2641 afterVault.lossUnrealized !=
zero ||
2642 updatedShares->sharesTotal != 0)
2645 <<
"Invariant failed: created vault must be empty";
2649 if (afterVault.pseudoId != updatedShares->share.getIssuer())
2652 <<
"Invariant failed: shares issuer and vault "
2653 "pseudo-account must be the same";
2657 auto const sleSharesIssuer = view.
read(
2659 if (!sleSharesIssuer)
2662 <<
"Invariant failed: shares issuer must exist";
2669 <<
"Invariant failed: shares issuer must be a "
2674 if (
auto const vaultId = (*sleSharesIssuer)[~sfVaultID];
2675 !vaultId || *vaultId != afterVault.key)
2678 <<
"Invariant failed: shares issuer pseudo-account "
2679 "must point back to the vault";
2690 "ripple::ValidVault::finalize : set updated a vault");
2693 auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId);
2694 if (vaultDeltaAssets)
2697 "Invariant failed: set must not change vault balance";
2701 if (beforeVault.assetsTotal != afterVault.assetsTotal)
2704 "Invariant failed: set must not change assets "
2709 if (afterVault.assetsMaximum >
zero &&
2710 afterVault.assetsTotal > afterVault.assetsMaximum)
2713 "Invariant failed: set assets outstanding must not "
2714 "exceed assets maximum";
2718 if (beforeVault.assetsAvailable != afterVault.assetsAvailable)
2721 "Invariant failed: set must not change assets "
2726 if (beforeShares && updatedShares &&
2727 beforeShares->sharesTotal != updatedShares->sharesTotal)
2730 "Invariant failed: set must not change shares "
2737 case ttVAULT_DEPOSIT: {
2742 "ripple::ValidVault::finalize : deposit updated a vault");
2745 auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId);
2747 if (!vaultDeltaAssets)
2750 "Invariant failed: deposit must change vault balance";
2754 if (*vaultDeltaAssets > tx[sfAmount])
2757 "Invariant failed: deposit must not change vault "
2758 "balance by more than deposited amount";
2762 if (*vaultDeltaAssets <=
zero)
2765 "Invariant failed: deposit must increase vault balance";
2771 bool const issuerDeposit = [&]() ->
bool {
2772 if (vaultAsset.native())
2774 return tx[sfAccount] == vaultAsset.getIssuer();
2779 auto const accountDeltaAssets = deltaAssetsTxAccount();
2780 if (!accountDeltaAssets)
2783 "Invariant failed: deposit must change depositor "
2788 if (*accountDeltaAssets >=
zero)
2791 "Invariant failed: deposit must decrease depositor "
2796 if (*accountDeltaAssets * -1 != *vaultDeltaAssets)
2799 "Invariant failed: deposit must change vault and "
2800 "depositor balance by equal amount";
2805 if (afterVault.assetsMaximum >
zero &&
2806 afterVault.assetsTotal > afterVault.assetsMaximum)
2809 "Invariant failed: deposit assets outstanding must not "
2810 "exceed assets maximum";
2814 auto const accountDeltaShares = deltaShares(tx[sfAccount]);
2815 if (!accountDeltaShares)
2818 "Invariant failed: deposit must change depositor "
2823 if (*accountDeltaShares <=
zero)
2826 "Invariant failed: deposit must increase depositor "
2831 auto const vaultDeltaShares = deltaShares(afterVault.pseudoId);
2832 if (!vaultDeltaShares || *vaultDeltaShares ==
zero)
2835 "Invariant failed: deposit must change vault shares";
2839 if (*vaultDeltaShares * -1 != *accountDeltaShares)
2842 "Invariant failed: deposit must change depositor and "
2843 "vault shares by equal amount";
2847 if (beforeVault.assetsTotal + *vaultDeltaAssets !=
2848 afterVault.assetsTotal)
2850 JLOG(j.
fatal()) <<
"Invariant failed: deposit and assets "
2851 "outstanding must add up";
2854 if (beforeVault.assetsAvailable + *vaultDeltaAssets !=
2855 afterVault.assetsAvailable)
2857 JLOG(j.
fatal()) <<
"Invariant failed: deposit and assets "
2858 "available must add up";
2864 case ttVAULT_WITHDRAW: {
2869 "ripple::ValidVault::finalize : withdrawal updated a "
2873 auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId);
2875 if (!vaultDeltaAssets)
2877 JLOG(j.
fatal()) <<
"Invariant failed: withdrawal must "
2878 "change vault balance";
2882 if (*vaultDeltaAssets >=
zero)
2884 JLOG(j.
fatal()) <<
"Invariant failed: withdrawal must "
2885 "decrease vault balance";
2891 bool const issuerWithdrawal = [&]() ->
bool {
2892 if (vaultAsset.native())
2894 auto const destination =
2895 tx[~sfDestination].value_or(tx[sfAccount]);
2896 return destination == vaultAsset.getIssuer();
2899 if (!issuerWithdrawal)
2901 auto const accountDeltaAssets = deltaAssetsTxAccount();
2902 auto const otherAccountDelta =
2904 if (
auto const destination = tx[~sfDestination];
2905 destination && *destination != tx[sfAccount])
2906 return deltaAssets(*destination);
2910 if (accountDeltaAssets.has_value() ==
2911 otherAccountDelta.has_value())
2914 "Invariant failed: withdrawal must change one "
2915 "destination balance";
2919 auto const destinationDelta =
2920 accountDeltaAssets ? *accountDeltaAssets
2921 : *otherAccountDelta;
2923 if (destinationDelta <=
zero)
2926 "Invariant failed: withdrawal must increase "
2927 "destination balance";
2931 if (*vaultDeltaAssets * -1 != destinationDelta)
2934 "Invariant failed: withdrawal must change vault "
2935 "and destination balance by equal amount";
2940 auto const accountDeltaShares = deltaShares(tx[sfAccount]);
2941 if (!accountDeltaShares)
2944 "Invariant failed: withdrawal must change depositor "
2949 if (*accountDeltaShares >=
zero)
2952 "Invariant failed: withdrawal must decrease depositor "
2957 auto const vaultDeltaShares = deltaShares(afterVault.pseudoId);
2958 if (!vaultDeltaShares || *vaultDeltaShares ==
zero)
2961 "Invariant failed: withdrawal must change vault shares";
2965 if (*vaultDeltaShares * -1 != *accountDeltaShares)
2968 "Invariant failed: withdrawal must change depositor "
2969 "and vault shares by equal amount";
2974 if (beforeVault.assetsTotal + *vaultDeltaAssets !=
2975 afterVault.assetsTotal)
2977 JLOG(j.
fatal()) <<
"Invariant failed: withdrawal and "
2978 "assets outstanding must add up";
2982 if (beforeVault.assetsAvailable + *vaultDeltaAssets !=
2983 afterVault.assetsAvailable)
2985 JLOG(j.
fatal()) <<
"Invariant failed: withdrawal and "
2986 "assets available must add up";
2992 case ttVAULT_CLAWBACK: {
2997 "ripple::ValidVault::finalize : clawback updated a vault");
3000 if (vaultAsset.native() ||
3001 vaultAsset.getIssuer() != tx[sfAccount])
3004 "Invariant failed: clawback may only be performed by "
3009 auto const vaultDeltaAssets = deltaAssets(afterVault.pseudoId);
3011 if (!vaultDeltaAssets)
3014 "Invariant failed: clawback must change vault balance";
3018 if (*vaultDeltaAssets >=
zero)
3021 "Invariant failed: clawback must decrease vault "
3026 auto const accountDeltaShares = deltaShares(tx[sfHolder]);
3027 if (!accountDeltaShares)
3030 "Invariant failed: clawback must change holder shares";
3034 if (*accountDeltaShares >=
zero)
3037 "Invariant failed: clawback must decrease holder "
3042 auto const vaultDeltaShares = deltaShares(afterVault.pseudoId);
3043 if (!vaultDeltaShares || *vaultDeltaShares ==
zero)
3046 "Invariant failed: clawback must change vault shares";
3050 if (*vaultDeltaShares * -1 != *accountDeltaShares)
3053 "Invariant failed: clawback must change holder and "
3054 "vault shares by equal amount";
3058 if (beforeVault.assetsTotal + *vaultDeltaAssets !=
3059 afterVault.assetsTotal)
3062 "Invariant failed: clawback and assets outstanding "
3067 if (beforeVault.assetsAvailable + *vaultDeltaAssets !=
3068 afterVault.assetsAvailable)
3071 "Invariant failed: clawback and assets available must "
3082 "ripple::ValidVault::finalize : unknown transaction type");
3092 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 &)