xrpld
Loading...
Searching...
No Matches
InvariantsMisc_test.cpp
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/escrow.h>
8#include <test/jtx/pay.h>
9#include <test/jtx/token.h>
10#include <test/jtx/trust.h>
11#include <test/jtx/vault.h>
12#include <test/unit_test/SuiteJournal.h>
13
14#include <xrpl/basics/Number.h>
15#include <xrpl/basics/base_uint.h>
16#include <xrpl/basics/chrono.h>
17#include <xrpl/beast/unit_test/suite.h>
18#include <xrpl/beast/utility/Journal.h>
19#include <xrpl/beast/utility/Zero.h>
20#include <xrpl/ledger/ApplyView.h>
21#include <xrpl/ledger/OpenView.h>
22#include <xrpl/ledger/ReadView.h>
23#include <xrpl/ledger/helpers/AccountRootHelpers.h>
24#include <xrpl/ledger/helpers/RippleStateHelpers.h>
25#include <xrpl/protocol/AccountID.h>
26#include <xrpl/protocol/Feature.h>
27#include <xrpl/protocol/Indexes.h>
28#include <xrpl/protocol/Issue.h>
29#include <xrpl/protocol/Keylet.h>
30#include <xrpl/protocol/LedgerFormats.h>
31#include <xrpl/protocol/MPTIssue.h>
32#include <xrpl/protocol/Protocol.h>
33#include <xrpl/protocol/Rules.h>
34#include <xrpl/protocol/SField.h>
35#include <xrpl/protocol/STAmount.h>
36#include <xrpl/protocol/STLedgerEntry.h>
37#include <xrpl/protocol/STObject.h>
38#include <xrpl/protocol/STTx.h>
39#include <xrpl/protocol/SeqProxy.h>
40#include <xrpl/protocol/SystemParameters.h>
41#include <xrpl/protocol/TER.h>
42#include <xrpl/protocol/TxFormats.h>
43#include <xrpl/protocol/XRPAmount.h>
44#include <xrpl/tx/ApplyContext.h>
45#include <xrpl/tx/Transactor.h>
46#include <xrpl/tx/applySteps.h>
47#include <xrpl/tx/invariants/InvariantRunner.h>
48
49#include <array>
50#include <cstdint>
51#include <functional>
52#include <initializer_list>
53#include <memory>
54#include <optional>
55#include <stdexcept>
56#include <string>
57#include <utility>
58#include <vector>
59
60namespace xrpl::test {
61
63{
65
66 void
68 {
69 using namespace test::jtx;
70 testcase << "XRP created";
72 {{"XRP net change was positive: 500"}},
73 [](Account const& a1, Account const&, ApplyContext& ac) {
74 // put a single account in the view and "manufacture" some XRP
75 auto const sle = ac.view().peek(keylet::account(a1.id()));
76 if (!sle)
77 return false;
78 auto const amt = sle->getFieldAmount(sfBalance);
79 sle->setFieldAmount(sfBalance, amt + STAmount{500});
80 ac.view().update(sle);
81 return true;
82 });
83 }
84
85 void
87 {
88 using namespace test::jtx;
89 testcase << "account root removed";
90
91 // An account was deleted, but not by an AccountDelete transaction.
93 {{"an account root was deleted"}},
94 [](Account const& a1, Account const&, ApplyContext& ac) {
95 // remove an account from the view
96 auto const sle = ac.view().peek(keylet::account(a1.id()));
97 if (!sle)
98 return false;
99 // Clear the balance so the "account deletion left behind a
100 // non-zero balance" check doesn't trip earlier than the desired
101 // check.
102 sle->at(sfBalance) = beast::kZero;
103 ac.view().erase(sle);
104 return true;
105 });
106
107 // Successful AccountDelete transaction that didn't delete an account.
108 //
109 // Note that this is a case where a second invocation of the invariant
110 // checker returns a tecINVARIANT_FAILED, not a tefINVARIANT_FAILED.
111 // After a discussion with the team, we believe that's okay.
113 {{"account deletion succeeded without deleting an account"}},
114 [](Account const&, Account const&, ApplyContext& ac) { return true; },
115 XRPAmount{},
116 STTx{ttACCOUNT_DELETE, [](STObject& tx) {}},
118
119 // Successful AccountDelete that deleted more than one account.
121 {{"account deletion succeeded but deleted multiple accounts"}},
122 [](Account const& a1, Account const& a2, ApplyContext& ac) {
123 // remove two accounts from the view
124 auto const sleA1 = ac.view().peek(keylet::account(a1.id()));
125 auto const sleA2 = ac.view().peek(keylet::account(a2.id()));
126 if (!sleA1 || !sleA2)
127 return false;
128 // Clear the balance so the "account deletion left behind a
129 // non-zero balance" check doesn't trip earlier than the desired
130 // check.
131 sleA1->at(sfBalance) = beast::kZero;
132 sleA2->at(sfBalance) = beast::kZero;
133 ac.view().erase(sleA1);
134 ac.view().erase(sleA2);
135 return true;
136 },
137 XRPAmount{},
138 STTx{ttACCOUNT_DELETE, [](STObject& tx) {}});
139 }
140
141 void
143 {
144 using namespace test::jtx;
145 testcase << "account root deletion left artifact";
146
148 {{"account deletion left behind a non-zero balance"}},
149 // NOLINTNEXTLINE(readability-identifier-naming)
150 [&](Account const& A1, Account const& A2, ApplyContext& ac) {
151 // A1 has a balance. Delete A1
152 auto const a1 = A1.id();
153 auto const sleA1 = ac.view().peek(keylet::account(a1));
154 if (!sleA1)
155 return false;
156 if (!BEAST_EXPECT(*sleA1->at(sfBalance) != beast::kZero))
157 return false;
158
159 ac.view().erase(sleA1);
160
161 return true;
162 },
163 XRPAmount{},
164 STTx{ttACCOUNT_DELETE, [](STObject& tx) {}});
165
167 {{"account deletion left behind a non-zero owner count"}},
168 // NOLINTNEXTLINE(readability-identifier-naming)
169 [&](Account const& A1, Account const& A2, ApplyContext& ac) {
170 // Increment A1's owner count, then delete A1
171 auto const a1 = A1.id();
172 auto const sleA1 = ac.view().peek(keylet::account(a1));
173 if (!sleA1)
174 return false;
175 // Clear the balance so the "account deletion left behind a
176 // non-zero balance" check doesn't trip earlier than the desired
177 // check.
178 sleA1->at(sfBalance) = beast::kZero;
179 BEAST_EXPECT(sleA1->at(sfOwnerCount) == 0);
180 increaseOwnerCount(ac.view(), sleA1, {}, 1, ac.journal);
181
182 ac.view().erase(sleA1);
183
184 return true;
185 },
186 XRPAmount{},
187 STTx{ttACCOUNT_DELETE, [](STObject& tx) {}});
188
190 {{"account deletion left behind a sponsorship field"}},
191 [&](Account const& a1, Account const& a2, ApplyContext& ac) {
192 auto const sleA1 = ac.view().peek(keylet::account(a1.id()));
193 if (!sleA1)
194 return false;
195 sleA1->at(sfBalance) = beast::kZero;
196 sleA1->setFieldU32(sfSponsoredOwnerCount, 1);
197
198 ac.view().erase(sleA1);
199
200 return true;
201 },
202 XRPAmount{},
203 STTx{ttACCOUNT_DELETE, [](STObject& tx) {}});
204
206 {{"account deletion left behind a sponsorship field"}},
207 [&](Account const& a1, Account const& a2, ApplyContext& ac) {
208 auto const sleA1 = ac.view().peek(keylet::account(a1.id()));
209 if (!sleA1)
210 return false;
211 sleA1->at(sfBalance) = beast::kZero;
212 sleA1->setFieldU32(sfSponsoringOwnerCount, 1);
213
214 ac.view().erase(sleA1);
215
216 return true;
217 },
218 XRPAmount{},
219 STTx{ttACCOUNT_DELETE, [](STObject& tx) {}});
220
222 {{"account deletion left behind a sponsorship field"}},
223 [&](Account const& a1, Account const& a2, ApplyContext& ac) {
224 auto const a1Id = a1.id();
225 auto const sleA1 = ac.view().peek(keylet::account(a1Id));
226 if (!sleA1)
227 return false;
228 sleA1->at(sfBalance) = beast::kZero;
229 sleA1->setFieldU32(sfSponsoringAccountCount, 1);
230
231 ac.view().erase(sleA1);
232
233 return true;
234 },
235 XRPAmount{},
236 STTx{ttACCOUNT_DELETE, [](STObject& tx) {}});
237
239 {{"account deletion left behind a sponsorship field"}},
240 [&](Account const& a1, Account const& a2, ApplyContext& ac) {
241 auto const sleA1 = ac.view().peek(keylet::account(a1.id()));
242 if (!sleA1)
243 return false;
244 sleA1->at(sfBalance) = beast::kZero;
245 sleA1->setAccountID(sfSponsor, a2.id());
246
247 ac.view().erase(sleA1);
248
249 return true;
250 },
251 XRPAmount{},
252 STTx{ttACCOUNT_DELETE, [](STObject& tx) {}});
253
255 Env{*this, FeatureBitset{featureSponsor}},
256 {{"account deletion left behind a sponsorship field"}},
257 [&](Account const& a1, Account const& a2, ApplyContext& ac) {
258 auto const sleA1 = ac.view().peek(keylet::account(a1.id()));
259 if (!sleA1)
260 return false;
261 sleA1->at(sfBalance) = beast::kZero;
262 sleA1->setAccountID(sfSponsor, a2.id());
263
264 ac.view().erase(sleA1);
265
266 return true;
267 },
268 XRPAmount{},
269 STTx{ttACCOUNT_DELETE, [](STObject& tx) {}});
270
271 for (auto const& [keyletfunc, type, includeInTests] : kDirectAccountKeylets)
272 {
273 if (!includeInTests)
274 continue;
275
276 using namespace std::string_literals;
277
279 {{"account deletion left behind a "s + type.cStr() + " object"}},
280 // NOLINTNEXTLINE(readability-identifier-naming)
281 [&](Account const& A1, Account const& A2, ApplyContext& ac) {
282 // Add an object to the ledger for account A1, then delete
283 // A1
284 auto const a1 = A1.id();
285 auto const sleA1 = ac.view().peek(keylet::account(a1));
286 if (!sleA1)
287 return false;
288
289 auto const key = std::invoke(keyletfunc, a1);
290 auto const newSLE = std::make_shared<SLE>(key);
291 ac.view().insert(newSLE);
292 // Clear the balance so the "account deletion left behind a
293 // non-zero balance" check doesn't trip earlier than the
294 // desired check.
295 sleA1->at(sfBalance) = beast::kZero;
296 ac.view().erase(sleA1);
297
298 return true;
299 },
300 XRPAmount{},
301 STTx{ttACCOUNT_DELETE, [](STObject& tx) {}});
302 }
303
304 // NFT special case
306 {{"account deletion left behind a NFTokenPage object"}},
307 [&](Account const& a1, Account const&, ApplyContext& ac) {
308 // remove an account from the view
309 auto const sle = ac.view().peek(keylet::account(a1.id()));
310 if (!sle)
311 return false;
312 // Clear the balance so the "account deletion left behind a
313 // non-zero balance" check doesn't trip earlier than the desired
314 // check.
315 sle->at(sfBalance) = beast::kZero;
316 sle->at(sfOwnerCount) = 0;
317 ac.view().erase(sle);
318 return true;
319 },
320 XRPAmount{},
321 STTx{ttACCOUNT_DELETE, [](STObject& tx) {}},
323 [&](Account const& a1, Account const&, Env& env) {
324 // Preclose callback to mint the NFT which will be deleted in
325 // the Precheck callback above.
326 env(token::mint(a1));
327
328 return true;
329 });
330
331 // AMM special cases
332 AccountID ammAcctID;
333 UInt256 ammKey;
334 Issue ammIssue;
336 {{"account deletion left behind a DirectoryNode object"}},
337 [&](Account const& a1, Account const& a2, ApplyContext& ac) {
338 // Delete the AMM account without cleaning up the directory or
339 // deleting the AMM object
340 auto const sle = ac.view().peek(keylet::account(ammAcctID));
341 if (!sle)
342 return false;
343
344 BEAST_EXPECT(sle->at(~sfAMMID));
345 BEAST_EXPECT(sle->at(~sfAMMID) == ammKey);
346
347 // Clear the balance so the "account deletion left behind a
348 // non-zero balance" check doesn't trip earlier than the desired
349 // check.
350 sle->at(sfBalance) = beast::kZero;
351 sle->at(sfOwnerCount) = 0;
352 ac.view().erase(sle);
353
354 return true;
355 },
356 XRPAmount{},
357 STTx{ttAMM_WITHDRAW, [](STObject& tx) {}},
359 [&](Account const& a1, Account const& a2, Env& env) {
360 // Preclose callback to create the AMM which will be partially
361 // deleted in the Precheck callback above.
362 AMM const amm(env, a1, XRP(100), a1["USD"](50));
363 ammAcctID = amm.ammAccount();
364 ammKey = amm.ammID();
365 ammIssue = amm.lptIssue();
366 return true;
367 });
369 {{"account deletion left behind a AMM object"}},
370 [&](Account const& a1, Account const& a2, ApplyContext& ac) {
371 // Delete all the AMM's trust lines, remove the AMM from the AMM
372 // account's directory (this deletes the directory), and delete
373 // the AMM account. Do not delete the AMM object.
374 auto const sle = ac.view().peek(keylet::account(ammAcctID));
375 if (!sle)
376 return false;
377
378 BEAST_EXPECT(sle->at(~sfAMMID));
379 BEAST_EXPECT(sle->at(~sfAMMID) == ammKey);
380
381 for (auto const& trustKeylet :
382 {keylet::trustLine(ammAcctID, a1["USD"]), keylet::trustLine(a1, ammIssue)})
383 {
384 auto const line = ac.view().peek(trustKeylet);
385 if (!line)
386 {
387 return false;
388 }
389
390 STAmount const lowLimit = line->at(sfLowLimit);
391 STAmount const highLimit = line->at(sfHighLimit);
392 BEAST_EXPECT(
394 ac.view(),
395 line,
396 lowLimit.getIssuer(),
397 highLimit.getIssuer(),
398 ac.journal) == tesSUCCESS);
399 }
400
401 auto const ammSle = ac.view().peek(keylet::amm(ammKey));
402 if (!BEAST_EXPECT(ammSle))
403 return false;
404 auto const ownerDirKeylet = keylet::ownerDir(ammAcctID);
405
406 BEAST_EXPECT(
407 ac.view().dirRemove(ownerDirKeylet, ammSle->at(sfOwnerNode), ammKey, false));
408 BEAST_EXPECT(
409 !ac.view().exists(ownerDirKeylet) || ac.view().emptyDirDelete(ownerDirKeylet));
410
411 // Clear the balance so the "account deletion left behind a
412 // non-zero balance" check doesn't trip earlier than the desired
413 // check.
414 sle->at(sfBalance) = beast::kZero;
415 sle->at(sfOwnerCount) = 0;
416 ac.view().erase(sle);
417
418 return true;
419 },
420 XRPAmount{},
421 STTx{ttAMM_WITHDRAW, [](STObject& tx) {}},
423 [&](Account const& a1, Account const& a2, Env& env) {
424 // Preclose callback to create the AMM which will be partially
425 // deleted in the Precheck callback above.
426 AMM const amm(env, a1, XRP(100), a1["USD"](50));
427 ammAcctID = amm.ammAccount();
428 ammKey = amm.ammID();
429 ammIssue = amm.lptIssue();
430 return true;
431 });
432 }
433
434 void
436 {
437 using namespace test::jtx;
438 testcase << "ledger entry types don't match";
440 {{"ledger entry type mismatch"}, {"XRP net change of -1000000000 doesn't match fee 0"}},
441 [](Account const& a1, Account const&, ApplyContext& ac) {
442 // replace an entry in the table with an SLE of a different type
443 auto const sle = ac.view().peek(keylet::account(a1.id()));
444 if (!sle)
445 return false;
446 auto const sleNew = std::make_shared<SLE>(ltTICKET, sle->key());
447 ac.rawView().rawReplace(sleNew);
448 return true;
449 });
450
452 {{"invalid ledger entry type added"}},
453 [](Account const& a1, Account const&, ApplyContext& ac) {
454 // add an entry in the table with an SLE of an invalid type
455 auto const sle = ac.view().peek(keylet::account(a1.id()));
456 if (!sle)
457 return false;
458
459 // make a dummy escrow ledger entry, then change the type to an
460 // unsupported value so that the valid type invariant check
461 // will fail.
462 auto const sleNew = std::make_shared<SLE>(
463 keylet::escrow(a1, SeqProxy::rawSequence((*sle)[sfSequence] + 2)));
464
465 // We don't use ltNICKNAME directly since it's marked deprecated
466 // to prevent accidental use elsewhere.
467 sleNew->type_ = static_cast<LedgerEntryType>('n');
468 ac.view().insert(sleNew);
469 return true;
470 });
471 }
472
473 void
475 {
476 using namespace test::jtx;
477 testcase << "XRP balance checks";
478
480 {{"Cannot return non-native STAmount as XRPAmount"}},
481 [](Account const& a1, Account const& a2, ApplyContext& ac) {
482 // non-native balance
483 auto const sle = ac.view().peek(keylet::account(a1.id()));
484 if (!sle)
485 return false;
486 STAmount const nonNative(a2["USD"](51));
487 sle->setFieldAmount(sfBalance, nonNative);
488 ac.view().update(sle);
489 return true;
490 });
491
493 {{"incorrect account XRP balance"}, {"XRP net change was positive: 99999999000000001"}},
494 [this](Account const& a1, Account const&, ApplyContext& ac) {
495 // balance exceeds genesis amount
496 auto const sle = ac.view().peek(keylet::account(a1.id()));
497 if (!sle)
498 return false;
499 // Use `drops(1)` to bypass a call to STAmount::canonicalize
500 // with an invalid value
501 sle->setFieldAmount(sfBalance, kInitialXrp + drops(1));
502 BEAST_EXPECT(!sle->getFieldAmount(sfBalance).negative());
503 ac.view().update(sle);
504 return true;
505 });
506
508 {
509 {"incorrect account XRP balance"},
510 {"XRP net change of -1000000001 doesn't match fee 0"},
511 },
512 [this](Account const& a1, Account const&, ApplyContext& ac) {
513 // balance is negative
514 auto const sle = ac.view().peek(keylet::account(a1.id()));
515 if (!sle)
516 return false;
517 sle->setFieldAmount(sfBalance, STAmount{1, true});
518 BEAST_EXPECT(sle->getFieldAmount(sfBalance).negative());
519 ac.view().update(sle);
520 return true;
521 });
522 }
523
524 void
526 {
527 using namespace test::jtx;
528 using namespace std::string_literals;
529 testcase << "Transaction fee checks";
530
532 {{"fee paid was negative: -1"}, {"XRP net change of 0 doesn't match fee -1"}},
533 [](Account const&, Account const&, ApplyContext&) { return true; },
534 XRPAmount{-1});
535
537 {
538 {"fee paid exceeds system limit: "s + to_string(kInitialXrp)},
539 {"XRP net change of 0 doesn't match fee "s + to_string(kInitialXrp)},
540 },
541 [](Account const&, Account const&, ApplyContext&) { return true; },
543
545 {
546 {"fee paid is 20 exceeds fee specified in transaction."},
547 {"XRP net change of 0 doesn't match fee 20"},
548 },
549 [](Account const&, Account const&, ApplyContext&) { return true; },
550 XRPAmount{20},
551 STTx{ttACCOUNT_SET, [](STObject& tx) { tx.setFieldAmount(sfFee, XRPAmount{10}); }});
552 }
553
554 void
556 {
557 using namespace test::jtx;
558 testcase << "no bad offers";
559
561 {{"offer with a bad amount"}}, [](Account const& a1, Account const&, ApplyContext& ac) {
562 // offer with negative takerpays
563 auto const sle = ac.view().peek(keylet::account(a1.id()));
564 if (!sle)
565 return false;
566 auto const sleNew = std::make_shared<SLE>(
567 keylet::offer(a1.id(), SeqProxy::rawSequence((*sle)[sfSequence])));
568 sleNew->setAccountID(sfAccount, a1.id());
569 sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]);
570 sleNew->setFieldAmount(sfTakerPays, XRP(-1));
571 ac.view().insert(sleNew);
572 return true;
573 });
574
576 {{"offer with a bad amount"}}, [](Account const& a1, Account const&, ApplyContext& ac) {
577 // offer with negative takergets
578 auto const sle = ac.view().peek(keylet::account(a1.id()));
579 if (!sle)
580 return false;
581 auto const sleNew = std::make_shared<SLE>(
582 keylet::offer(a1.id(), SeqProxy::rawSequence((*sle)[sfSequence])));
583 sleNew->setAccountID(sfAccount, a1.id());
584 sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]);
585 sleNew->setFieldAmount(sfTakerPays, a1["USD"](10));
586 sleNew->setFieldAmount(sfTakerGets, XRP(-1));
587 ac.view().insert(sleNew);
588 return true;
589 });
590
592 {{"offer with a bad amount"}}, [](Account const& a1, Account const&, ApplyContext& ac) {
593 // offer XRP to XRP
594 auto const sle = ac.view().peek(keylet::account(a1.id()));
595 if (!sle)
596 return false;
597 auto const sleNew = std::make_shared<SLE>(
598 keylet::offer(a1.id(), SeqProxy::rawSequence((*sle)[sfSequence])));
599 sleNew->setAccountID(sfAccount, a1.id());
600 sleNew->setFieldU32(sfSequence, (*sle)[sfSequence]);
601 sleNew->setFieldAmount(sfTakerPays, XRP(10));
602 sleNew->setFieldAmount(sfTakerGets, XRP(11));
603 ac.view().insert(sleNew);
604 return true;
605 });
606 }
607
608 void
610 {
611 using namespace test::jtx;
612 testcase << "valid new account root";
613
615 {{"account root created illegally"}},
616 [](Account const&, Account const&, ApplyContext& ac) {
617 // Insert a new account root created by a non-payment into
618 // the view.
619 Account const a3{"A3"};
620 Keylet const acctKeylet = keylet::account(a3);
621 auto const sleNew = std::make_shared<SLE>(acctKeylet);
622 ac.view().insert(sleNew);
623 return true;
624 });
625
627 {{"multiple accounts created in a single transaction"}},
628 [](Account const&, Account const&, ApplyContext& ac) {
629 // Insert two new account roots into the view.
630 {
631 Account const a3{"A3"};
632 Keylet const acctKeylet = keylet::account(a3);
633 auto const sleA3 = std::make_shared<SLE>(acctKeylet);
634 ac.view().insert(sleA3);
635 }
636 {
637 Account const a4{"A4"};
638 Keylet const acctKeylet = keylet::account(a4);
639 auto const sleA4 = std::make_shared<SLE>(acctKeylet);
640 ac.view().insert(sleA4);
641 }
642 return true;
643 });
644
646 {{"account created with wrong starting sequence number"}},
647 [](Account const&, Account const&, ApplyContext& ac) {
648 // Insert a new account root with the wrong starting sequence.
649 Account const a3{"A3"};
650 Keylet const acctKeylet = keylet::account(a3);
651 auto const sleNew = std::make_shared<SLE>(acctKeylet);
652 sleNew->setFieldU32(sfSequence, ac.view().seq() + 1);
653 ac.view().insert(sleNew);
654 return true;
655 },
656 XRPAmount{},
657 STTx{ttPAYMENT, [](STObject& tx) {}});
658
660 {{"pseudo-account created by a wrong transaction type"}},
661 [](Account const&, Account const&, ApplyContext& ac) {
662 Account const a3{"A3"};
663 Keylet const acctKeylet = keylet::account(a3);
664 auto const sleNew = std::make_shared<SLE>(acctKeylet);
665 sleNew->setFieldU32(sfSequence, 0);
666 sleNew->setFieldH256(sfAMMID, UInt256(1));
667 sleNew->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple);
668 ac.view().insert(sleNew);
669 return true;
670 },
671 XRPAmount{},
672 STTx{ttPAYMENT, [](STObject& tx) {}});
673
675 {{"account created with wrong starting sequence number"}},
676 [](Account const&, Account const&, ApplyContext& ac) {
677 Account const a3{"A3"};
678 Keylet const acctKeylet = keylet::account(a3);
679 auto const sleNew = std::make_shared<SLE>(acctKeylet);
680 sleNew->setFieldU32(sfSequence, ac.view().seq());
681 sleNew->setFieldH256(sfAMMID, UInt256(1));
682 sleNew->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth);
683 ac.view().insert(sleNew);
684 return true;
685 },
686 XRPAmount{},
687 STTx{ttAMM_CREATE, [](STObject& tx) {}});
688
690 {{"pseudo-account created with wrong flags"}},
691 [](Account const&, Account const&, ApplyContext& ac) {
692 Account const a3{"A3"};
693 Keylet const acctKeylet = keylet::account(a3);
694 auto const sleNew = std::make_shared<SLE>(acctKeylet);
695 sleNew->setFieldU32(sfSequence, 0);
696 sleNew->setFieldH256(sfAMMID, UInt256(1));
697 sleNew->setFieldU32(sfFlags, lsfDisableMaster | lsfDefaultRipple);
698 ac.view().insert(sleNew);
699 return true;
700 },
701 XRPAmount{},
702 STTx{ttVAULT_CREATE, [](STObject& tx) {}});
703
705 {{"pseudo-account created with wrong flags"}},
706 [](Account const&, Account const&, ApplyContext& ac) {
707 Account const a3{"A3"};
708 Keylet const acctKeylet = keylet::account(a3);
709 auto const sleNew = std::make_shared<SLE>(acctKeylet);
710 sleNew->setFieldU32(sfSequence, 0);
711 sleNew->setFieldH256(sfAMMID, UInt256(1));
712 sleNew->setFieldU32(
713 sfFlags,
714 lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth | lsfRequireDestTag);
715 ac.view().insert(sleNew);
716 return true;
717 },
718 XRPAmount{},
719 STTx{ttAMM_CREATE, [](STObject& tx) {}});
720 }
721
722 void
724 {
725 testcase("no modified unmodifiable fields");
726 using namespace jtx;
727
728 // Initialize with a placeholder value because there's no default ctor
729 Keylet loanBrokerKeylet = keylet::amendments();
730 Preclose const createLoanBroker = [&, this](Account const& a, Account const& b, Env& env) {
731 PrettyAsset const xrpAsset{xrpIssue(), 1'000'000};
732
733 loanBrokerKeylet = this->createLoanBroker(a, env, xrpAsset);
734 return BEAST_EXPECT(env.le(loanBrokerKeylet));
735 };
736
737 {
738 auto const mods = std::to_array<std::function<void(SLE::pointer&)>>({
739 [](SLE::pointer& sle) { sle->at(sfSequence) += 1; },
740 [](SLE::pointer& sle) { sle->at(sfOwnerNode) += 1; },
741 [](SLE::pointer& sle) { sle->at(sfVaultNode) += 1; },
742 [](SLE::pointer& sle) { sle->at(sfVaultID) = UInt256(1u); },
743 [](SLE::pointer& sle) { sle->at(sfAccount) = sle->at(sfOwner); },
744 [](SLE::pointer& sle) { sle->at(sfOwner) = sle->at(sfAccount); },
745 [](SLE::pointer& sle) { sle->at(sfManagementFeeRate) += 1; },
746 [](SLE::pointer& sle) { sle->at(sfCoverRateMinimum) += 1; },
747 [](SLE::pointer& sle) { sle->at(sfCoverRateLiquidation) += 1; },
748 [](SLE::pointer& sle) { sle->setFlag(lsfLoanBrokerPrivate); },
749 [](SLE::pointer& sle) { sle->at(sfLedgerEntryType) += 1; },
750 [](SLE::pointer& sle) { sle->at(sfLedgerIndex) = sle->at(sfVaultID).value(); },
751 });
752
753 for (auto const& mod : mods)
754 {
756 {{"changed an unchangeable field"}},
757 [&](Account const& a1, Account const&, ApplyContext& ac) {
758 auto sle = ac.view().peek(loanBrokerKeylet);
759 if (!sle)
760 return false;
761 mod(sle);
762 ac.view().update(sle);
763 return true;
764 },
765 XRPAmount{},
766 STTx{ttACCOUNT_SET, [](STObject& tx) {}},
769 }
770 }
771
772 // LoanBroker sfFlags immutability is gated on featureLendingProtocolV1_2,
773 // so without it a flag change is not caught by this invariant.
774 {
776 Env{*this, all_ - featureLendingProtocolV1_2},
777 {},
778 [&](Account const&, Account const&, ApplyContext& ac) {
779 auto const sle = ac.view().peek(loanBrokerKeylet);
780 if (!sle)
781 return false;
782 sle->setFlag(lsfLoanBrokerPrivate);
783 ac.view().update(sle);
784 return true;
785 },
786 XRPAmount{},
787 STTx{ttACCOUNT_SET, [](STObject&) {}},
790 }
791
792 // Loan flag immutability lives in NoModifiedUnmodifiableFields's
793 // ltLOAN case: lsfLoanOverpayment must never toggle in either
794 // direction, and lsfLoanDefault (gated on featureLendingProtocolV1_1)
795 // may only transition from unset to set. Each case needs a loan that
796 // already exists in the base ledger, so that the apply-view modification
797 // is seen as a before/after change rather than an insertion.
798 {
799 struct Case
800 {
801 std::uint32_t before;
803 std::string expected;
804 };
805 auto const cases = std::to_array<Case>({
806 {
807 .before = lsfLoanOverpayment,
808 .after = 0,
809 .expected = "lsfLoanOverpayment flag toggled on immutable ledger entry",
810 },
811 {
812 .before = 0,
813 .after = lsfLoanOverpayment,
814 .expected = "lsfLoanOverpayment flag toggled on immutable ledger entry",
815 },
816 {
817 .before = lsfLoanDefault,
818 .after = 0,
819 .expected = "lsfLoanDefault flag cleared on immutable ledger entry",
820 },
821 });
822
823 for (auto const& c : cases)
824 {
825 Env env{*this, all_};
826 Account const a1{"A1"};
827 env.fund(XRP(1000), a1);
828 env.close();
829
830 OpenView ov{*env.current()};
831
832 auto const brokerKeylet =
834 auto const loanKeylet = keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(1));
835 {
836 auto const sleLoan = makeLoanSle(brokerKeylet.key, 1, a1.id());
837 sleLoan->at(sfPrincipalOutstanding) = Number(100);
838 sleLoan->at(sfTotalValueOutstanding) = Number(150);
839 sleLoan->setFieldU32(sfPaymentRemaining, 1);
840 sleLoan->setFieldU32(sfFlags, c.before);
841 ov.rawInsert(sleLoan);
842 }
843
844 STTx const tx{ttACCOUNT_SET, [](STObject&) {}};
846 beast::Journal const jlog{sink};
847 ApplyContext ac{
848 env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, TapNone, jlog};
849 CurrentTransactionRulesGuard const rulesGuard(ov.rules());
850
851 auto const sleLoan = ac.view().peek(loanKeylet);
852 if (!BEAST_EXPECT(sleLoan))
853 continue;
854 sleLoan->setFieldU32(sfFlags, c.after);
855 ac.view().update(sleLoan);
856
857 auto transactor = makeTransactor(ac);
858 if (!BEAST_EXPECT(transactor))
859 continue;
860 TER const result = transactor->checkInvariants(
862 BEAST_EXPECT(result == tecINVARIANT_FAILED);
863 BEAST_EXPECT(sink.messages().str().contains(c.expected));
864 }
865 }
866
867 // Pre-featureLendingProtocolV1_1 sibling of the lsfLoanOverpayment
868 // cases above: the same set-once immutability was originally enforced
869 // by ValidLoan::finalize, so with V1_1 disabled toggling the flag
870 // must trip that legacy check instead. lsfLoanDefault immutability
871 // did not exist pre-V1_1 and is not tested here.
872 {
873 auto const cases = std::to_array<std::pair<std::uint32_t, std::uint32_t>>({
874 {lsfLoanOverpayment, 0},
875 {0, lsfLoanOverpayment},
876 });
877
878 for (auto const& [before, after] : cases)
879 {
880 Env env{*this, all_ - featureLendingProtocolV1_1};
881 Account const a1{"A1"};
882 env.fund(XRP(1000), a1);
883 env.close();
884
885 OpenView ov{*env.current()};
886
887 auto const brokerKeylet =
889 auto const loanKeylet = keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(1));
890 {
891 auto const sleLoan = makeLoanSle(brokerKeylet.key, 1, a1.id());
892 sleLoan->at(sfPrincipalOutstanding) = Number(100);
893 sleLoan->at(sfTotalValueOutstanding) = Number(150);
894 sleLoan->setFieldU32(sfPaymentRemaining, 1);
895 sleLoan->setFieldU32(sfFlags, before);
896 ov.rawInsert(sleLoan);
897 }
898
899 STTx const tx{ttACCOUNT_SET, [](STObject&) {}};
901 beast::Journal const jlog{sink};
902 ApplyContext ac{
903 env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, TapNone, jlog};
904 CurrentTransactionRulesGuard const rulesGuard(ov.rules());
905
906 auto const sleLoan = ac.view().peek(loanKeylet);
907 if (!BEAST_EXPECT(sleLoan))
908 continue;
909 sleLoan->setFieldU32(sfFlags, after);
910 ac.view().update(sleLoan);
911
912 auto transactor = makeTransactor(ac);
913 if (!BEAST_EXPECT(transactor))
914 continue;
915 TER const result = transactor->checkInvariants(
917 BEAST_EXPECT(result == tecINVARIANT_FAILED);
918 BEAST_EXPECT(sink.messages().str().contains("Loan Overpayment flag changed"));
919 }
920 }
921
922 // Under featureLendingProtocolV1_1, ValidLoan::finalize requires
923 // interest due (total value minus principal and management fee) to be
924 // non-negative after each value is rounded to sfLoanScale. Test zero,
925 // each way to produce a one-unit deficit, and a two-unit deficit. At
926 // scale 0, an XRP-backed broker rejects any deficit, while an
927 // IOU-backed one permits one unit of rounding tolerance.
928 {
929 struct Case
930 {
931 Number totalValue;
932 Number principal;
933 Number managementFee;
934 bool expectFireIntegral;
935 bool expectFireTolerant;
936 };
937 // The first case sits exactly at the boundary, the middle three
938 // perturb one component so that interest due is -1, which is within
939 // the tolerance, and the last overshoots it at -2.
940 auto const cases = std::to_array<Case>({
941 {
942 .totalValue = Number(100),
943 .principal = Number(100),
944 .managementFee = Number(0),
945 .expectFireIntegral = false,
946 .expectFireTolerant = false,
947 },
948 {
949 .totalValue = Number(99),
950 .principal = Number(100),
951 .managementFee = Number(0),
952 .expectFireIntegral = true,
953 .expectFireTolerant = false,
954 },
955 {
956 .totalValue = Number(100),
957 .principal = Number(101),
958 .managementFee = Number(0),
959 .expectFireIntegral = true,
960 .expectFireTolerant = false,
961 },
962 {
963 .totalValue = Number(100),
964 .principal = Number(100),
965 .managementFee = Number(1),
966 .expectFireIntegral = true,
967 .expectFireTolerant = false,
968 },
969 {
970 .totalValue = Number(98),
971 .principal = Number(100),
972 .managementFee = Number(0),
973 .expectFireIntegral = true,
974 .expectFireTolerant = true,
975 },
976 });
977
978 for (bool const integralAsset : {true, false})
979 {
980 for (auto const& c : cases)
981 {
982 Env env{*this, all_};
983 Account const a1{"A1"};
984 Account const issuer{"issuer"};
985 env.fund(XRP(1000), a1, issuer);
986 env.close();
987
988 // The check reads the broker's vault asset to decide
989 // whether the rounding tolerance applies, so both
990 // branches need a real broker over the relevant asset.
991 auto const asset = [&] -> PrettyAsset {
992 if (integralAsset)
993 return PrettyAsset{xrpIssue(), 1'000'000};
994 PrettyAsset const iouAsset = issuer["IOU"];
995 env(trust(a1, iouAsset(1000)));
996 env(pay(issuer, a1, iouAsset(1000)));
997 env.close();
998 return iouAsset;
999 }();
1000
1001 auto const brokerKeylet = this->createLoanBroker(a1, env, asset);
1002 if (!BEAST_EXPECT(env.le(brokerKeylet)))
1003 continue;
1004 env.close();
1005
1006 OpenView ov{*env.current()};
1007
1008 auto const loanKeylet =
1009 keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(1));
1010 // Seed a loan whose interest due sits at the boundary. The
1011 // apply-view update below moves it.
1012 {
1013 auto const sleLoan = makeLoanSle(brokerKeylet.key, 1, a1.id());
1014 sleLoan->at(sfPrincipalOutstanding) = Number(100);
1015 sleLoan->at(sfTotalValueOutstanding) = Number(100);
1016 sleLoan->at(sfManagementFeeOutstanding) = Number(0);
1017 sleLoan->at(sfLoanScale) = 0;
1018 sleLoan->setFieldU32(sfPaymentRemaining, 1);
1019 ov.rawInsert(sleLoan);
1020 }
1021
1022 STTx const tx{ttACCOUNT_SET, [](STObject&) {}};
1024 beast::Journal const jlog{sink};
1025 ApplyContext ac{
1026 env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, TapNone, jlog};
1027 CurrentTransactionRulesGuard const rulesGuard(ov.rules());
1028
1029 auto const sleLoan = ac.view().peek(loanKeylet);
1030 if (!BEAST_EXPECT(sleLoan))
1031 continue;
1032 sleLoan->at(sfTotalValueOutstanding) = c.totalValue;
1033 sleLoan->at(sfPrincipalOutstanding) = c.principal;
1034 sleLoan->at(sfManagementFeeOutstanding) = c.managementFee;
1035 ac.view().update(sleLoan);
1036
1037 auto transactor = makeTransactor(ac);
1038 if (!BEAST_EXPECT(transactor))
1039 continue;
1040 TER const result = transactor->checkInvariants(
1042 auto const messages = sink.messages().str();
1043 if (integralAsset ? c.expectFireIntegral : c.expectFireTolerant)
1044 {
1045 BEAST_EXPECT(result == tecINVARIANT_FAILED);
1046 BEAST_EXPECT(messages.contains("Loan interest due is negative"));
1047 }
1048 else
1049 {
1050 // Other invariants may still fire on this raw-inserted
1051 // loan, so only assert the specific message is absent.
1052 BEAST_EXPECT(!messages.contains("Loan interest due is negative"));
1053 }
1054 }
1055 }
1056 }
1057
1058 // VaultKind, SubscriptionDate and RedemptionDate are immutable once set at creation.
1059 // Enforced by NoModifiedUnmodifiableFields on ltVAULT via kFieldChanged.
1060 Keylet closedEndedVaultKeylet = keylet::amendments();
1061 Preclose const createClosedEndedVault = [&, this](
1062 Account const& a, Account const&, Env& env) {
1063 auto const sub = env.now().time_since_epoch().count() + 60;
1064 auto const red = sub + kMinInvestmentPeriod + 1'000'000;
1065 Vault const vault{env};
1066 auto [tx, keylet] = vault.create({
1067 .owner = a,
1068 .asset = xrpIssue(),
1069 .vaultKind = std::to_underlying(VaultKind::ClosedEnded),
1070 .subscriptionDate = sub,
1071 .redemptionDate = red,
1072 });
1073 env(tx);
1074 closedEndedVaultKeylet = keylet;
1075 return BEAST_EXPECT(env.le(closedEndedVaultKeylet));
1076 };
1077
1078 {
1079 // Each mutation must keep the vault otherwise valid so that only the immutability check
1080 // fires. Shifting both dates by the same offset preserves the gap; bumping sfVaultKind
1081 // stays within the recognised range.
1082 auto const mods = std::to_array<std::function<void(SLE::pointer&)>>({
1083 [](SLE::pointer& sle) { sle->at(sfVaultKind) += 1; },
1084 [](SLE::pointer& sle) { sle->at(sfSubscriptionDate) += 1; },
1085 [](SLE::pointer& sle) { sle->at(sfRedemptionDate) += 1; },
1086 });
1087
1088 for (auto const& mod : mods)
1089 {
1091 {{"changed an unchangeable field"}},
1092 [&](Account const&, Account const&, ApplyContext& ac) {
1093 auto sle = ac.view().peek(closedEndedVaultKeylet);
1094 if (!sle)
1095 return false;
1096 mod(sle);
1097 ac.view().update(sle);
1098 return true;
1099 },
1100 XRPAmount{},
1101 STTx{ttACCOUNT_SET, [](STObject&) {}},
1103 createClosedEndedVault);
1104 }
1105 }
1106
1107 {
1108 auto const mods = std::to_array<std::function<void(SLE::pointer&)>>({
1109 [](SLE::pointer& sle) { sle->at(sfLedgerEntryType) += 1; },
1110 [](SLE::pointer& sle) { sle->at(sfLedgerIndex) = UInt256(1u); },
1111 });
1112
1113 for (auto const& mod : mods)
1114 {
1116 {{"changed an unchangeable field"}},
1117 [&](Account const& a1, Account const&, ApplyContext& ac) {
1118 auto sle = ac.view().peek(keylet::account(a1.id()));
1119 if (!sle)
1120 return false;
1121 mod(sle);
1122 ac.view().update(sle);
1123 return true;
1124 });
1125 }
1126 }
1127 }
1128
1129 void
1131 {
1132 using namespace test::jtx;
1133 bool const fixEnabled = features[fixCleanup3_1_3];
1136
1137 // Insert two trust line SLEs in hash-sorted order, with the "bad"
1138 // entry at the lower-sorting key so it is visited first by
1139 // ApplyStateTable::visit(). The configurer callables receive the
1140 // SLE and the Issue corresponding to that side's keylet currency.
1141 auto const insertOrderedTrustLinePair = [](ApplyContext& ac,
1142 Account const& a1,
1143 Account const& a2,
1144 Account const& a3,
1145 auto const& badConfig,
1146 auto const& goodConfig) {
1147 char const* const c1 = "USD";
1148 char const* const c2 = "EUR";
1149 auto const k1 = keylet::trustLine(a1, a2, a1[c1].currency);
1150 auto const k2 = keylet::trustLine(a1, a3, a1[c2].currency);
1151
1152 bool const k1First = k1.key < k2.key;
1153 auto const& badKey = k1First ? k1 : k2;
1154 auto const& goodKey = k1First ? k2 : k1;
1155 Issue const badIss{k1First ? a1[c1].currency : a1[c2].currency, a1.id()};
1156 Issue const goodIss{k1First ? a1[c2].currency : a1[c1].currency, a1.id()};
1157
1158 auto const sleBad = std::make_shared<SLE>(badKey);
1159 badConfig(*sleBad, badIss);
1160 ac.view().insert(sleBad);
1161
1162 auto const sleGood = std::make_shared<SLE>(goodKey);
1163 goodConfig(*sleGood, goodIss);
1164 ac.view().insert(sleGood);
1165 };
1166
1167 // Regression: bad XRP trust line followed by a valid trust line.
1168 // With the fix, the invariant catches the violation. Without it,
1169 // the valid entry overwrites the flag to false. The keylet
1170 // currencies are non-XRP (the invariant inspects sfLowLimit /
1171 // sfHighLimit issue, not the keylet currency).
1172 testcase << "overwrite: NoXRPTrustLines" + std::string(fixEnabled ? " fix" : "");
1174 makeEnv(features),
1175 fixEnabled ? std::vector<std::string>{{"an XRP trust line was created"}}
1177 [&insertOrderedTrustLinePair](Account const& a1, Account const& a2, ApplyContext& ac) {
1178 Account const a3{"A3"};
1179 insertOrderedTrustLinePair(
1180 ac,
1181 a1,
1182 a2,
1183 a3,
1184 [](SLE& sle, Issue const& iss) {
1185 // sfLowLimit has xrpIssue, making isXrp = true
1186 sle.setFieldAmount(sfLowLimit, STAmount{xrpIssue(), 0});
1187 sle.setFieldAmount(sfHighLimit, STAmount{iss, 0});
1188 },
1189 [](SLE& sle, Issue const& iss) {
1190 sle.setFieldAmount(sfLowLimit, STAmount{iss, 0});
1191 sle.setFieldAmount(sfHighLimit, STAmount{iss, 0});
1192 });
1193 return true;
1194 },
1195 XRPAmount{},
1196 STTx{ttACCOUNT_SET, [](STObject&) {}},
1197 fixEnabled ? failTers : passTers);
1198
1199 // Regression: bad deep-freeze trust line followed by a valid one.
1200 testcase << "overwrite: NoDeepFreeze" + std::string(fixEnabled ? " fix" : "");
1202 makeEnv(features),
1203 fixEnabled ? std::vector<std::string>{{"a trust line with deep freeze flag without "
1204 "normal freeze was created",},}
1206 [&insertOrderedTrustLinePair](Account const& a1, Account const& a2, ApplyContext& ac) {
1207 Account const a3{"A3"};
1208 insertOrderedTrustLinePair(
1209 ac,
1210 a1,
1211 a2,
1212 a3,
1213 [](SLE& sle, Issue const& iss) {
1214 sle.setFieldAmount(sfLowLimit, STAmount{iss, 0});
1215 sle.setFieldAmount(sfHighLimit, STAmount{iss, 0});
1216 sle.setFieldU32(sfFlags, lsfLowDeepFreeze);
1217 },
1218 [](SLE& sle, Issue const& iss) {
1219 sle.setFieldAmount(sfLowLimit, STAmount{iss, 0});
1220 sle.setFieldAmount(sfHighLimit, STAmount{iss, 0});
1221 sle.setFieldU32(sfFlags, 0u);
1222 });
1223 return true;
1224 },
1225 XRPAmount{},
1226 STTx{ttACCOUNT_SET, [](STObject&) {}},
1227 fixEnabled ? failTers : passTers);
1228
1229 // Regression: MPT OutstandingAmount exceeds max, but locked <=
1230 // outstanding. Plain assignment would overwrite bad_ = true.
1231 // With the fix, NoZeroEscrow catches it.
1232 // Without the fix, NoZeroEscrow passes but ValidMPTIssuance
1233 // still fires ("a MPT issuance was created").
1234 testcase << "overwrite: NoZeroEscrow MPT" + std::string(fixEnabled ? " fix" : "");
1236 makeEnv(features),
1237 fixEnabled ? std::vector<std::string>{{"escrow specifies invalid amount"}}
1238 : std::vector<std::string>{{"a MPT issuance was created"}},
1239 [](Account const& a1, Account const&, ApplyContext& ac) {
1240 auto const sle = ac.view().peek(keylet::account(a1.id()));
1241 if (!sle)
1242 return false;
1243
1244 MPTIssue const mpt{makeMptID(1, AccountID(0x4985601))};
1245 auto const sleNew = std::make_shared<SLE>(keylet::mptokenIssuance(mpt.getMptID()));
1246 // outstanding exceeds kMaxMpTokenAmount -> checkAmount sets bad_
1247 sleNew->setFieldU64(sfOutstandingAmount, kMaxMpTokenAmount + 1);
1248 // locked is valid and <= outstanding -> must NOT clear bad_
1249 sleNew->setFieldU64(sfLockedAmount, 10);
1250 ac.view().insert(sleNew);
1251 return true;
1252 },
1253 XRPAmount{},
1254 STTx{ttACCOUNT_SET, [](STObject&) {}},
1255 failTers);
1256 }
1257
1258 void
1260 {
1261 using namespace test::jtx;
1262 using namespace std::string_literals;
1263 testcase("Sponsorship");
1264 {
1265 auto const expectMessage =
1266 "SponsoredOwnerCount does not equal SponsoringOwnerCount delta.";
1267
1269 {{expectMessage}}, [&](Account const& a1, Account const& a2, ApplyContext& ac) {
1270 auto const sle = ac.view().peek(keylet::account(a1.id()));
1271 if (!sle)
1272 return false;
1273 sle->setFieldU32(sfSponsoredOwnerCount, 1);
1274 ac.view().update(sle);
1275 return true;
1276 });
1277
1279 {{expectMessage}}, [&](Account const& a1, Account const& a2, ApplyContext& ac) {
1280 auto const sle = ac.view().peek(keylet::account(a1.id()));
1281 if (!sle)
1282 return false;
1283 sle->setFieldU32(sfSponsoringOwnerCount, 1);
1284 ac.view().update(sle);
1285 return true;
1286 });
1287 }
1288
1289 {
1290 auto const expectMessage =
1291 "OwnerCount must be greater than or equal to SponsoredOwnerCount.";
1292
1294 {{expectMessage}}, [&](Account const& a1, Account const& a2, ApplyContext& ac) {
1295 auto const sle = ac.view().peek(keylet::account(a1.id()));
1296 if (!sle)
1297 return false;
1298 sle->setFieldU32(sfOwnerCount, 0);
1299 sle->setFieldU32(sfSponsoredOwnerCount, 1);
1300 ac.view().update(sle);
1301
1302 auto const sle2 = ac.view().peek(keylet::account(a2.id()));
1303 if (!sle2)
1304 return false;
1305 sle2->setFieldU32(sfSponsoringOwnerCount, 1);
1306 ac.view().update(sle2);
1307 return true;
1308 });
1309 }
1310
1311 {
1312 auto const expectMessage =
1313 "SponsoredObjectOwnerCount does not equal SponsoredOwnerCount delta.";
1314 UInt256 checkID;
1315
1317 {{expectMessage}},
1318 [&](Account const&, Account const& a2, ApplyContext& ac) {
1319 auto const check = ac.view().peek(keylet::check(checkID));
1320 if (!check)
1321 return false;
1322 check->setAccountID(sfSponsor, a2.id());
1323 ac.view().update(check);
1324 return true;
1325 },
1326 XRPAmount{},
1327 STTx{ttACCOUNT_SET, [](STObject&) {}},
1329 [&checkID](Account const& a1, Account const& a2, Env& env) {
1330 checkID = keylet::check(a1.id(), SeqProxy::rawSequence(env.seq(a1))).key;
1331 env(check::create(a1, a2, XRP(1)));
1332 return true;
1333 });
1334
1335 // An escrow's owner count scales with its Bytecode size, so
1336 // sponsoring one has to move that whole weight. Counting it as a
1337 // single unit leaves the sponsored counters short of the object's
1338 // real weight, which is what this check exists to catch.
1339 UInt256 escrowID;
1340
1342 {{expectMessage}},
1343 [&](Account const& a1, Account const& a2, ApplyContext& ac) {
1344 auto const escrow = ac.view().peek(keylet::unchecked(escrowID));
1345 if (!escrow)
1346 {
1347 return false;
1348 }
1349 // ceil(1200 / 500) == 3 owner counts
1350 escrow->setFieldVL(sfBytecode, Blob(1200, 0x00));
1351 escrow->setAccountID(sfSponsor, a2.id());
1352 ac.view().update(escrow);
1353
1354 // Move the counters by a single unit, as a sponsorship
1355 // blind to the Bytecode weight would.
1356 auto const sle1 = ac.view().peek(keylet::account(a1.id()));
1357 auto const sle2 = ac.view().peek(keylet::account(a2.id()));
1358 if (!sle1 || !sle2)
1359 {
1360 return false;
1361 }
1362 sle1->setFieldU32(sfSponsoredOwnerCount, 1);
1363 sle2->setFieldU32(sfSponsoringOwnerCount, 1);
1364 ac.view().update(sle1);
1365 ac.view().update(sle2);
1366 return true;
1367 },
1368 XRPAmount{},
1369 STTx{ttACCOUNT_SET, [](STObject&) {}},
1371 [&escrowID](Account const& a1, Account const& a2, Env& env) {
1372 using namespace std::chrono_literals;
1373 escrowID = keylet::escrow(a1.id(), SeqProxy::rawSequence(env.seq(a1))).key;
1374 env(escrow::create(a1, a2, XRP(1)),
1376 escrow::kCancelTime(env.now() + 100s));
1377 return true;
1378 });
1379 }
1380
1381 {
1382 auto const expectMessage =
1383 "Invariant failed: Net delta of SponsoringAccountCount does "
1384 "not match net delta of sfSponsor presence.";
1385
1387 {{expectMessage}}, [&](Account const& a1, Account const& a2, ApplyContext& ac) {
1388 auto const sle = ac.view().peek(keylet::account(a1.id()));
1389 if (!sle)
1390 return false;
1391 sle->setFieldU32(sfSponsoringAccountCount, 1);
1392 ac.view().update(sle);
1393 return true;
1394 });
1395
1397 {{expectMessage}}, [&](Account const& a1, Account const& a2, ApplyContext& ac) {
1398 auto const sle = ac.view().peek(keylet::account(a1.id()));
1399 if (!sle)
1400 return false;
1401 sle->setAccountID(sfSponsor, a2.id());
1402 ac.view().update(sle);
1403 return true;
1404 });
1405 }
1406 }
1407
1408 void
1410 {
1411 testcase << "object has pseudo-account";
1412 using namespace jtx;
1413
1414 auto const amendments = all_ | fixCleanup3_3_0;
1415
1416 // Vault: object deleted without its pseudo-account
1417 {
1418 Keylet vaultKeylet = keylet::amendments();
1420 Env{*this, amendments},
1421 {{"deleted Vault without deleting its pseudo-account"}},
1422 [&vaultKeylet](Account const&, Account const&, ApplyContext& ac) {
1423 auto const sle = ac.view().peek(vaultKeylet);
1424 if (!sle)
1425 return false;
1426 ac.view().erase(sle);
1427 return true;
1428 },
1429 XRPAmount{},
1430 STTx{ttVAULT_DELETE, [](STObject&) {}},
1432 [&vaultKeylet](Account const& a1, Account const&, Env& env) {
1433 Vault const vault{env};
1434 auto [tx, keylet] = vault.create({.owner = a1, .asset = xrpIssue()});
1435 env(tx);
1436 vaultKeylet = keylet;
1437 return true;
1438 });
1439 }
1440
1441 // AMM: object deleted without its pseudo-account
1442 {
1443 UInt256 ammID{};
1444 Account const gw{"gw"};
1446 Env{*this, amendments},
1447 {{"deleted AMM without deleting its pseudo-account"}},
1448 [&ammID](Account const&, Account const&, ApplyContext& ac) {
1449 auto const sle = ac.view().peek(keylet::amm(ammID));
1450 if (!sle)
1451 return false;
1452 ac.view().erase(sle);
1453 return true;
1454 },
1455 XRPAmount{},
1456 STTx{ttAMM_DELETE, [](STObject&) {}},
1458 [&ammID, &gw](Account const&, Account const&, Env& env) {
1459 env.fund(XRP(1'000), gw);
1460 AMM const amm(env, gw, XRP(100), gw["USD"](100));
1461 ammID = amm.ammID();
1462 return true;
1463 });
1464 }
1465
1466 // LoanBroker: object deleted without its pseudo-account
1467 {
1468 Keylet loanBrokerKeylet = keylet::amendments();
1470 Env{*this, amendments},
1471 {{"deleted LoanBroker without deleting its pseudo-account"}},
1472 [&loanBrokerKeylet](Account const&, Account const&, ApplyContext& ac) {
1473 auto const sle = ac.view().peek(loanBrokerKeylet);
1474 if (!sle)
1475 return false;
1476 ac.view().erase(sle);
1477 return true;
1478 },
1479 XRPAmount{},
1480 STTx{ttLOAN_BROKER_DELETE, [](STObject&) {}},
1482 [&loanBrokerKeylet, this](Account const& a1, Account const&, Env& env) {
1483 PrettyAsset const xrpAsset{xrpIssue(), 1'000'000};
1484 loanBrokerKeylet = this->createLoanBroker(a1, env, xrpAsset);
1485 return BEAST_EXPECT(env.le(loanBrokerKeylet));
1486 });
1487 }
1488
1489 // Deleted object missing sfAccount field (defensive check).
1490 // Manually construct the view to place a vault SLE without
1491 // sfAccount into the base ledger, then erase it.
1492 {
1493 Env env{*this, amendments};
1494 Account const a1{"A1"};
1495 Account const a2{"A2"};
1496 env.fund(XRP(1000), a1, a2);
1497 env.close();
1498
1499 OpenView ov{*env.current()};
1500
1501 auto const vaultKeylet = keylet::vault(a1.id(), SeqProxy::rawSequence(ov.seq()));
1502 auto const sleVault = std::make_shared<SLE>(vaultKeylet);
1503 sleVault->makeFieldAbsent(sfAccount);
1504 ov.rawInsert(sleVault);
1505
1506 STTx const tx{ttVAULT_DELETE, [](STObject&) {}};
1508 beast::Journal const jlog{sink};
1509 ApplyContext ac{
1510 env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, TapNone, jlog};
1511 CurrentTransactionRulesGuard const rulesGuard(ov.rules());
1512
1513 auto const sle = ac.view().peek(vaultKeylet);
1514 if (!BEAST_EXPECT(sle))
1515 return;
1516 ac.view().erase(sle);
1517
1518 auto transactor = makeTransactor(ac);
1519 if (!BEAST_EXPECT(transactor))
1520 return;
1521 TER const result = transactor->checkInvariants(
1523 BEAST_EXPECT(result == tecINVARIANT_FAILED);
1524 BEAST_EXPECT(sink.messages().str().contains("is missing pseudo-account field"));
1525 }
1526 }
1527
1528 void
1530 {
1531 testcase << "txCheck exception";
1532 using namespace jtx;
1533
1534 // A TxInvariantCheck that throws from the requested hook, so we can
1535 // exercise checkInvariantsHelper's catch block via the
1536 // transaction-specific layer (as opposed to the protocol layer,
1537 // which testObjectHasPseudoAccount's last case already covers via a
1538 // real Transactor's finalizeInvariants).
1539 enum class ThrowFrom { VisitEntry, Finalize };
1540
1541 struct ThrowingTxInvariantCheck : TxInvariantCheck
1542 {
1543 ThrowFrom const throwFrom;
1544
1545 explicit ThrowingTxInvariantCheck(ThrowFrom throwFrom) : throwFrom(throwFrom)
1546 {
1547 }
1548
1549 void
1550 visitEntry(bool, SLE::ConstRef, SLE::ConstRef) override
1551 {
1552 if (throwFrom == ThrowFrom::VisitEntry)
1553 throw std::runtime_error("test-injected visitEntry exception");
1554 }
1555
1556 [[nodiscard]] bool
1557 finalize(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) override
1558 {
1559 if (throwFrom == ThrowFrom::Finalize)
1560 throw std::runtime_error("test-injected finalize exception");
1561 return true;
1562 }
1563 };
1564
1565 for (auto const throwFrom : {ThrowFrom::VisitEntry, ThrowFrom::Finalize})
1566 {
1567 Env env{*this};
1568 Account const alice{"alice"};
1569 env.fund(XRP(1000), alice);
1570 env.close();
1571
1572 OpenView ov{*env.current()};
1573 STTx const tx{ttACCOUNT_SET, [](STObject&) {}};
1575 beast::Journal const jlog{sink};
1576 ApplyContext ac{
1577 env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, TapNone, jlog};
1578 CurrentTransactionRulesGuard const rulesGuard(ov.rules());
1579
1580 // visitEntry only runs for entries the transaction touched, so
1581 // make a modification for the traversal to report.
1582 auto const sle = ac.view().peek(keylet::account(alice.id()));
1583 if (!BEAST_EXPECT(sle))
1584 return;
1585 sle->at(sfSequence) = sle->at(sfSequence) + 1;
1586 ac.view().update(sle);
1587
1588 ThrowingTxInvariantCheck throwing{throwFrom};
1589 TER terActual = tesSUCCESS;
1590 for (TER const& terExpect : {TER(tecINVARIANT_FAILED), TER(tefINVARIANT_FAILED)})
1591 {
1592 terActual = checkInvariants(ac, terActual, XRPAmount{}, throwing);
1593 BEAST_EXPECT(terExpect == terActual);
1594 BEAST_EXPECT(sink.messages().str().contains(
1595 "Transaction caused an exception during invariant checks"));
1596 }
1597 }
1598 }
1599
1600 void
1602 {
1603 testcase << "txCheck finalize returns false";
1604 using namespace jtx;
1605
1606 // A TxInvariantCheck whose finalize returns false, so we can exercise
1607 // the "Transaction has failed one or more transaction invariants"
1608 // log path in checkInvariantsHelper independently of any real
1609 // transactor. This is the transaction-layer analogue of the
1610 // protocol-layer coverage in testObjectHasPseudoAccount / others.
1611 struct FailingTxInvariantCheck : TxInvariantCheck
1612 {
1613 void
1614 visitEntry(bool, SLE::ConstRef, SLE::ConstRef) override
1615 {
1616 }
1617
1618 [[nodiscard]] bool
1619 finalize(STTx const&, TER, XRPAmount, ReadView const&, beast::Journal const&) override
1620 {
1621 return false;
1622 }
1623 };
1624
1625 Env env{*this};
1626 Account const alice{"alice"};
1627 env.fund(XRP(1000), alice);
1628 env.close();
1629
1630 OpenView ov{*env.current()};
1631 STTx const tx{ttACCOUNT_SET, [](STObject&) {}};
1633 beast::Journal const jlog{sink};
1634 ApplyContext ac{env.app(), ov, tx, tesSUCCESS, env.current()->fees().base, TapNone, jlog};
1635 CurrentTransactionRulesGuard const rulesGuard(ov.rules());
1636
1637 FailingTxInvariantCheck failing;
1638 TER terActual = tesSUCCESS;
1639 for (TER const& terExpect : {TER(tecINVARIANT_FAILED), TER(tefINVARIANT_FAILED)})
1640 {
1641 terActual = checkInvariants(ac, terActual, XRPAmount{}, failing);
1642 BEAST_EXPECT(terExpect == terActual);
1643 BEAST_EXPECT(sink.messages().str().contains(
1644 "Transaction has failed one or more transaction invariants"));
1645 // The protocol-layer log must not appear: only the tx-layer
1646 // finalize failed here.
1647 BEAST_EXPECT(!sink.messages().str().contains(
1648 "Transaction has failed one or more global invariants"));
1649 }
1650 }
1651
1652 void
1671};
1672
1673BEAST_DEFINE_TESTSUITE(InvariantsMisc, app, xrpl);
1674
1675} // namespace xrpl::test
A generic endpoint for log messages.
Definition Journal.h:44
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
State information when applying a tx.
ApplyView & view()
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.
virtual void erase(SLE::Ref sle)=0
Remove a peeked SLE.
virtual void update(SLE::Ref sle)=0
Indicate changes to a peeked SLE.
RAII class to set and restore the current transaction rules.
Definition Rules.h:113
A currency issued by an account.
Definition Issue.h:18
constexpr MPTID const & getMptID() const
Definition MPTIssue.h:43
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
Writable ledger view that accumulates state and tx changes.
Definition OpenView.h:59
void rawInsert(SLE::Ref sle) override
Unconditionally insert a state item.
Definition OpenView.cpp:240
Rules const & rules() const override
Returns the tx processing rules.
Definition OpenView.cpp:151
A view into a ledger.
Definition ReadView.h:41
LedgerIndex seq() const
Returns the sequence number of the base ledger.
Definition ReadView.h:115
AccountID const & getIssuer() const
Definition STAmount.h:516
std::shared_ptr< STLedgerEntry > pointer
std::shared_ptr< STLedgerEntry const > const & ConstRef
void setFieldU32(SField const &field, std::uint32_t)
Definition STObject.cpp:743
void setFieldAmount(SField const &field, STAmount const &)
Definition STObject.cpp:803
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
Runtime interface for a transaction-specific invariant check.
Keylet createLoanBroker(jtx::Account const &a, jtx::Env &env, jtx::PrettyAsset const &asset)
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.
static SLE::pointer makeLoanSle(UInt256 const &loanBrokerID, std::uint32_t loanSeq, AccountID const &borrower)
std::function< bool(test::jtx::Account const &a, test::jtx::Account const &b, test::jtx::Env &env)> Preclose
void testInvariantOverwrite(FeatureBitset features)
void run() override
Runs the suite.
std::stringstream const & messages() const
Convenience class to test AMM functionality.
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
AccountID id() const
Returns the Account ID.
A transaction testing environment.
Definition Env.h:161
Application & app()
Definition Env.h:300
bool close(NetClock::time_point closeTime, std::optional< std::chrono::milliseconds > consensusDelay=std::nullopt)
Close and advance the ledger.
Definition Env.cpp:133
SLE::const_pointer le(Account const &account) const
Return an account root.
Definition Env.cpp:311
void fund(bool setDefaultRipple, STAmount const &amount, Account const &account)
Definition Env.cpp:323
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Definition Env.h:377
T invoke(T... args)
T make_shared(T... args)
constexpr Zero kZero
Definition Zero.h:30
Keylet computation functions.
Definition Indexes.h:39
Keylet escrow(AccountID const &src, SeqProxy const &seq) noexcept
An escrow entry.
Definition Indexes.cpp:430
Keylet offer(AccountID const &id, SeqProxy const &seq) noexcept
An offer from an account.
Definition Indexes.cpp:310
Keylet const & amendments() noexcept
The index of the amendment table.
Definition Indexes.cpp:260
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Definition Indexes.cpp:415
Keylet check(AccountID const &id, SeqProxy const &seq) noexcept
A Check.
Definition Indexes.cpp:372
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Definition Indexes.cpp:483
Keylet unchecked(UInt256 const &key) noexcept
Any ledger entry.
Definition Indexes.cpp:409
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:565
Keylet loanBroker(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:571
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet loan(UInt256 const &loanBrokerID, SeqProxy const &loanSeq) noexcept
Definition Indexes.cpp:577
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
Keylet trustLine(AccountID const &id0, AccountID const &id1, Currency const &currency) noexcept
The index of a trust line for a given currency.
Definition Indexes.cpp:287
Check operations.
Definition check.h:18
json::Value create(A const &account, A const &dest, STAmount const &sendMax)
Create a check.
Escrow operations.
Definition escrow.h:25
json::Value create(AccountID const &account, AccountID const &to, STAmount const &amount)
Definition escrow.cpp:24
auto const kCondition
Definition escrow.h:100
auto const kCancelTime
Set the "CancelAfter" time tag on a JTx.
Definition escrow.h:98
std::array< std::uint8_t, 39 > const kCb1
Definition escrow.h:60
json::Value mint(jtx::Account const &account, std::uint32_t nfTokenTaxon)
Mint an NFToken.
Definition token.cpp:23
json::Value pay(AccountID const &account, AccountID const &to, AnyAmount amount)
Create a payment.
Definition pay.cpp:14
XrpT const XRP
Converts to XRP Issue or STAmount.
Definition amount.cpp:92
FeatureBitset testableAmendments()
Definition Env.h:92
json::Value trust(Account const &account, STAmount const &amount, std::uint32_t flags)
Modify a trust line.
Definition trust.cpp:18
PrettyAmount drops(Integer i)
Returns an XRP PrettyAmount, which is trivially convertible to STAmount.
BEAST_DEFINE_TESTSUITE(AMMClawback, app, xrpl)
constexpr XRPAmount
Convert XRP to drops (integral types).
Definition TxTest.h:53
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Definition Issue.h:108
@ tefINVARIANT_FAILED
Definition TER.h:177
void increaseOwnerCount(ApplyView &view, SLE::Ref accountSle, SLE::Ref sponsorSle, std::uint32_t count, beast::Journal j)
Increase owner-count fields when the caller supplies the sponsor.
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
STLedgerEntry SLE
TER checkInvariants(ApplyContext &ctx, TER result, XRPAmount fee, std::optional< std::reference_wrapper< TxInvariantCheck > > txCheck)
Run all protocol invariant checks plus the transaction-specific check in a single pass over the modif...
BaseUInt< 256 > UInt256
Definition base_uint.h:581
std::unique_ptr< Transactor > makeTransactor(ApplyContext &ctx)
bool after(NetClock::time_point now, std::uint32_t mark)
Has the specified time passed?
Definition View.cpp:668
MPTID makeMptID(std::uint32_t const sequence, AccountID const &account)
Definition Indexes.cpp:219
@ TapNone
Definition ApplyView.h:28
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
TERSubset< CanCvtToTER > TER
Definition TER.h:657
LedgerEntryType
Identifiers for on-ledger objects.
@ tecINVARIANT_FAILED
Definition TER.h:324
std::vector< unsigned char > Blob
Storage for linear binary data.
Definition Blob.h:11
constexpr std::uint64_t kMaxMpTokenAmount
The maximum amount of MPTokenIssuance.
Definition Protocol.h:297
constexpr XRPAmount kInitialXrp
Configure the native currency.
TER trustDelete(ApplyView &view, SLE::Ref sleRippleState, AccountID const &uLowAccountID, AccountID const &uHighAccountID, beast::Journal j)
std::array< KeyletDesc< AccountID const & >, 6 > const kDirectAccountKeylets
Definition Indexes.cpp:37
constexpr std::uint32_t kMinInvestmentPeriod
Bounds on the length of a closed-ended vault's Investment phase (RedemptionDate - SubscriptionDate).
Definition Protocol.h:391
@ tesSUCCESS
Definition TER.h:253
T str(T... args)
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:20
UInt256 key
Definition Keylet.h:21