xrpld
Loading...
Searching...
No Matches
LoanRounding_test.cpp
1#include <test/app/lending/LoanTestBase.h>
2#include <test/jtx/Account.h>
3#include <test/jtx/Env.h>
4#include <test/jtx/TestHelpers.h>
5#include <test/jtx/amount.h>
6#include <test/jtx/fee.h>
7#include <test/jtx/flags.h>
8#include <test/jtx/jtx_json.h>
9#include <test/jtx/mpt.h>
10#include <test/jtx/pay.h>
11#include <test/jtx/ter.h>
12#include <test/jtx/trust.h>
13#include <test/jtx/txflags.h>
14#include <test/jtx/vault.h>
15
16#include <xrpl/basics/Number.h>
17#include <xrpl/beast/unit_test/suite.h>
18#include <xrpl/beast/utility/Zero.h>
19#include <xrpl/json/json_value.h>
20#include <xrpl/ledger/helpers/LendingHelpers.h>
21#include <xrpl/protocol/Asset.h>
22#include <xrpl/protocol/Feature.h>
23#include <xrpl/protocol/Indexes.h>
24#include <xrpl/protocol/Issue.h>
25#include <xrpl/protocol/Keylet.h>
26#include <xrpl/protocol/Protocol.h>
27#include <xrpl/protocol/SField.h>
28#include <xrpl/protocol/STAmount.h>
29#include <xrpl/protocol/SeqProxy.h>
30#include <xrpl/protocol/TER.h>
31#include <xrpl/protocol/TxFlags.h>
32#include <xrpl/protocol/Units.h>
33
34#include <array>
35#include <chrono>
36#include <cstdint>
37#include <optional>
38#include <ostream>
39#include <string>
40#include <tuple>
41
42namespace xrpl::test {
43
45{
46private:
47 void
49 {
50 testcase("Dust manipulation");
51
52 using namespace jtx;
53 using namespace std::chrono_literals;
54 Env env{*this, features};
55
56 // Setup: Create accounts
57 Account const issuer{"issuer"};
58 Account const lender{"lender"};
59 Account const borrower{"borrower"};
60 Account const victim{"victim"};
61
62 env.fund(XRP(1'000'000'00), issuer, lender, borrower, victim);
63 env.close();
64
65 // Step 1: Create vault with IOU asset
66 auto const asset = issuer["USD"];
67 env(trust(lender, asset(100000)));
68 env(trust(borrower, asset(100000)));
69 env(trust(victim, asset(100000)));
70 env(pay(issuer, lender, asset(50000)));
71 env(pay(issuer, borrower, asset(50000)));
72 env(pay(issuer, victim, asset(50000)));
73 env.close();
74
75 BrokerParameters const brokerParams{
76 .vaultDeposit = 10000,
77 .debtMax = Number{0},
78 .coverRateMin = TenthBips32{1000},
79 .coverRateLiquidation = TenthBips32{2500},
80 };
81
82 auto broker = createVaultAndBroker(env, asset, lender, brokerParams);
83
84 auto const loanKeyletOpt = [&] -> std::optional<Keylet> {
85 auto const brokerSle = env.le(keylet::loanBroker(broker.brokerID));
86 if (!BEAST_EXPECT(brokerSle))
87 return std::nullopt;
88
89 // Broker has no loans
90 BEAST_EXPECT(brokerSle->at(sfOwnerCount) == 0);
91
92 // The loan keylet is based on the LoanSequence of the
93 // _LOAN_BROKER_ object.
94 auto const loanSequence = brokerSle->at(sfLoanSequence);
95 return keylet::loan(broker.brokerID, SeqProxy::rawSequence(loanSequence));
96 }();
97 if (!loanKeyletOpt)
98 return;
99
100 auto const& vaultKeylet = broker.vaultKeylet();
101
102 {
103 auto const vaultSle = env.le(vaultKeylet);
104 Number const assetsTotal = vaultSle->at(sfAssetsTotal);
105 Number const assetsAvail = vaultSle->at(sfAssetsAvailable);
106
107 log << "Before loan creation:" << std::endl;
108 log << " AssetsTotal: " << assetsTotal << std::endl;
109 log << " AssetsAvailable: " << assetsAvail << std::endl;
110 log << " Difference: " << (assetsTotal - assetsAvail) << std::endl;
111
112 // before the loan the assets total and available should be equal
113 BEAST_EXPECT(assetsAvail == assetsTotal);
114 BEAST_EXPECT(assetsAvail == broker.asset(brokerParams.vaultDeposit).number());
115 }
116
117 Keylet const& loanKeylet = *loanKeyletOpt;
118
119 LoanParameters const loanParams{
120 .account = lender,
121 .counter = borrower,
122 .principalRequest = Number{100},
123 .interest = TenthBips32{1922},
124 .payTotal = 5816,
125 .payInterval = 86400 * 6,
126 .gracePd = 86400 * 5,
127 };
128
129 env(loanParams(env, broker));
130 env.close();
131
132 // Wait for loan to be late enough to default
133 env.close(std::chrono::seconds(86400 * 40)); // 40 days
134
135 {
136 auto const vaultSle = env.le(vaultKeylet);
137 Number const assetsTotal = vaultSle->at(sfAssetsTotal);
138 Number const assetsAvail = vaultSle->at(sfAssetsAvailable);
139
140 log << "After loan creation:" << std::endl;
141 log << " AssetsTotal: " << assetsTotal << std::endl;
142 log << " AssetsAvailable: " << assetsAvail << std::endl;
143 log << " Difference: " << (assetsTotal - assetsAvail) << std::endl;
144
145 auto const loanSle = env.le(loanKeylet);
146 if (!BEAST_EXPECT(loanSle))
147 return;
148 auto const state = constructLoanState(loanSle);
149
150 log << "Loan state:" << std::endl;
151 log << " ValueOutstanding: " << state.valueOutstanding << std::endl;
152 log << " PrincipalOutstanding: " << state.principalOutstanding << std::endl;
153 log << " InterestOutstanding: " << state.interestOutstanding() << std::endl;
154 log << " InterestDue: " << state.interestDue << std::endl;
155 log << " FeeDue: " << state.managementFeeDue << std::endl;
156
157 // after loan creation the assets total and available should
158 // reflect the value of the loan
159 BEAST_EXPECT(assetsAvail < assetsTotal);
160 BEAST_EXPECT(
161 assetsAvail ==
162 broker.asset(brokerParams.vaultDeposit - loanParams.principalRequest).number());
163 BEAST_EXPECT(
164 assetsTotal ==
165 broker.asset(brokerParams.vaultDeposit + state.interestDue).number());
166 }
167
168 // Step 7: Trigger default (dust adjustment will occur)
169 env(jtx::loan::manage(lender, loanKeylet.key, tfLoanDefault));
170 env.close();
171
172 // Step 8: Verify phantom assets created
173 {
174 auto const vaultSle2 = env.le(vaultKeylet);
175 Number const assetsTotal2 = vaultSle2->at(sfAssetsTotal);
176 Number const assetsAvail2 = vaultSle2->at(sfAssetsAvailable);
177
178 log << "After default:" << std::endl;
179 log << " AssetsTotal: " << assetsTotal2 << std::endl;
180 log << " AssetsAvailable: " << assetsAvail2 << std::endl;
181 log << " Difference: " << (assetsTotal2 - assetsAvail2) << std::endl;
182
183 // after a default the assets total and available should be equal
184 BEAST_EXPECT(assetsAvail2 == assetsTotal2);
185 }
186 }
187
188 void
190 {
191 testcase("Minimum cover rounding allows undercoverage (XRP)");
192
193 using namespace jtx;
194 using namespace loan_broker;
195
196 Env env{*this, features};
197
198 Account const lender{"lender"};
199 Account const borrower{"borrower"};
200
201 env.fund(XRP(200'000), lender, borrower);
202 env.close();
203
204 // Vault with XRP asset
205 Vault const vault{env};
206 auto [vaultCreate, vaultKeylet] = vault.create({.owner = lender, .asset = xrpIssue()});
207 env(vaultCreate);
208 env.close();
209 BEAST_EXPECT(env.le(vaultKeylet));
210
211 // Seed the vault with XRP so it can fund the loan principal
212 PrettyAsset const xrpAsset{xrpIssue(), 1};
213
214 BrokerParameters const brokerParams{
215 .vaultDeposit = 1'000,
216 .debtMax = Number{0},
217 .coverRateMin = TenthBips32{10'000},
218 .coverDeposit = 82,
219 };
220
221 auto const brokerInfo = createVaultAndBroker(env, xrpAsset, lender, brokerParams);
222 // Create a loan with principal 804 XRP and 0% interest (so
223 // DebtTotal increases by exactly 804)
224 env(loan::set(borrower, brokerInfo.brokerID, xrpAsset(804).value()),
226 Sig(sfCounterpartySignature, lender),
227 Fee(env.current()->fees().base * 2));
228 BEAST_EXPECT(env.ter() == tesSUCCESS);
229 env.close();
230
231 // Verify DebtTotal is exactly 804
232 if (auto const brokerSle = env.le(keylet::loanBroker(brokerInfo.brokerID));
233 BEAST_EXPECT(brokerSle))
234 {
235 log << *brokerSle << std::endl;
236 BEAST_EXPECT(brokerSle->at(sfDebtTotal) == Number(804));
237 }
238
239 // Attempt to withdraw 2 XRP to self, leaving 80 XRP CoverAvailable.
240 // The minimum is 80.4 XRP, which rounds up to 81 XRP, so this fails.
241 env(coverWithdraw(lender, brokerInfo.brokerID, xrpAsset(2).value()),
243 BEAST_EXPECT(env.ter() == tecINSUFFICIENT_FUNDS);
244 env.close();
245
246 // Attempt to withdraw 1 XRP to self, leaving 81 XRP CoverAvailable.
247 // because that leaves sufficient cover, this succeeds
248 env(coverWithdraw(lender, brokerInfo.brokerID, xrpAsset(1).value()));
249 BEAST_EXPECT(env.ter() == tesSUCCESS);
250 env.close();
251
252 // Validate CoverAvailable == 81 XRP and DebtTotal remains 804
253 if (auto const brokerSle = env.le(keylet::loanBroker(brokerInfo.brokerID));
254 BEAST_EXPECT(brokerSle))
255 {
256 log << *brokerSle << std::endl;
257 BEAST_EXPECT(brokerSle->at(sfCoverAvailable) == xrpAsset(81).value());
258 BEAST_EXPECT(brokerSle->at(sfDebtTotal) == Number(804));
259
260 // Also demonstrate that the true minimum (804 * 10%) exceeds 80
261 auto const theoreticalMin = tenthBipsOfValue(Number(804), TenthBips32(10'000));
262 log << "Theoretical min cover: " << theoreticalMin << std::endl;
263 BEAST_EXPECT(Number(804, -1) == theoreticalMin);
264 }
265 }
266
267 void
269 {
270 testcase("Rounding manipulation does not permit yield theft");
271 using namespace jtx;
272 using namespace loan;
273
274 // 1. Setup Environment
275 Env env(*this, all_);
276 Account const issuer{"issuer"};
277 Account const lender{"lender"};
278 Account const borrower{"borrower"};
279
280 env.fund(XRP(1000), issuer, lender, borrower);
281 env.close();
282
283 // 2. Asset Selection
284 PrettyAsset const iou = issuer["USD"];
285 env(trust(lender, iou(100'000'000)));
286 env(trust(borrower, iou(100'000'000)));
287 env(pay(issuer, lender, iou(100'000'000)));
288 env(pay(issuer, borrower, iou(100'000'000)));
289 env.close();
290
291 // 3. Create Vault and Broker with High Debt Limit (100M)
292 auto const brokerInfo = createVaultAndBroker(
293 env,
294 iou,
295 lender,
296 {
297 .vaultDeposit = 5'000'000,
298 .debtMax = Number{100'000'000},
299 .coverDeposit = 500'000,
300 });
301 auto const [currentSeq, vaultKeylet] = [&] {
302 auto const brokerSle = env.le(keylet::loanBroker(brokerInfo.brokerID));
303 if (!BEAST_EXPECT(brokerSle))
305 auto const currentSeq = brokerSle->at(sfLoanSequence);
306 auto const vaultKeylet = keylet::vault(brokerSle->at(sfVaultID));
307 return std::make_tuple(currentSeq, vaultKeylet);
308 }();
309
310 // 4. Loan Parameters (Attack Vector)
311 Number const principal = 1'000'000;
312 TenthBips32 const interestRate = TenthBips32{1}; // 0.001%
313 std::uint32_t const paymentInterval = 86400;
314 std::uint32_t const paymentTotal = 3650;
315
316 auto const loanSetFee = Fee(env.current()->fees().base * 2);
317 env(set(borrower, brokerInfo.brokerID, iou(principal).value(), flags),
318 Sig(sfCounterpartySignature, lender),
319 loan::kInterestRate(interestRate),
320 loan::kPaymentInterval(paymentInterval),
321 loan::kPaymentTotal(paymentTotal),
322 Fee(loanSetFee));
323 env.close();
324
325 // --- RETRIEVE OBJECTS & SETUP ATTACK ---
326
327 auto const borrowerBalance = [&] { return env.balance(borrower, iou); };
328 auto const borrowerScale = static_cast<STAmount const&>(borrowerBalance()).exponent();
329
330 auto const loanKeylet =
331 keylet::loan(brokerInfo.brokerID, SeqProxy::rawSequence(currentSeq));
332 auto const maybePeriodicPayment = [&] -> std::optional<STAmount> {
333 auto const loanSle = env.le(loanKeylet);
334 if (!BEAST_EXPECT(loanSle))
335 return std::nullopt;
336 // Construct Payment
337 return STAmount{iou, loanSle->at(sfPeriodicPayment)};
338 }();
339 if (!maybePeriodicPayment)
340 return;
341 auto const periodicPayment = *maybePeriodicPayment;
342 auto const roundedPayment =
343 roundToScale(periodicPayment, borrowerScale, Number::RoundingMode::Upward);
344
345 // ATTACK: Add dust buffer (1e-9) to force 'excess' logic execution
346 STAmount const paymentBuffer{iou, Number(1, -9)};
347 STAmount const attackPayment = periodicPayment + paymentBuffer;
348
349 auto const maybeInitialVaultAssets = [&] -> std::optional<Number> {
350 auto const vault = env.le(vaultKeylet);
351 if (!BEAST_EXPECT(vault))
352 return std::nullopt;
353 return vault->at(sfAssetsTotal);
354 }();
355 if (!maybeInitialVaultAssets)
356 return;
357 auto const initialVaultAssets = *maybeInitialVaultAssets;
358
359 // 5. Execution Loop
360 int yieldTheftCount = 0;
361 auto previousAssetsTotal = initialVaultAssets;
362
363 for (int i = 0; i < 100; ++i)
364 {
365 auto const balanceBefore = borrowerBalance();
366 env(pay(borrower, loanKeylet.key, attackPayment, flags));
367 env.close();
368 auto const borrowerDelta = balanceBefore - borrowerBalance();
369 BEAST_EXPECT(borrowerDelta.signum() == roundedPayment.signum());
370
371 auto const loanSle = env.le(loanKeylet);
372 if (!BEAST_EXPECT(loanSle))
373 break;
374 auto const updatedPayment = STAmount{iou, loanSle->at(sfPeriodicPayment)};
375 BEAST_EXPECT(
376 (roundToScale(updatedPayment, borrowerScale, Number::RoundingMode::Upward) ==
377 roundedPayment));
378 BEAST_EXPECT(
379 (updatedPayment == periodicPayment) ||
380 (flags == tfLoanOverpayment && i >= 2 && updatedPayment < periodicPayment));
381
382 auto const currentVaultSle = env.le(vaultKeylet);
383 if (!BEAST_EXPECT(currentVaultSle))
384 break;
385
386 auto const currentAssetsTotal = currentVaultSle->at(sfAssetsTotal);
387 auto const delta = currentAssetsTotal - previousAssetsTotal;
388
389 BEAST_EXPECT(
390 (delta == beast::kZero && borrowerDelta <= roundedPayment) ||
391 (delta > beast::kZero && borrowerDelta > roundedPayment));
392
393 // If tx succeeded but Assets Total didn't change, interest was
394 // stolen.
395 if (delta == beast::kZero && borrowerDelta > roundedPayment)
396 {
397 yieldTheftCount++;
398 }
399
400 previousAssetsTotal = currentAssetsTotal;
401 }
402
403 BEAST_EXPECTS(yieldTheftCount == 0, std::to_string(yieldTheftCount));
404 }
405
406 // Regression for the dual-rounding fix at coarse (integer-MPT) scale.
407 //
408 // Loan: P=1, r=50% (50000 tenth-bips), n=3, yearly interval. The
409 // amortization schedule produces a fractional principal
410 // (~0.47) which under round-to-nearest collapses to 0 in a single
411 // step, causing `doPayment`'s strict `>` assertion on principal to
412 // fire mid-loan. With fixCleanup3_2_0 enabled, principal is rounded
413 // upward (sticks at 1 across the first two periods) and only clears
414 // in the final payment.
415 //
416 // The test pays one period at a time across three LoanPay
417 // transactions and verifies the loan completes (paymentRemaining=0)
418 // with totals matching the loan's economics (1 principal + 2 interest).
419 // Also run under featureLendingProtocolV1_1: ValidLoan must allow the
420 // two sticking pays (TVO falls, PO does not) and the final clear
421 // (PaymentRemaining 0, NextPaymentDueDate 0).
422 void
424 {
425 // Without fixCleanup3_2_0, this behavior will abort the server, so
426 // don't run without it.
427 if (!features[fixCleanup3_2_0])
428 return;
429
430 testcase("edge: integer MPT principal stuck mid-loan completes via final");
431
432 using namespace jtx;
433 Env env(*this, features);
434
435 Account const issuer{"issuer"};
436 Account const lender{"lender"};
437 Account const borrower{"borrower"};
438
439 env.fund(XRP(100'000), issuer, lender, borrower);
440 env.close();
441
442 MPTTester mptt{env, issuer, kMptInitNoFund};
443 mptt.create({.maxAmt = 100'000, .flags = tfMPTCanTransfer});
444 PrettyAsset const asset{mptt.issuanceID()};
445
446 mptt.authorize({.account = lender});
447 mptt.authorize({.account = borrower});
448
449 env(pay(issuer, lender, asset(10'000)));
450 env(pay(issuer, borrower, asset(10'000)));
451 env.close();
452
453 // createVaultAndBroker promotes the vault to ClosedEnded under
454 // featureLendingProtocolV1_1 (LoanBrokerSet rejects open-ended).
455 BrokerParameters const params{
456 .vaultDeposit = Number{5'000},
457 .debtMax = Number{100},
458 .coverRateMin = TenthBips32{0},
459 .coverDeposit = 0,
460 .managementFeeRate = TenthBips16{0},
461 .coverRateLiquidation = TenthBips32{0},
462 };
463 BrokerInfo const broker = createVaultAndBroker(env, asset, lender, params);
464
465 auto const loanKeylet = nextLoanKeylet(env, broker);
466 env(loan::set(borrower, broker.brokerID, Number{1}),
467 Sig(sfCounterpartySignature, lender),
470 loan::kPaymentInterval(31'536'000),
471 Fee(env.current()->fees().base * 2));
472 env.close();
473
474 auto const borrowerStart = env.balance(borrower, asset).value();
475
476 // Three separate periodic payments of 1 each. Expected per-period
477 // evolution at integer MPT scale (TVO = PO + interestDue +
478 // managementFeeDue):
479 // start: PO=1, TVO=3, paymentRemaining=3
480 // after pay #1: PO=1, TVO=2, paymentRemaining=2 (principal sticks)
481 // after pay #2: PO=1, TVO=1, paymentRemaining=1 (principal sticks)
482 // after pay #3: PO=0, TVO=0, paymentRemaining=0 (final clears)
483 std::array<Number, 3> const expectedPO{Number{1}, Number{1}, Number{0}};
484 std::array<Number, 3> const expectedTVO{Number{2}, Number{1}, Number{0}};
485 std::array<std::uint32_t, 3> const expectedRemaining{2, 1, 0};
486
487 for (int i = 0; i < 3; ++i)
488 {
489 env(loan::pay(borrower, loanKeylet.key, asset(1)), Ter(tesSUCCESS));
490 env.close();
491
492 auto const sle = env.le(loanKeylet);
493 if (!BEAST_EXPECT(sle))
494 return;
495 BEAST_EXPECT(sle->at(sfPrincipalOutstanding) == expectedPO[i]);
496 BEAST_EXPECT(sle->at(sfTotalValueOutstanding) == expectedTVO[i]);
497 BEAST_EXPECT(sle->at(sfPaymentRemaining) == expectedRemaining[i]);
498 if (expectedRemaining[i] == 0)
499 BEAST_EXPECT(sle->at(~sfNextPaymentDueDate).value_or(0) == 0);
500 }
501
502 // Borrower paid 3 total regardless of fee split (1 principal + 2
503 // interest+fee, matching loan economics).
504 auto const borrowerEnd = env.balance(borrower, asset).value();
505 BEAST_EXPECT(borrowerStart - borrowerEnd == asset(3).value());
506 }
507
508#if LOAN_TODO
509 void
510 testLoanCoverMinimumRoundingExploit(FeatureBitset features)
511 {
512 auto testLoanCoverMinimumRoundingExploit = [&, this](Number const& principalRequest) {
513 testcase << "LoanBrokerCoverClawback drains cover via rounding"
514 << " principalRequested=" << to_string(principalRequest);
515
516 using namespace jtx;
517 using namespace loan;
518 using namespace loan_broker;
519
520 Env env(*this, features);
521
522 Account const issuer{"issuer"};
523 Account const lender{"lender"};
524 Account const borrower{"borrower"};
525
526 env.fund(XRP(1'000'000'000), issuer, lender, borrower);
527 env.close();
528
529 env(fset(issuer, asfAllowTrustLineClawback));
530 env.close();
531
532 PrettyAsset const asset = issuer[iouCurrency];
533 env(trust(lender, asset(2'000'0000)));
534 env(trust(borrower, asset(2'000'0000)));
535 env.close();
536
537 env(pay(issuer, lender, asset(2'000'0000)));
538 env.close();
539
540 BrokerParameters brokerParams{.debtMax = 0, .coverRateMin = TenthBips32{10'000}};
541 BrokerInfo broker{createVaultAndBroker(env, asset, lender, brokerParams)};
542
543 auto const loanSetFee = Fee(env.current()->fees().base * 2);
544 auto createTx = env.jt(
545 set(borrower, broker.brokerID, principalRequest),
546 Sig(sfCounterpartySignature, lender),
547 loanSetFee,
548 kPaymentInterval(600),
549 kPaymentTotal(1),
550 kGracePeriod(60));
551 env(createTx);
552 env.close();
553
554 auto const brokerBefore = env.le(keylet::loanBroker(broker.brokerID));
555 BEAST_EXPECT(brokerBefore);
556 if (!brokerBefore)
557 return;
558
559 Number const debtOutstanding = brokerBefore->at(sfDebtTotal);
560 Number const coverAvailableBefore = brokerBefore->at(sfCoverAvailable);
561
562 BEAST_EXPECT(debtOutstanding > Number{});
563 BEAST_EXPECT(coverAvailableBefore > Number{});
564
565 log << "debt=" << to_string(debtOutstanding)
566 << " cover_available=" << to_string(coverAvailableBefore);
567
568 env(coverClawback(issuer, 0), loanBrokerID(broker.brokerID));
569 env.close();
570
571 auto const brokerAfter = env.le(keylet::loanBroker(broker.brokerID));
572 BEAST_EXPECT(brokerAfter);
573 if (!brokerAfter)
574 return;
575
576 Number const debtAfter = brokerAfter->at(sfDebtTotal);
577 // the debt has not changed
578 BEAST_EXPECT(debtAfter == debtOutstanding);
579
580 Number const coverAvailableAfter = brokerAfter->at(sfCoverAvailable);
581
582 // since the cover rate min != 0, the cover available should not
583 // be zero
584 BEAST_EXPECT(coverAvailableAfter != Number{});
585 };
586
587 // Call the lambda with different principal values
588 testLoanCoverMinimumRoundingExploit(Number{1, -30}); // 1e-30 units
589 testLoanCoverMinimumRoundingExploit(Number{1, -20}); // 1e-20 units
590 testLoanCoverMinimumRoundingExploit(Number{1, -10}); // 1e-10 units
591 testLoanCoverMinimumRoundingExploit(Number{1, 1}); // 1e-10 units
592 }
593#endif
594
595 // A residual overpayment can reduce the stored principal by one scale-unit
596 // *less* than computeOverpaymentComponents predicts, firing the
597 // "principal change agrees" XRPL_ASSERT_PARTS in doOverpayment:
598 //
599 // trackedPrincipalDelta == principalOutstanding - newPrincipalOutstanding
600 //
601 // tryOverpayment re-amortizes the loan at the reduced principal, then
602 // re-derives the theoretical principal from the new periodic payment via
603 // (P * paymentFactor) / paymentFactor. That round-trip is not exact in
604 // Number's 19-digit arithmetic; a positive residual pushes the recomputed
605 // principal a hair above the exact grid point `oldPrincipal - delta`, and
606 // the Upward rounding in tryOverpayment then bumps it a full scale-unit
607 // higher. The principal therefore drops by `delta - 1 unit`, not `delta`.
608 //
609 // Concrete case (isolated, at the tryOverpayment level):
610 // A 100 USD loan at the minimum non-zero rate, 3 payments, loanScale -10.
611 // After one regular payment (principalOutstanding 66.6666666674) a residual overpayment of
612 // 0.049999998 yields trackedPrincipalDelta 0.048999998 but only reduces the principal by
613 // 0.0489999979 (newPrincipal 66.6176666695) — short by 1e-10.
614 //
615 // With fixCleanup3_2_0, tryOverpayment pins the new principal to the exact,
616 // on-grid reduction (oldPrincipal - trackedPrincipalDelta) instead of the
617 // lossy (P*factor)/factor round-trip, so the assertion holds and the
618 // overpayment applies cleanly. The three "principal change agrees" /
619 // "interest paid agrees" / "principal payment matches" assertions are
620 // gated behind the same amendment, so without it they are disabled (the
621 // server does not abort) and the loan keeps the pre-amendment computation.
622 //
623 // The test runs the same scenario under both amendment settings and checks
624 // the stored principal against a ground-truth value derived independently of
625 // the loan-state computation under test.
626 void
628 {
629 testcase("bug: doOverpayment asserts 'principal change agrees'");
630
631 using namespace jtx;
632 using namespace loan;
633 using namespace xrpl::detail;
634
635 struct Params
636 {
637 TenthBips32 interestRate;
638 TenthBips16 managementFeeRate;
639 std::uint32_t paymentTotal;
640 std::uint32_t paymentInterval;
641 std::int64_t principal;
642 Number overpayment;
643 TenthBips32 overpaymentInterestRate;
644 TenthBips32 overpaymentFeeRate;
645 std::optional<int> vaultScale;
646 };
647
648 struct Result
649 {
650 Number principalOutstanding; // stored principal after the LoanPay
651 Number expectedNewPrincipal; // ground truth, independent of the fix
652 Number managementFeeChange; // managementFeeOutstanding after - before
653 Number unit; // one scale-unit at the loan scale
654 };
655
656 auto const runScenario = [this](FeatureBitset features, Params const& p) -> Result {
657 Env env(*this, features);
658
659 Account const issuer{"issuer"};
660 Account const lender{"vaultOwner"};
661 Account const borrower{"borrower"};
662
663 PrettyAsset const iouAsset = createFundedRippleIouAsset(env, issuer, lender, borrower);
664 Asset const asset = iouAsset.raw();
665
666 auto const broker = createVaultAndBroker(
667 env,
668 iouAsset,
669 lender,
670 {
671 .vaultDeposit = 900'000,
672 .debtMax = 0,
673 .managementFeeRate = p.managementFeeRate,
674 .vaultScale = p.vaultScale,
675 });
676
677 auto const brokerSle = env.le(broker.brokerKeylet());
678 BEAST_EXPECT(brokerSle);
679 auto const loanSequence = brokerSle ? brokerSle->at(sfLoanSequence) : 0;
680 auto const loanKeylet =
681 keylet::loan(broker.brokerID, SeqProxy::rawSequence(loanSequence));
682
683 env(set(borrower, broker.brokerID, Number{p.principal}, tfLoanOverpayment),
684 Sig(sfCounterpartySignature, lender),
685 kInterestRate(p.interestRate),
686 kPaymentTotal(p.paymentTotal),
687 kPaymentInterval(p.paymentInterval),
688 kGracePeriod(p.paymentInterval),
689 kOverpaymentFee(p.overpaymentFeeRate),
690 kOverpaymentInterestRate(p.overpaymentInterestRate),
691 Fee(env.current()->fees().base * 2),
692 Ter(tesSUCCESS));
693 env.close();
694
695 // The single LoanPay below makes one regular payment (the overpayment
696 // is smaller than one period) and leaves the residual as an
697 // overpayment.
698 auto const s = getCurrentState(env, broker, loanKeylet);
699 auto const periodicRate = loanPeriodicRate(s.interestRate, s.paymentInterval);
700 auto const onePeriod = computePaymentComponents(
701 env.current()->rules(),
702 asset,
703 s.loanScale,
704 s.totalValue,
705 s.principalOutstanding,
706 s.managementFeeOutstanding,
707 s.periodicPayment,
708 periodicRate,
709 s.paymentRemaining,
710 p.managementFeeRate);
711
712 // Ground truth: the stored principal must drop by exactly the regular
713 // payment's principal portion plus the overpayment's principal
714 // portion. computeOverpaymentComponents depends only on the
715 // overpayment amount and rates (not on the loan-state computation
716 // under test), so it is an independent oracle. Both components are
717 // computed under the same rules as the env so the payment factor
718 // matches.
719 auto const overpaymentComponents = computeOverpaymentComponents(
720 env.current()->rules(),
721 asset,
722 s.loanScale,
723 p.overpayment,
724 p.overpaymentInterestRate,
725 p.overpaymentFeeRate,
726 p.managementFeeRate);
727 Number const expectedNewPrincipal = s.principalOutstanding -
728 onePeriod.trackedPrincipalDelta - overpaymentComponents.trackedPrincipalDelta;
729
730 Number const managementFeeBefore = s.managementFeeOutstanding;
731
732 STAmount const payAmount{asset, onePeriod.trackedValueDelta + p.overpayment};
733 env(pay(borrower, loanKeylet.key, payAmount),
734 Txflags(tfLoanOverpayment),
735 Ter(tesSUCCESS));
736 env.close();
737
738 auto const loanSle = env.le(loanKeylet);
739 BEAST_EXPECT(loanSle);
740
741 return Result{
742 .principalOutstanding = loanSle ? Number{loanSle->at(sfPrincipalOutstanding)} : 0,
743 .expectedNewPrincipal = expectedNewPrincipal,
744 .managementFeeChange =
745 (loanSle ? Number{loanSle->at(sfManagementFeeOutstanding)} : Number{0}) -
746 managementFeeBefore,
747 .unit = Number{1, s.loanScale},
748 };
749 };
750
751 // Scenario 1: the original near-zero-rate principal reproduction
752 // (loanScale -10, no management fee). 0.049999998 is smaller than one
753 // period, so it stays a residual overpayment.
754 Params const principalCase{
755 .interestRate = TenthBips32{1},
756 .managementFeeRate = TenthBips16{0},
757 .paymentTotal = 3,
758 .paymentInterval = 60,
759 .principal = 100,
760 .overpayment = Number{49999998, -9},
761 .overpaymentInterestRate = TenthBips32{1000},
762 .overpaymentFeeRate = TenthBips32{1000},
763 .vaultScale = 1,
764 };
765
766 // With fixCleanup3_2_0 the stored principal lands exactly on the
767 // ground-truth grid point: it is reduced by exactly the overpayment's
768 // principal portion. This is the key correctness check: if the principal
769 // pin were removed (even with the assertions still gated off), the lossy
770 // (P * factor) / factor round-trip would leave the principal one
771 // scale-unit high and this would fail.
772 Result const fixed = runScenario(all_, principalCase);
773 BEAST_EXPECTS(
774 fixed.principalOutstanding == fixed.expectedNewPrincipal,
775 "fixed principal " + to_string(fixed.principalOutstanding) + " != expected " +
776 to_string(fixed.expectedNewPrincipal));
777
778 // Without the amendment the loan amortizes with the catastrophically
779 // cancelling near-zero payment factor, so its schedule (and ground truth)
780 // differ from the fixed case; the gated assertions keep the server from
781 // aborting and the overpayment still lands exactly on that schedule.
782 Result const legacy = runScenario(all_ - fixCleanup3_2_0, principalCase);
783 BEAST_EXPECTS(
784 legacy.principalOutstanding == legacy.expectedNewPrincipal,
785 "legacy principal " + to_string(legacy.principalOutstanding) + " != expected " +
786 to_string(legacy.expectedNewPrincipal));
787
788 // Scenario 2: a normal-rate loan with a 10% management fee. At a normal
789 // rate the payment factor is identical across the amendment, so toggling
790 // fixCleanup3_2_0 isolates the fix. This overpayment (found by search)
791 // lands on a state where both the principal and the management fee differ
792 // by one scale-unit between the fixed and legacy paths.
793 Params const feeCase{
794 .interestRate = TenthBips32{10000},
795 .managementFeeRate = TenthBips16{10000},
796 .paymentTotal = 6,
797 .paymentInterval = 30u * 24 * 60 * 60,
798 .principal = 1000,
799 .overpayment = Number{214367363, -10},
800 .overpaymentInterestRate = TenthBips32{0},
801 .overpaymentFeeRate = TenthBips32{0},
802 .vaultScale = std::nullopt,
803 };
804
805 Result const feeFixed = runScenario(all_, feeCase);
806 Result const feeLegacy = runScenario(all_ - fixCleanup3_2_0, feeCase);
807
808 // With the fix the principal is the exact reduction; without it the lossy
809 // (P * factor) / factor round-trip leaves it one scale-unit high.
810 BEAST_EXPECTS(
811 feeFixed.principalOutstanding == feeFixed.expectedNewPrincipal,
812 "fee-case fixed principal " + to_string(feeFixed.principalOutstanding) +
813 " != expected " + to_string(feeFixed.expectedNewPrincipal));
814 BEAST_EXPECTS(
815 feeLegacy.principalOutstanding == feeLegacy.expectedNewPrincipal + feeLegacy.unit,
816 "fee-case legacy principal " + to_string(feeLegacy.principalOutstanding) +
817 " != expected " + to_string(feeLegacy.expectedNewPrincipal + feeLegacy.unit));
818
819 // Management fee: the overpayment re-amortizes a fee-bearing loan, so the management fee
820 // outstanding drops.
821 //
822 // Unlike the principal that is already at the correct precision, the re-amortized
823 // management fee is tenthBipsOfValue of the new schedule's gross interest, which depends
824 // on the recomputed periodic payment. So the expected change below is a pinned constant
825 // captured from a passing run a magic value only because there is nothing simpler to
826 // compare against.
827 //
828 // At the integration level, toggling the amendment also changes the regular payment's
829 // rounding so a fixed-vs-legacy comparison cannot isolate the overpayment management-fee
830 // fix.
831 BEAST_EXPECT(feeFixed.managementFeeChange == feeLegacy.managementFeeChange);
832 BEAST_EXPECTS(
833 (feeFixed.managementFeeChange == Number{-8219709543, -10}),
834 "fee-case mgmt fee change " + to_string(feeFixed.managementFeeChange));
835 }
836
837 // An overpayment whose residual amount has more precision than loanScale
838 // fires the isRounded(asset, overpayment, loanScale) assertion in
839 // computeOverpaymentComponents (and a downstream "interest paid agrees"
840 // assertion in doOverpayment). fixCleanup3_2_0 rounds the residual down
841 // to loanScale before passing it in. The pre-amendment path can't be
842 // tested here because the assertion fires in Debug builds and aborts
843 // the test process — see the PR description for context.
844 void
846 {
847 testcase("bug: computeOverpaymentComponents isRounded assertion");
848
849 using namespace jtx;
850 using namespace loan;
851 Env env(*this, all_);
852
853 Account const issuer{"issuer"};
854 Account const lender{"vaultOwner"};
855 Account const borrower{"borrower"};
856
857 PrettyAsset const iouAsset = createFundedRippleIouAsset(env, issuer, lender, borrower);
858
859 auto const broker = createVaultAndBroker(
860 env,
861 iouAsset,
862 lender,
863 {
864 .vaultDeposit = 100'000,
865 .debtMax = 5000,
866 .managementFeeRate = TenthBips16{1000},
867 .vaultScale = 1,
868 });
869
870 auto const sleBroker = env.le(broker.brokerKeylet());
871 if (!BEAST_EXPECT(sleBroker))
872 return;
873 auto const loanSequence = sleBroker->at(sfLoanSequence);
874 auto const loanKeylet = keylet::loan(broker.brokerID, SeqProxy::rawSequence(loanSequence));
875
876 using namespace loan;
877 env(set(borrower, broker.brokerID, Number{1000}, tfLoanOverpayment),
878 Sig(sfCounterpartySignature, lender),
879 kInterestRate(TenthBips32{10000}),
880 kPaymentTotal(12),
881 kPaymentInterval(60),
882 kGracePeriod(60),
883 kOverpaymentFee(TenthBips32{1000}),
884 kOverpaymentInterestRate(TenthBips32{1000}),
885 Fee(env.current()->fees().base * 2),
886 Ter(tesSUCCESS));
887 env.close();
888
889 // periodic * 1.5 at 15-sig-digit precision: 125.000154585042. This
890 // has too many digits to round cleanly to loanScale=-10, so the
891 // overpayment residual fails the isRounded check.
892 STAmount const payAmount{iouAsset.raw(), Number{125'000'154'585'042LL, -12}};
893 env(pay(borrower, loanKeylet.key, payAmount), Txflags(tfLoanOverpayment), Ter(tesSUCCESS));
894 env.close();
895 }
896
897 // Pre-fixCleanup3_4_0 bug: VaultWithdraw for a fixed *share* amount that
898 // rounds to zero assets trips tecINVARIANT_FAILED instead of failing
899 // cleanly or succeeding, depending on why it's zero. The fixed-shares
900 // branch had no zero guard, unlike the fixed-assets branch.
901 // XRP case: pool value is nonzero (2,000,000) but 1 share's worth (0.5
902 // drops) truncates to zero drops -> real precision loss -> tecPRECISION_LOSS.
903 // IOU case: loan drew 100% of the vault and is fully impaired, so
904 // AssetsTotal == LossUnrealized exactly -> pool value is genuinely zero
905 // -> legitimate zero-value withdrawal -> tesSUCCESS.
906 void
908 {
909 testcase("bug: VaultWithdraw fixed shares round down to zero assets");
910
911 using namespace jtx;
912 using namespace loan;
913
914 bool const fixed = features[fixCleanup3_4_0];
915
916 Env env(*this, features);
917
918 Account const lender{"lender"};
919 Account const depositorB{"depositorB"};
920 Account const borrower{"borrower"};
921
922 env.fund(XRP(10'000'000), lender, depositorB, borrower);
923 env.close();
924
925 // asset(n) == n drops.
926 PrettyAsset const xrpAsset{xrpIssue(), 1};
927
928 auto const broker = createVaultAndBroker(
929 env,
930 xrpAsset,
931 lender,
932 {.vaultDeposit = 1'000'000, .debtMax = 3'000'000, .coverDeposit = 1'000'000});
933
934 Vault const v{env};
935 env(v.deposit({
936 .depositor = depositorB,
937 .id = broker.vaultKeylet().key,
938 .amount = xrpAsset(3'000'000),
939 }));
940 env.close();
941
942 auto const brokerSle = env.le(broker.brokerKeylet());
943 if (!BEAST_EXPECT(brokerSle))
944 return;
945 auto const loanKeylet =
946 keylet::loan(broker.brokerID, SeqProxy::rawSequence(brokerSle->at(sfLoanSequence)));
947
948 env(set(borrower, broker.brokerID, Number{2'000'000}),
949 Sig(sfCounterpartySignature, lender),
950 kPaymentTotal(2),
951 kPaymentInterval(600),
952 Fee(env.current()->fees().base * 2),
953 Ter(tesSUCCESS));
954 env.close();
955
956 // Impair the loan so LossUnrealized > 0.
957 advancePastDueDate(env, loanKeylet);
958 env(manage(lender, loanKeylet.key, tfLoanImpair), Ter(tesSUCCESS));
959 env.close();
960
961 auto const vaultSle = env.le(broker.vaultKeylet());
962 if (!BEAST_EXPECT(vaultSle))
963 return;
964 BEAST_EXPECT(vaultSle->at(sfLossUnrealized) > beast::kZero);
965
966 // (AssetsTotal 4M - LossUnrealized 2M) * 1 share / 4M shares = 0.5,
967 // rounds down to zero drops.
968 auto const shareAsset = vaultSle->at(sfShareMPTID);
969 STAmount const oneShare{MPTIssue{shareAsset}, Number(1)};
970
971 env(v.withdraw({.depositor = lender, .id = broker.vaultKeylet().key, .amount = oneShare}),
973 env.close();
974
975 // Same bug, IOU asset. Needs a 2nd, minimal depositor: a sole
976 // shareholder would waive the loss subtraction (fixCleanup3_2_0),
977 // returning full value instead of zero.
978 {
979 Account const issuer{"issuer"};
980 Account const iouLender{"iouLender"};
981 Account const iouDepositorB{"iouDepositorB"};
982 Account const iouBorrower{"iouBorrower"};
983
984 env.fund(XRP(10'000'000), issuer, iouLender, iouDepositorB, iouBorrower);
985 env.close();
986
987 PrettyAsset const iouAsset = issuer[iouCurrency_];
988 env(trust(iouLender, iouAsset(10'000'000)));
989 env(trust(iouDepositorB, iouAsset(10'000'000)));
990 env(trust(iouBorrower, iouAsset(10'000'000)));
991 // iouLender funds the vault deposit and the broker's cover deposit.
992 env(pay(issuer, iouLender, iouAsset(9'000'000)));
993 env(pay(issuer, iouDepositorB, iouAsset(1)));
994 env.close();
995
996 // No management fee -> LossUnrealized ends up == AssetsTotal.
997 auto const iouBroker = createVaultAndBroker(
998 env,
999 iouAsset,
1000 iouLender,
1001 {
1002 .vaultDeposit = 3'999'999,
1003 .debtMax = 4'000'000,
1004 .coverDeposit = 4'000'000,
1005 .managementFeeRate = TenthBips16{0},
1006 });
1007
1008 env(v.deposit({
1009 .depositor = iouDepositorB,
1010 .id = iouBroker.vaultKeylet().key,
1011 .amount = iouAsset(1),
1012 }));
1013 env.close();
1014
1015 auto const iouBrokerSle = env.le(iouBroker.brokerKeylet());
1016 if (!BEAST_EXPECT(iouBrokerSle))
1017 return;
1018 auto const iouLoanKeylet = keylet::loan(
1019 iouBroker.brokerID, SeqProxy::rawSequence(iouBrokerSle->at(sfLoanSequence)));
1020
1021 // Draw the entire vault out as a single loan.
1022 env(set(iouBorrower, iouBroker.brokerID, Number{4'000'000}),
1023 Sig(sfCounterpartySignature, iouLender),
1024 kPaymentTotal(2),
1025 kPaymentInterval(600),
1026 Fee(env.current()->fees().base * 2),
1027 Ter(tesSUCCESS));
1028 env.close();
1029
1030 advancePastDueDate(env, iouLoanKeylet);
1031 env(manage(iouLender, iouLoanKeylet.key, tfLoanImpair), Ter(tesSUCCESS));
1032 env.close();
1033
1034 auto const iouVaultSle = env.le(iouBroker.vaultKeylet());
1035 if (!BEAST_EXPECT(iouVaultSle))
1036 return;
1037 BEAST_EXPECT(iouVaultSle->at(sfLossUnrealized) == iouVaultSle->at(sfAssetsTotal));
1038
1039 auto const iouShareAsset = iouVaultSle->at(sfShareMPTID);
1040 STAmount const oneIouShare{MPTIssue{iouShareAsset}, Number(1)};
1041
1042 auto const iouLenderBalanceBefore = env.balance(iouLender, iouAsset);
1043 auto const iouVaultAvailableBefore = iouVaultSle->at(sfAssetsAvailable);
1044 // Env::balance can't be used for shares: it resolves the issuer
1045 // name, and the share issuer is the vault pseudo-account, which
1046 // Env doesn't know.
1047 auto const lenderShares = [&] -> std::uint64_t {
1048 auto const sle = env.le(keylet::mptoken(iouShareAsset, iouLender.id()));
1049 return sle ? sle->at(sfMPTAmount) : 0;
1050 };
1051 auto const iouLenderSharesBefore = lenderShares();
1052 auto const iouIssuanceBefore = env.le(keylet::mptokenIssuance(iouShareAsset));
1053 if (!BEAST_EXPECT(iouIssuanceBefore))
1054 return;
1055 auto const iouSharesOutstandingBefore = iouIssuanceBefore->at(sfOutstandingAmount);
1056 env(v.withdraw({
1057 .depositor = iouLender,
1058 .id = iouBroker.vaultKeylet().key,
1059 .amount = oneIouShare,
1060 }),
1062 env.close();
1063
1064 if (fixed)
1065 {
1066 // Confirm this was a true zero-value transfer: balances
1067 // unchanged even though a share was burned.
1068 BEAST_EXPECT(env.balance(iouLender, iouAsset) == iouLenderBalanceBefore);
1069 BEAST_EXPECT(lenderShares() == iouLenderSharesBefore - 1);
1070 auto const iouIssuanceAfter = env.le(keylet::mptokenIssuance(iouShareAsset));
1071 if (BEAST_EXPECT(iouIssuanceAfter))
1072 {
1073 BEAST_EXPECT(
1074 iouIssuanceAfter->at(sfOutstandingAmount) ==
1075 iouSharesOutstandingBefore - 1);
1076 }
1077 auto const iouVaultAfter = env.le(iouBroker.vaultKeylet());
1078 if (BEAST_EXPECT(iouVaultAfter))
1079 {
1080 BEAST_EXPECT(iouVaultAfter->at(sfAssetsAvailable) == iouVaultAvailableBefore);
1081 }
1082 }
1083 }
1084 }
1085
1086 // Companion to the Vault_test dust-debit tests, which use a single
1087 // depositor so AssetsTotal == AssetsAvailable and both debitIsNonZeroDust
1088 // operands in VaultWithdraw::doApply trip together. Here a loan draws
1089 // almost the entire vault, leaving AssetsTotal (1e7) far above
1090 // AssetsAvailable (100): redeeming 1 share moves 1e-10 assets, which is
1091 // dust against AssetsTotal but representable against AssetsAvailable, so
1092 // the AssetsTotal operand alone carries the rejection.
1093 void
1095 {
1096 testcase("bug: VaultWithdraw dust debit vs AssetsTotal only");
1097
1098 using namespace jtx;
1099 using namespace loan;
1100
1101 bool const fixed = features[fixCleanup3_4_0];
1102
1103 Env env(*this, features);
1104
1105 Account const issuer{"issuer"};
1106 Account const lender{"lender"};
1107 Account const borrower{"borrower"};
1108
1109 env.fund(XRP(10'000'000), issuer, lender, borrower);
1110 env.close();
1111
1112 PrettyAsset const iouAsset = issuer[iouCurrency_];
1113 env(trust(lender, iouAsset(100'000'000)));
1114 env(trust(borrower, iouAsset(100'000'000)));
1115 env(pay(issuer, lender, iouAsset(20'000'000)));
1116 env.close();
1117
1118 // Scale 10 so 1 share is worth 1e-10 assets against the 1e7 pool.
1119 auto const broker = createVaultAndBroker(
1120 env,
1121 iouAsset,
1122 lender,
1123 {
1124 .vaultDeposit = 10'000'000,
1125 .debtMax = 10'000'000,
1126 .coverDeposit = 1'000'000,
1127 .vaultScale = 10,
1128 });
1129
1130 // Draw all but 100 units: AssetsAvailable drops to 100 while
1131 // AssetsTotal stays at 1e7 (the loan is still an asset of the vault).
1132 env(set(borrower, broker.brokerID, Number{9'999'900}),
1133 Sig(sfCounterpartySignature, lender),
1134 kPaymentTotal(2),
1135 kPaymentInterval(600),
1136 Fee(env.current()->fees().base * 2),
1137 Ter(tesSUCCESS));
1138 env.close();
1139
1140 auto const vaultSle = env.le(broker.vaultKeylet());
1141 if (!BEAST_EXPECT(vaultSle))
1142 return;
1143 BEAST_EXPECT(vaultSle->at(sfAssetsTotal) == Number{10'000'000});
1144 BEAST_EXPECT(vaultSle->at(sfAssetsAvailable) == Number{100});
1145
1146 // 1 share redeems 1e7 * 1 / 1e17 = 1e-10 assets. Subtracting that
1147 // from AssetsTotal needs 18 significant digits and canonicalizes
1148 // straight back to 1e7 (no-op), while AssetsAvailable would become
1149 // 99.9999999999 — perfectly representable.
1150 auto const shareAsset = vaultSle->at(sfShareMPTID);
1151 STAmount const oneShare{MPTIssue{shareAsset}, Number(1)};
1152
1153 Vault const v{env};
1154 env(v.withdraw({.depositor = lender, .id = broker.vaultKeylet().key, .amount = oneShare}),
1156 env.close();
1157 }
1158
1159 // A near-zero interest rate on a 100 USD loan
1160 // produces total interest of ~6 units at loanScale -9. Numerical error
1161 // in the amortization formula pushes the theoretical principal above
1162 // the theoretical value, producing a negative theoretical interest.
1163 // The payment delta then exceeds the actual outstanding interest,
1164 // violating XRPL_ASSERT_PARTS in computePaymentComponents.
1165 void
1167 {
1168 testcase("bug: LoanPay asserts 'interest due delta' on near-zero rate");
1169
1170 using namespace jtx;
1171 using namespace std::chrono_literals;
1172 Env env(*this, all_);
1173
1174 Account const issuer{"issuer"};
1175 Account const lender{"lender"};
1176 Account const borrower{"borrower"};
1177
1178 env.fund(XRP(1'000'000), issuer, lender, borrower);
1179 env.close();
1180 env(fset(issuer, asfDefaultRipple));
1181 env.close();
1182
1183 PrettyAsset const iouAsset = issuer["USD"];
1184 env(trust(lender, iouAsset(1'000'000'000)));
1185 env(trust(borrower, iouAsset(1'000'000'000)));
1186 env(pay(issuer, lender, iouAsset(5'000'000)));
1187 env(pay(issuer, borrower, iouAsset(5'000'000)));
1188 env.close();
1189
1190 BrokerParameters const brokerParams{
1191 .vaultDeposit = 1'000'000,
1192 .debtMax = 1'000'000,
1193 .coverRateMin = TenthBips32{0},
1194 .coverDeposit = 0,
1195 .managementFeeRate = TenthBips16{0},
1196 .coverRateLiquidation = TenthBips32{0},
1197 };
1198
1199 BrokerInfo const broker{createVaultAndBroker(env, iouAsset, lender, brokerParams)};
1200
1201 using namespace loan;
1202
1203 auto const loanSetFee = Fee(env.current()->fees().base * 2);
1204 Number const principalRequest{100};
1205
1206 auto createJson = env.json(
1207 set(borrower, broker.brokerID, principalRequest),
1208 Fee(loanSetFee),
1209 Json(sfCounterpartySignature, json::ValueType::Object));
1210
1211 createJson["InterestRate"] = 1; // minimum non-zero rate
1212 createJson["PaymentTotal"] = 3;
1213 createJson["PaymentInterval"] = 600;
1214
1215 auto const keylet = nextLoanKeylet(env, broker);
1216
1217 createJson = env.json(createJson, Sig(sfCounterpartySignature, lender));
1218 env(createJson, Ter(tesSUCCESS));
1219 env.close();
1220
1221 // For principal=100, n=3 the amortization schedule produces a
1222 // periodic payment ≈ 33.33 USD. We pay 35 USD, which is more than
1223 // one period's worth — enough for the LoanPay path to enter
1224 // computePaymentComponents and reach the assertion that fires
1225 // when the bug is present. With the fix, the tx applies cleanly.
1226 env(pay(borrower, keylet.key, iouAsset(35)), Ter(tesSUCCESS));
1227 env.close();
1228 }
1229
1230 void
1232 {
1233 for (auto const flags : {0u, tfLoanOverpayment})
1242 // all_ excludes V1.1; amendmentCombinations never pairs it with the
1243 // sticking schedule. Run that combination explicitly.
1244 testIntegerScalePrincipalSticks(all_ | featureLendingProtocolV1_1);
1245 }
1246
1247 // Tests run under each entry in amendmentCombinations().
1248 void
1250 {
1251 testDustManipulation(features);
1254#if LOAN_TODO
1255 testLoanCoverMinimumRoundingExploit(features);
1256#endif
1257 }
1258
1259public:
1260 void
1261 run() override
1262 {
1264 for (auto const& features : jtx::amendmentCombinations(
1265 {fixCleanup3_1_3, fixCleanup3_2_0, featureMPTokensV2}, all_))
1266 runAmendmentSensitive(features);
1267 }
1268};
1269
1270BEAST_DEFINE_TESTSUITE(LoanRounding, tx, xrpl);
1271
1272} // namespace xrpl::test
LogOs< char > log
Logging output stream.
Definition suite.h:150
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
void testYieldTheftRounding(std::uint32_t flags)
void testDustManipulation(FeatureBitset features)
void testRoundingAllowsUndercoverage(FeatureBitset features)
void runAmendmentSensitive(FeatureBitset features)
void testIntegerScalePrincipalSticks(FeatureBitset features)
void testBugVaultWithdrawDustVsAssetsTotal(FeatureBitset features)
void testBugVaultWithdrawFixedSharesRoundsToZero(FeatureBitset features)
void run() override
Runs the suite.
Shared base for the Loan*_test family under src/test/app/lending/.
FeatureBitset const all_
void advancePastDueDate(jtx::Env &env, Keylet const &loanKeylet)
BrokerInfo createVaultAndBroker(jtx::Env &env, jtx::PrettyAsset const &asset, jtx::Account const &lender, BrokerParameters const &params=BrokerParameters::defaults())
LoanState getCurrentState(jtx::Env const &env, BrokerInfo const &broker, Keylet const &loanKeylet)
Get the state without checking anything.
Keylet nextLoanKeylet(jtx::Env const &env, BrokerInfo const &broker)
static jtx::PrettyAsset createFundedRippleIouAsset(jtx::Env &env, jtx::Account const &issuer, jtx::Account const &lender, jtx::Account const &borrower, Number const &lenderPay=1 '000 '000, Number const &borrowerPay=1 '000 '000)
std::string const iouCurrency_
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
AccountID id() const
Returns the Account ID.
A transaction testing environment.
Definition Env.h:161
bool close(NetClock::time_point closeTime, std::optional< std::chrono::milliseconds > consensusDelay=std::nullopt)
Close and advance the ledger.
Definition Env.cpp:133
TER ter() const
Return the TER for the last JTx.
Definition Env.h:844
json::Value json(JsonValue &&jv, FN const &... fN)
Create JSON from parameters.
Definition Env.h:752
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
PrettyAmount balance(Account const &account) const
Returns the XRP balance on an account.
Definition Env.cpp:201
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Definition Env.h:377
Set the fee on a JTx.
Definition fee.h:20
Inject raw JSON.
Definition jtx_json.h:16
Test helper for creating, mutating, and asserting MPT and confidential MPT ledger state.
Definition mpt.h:512
MPTID const & issuanceID() const
Definition mpt.h:777
void create(MPTCreate const &arg=MPTCreate{}, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:346
void authorize(MPTAuthorize const &arg=MPTAuthorize{}, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:459
Set the regular signature on a JTx.
Definition sig.h:19
Set the expected result code for a JTx The test will fail if the code doesn't match.
Definition ter.h:18
Set the flags on a JTx.
Definition txflags.h:14
T endl(T... args)
T make_tuple(T... args)
constexpr Zero kZero
Definition Zero.h:30
@ Object
object value (collection of name/value pairs).
Definition json_value.h:33
ExtendedPaymentComponents computeOverpaymentComponents(Rules const &rules, Asset const &asset, int32_t const loanScale, Number const &overpayment, TenthBips32 const overpaymentInterestRate, TenthBips32 const overpaymentFeeRate, TenthBips16 const managementFeeRate)
PaymentComponents computePaymentComponents(Rules const &rules, Asset const &asset, std::int32_t scale, Number const &totalValueOutstanding, Number const &principalOutstanding, Number const &managementFeeOutstanding, Number const &periodicPayment, Number const &periodicRate, std::uint32_t paymentRemaining, TenthBips16 managementFeeRate)
Keylet computation functions.
Definition Indexes.h:39
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 mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:547
Keylet loanBroker(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:571
Keylet loan(UInt256 const &loanBrokerID, SeqProxy const &loanSeq) noexcept
Definition Indexes.cpp:577
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
json::Value coverClawback(AccountID const &account, std::uint32_t flags)
json::Value manage(AccountID const &account, UInt256 const &loanID, std::uint32_t flags)
json::Value set(AccountID const &account, UInt256 const &loanBrokerID, Number principalRequested, std::uint32_t flags)
json::Value pay(AccountID const &account, UInt256 const &loanID, STAmount const &amount, std::uint32_t flags)
json::Value pay(AccountID const &account, AccountID const &to, AnyAmount amount)
Create a payment.
Definition pay.cpp:14
std::vector< FeatureBitset > amendmentCombinations(std::initializer_list< UInt256 > features, FeatureBitset seed)
Returns all 2^N permutations of a seed FeatureBitset with each subset of the given features excluded.
Definition Env.h:123
XrpT const XRP
Converts to XRP Issue or STAmount.
Definition amount.cpp:92
json::Value trust(Account const &account, STAmount const &amount, std::uint32_t flags)
Modify a trust line.
Definition trust.cpp:18
json::Value fset(Account const &account, std::uint32_t on, std::uint32_t off=0)
Add and/or remove flag.
Definition flags.cpp:15
static MPTInit const kMptInitNoFund
Definition mpt.h:201
BEAST_DEFINE_TESTSUITE(AMMClawback, app, xrpl)
STTx createTx(bool disabling, LedgerIndex seq, PublicKey const &txKey)
Create ttUNL_MODIFY Tx.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
bool set(T &target, std::string const &name, Section const &section)
Set a value from a configuration Section If the named value is not found or doesn't parse as a T,...
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Definition Issue.h:108
Number loanPeriodicRate(TenthBips32 interestRate, std::uint32_t paymentInterval)
constexpr T tenthBipsOfValue(T value, TenthBips< TBips > bips)
Definition Protocol.h:139
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
static FunctionType fixed(Keylet const &keylet)
TenthBips< std::uint16_t > TenthBips16
Definition Units.h:453
boost::outcome_v2::result< T, std::error_code > Result
Definition b58_utils.h:19
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
STAmount roundToScale(STAmount const &value, std::int32_t scale, Number::RoundingMode rounding=Number::getround())
Round an arbitrary precision Amount to the precision of an STAmount that has a given exponent.
@ tecINVARIANT_FAILED
Definition TER.h:324
@ tecINSUFFICIENT_FUNDS
Definition TER.h:336
@ tecPRECISION_LOSS
Definition TER.h:374
LoanState constructLoanState(Number const &totalValueOutstanding, Number const &principalOutstanding, Number const &managementFeeOutstanding)
@ tesSUCCESS
Definition TER.h:253
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:20
UInt256 key
Definition Keylet.h:21
STAmount const & value() const
static json::Value withdraw(WithdrawArgs const &args)
Definition vault.cpp:101
T to_string(T... args)