1#include <test/app/invariants/InvariantsBase.h>
2#include <test/jtx/AMM.h>
3#include <test/jtx/Account.h>
4#include <test/jtx/Env.h>
5#include <test/jtx/TestHelpers.h>
6#include <test/jtx/amount.h>
7#include <test/jtx/fee.h>
8#include <test/jtx/mpt.h>
9#include <test/jtx/pay.h>
10#include <test/jtx/sig.h>
11#include <test/jtx/trust.h>
12#include <test/jtx/vault.h>
13#include <test/unit_test/SuiteJournal.h>
15#include <xrpl/basics/Number.h>
16#include <xrpl/basics/Slice.h>
17#include <xrpl/basics/base_uint.h>
18#include <xrpl/beast/unit_test/suite.h>
19#include <xrpl/beast/utility/Journal.h>
20#include <xrpl/ledger/ApplyView.h>
21#include <xrpl/ledger/OpenView.h>
22#include <xrpl/ledger/helpers/AccountRootHelpers.h>
23#include <xrpl/ledger/helpers/DirectoryHelpers.h>
24#include <xrpl/protocol/AccountID.h>
25#include <xrpl/protocol/Feature.h>
26#include <xrpl/protocol/Indexes.h>
27#include <xrpl/protocol/Issue.h>
28#include <xrpl/protocol/Keylet.h>
29#include <xrpl/protocol/LedgerFormats.h>
30#include <xrpl/protocol/Rules.h>
31#include <xrpl/protocol/SField.h>
32#include <xrpl/protocol/STLedgerEntry.h>
33#include <xrpl/protocol/STObject.h>
34#include <xrpl/protocol/STTx.h>
35#include <xrpl/protocol/SeqProxy.h>
36#include <xrpl/protocol/TER.h>
37#include <xrpl/protocol/TxFlags.h>
38#include <xrpl/protocol/TxFormats.h>
39#include <xrpl/protocol/XRPAmount.h>
40#include <xrpl/tx/ApplyContext.h>
41#include <xrpl/tx/Transactor.h>
42#include <xrpl/tx/applySteps.h>
73 Vault const vault{env};
74 auto [tx, vKeylet] = vault.create({.owner = a, .asset = xrpAsset});
77 if (
auto const vSle = env.le(vKeylet); BEAST_EXPECT(vSle))
79 pseudoAccountID = vSle->at(sfAccount);
98 auto const mods = std::to_array<Mod>({
100 .expectedFailure =
"pseudo-account has 0 pseudo-account fields set",
103 BEAST_EXPECT(sle->at(~sfVaultID));
104 sle->at(~sfVaultID) = std::nullopt;
108 .expectedFailure =
"pseudo-account sequence changed",
109 .func = [](
SLE::pointer& sle) { sle->at(sfSequence) = 12345; },
112 .expectedFailure =
"pseudo-account flags are not set",
113 .func = [](
SLE::pointer& sle) { sle->at(sfFlags) = lsfNoFreeze; },
116 .expectedFailure =
"pseudo-account has a regular key",
120 .expectedFailure =
"pseudo-account has a sponsorship field",
121 .func = [](
SLE::pointer& sle) { sle->at(sfSponsoredOwnerCount) = 1; },
124 .expectedFailure =
"pseudo-account has a sponsorship field",
125 .func = [](
SLE::pointer& sle) { sle->at(sfSponsoringOwnerCount) = 1; },
128 .expectedFailure =
"pseudo-account has a sponsorship field",
129 .func = [](
SLE::pointer& sle) { sle->at(sfSponsoringAccountCount) = 1; },
132 .expectedFailure =
"pseudo-account has a sponsorship field",
137 for (
auto const& mod : mods)
140 {{mod.expectedFailure}},
146 ac.view().update(sle);
158 if (pField == &sfVaultID)
161 {{
"pseudo-account has 2 pseudo-account fields set"}},
167 auto const vaultID = ~sle->at(~sfVaultID);
168 BEAST_EXPECT(vaultID && !sle->isFieldPresent(*pField));
169 sle->setFieldH256(*pField, *vaultID);
171 ac.view().update(sle);
184 {
"pseudo-account has 0 pseudo-account fields set"},
185 {
"pseudo-account sequence changed"},
186 {
"pseudo-account flags are not set"},
192 sle->at(sfSequence) = 0;
193 ac.view().update(sle);
206 auto const assetTypes = std::to_array({Asset::XRP, Asset::IOU, Asset::MPT});
208 for (
auto const assetType : assetTypes)
212 auto const setupAsset =
218 env(
trust(alice, iouAsset(1000)));
219 env(
pay(issuer, alice, iouAsset(1000)));
225 mptt.
create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock});
228 env(
pay(issuer, alice, mptAsset(1000)));
241 auto const asset = setupAsset(alice, issuer, env);
243 return BEAST_EXPECT(env.le(loanBrokerKeylet));
251 if (loanBrokerKeylet.
type != ltLOAN_BROKER)
253 auto const sleBroker = ac.view().peek(loanBrokerKeylet);
256 if (!BEAST_EXPECT(sleBroker->at(sfOwnerCount) == 0))
260 ac.view().update(sleBroker);
263 auto const pseudoAccountID = sleBroker->at(sfAccount);
267 auto const slePseudo = ac.view().peek(pseudoAccountKeylet);
268 if (!BEAST_EXPECT(slePseudo))
272 auto sleDir = ac.view().peek(dirKeylet);
279 ac.view(), dirKeylet, loanBrokerKeylet.
key, describe) == 0);
281 sleDir = ac.view().peek(dirKeylet);
290 "Loan Broker with zero OwnerCount has multiple directory "
295 auto test = setupTest(a1, a2, ac);
299 auto const slePseudo =
test->first;
300 auto const sleDir =
test->second;
324 "Loan Broker with zero OwnerCount has multiple indexes in "
325 "the Directory root",
329 auto test = setupTest(a1, a2, ac);
333 auto const slePseudo =
test->first;
334 auto const sleDir =
test->second;
335 auto indexes = sleDir->getFieldV256(sfIndexes);
338 for (
auto const& key : {slePseudo->key(), sleDir->key()})
351 {{
"Loan Broker directory corrupt"}},
353 auto test = setupTest(a1, a2, ac);
357 auto const slePseudo =
test->first;
358 auto const sleDir =
test->second;
379 "Loan Broker with zero OwnerCount has an unexpected entry in "
384 auto test = setupTest(a1, a2, ac);
388 auto const slePseudo =
test->first;
389 auto const sleDir =
test->second;
396 ac.view(), sleDir, 0,
false, indexes, slePseudo->key());
406 {{
"Loan Broker sequence number decreased"}},
408 if (loanBrokerKeylet.
type != ltLOAN_BROKER)
410 auto const sleBroker = ac.view().peek(loanBrokerKeylet);
413 if (!BEAST_EXPECT(sleBroker->at(sfLoanSequence) > 0))
417 ac.view().update(sleBroker);
419 sleBroker->at(sfLoanSequence) -= 1;
431 Preclose const createBrokerWithCover =
433 auto const asset = setupAsset(alice, issuer, env);
435 if (!BEAST_EXPECT(env.le(brokerKeylet)))
439 return BEAST_EXPECT(env.le(brokerKeylet));
443 {{
"Loan Broker cover available is less than pseudo-account asset balance"}},
445 auto const sle = ac.view().peek(brokerKeylet);
446 if (!BEAST_EXPECT(sle))
449 sle->at(sfCoverAvailable) =
Number(5);
450 ac.view().update(sle);
456 createBrokerWithCover);
462 {{
"Loan Broker cover available is greater than pseudo-account asset balance"}},
464 auto const sle = ac.view().peek(loanBrokerKeylet);
465 if (!BEAST_EXPECT(sle))
469 sle->at(sfCoverAvailable) =
Number(1'000'000);
470 ac.view().update(sle);
479 {{
"DomainID is set on public Loan Broker"}},
481 if (loanBrokerKeylet.
type != ltLOAN_BROKER)
483 auto const sleBroker = ac.view().peek(loanBrokerKeylet);
487 sleBroker->clearFlag(lsfLoanBrokerPrivate);
488 sleBroker->at(sfDomainID) =
uint256(42);
489 ac.view().update(sleBroker);
498 {{
"Loan Broker DomainID is zero"}},
500 if (loanBrokerKeylet.
type != ltLOAN_BROKER)
502 auto const sleBroker = ac.view().peek(loanBrokerKeylet);
506 sleBroker->setFlag(lsfLoanBrokerPrivate);
507 sleBroker->at(sfDomainID) =
uint256{};
508 ac.view().update(sleBroker);
521 {{
"Loan Broker contains an unknown flag"}},
523 if (loanBrokerKeylet.
type != ltLOAN_BROKER)
525 auto const sleBroker = ac.view().peek(loanBrokerKeylet);
529 sleBroker->setFlag(unknownFlag);
530 ac.view().update(sleBroker);
539 {{
"Loan Broker contains an unknown flag"}},
541 if (loanBrokerKeylet.
type != ltLOAN_BROKER)
543 auto const sleBroker = ac.view().peek(loanBrokerKeylet);
547 sleBroker->setFlag(lsfLoanBrokerPrivate | unknownFlag);
548 sleBroker->at(sfDomainID) =
uint256(42);
549 ac.view().update(sleBroker);
563 if (assetType == Asset::IOU)
566 Preclose const createBrokerWithCover =
568 auto const asset = setupAsset(alice, issuer, env);
570 if (!BEAST_EXPECT(env.le(brokerKeylet)))
574 return BEAST_EXPECT(env.le(brokerKeylet));
579 if (brokerKeylet.
type != ltLOAN_BROKER)
583 auto const sleBroker = ac.view().read(brokerKeylet);
584 if (!BEAST_EXPECT(sleBroker))
586 auto const pseudoAccountID = sleBroker->at(sfAccount);
594 if (!BEAST_EXPECT(sleDir))
596 for (
auto const& index : sleDir->getFieldV256(sfIndexes))
600 ac.view().erase(holding);
603 ac.view().erase(sleDir);
610 {{
"Loan Broker cover available is greater than pseudo-account asset balance"}},
615 createBrokerWithCover);
625 createBrokerWithCover);
632 {{
"Loan Broker deleted by a transaction other than LoanBrokerDelete"}},
634 if (loanBrokerKeylet.
type != ltLOAN_BROKER)
636 auto const sleBroker = ac.view().peek(loanBrokerKeylet);
637 if (!BEAST_EXPECT(sleBroker))
639 ac.view().erase(sleBroker);
663 if (!BEAST_EXPECT(env.
le(brokerKeylet)))
672 auto const sleBrokerRead = ov.
read(brokerKeylet);
673 if (!BEAST_EXPECT(sleBrokerRead))
676 sleBroker->at(sfDebtTotal) =
Number(1);
687 auto const sleBroker = ac.
view().
peek(brokerKeylet);
688 if (!BEAST_EXPECT(sleBroker))
693 if (!BEAST_EXPECT(transactor))
695 TER const result = transactor->checkInvariants(
699 sink.
messages().
str().contains(
"Loan Broker deleted with non-zero debt total"));
716 if (!BEAST_EXPECT(env.
le(brokerKeylet)))
724 auto const sleBrokerRead = ov.
read(brokerKeylet);
725 if (!BEAST_EXPECT(sleBrokerRead))
728 sleBroker->at(sfDebtTotal) =
Number(1, -3);
739 auto const sleBroker = ac.
view().
peek(brokerKeylet);
740 if (!BEAST_EXPECT(sleBroker))
745 if (!BEAST_EXPECT(transactor))
747 [[maybe_unused]]
TER const result = transactor->checkInvariants(
750 !sink.
messages().
str().contains(
"Loan Broker deleted with non-zero debt total"));
765 if (!BEAST_EXPECT(env.
le(brokerKeylet)))
772 auto const sleBrokerRead = ov.
read(brokerKeylet);
773 if (!BEAST_EXPECT(sleBrokerRead))
776 sleBroker->at(sfOwnerCount) = 1;
787 auto const sleBroker = ac.
view().
peek(brokerKeylet);
788 if (!BEAST_EXPECT(sleBroker))
793 if (!BEAST_EXPECT(transactor))
795 TER const result = transactor->checkInvariants(
799 sink.
messages().
str().contains(
"Loan Broker deleted with non-zero owner count"));
808 Preclose const createTwoBrokers = [&,
this](
813 return BEAST_EXPECT(env.le(loanBrokerKeylet1) && env.le(loanBrokerKeylet2));
817 {{
"more than one Loan Broker deleted in a single transaction"}},
819 auto const sle1 = ac.view().peek(loanBrokerKeylet1);
820 auto const sle2 = ac.view().peek(loanBrokerKeylet2);
821 if (!BEAST_EXPECT(sle1 && sle2))
823 ac.view().erase(sle1);
824 ac.view().erase(sle2);
840 Slice const credType{
"pinned", 6};
842 cred->setAccountID(sfSubject, subject);
843 cred->setAccountID(sfIssuer, issuer);
844 cred->setFieldVL(sfCredentialType, credType);
849 cred->setFieldU64(sfSubjectNode, *page);
873 bool const enabled = features[fixCleanup3_5_0];
890 auto const sleBroker = ac.
view().
read(brokerKeylet);
896 return sleVault->at(sfAccount);
902 return features[fixCleanup3_5_0] ?
"post-Cleanup3.5" :
"pre-Cleanup3.5";
912 Vault const vault{env};
913 auto [tx, k] = vault.create({.owner = a1, .asset =
xrpIssue()});
923 auto const sleVault = ac.view().read(*vaultKeylet);
926 return sleVault->at(sfAccount);
932 "may not own Credential",
934 auto const pseudo = vaultPseudo(ac);
945 auto const pseudo = vaultPseudo(ac);
955 check->setAccountID(sfAccount, a2.
id());
956 check->setAccountID(sfDestination, *pseudo);
961 check->setFieldU64(sfDestinationNode, *page);
971 "owner directory links a missing object",
973 auto const pseudo = vaultPseudo(ac);
979 return linkEntry(*pseudo, missing.key, ac);
983 testcase <<
"vault pseudo-account linked to an unrelated trust line, "
988 "may not own RippleState",
990 auto const pseudo = vaultPseudo(ac);
994 env(
trust(a1, a2[
"EUR"](100)));
995 return createVault(a1, a2, env);
998 testcase <<
"vault pseudo-account linked to another vault's loan broker, "
1004 "may not own LoanBroker",
1006 if (!broker || !otherBroker)
1009 return pseudo &&
linkEntry(*pseudo, otherBroker->key, ac);
1015 return BEAST_EXPECT(env.le(*broker) && env.le(*otherBroker));
1022 using namespace jtx;
1028 "may not own Credential",
1032 auto const sleBroker = ac.
view().
read(*brokerKeylet);
1035 AccountID const pseudo = sleBroker->at(sfAccount);
1044 testcase <<
"loan broker pseudo-account linked to another broker's loan, "
1051 if (!brokerKeylet || !otherLoan)
1053 auto const sleBroker = ac.
view().
read(*brokerKeylet);
1054 return sleBroker &&
linkEntry(sleBroker->at(sfAccount), otherLoan->key, ac);
1070 Keylet const& brokerKeylet)
1072 using namespace jtx;
1075 auto const sleBroker = env.
le(brokerKeylet);
1076 if (!BEAST_EXPECT(sleBroker))
1077 return std::nullopt;
1078 Vault const vault{env};
1080 {.depositor = lender, .id = sleBroker->at(sfVaultID), .amount = xrpAsset(100)}));
1083 auto const loanKeylet =
1085 env(
loan::set(borrower, brokerKeylet.
key, xrpAsset(50).value()),
1087 Sig(sfCounterpartySignature, lender),
1092 if (!BEAST_EXPECT(env.
le(loanKeylet)))
1093 return std::nullopt;
1100 using namespace jtx;
1106 "may not own Credential",
1111 AMM const amm(env, a1,
XRP(100), a1[
"USD"](100));
1112 ammAccount =
amm.ammAccount();
1116 testcase <<
"AMM pseudo-account linked to an unrelated trust line, "
1121 "may not own RippleState",
1123 return ammAccount &&
1127 env(
trust(a2, a1[
"EUR"](100)));
1128 AMM const amm(env, a1,
XRP(100), a1[
"USD"](100));
1129 ammAccount =
amm.ammAccount();
1139 using namespace jtx;
1141 testcase <<
"pseudo-accounts own their own entries, post-Cleanup3.5";
1144 Account const borrower{
"borrower"};
1145 Account const issuer{
"issuer"};
1146 env.
fund(
XRP(100'000), owner, borrower, issuer);
1152 env(
trust(owner, iou(1'000)));
1153 env(
pay(issuer, owner, iou(1'000)));
1155 mptt.
create({.flags = tfMPTCanClawback | tfMPTCanTransfer | tfMPTCanLock});
1158 env(
pay(issuer, owner, mpt(1'000)));
1160 for (
auto const& asset : {iou, mpt})
1172 AMM amm(env, issuer,
XRP(100), iou(100));
1173 amm.deposit(owner, iou(10));
A generic endpoint for log messages.
TestcaseT testcase
Memberspace for declaring test cases.
State information when applying a tx.
virtual SLE::pointer peek(Keylet const &k)=0
Prepare to modify the SLE associated with key.
virtual void insert(SLE::Ref sle)=0
Insert a new state SLE.
std::optional< std::uint64_t > dirInsert(Keylet const &directory, UInt256 const &key, std::function< void(SLE::Ref)> const &describe)
Insert an entry to a directory.
virtual void erase(SLE::Ref sle)=0
Remove a peeked SLE.
RAII class to set and restore the current transaction rules.
Number is a floating point type that can represent a wide range of values.
Writable ledger view that accumulates state and tx changes.
void rawReplace(SLE::Ref sle) override
Unconditionally replace a state item.
SLE::const_pointer read(Keylet const &k) const override
Return the state item associated with a key.
Rules const & rules() const override
Returns the tx processing rules.
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
std::shared_ptr< STLedgerEntry > pointer
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
An immutable linear range of bytes.
Keylet createLoanBroker(jtx::Account const &a, jtx::Env &env, jtx::PrettyAsset const &asset)
std::function< bool(test::jtx::Account const &a, test::jtx::Account const &b, ApplyContext &ac)> Precheck
test::jtx::Env makeEnv(FeatureBitset features)
void doInvariantCheck(std::vector< std::string > const &expectLogs, Precheck const &precheck, XRPAmount fee=XRPAmount{}, STTx tx=STTx{ttACCOUNT_SET, [](STObject &) {}}, std::initializer_list< TER > ters={tecINVARIANT_FAILED, tefINVARIANT_FAILED}, Preclose const &preclose={}, TxAccount setTxAccount=TxAccount::None, std::source_location const &loc=std::source_location::current(), TER initialResult=tesSUCCESS)
Run a specific test case to put the ledger into a state that will be detected by an invariant.
std::function< bool(test::jtx::Account const &a, test::jtx::Account const &b, test::jtx::Env &env)> Preclose
static char const * cleanupLabel(FeatureBitset features)
void testVaultOwnership(FeatureBitset features)
static bool linkEntry(AccountID const &owner, uint256 const &key, ApplyContext &ac)
std::optional< Keylet > createLoan(jtx::Account const &lender, jtx::Account const &borrower, jtx::Env &env, Keylet const &brokerKeylet)
static bool pinCredential(AccountID const &subject, AccountID const &issuer, ApplyContext &ac)
void testLoanBrokerOwnership(FeatureBitset features)
void run() override
Runs the suite.
void testValidPseudoAccounts()
void testOwnEntriesAllowed()
static std::optional< AccountID > brokerVaultPseudo(Keylet const &brokerKeylet, ApplyContext &ac)
void testAMMOwnership(FeatureBitset features)
void testValidLoanBroker()
void checkPinned(FeatureBitset features, std::string const &message, Precheck const &pin, Preclose const &setup)
std::stringstream const & messages() const
Convenience class to test AMM functionality.
Immutable cryptographic account descriptor.
AccountID id() const
Returns the Account ID.
A transaction testing environment.
bool close(NetClock::time_point closeTime, std::optional< std::chrono::milliseconds > consensusDelay=std::nullopt)
Close and advance the ledger.
SLE::const_pointer le(Account const &account) const
Return an account root.
void fund(bool setDefaultRipple, STAmount const &amount, Account const &account)
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Converts to IOU Issue or STAmount.
Test helper for creating, mutating, and asserting MPT and confidential MPT ledger state.
MPTID const & issuanceID() const
void create(MPTCreate const &arg=MPTCreate{}, std::source_location const &loc=std::source_location::current())
void authorize(MPTAuthorize const &arg=MPTAuthorize{}, std::source_location const &loc=std::source_location::current())
Converts to MPT Issue or STAmount.
Set the regular signature on a JTx.
std::optional< std::uint64_t > insertPage(ApplyView &view, std::uint64_t page, SLE::pointer node, std::uint64_t nextPage, SLE::Ref next, UInt256 const &key, Keylet const &directory, std::function< void(SLE::Ref)> const &describe)
std::uint64_t insertKey(ApplyView &view, SLE::Ref node, std::uint64_t page, bool preserveOrder, STVector256 &indexes, UInt256 const &key)
std::uint64_t createRoot(ApplyView &view, Keylet const &directory, UInt256 const &key, std::function< void(SLE::Ref)> const &describe)
Helper functions for managing low-level directory operations.
Keylet const & amendments() noexcept
The index of the amendment table.
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Keylet check(AccountID const &id, SeqProxy const &seq) noexcept
A Check.
Keylet unchecked(UInt256 const &key) noexcept
Any ledger entry.
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Keylet page(UInt256 const &root, std::uint64_t const index=0) noexcept
A page in a directory.
Keylet account(AccountID const &id) noexcept
AccountID root.
Keylet loan(UInt256 const &loanBrokerID, SeqProxy const &loanSeq) noexcept
Keylet credential(AccountID const &subject, AccountID const &issuer, Slice const &credType) noexcept
Keylet trustLine(AccountID const &id0, AccountID const &id1, Currency const ¤cy) noexcept
The index of a trust line for a given currency.
json::Value coverDeposit(AccountID const &account, UInt256 const &brokerID, STAmount const &amount, uint32_t flags)
json::Value set(AccountID const &account, UInt256 const &loanBrokerID, Number principalRequested, std::uint32_t flags)
auto const kPaymentInterval
json::Value pay(AccountID const &account, AccountID const &to, AnyAmount amount)
Create a payment.
XrpT const XRP
Converts to XRP Issue or STAmount.
FeatureBitset testableAmendments()
json::Value trust(Account const &account, STAmount const &amount, std::uint32_t flags)
Modify a trust line.
static MPTInit const kMptInitNoFund
BEAST_DEFINE_TESTSUITE(AMMClawback, app, xrpl)
constexpr XRPAmount
Convert XRP to drops (integral types).
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
std::vector< SField const * > const & getPseudoAccountFields()
Returns the list of fields that define an ACCOUNT_ROOT as a pseudo-account if set.
std::unique_ptr< Transactor > makeTransactor(ApplyContext &ctx)
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
TERSubset< CanCvtToTER > TER
std::function< void(SLE::Ref)> describeOwnerDir(AccountID const &account)
Returns a function that sets the owner on a directory SLE.
A pair of SHAMap key and LedgerEntryType.