rippled
Loading...
Searching...
No Matches
TheoreticalQuality_test.cpp
1#include <test/jtx.h>
2#include <test/jtx/PathSet.h>
3
4#include <xrpld/app/paths/AMMContext.h>
5#include <xrpld/app/paths/Flow.h>
6#include <xrpld/app/paths/detail/Steps.h>
7#include <xrpld/app/paths/detail/StrandFlow.h>
8
9#include <xrpl/basics/contract.h>
10#include <xrpl/basics/random.h>
11#include <xrpl/ledger/PaymentSandbox.h>
12#include <xrpl/protocol/Feature.h>
13#include <xrpl/protocol/jss.h>
14
15namespace xrpl {
16namespace test {
17
19{
22
25
27
29 : srcAccount{*parseBase58<AccountID>(jv[jss::Account].asString())}
30 , dstAccount{*parseBase58<AccountID>(jv[jss::Destination].asString())}
31 , dstAmt{amountFromJson(sfAmount, jv[jss::Amount])}
32 {
33 if (jv.isMember(jss::SendMax))
34 sendMax = amountFromJson(sfSendMax, jv[jss::SendMax]);
35
36 if (jv.isMember(jss::Paths))
37 {
38 // paths is an array of arrays
39 // each leaf element will be of the form
40 for (auto const& path : jv[jss::Paths])
41 {
42 STPath p;
43 for (auto const& pe : path)
44 {
45 if (pe.isMember(jss::account))
46 {
47 assert(!pe.isMember(jss::currency) && !pe.isMember(jss::issuer));
49 *parseBase58<AccountID>(pe[jss::account].asString()), std::nullopt, std::nullopt);
50 }
51 else if (pe.isMember(jss::currency) && pe.isMember(jss::issuer))
52 {
53 auto const currency = to_currency(pe[jss::currency].asString());
55 if (!isXRP(currency))
56 issuer = *parseBase58<AccountID>(pe[jss::issuer].asString());
57 else
58 assert(isXRP(*parseBase58<AccountID>(pe[jss::issuer].asString())));
59 p.emplace_back(std::nullopt, currency, issuer);
60 }
61 else
62 {
63 assert(0);
64 }
65 }
66 paths.emplace_back(std::move(p));
67 }
68 }
69 }
70};
71
72// Class to randomly set an account's transfer rate, quality in, quality out,
73// and initial balance
75{
78 // Balance to set if an account redeems into another account. Otherwise
79 // the balance will be zero. Since we are testing quality measures, the
80 // payment should not use multiple qualities, so the initialBalance
81 // needs to be able to handle an entire payment (otherwise an account
82 // will go from redeeming to issuing and the fees/qualities can change)
84
85 // probability of changing a value from its default
86 constexpr static double probChangeDefault_ = 0.75;
87 // probability that an account redeems into another account
88 constexpr static double probRedeem_ = 0.5;
92
93 bool
95 {
97 };
98
99 void
101 {
102 if (!shouldSet())
103 return;
104
105 auto const percent = qualityPercentDist_(engine_);
106 auto const& field = qDir == QualityDirection::in ? sfQualityIn : sfQualityOut;
107 auto const value = static_cast<std::uint32_t>((percent / 100) * QUALITY_ONE);
108 jv[field.jsonName] = value;
109 };
110
111 // Setup the trust amounts and in/out qualities (but not the balances)
112 void
113 setupTrustLine(jtx::Env& env, jtx::Account const& acc, jtx::Account const& peer, Currency const& currency)
114 {
115 using namespace jtx;
116 IOU const iou{peer, currency};
117 Json::Value jv = trust(acc, iou(trustAmount_));
120 env(jv);
121 env.close();
122 };
123
124public:
125 explicit RandomAccountParams(std::uint32_t trustAmount = 100, std::uint32_t initialBalance = 50)
126 // Use a deterministic seed so the unit tests run in a reproducible way
127 : engine_{1977u}, trustAmount_{trustAmount}, initialBalance_{initialBalance} {};
128
129 void
131 {
132 if (shouldSet())
133 env(rate(acc, transferRateDist_(engine_)));
134 }
135
136 // Set the initial balance, taking into account the qualities
137 void
138 setInitialBalance(jtx::Env& env, jtx::Account const& acc, jtx::Account const& peer, Currency const& currency)
139 {
140 using namespace jtx;
141 IOU const iou{acc, currency};
142 // This payment sets the acc's balance to `initialBalance`.
143 // Since input qualities complicate this payment, use `sendMax` with
144 // `initialBalance` to make sure the balance is set correctly.
145 env(pay(peer, acc, iou(trustAmount_)), sendmax(iou(initialBalance_)), txflags(tfPartialPayment));
146 env.close();
147 }
148
149 void
150 maybeSetInitialBalance(jtx::Env& env, jtx::Account const& acc, jtx::Account const& peer, Currency const& currency)
151 {
152 using namespace jtx;
154 return;
155 setInitialBalance(env, acc, peer, currency);
156 }
157
158 // Setup the trust amounts and in/out qualities (but not the balances) on
159 // both sides of the trust line
160 void
161 setupTrustLines(jtx::Env& env, jtx::Account const& acc1, jtx::Account const& acc2, Currency const& currency)
162 {
163 setupTrustLine(env, acc1, acc2, currency);
164 setupTrustLine(env, acc2, acc1, currency);
165 };
166};
167
169{
170 static std::string
171 prettyQuality(Quality const& q)
172 {
174 STAmount rate = q.rate();
175 sstr << rate << " (" << q << ")";
176 return sstr.str();
177 };
178
179 template <class Stream>
180 static void
181 logStrand(Stream& stream, Strand const& strand)
182 {
183 stream << "Strand:\n";
184 for (auto const& step : strand)
185 stream << "\n" << *step;
186 stream << "\n\n";
187 };
188
189 void
191 RippleCalcTestParams const& rcp,
193 std::optional<Quality> const& expectedQ = {})
194 {
195 PaymentSandbox sb(closed.get(), tapNONE);
196 AMMContext ammContext(rcp.srcAccount, false);
197
198 auto const sendMaxIssue = [&rcp]() -> std::optional<Issue> {
199 if (rcp.sendMax)
200 return rcp.sendMax->issue();
201 return std::nullopt;
202 }();
203
205
206 auto sr = toStrands(
207 sb,
208 rcp.srcAccount,
209 rcp.dstAccount,
210 rcp.dstAmt.issue(),
211 /*limitQuality*/ std::nullopt,
212 sendMaxIssue,
213 rcp.paths,
214 /*defaultPaths*/ rcp.paths.empty(),
215 false,
217 ammContext,
219 dummyJ);
220
221 BEAST_EXPECT(sr.first == tesSUCCESS);
222
223 if (sr.first != tesSUCCESS)
224 return;
225
226 // Due to the floating point calculations, theoretical and actual
227 // qualities are not expected to always be exactly equal. However, they
228 // should always be very close. This function checks that that two
229 // qualities are "close enough".
230 auto compareClose = [](Quality const& q1, Quality const& q2) {
231 // relative diff is fabs(a-b)/min(a,b)
232 // can't get access to internal value. Use the rate
233 constexpr double tolerance = 0.0000001;
234 return relativeDistance(q1, q2) <= tolerance;
235 };
236
237 for (auto const& strand : sr.second)
238 {
239 Quality const theoreticalQ = *qualityUpperBound(sb, strand);
240 auto const f = flow<IOUAmount, IOUAmount>(sb, strand, IOUAmount(10, 0), IOUAmount(5, 0), dummyJ);
241 BEAST_EXPECT(f.success);
242 Quality const actualQ(f.out, f.in);
243 if (actualQ != theoreticalQ && !compareClose(actualQ, theoreticalQ))
244 {
245 BEAST_EXPECT(actualQ == theoreticalQ); // get the failure
246 log << "\nActual != Theoretical\n";
247 log << "\nTQ: " << prettyQuality(theoreticalQ) << "\n";
248 log << "AQ: " << prettyQuality(actualQ) << "\n";
249 logStrand(log, strand);
250 }
251 if (expectedQ && expectedQ != theoreticalQ && !compareClose(*expectedQ, theoreticalQ))
252 {
253 BEAST_EXPECT(expectedQ == theoreticalQ); // get the failure
254 log << "\nExpected != Theoretical\n";
255 log << "\nTQ: " << prettyQuality(theoreticalQ) << "\n";
256 log << "EQ: " << prettyQuality(*expectedQ) << "\n";
257 logStrand(log, strand);
258 }
259 };
260 }
261
262public:
263 void
264 testDirectStep(std::optional<int> const& reqNumIterations)
265 {
266 testcase("Direct Step");
267
268 // clang-format off
269
270 // Set up a payment through four accounts: alice -> bob -> carol -> dan
271 // For each relevant trust line on the path, there are three things that can vary:
272 // 1) input quality
273 // 2) output quality
274 // 3) debt direction
275 // For each account, there is one thing that can vary:
276 // 1) transfer rate
277
278 // clang-format on
279
280 using namespace jtx;
281
282 auto const currency = to_currency("USD");
283
284 constexpr std::size_t const numAccounts = 4;
285
286 // There are three relevant trust lines: `alice->bob`, `bob->carol`, and
287 // `carol->dan`. There are four accounts. If we count the number of
288 // combinations of parameters where a parameter is changed from its
289 // default value, there are
290 // 2^(num_trust_lines*num_trust_qualities+numAccounts) combinations of
291 // values to test, or 2^13 combinations. Use this value to set the
292 // number of iterations. Note however that many of these parameter
293 // combinations run essentially the same test. For example, changing the
294 // quality values for bob and carol test almost the same thing.
295 // Similarly, changing the transfer rates on bob and carol test almost
296 // the same thing. Instead of systematically running these 8k tests,
297 // randomly sample the test space.
298 int const numTestIterations = reqNumIterations.value_or(250);
299
300 constexpr std::uint32_t paymentAmount = 1;
301
302 // Class to randomly set account transfer rates, qualities, and other
303 // params.
304 RandomAccountParams rndAccParams;
305
306 // Tests are sped up by a factor of 2 if a new environment isn't created
307 // on every iteration.
308 Env env(*this, testable_amendments());
309 for (int i = 0; i < numTestIterations; ++i)
310 {
311 auto const iterAsStr = std::to_string(i);
312 // New set of accounts on every iteration so the environment doesn't
313 // need to be recreated (2x speedup)
314 auto const alice = Account("alice" + iterAsStr);
315 auto const bob = Account("bob" + iterAsStr);
316 auto const carol = Account("carol" + iterAsStr);
317 auto const dan = Account("dan" + iterAsStr);
318 std::array<Account, numAccounts> accounts{{alice, bob, carol, dan}};
319 static_assert(numAccounts == 4, "Path is only correct for four accounts");
320 path const accountsPath(accounts[1], accounts[2]);
321 env.fund(XRP(10000), alice, bob, carol, dan);
322 env.close();
323
324 // iterate through all pairs of accounts, randomly set the transfer
325 // rate, qIn, qOut, and if the account issues or redeems
326 for (std::size_t ii = 0; ii < numAccounts; ++ii)
327 {
328 rndAccParams.maybeSetTransferRate(env, accounts[ii]);
329 // The payment is from:
330 // account[0] -> account[1] -> account[2] -> account[3]
331 // set the trust lines and initial balances for each pair of
332 // neighboring accounts
333 std::size_t const j = ii + 1;
334 if (j == numAccounts)
335 continue;
336
337 rndAccParams.setupTrustLines(env, accounts[ii], accounts[j], currency);
338 rndAccParams.maybeSetInitialBalance(env, accounts[ii], accounts[j], currency);
339 }
340
341 // Accounts are set up, make the payment
342 IOU const iou{accounts.back(), currency};
344 pay(accounts.front(), accounts.back(), iou(paymentAmount)), accountsPath, txflags(tfNoRippleDirect))};
345
346 testCase(rcp, env.closed());
347 }
348 }
349
350 void
351 testBookStep(std::optional<int> const& reqNumIterations)
352 {
353 testcase("Book Step");
354 using namespace jtx;
355
356 // clang-format off
357
358 // Setup a payment through an offer: alice (USD/bob) -> bob -> (USD/bob)|(EUR/carol) -> carol -> dan
359 // For each relevant trust line, vary input quality, output quality, debt direction.
360 // For each account, vary transfer rate.
361 // The USD/bob|EUR/carol offer owner is "Oscar"
362
363 // clang-format on
364
365 int const numTestIterations = reqNumIterations.value_or(100);
366
367 constexpr std::uint32_t paymentAmount = 1;
368
369 Currency const eurCurrency = to_currency("EUR");
370 Currency const usdCurrency = to_currency("USD");
371
372 // Class to randomly set account transfer rates, qualities, and other
373 // params.
374 RandomAccountParams rndAccParams;
375
376 // Speed up tests by creating the environment outside the loop
377 // (factor of 2 speedup on the DirectStep tests)
378 Env env(*this, testable_amendments());
379 for (int i = 0; i < numTestIterations; ++i)
380 {
381 auto const iterAsStr = std::to_string(i);
382 auto const alice = Account("alice" + iterAsStr);
383 auto const bob = Account("bob" + iterAsStr);
384 auto const carol = Account("carol" + iterAsStr);
385 auto const dan = Account("dan" + iterAsStr);
386 auto const oscar = Account("oscar" + iterAsStr); // offer owner
387 auto const USDB = bob["USD"];
388 auto const EURC = carol["EUR"];
389 constexpr std::size_t const numAccounts = 5;
390 std::array<Account, numAccounts> accounts{{alice, bob, carol, dan, oscar}};
391
392 // sendmax should be in USDB and delivered amount should be in EURC
393 // normalized path should be:
394 // alice -> bob -> (USD/bob)|(EUR/carol) -> carol -> dan
395 path const bookPath(~EURC);
396
397 env.fund(XRP(10000), alice, bob, carol, dan, oscar);
398 env.close();
399
400 for (auto const& acc : accounts)
401 rndAccParams.maybeSetTransferRate(env, acc);
402
403 for (auto const& currency : {usdCurrency, eurCurrency})
404 {
405 rndAccParams.setupTrustLines(env, alice, bob, currency); // first step in payment
406 rndAccParams.setupTrustLines(env, carol, dan, currency); // last step in payment
407 rndAccParams.setupTrustLines(env, oscar, bob, currency); // offer owner
408 rndAccParams.setupTrustLines(env, oscar, carol, currency); // offer owner
409 }
410
411 rndAccParams.maybeSetInitialBalance(env, alice, bob, usdCurrency);
412 rndAccParams.maybeSetInitialBalance(env, carol, dan, eurCurrency);
413 rndAccParams.setInitialBalance(env, oscar, bob, usdCurrency);
414 rndAccParams.setInitialBalance(env, oscar, carol, eurCurrency);
415
416 env(offer(oscar, USDB(50), EURC(50)));
417 env.close();
418
419 // Accounts are set up, make the payment
420 IOU const srcIOU{bob, usdCurrency};
421 IOU const dstIOU{carol, eurCurrency};
423 pay(alice, dan, dstIOU(paymentAmount)),
424 sendmax(srcIOU(100 * paymentAmount)),
425 bookPath,
427
428 testCase(rcp, env.closed());
429 }
430 }
431
432 void
434 {
435 testcase("Relative quality distance");
436
437 auto toQuality = [](std::uint64_t mantissa, int exponent = 0) -> Quality {
438 // The only way to construct a Quality from an STAmount is to take
439 // their ratio. Set the denominator STAmount to `one` to easily
440 // create a quality from a single amount
441 STAmount const one{noIssue(), 1};
442 STAmount const v{noIssue(), mantissa, exponent};
443 return Quality{one, v};
444 };
445
446 BEAST_EXPECT(relativeDistance(toQuality(100), toQuality(100)) == 0);
447 BEAST_EXPECT(relativeDistance(toQuality(100), toQuality(100, 1)) == 9);
448 BEAST_EXPECT(relativeDistance(toQuality(100), toQuality(110)) == .1);
449 BEAST_EXPECT(relativeDistance(toQuality(100, 90), toQuality(110, 90)) == .1);
450 BEAST_EXPECT(relativeDistance(toQuality(100, 90), toQuality(110, 91)) == 10);
451 BEAST_EXPECT(relativeDistance(toQuality(100, 0), toQuality(100, 90)) == 1e90);
452 // Make the mantissa in the smaller value bigger than the mantissa in
453 // the larger value. Instead of checking the exact result, we check that
454 // it's large. If the values did not compare correctly in
455 // `relativeDistance`, then the returned value would be negative.
456 BEAST_EXPECT(relativeDistance(toQuality(102, 0), toQuality(101, 90)) >= 1e89);
457 }
458
459 void
460 run() override
461 {
462 // Use the command line argument `--unittest-arg=500 ` to change the
463 // number of iterations to 500
464 auto const numIterations = [s = arg()]() -> std::optional<int> {
465 if (s.empty())
466 return std::nullopt;
467 try
468 {
469 std::size_t pos;
470 auto const r = stoi(s, &pos);
471 if (pos != s.size())
472 return std::nullopt;
473 return r;
474 }
475 catch (...)
476 {
477 return std::nullopt;
478 }
479 }();
481 testDirectStep(numIterations);
482 testBookStep(numIterations);
483 }
484};
485
486BEAST_DEFINE_TESTSUITE_PRIO(TheoreticalQuality, app, xrpl, 3);
487
488} // namespace test
489} // namespace xrpl
Represents a JSON value.
Definition json_value.h:130
bool isMember(char const *key) const
Return true if the object has a member named key.
A generic endpoint for log messages.
Definition Journal.h:40
static Sink & getNullSink()
Returns a Sink which does nothing.
A testsuite class.
Definition suite.h:51
log_os< char > log
Logging output stream.
Definition suite.h:144
testcase_t testcase
Memberspace for declaring test cases.
Definition suite.h:147
std::string const & arg() const
Return the argument associated with the runner.
Definition suite.h:276
Maintains AMM info per overall payment engine execution and individual iteration.
Definition AMMContext.h:16
A wrapper which makes credits unavailable to balances.
Issue const & issue() const
Definition STAmount.h:454
bool empty() const
Definition STPathSet.h:467
void emplace_back(Args &&... args)
Definition STPathSet.h:376
void setupTrustLine(jtx::Env &env, jtx::Account const &acc, jtx::Account const &peer, Currency const &currency)
std::uniform_real_distribution qualityPercentDist_
void setupTrustLines(jtx::Env &env, jtx::Account const &acc1, jtx::Account const &acc2, Currency const &currency)
void setInitialBalance(jtx::Env &env, jtx::Account const &acc, jtx::Account const &peer, Currency const &currency)
RandomAccountParams(std::uint32_t trustAmount=100, std::uint32_t initialBalance=50)
std::uniform_real_distribution transferRateDist_
void maybeInsertQuality(Json::Value &jv, QualityDirection qDir)
void maybeSetInitialBalance(jtx::Env &env, jtx::Account const &acc, jtx::Account const &peer, Currency const &currency)
void maybeSetTransferRate(jtx::Env &env, jtx::Account const &acc)
std::uniform_real_distribution zeroOneDist_
static std::string prettyQuality(Quality const &q)
void testDirectStep(std::optional< int > const &reqNumIterations)
void testCase(RippleCalcTestParams const &rcp, std::shared_ptr< ReadView const > closed, std::optional< Quality > const &expectedQ={})
void testBookStep(std::optional< int > const &reqNumIterations)
static void logStrand(Stream &stream, Strand const &strand)
Immutable cryptographic account descriptor.
Definition Account.h:19
A transaction testing environment.
Definition Env.h:119
bool close(NetClock::time_point closeTime, std::optional< std::chrono::milliseconds > consensusDelay=std::nullopt)
Close and advance the ledger.
Definition Env.cpp:98
std::shared_ptr< ReadView const > closed()
Returns the last closed ledger.
Definition Env.cpp:92
void fund(bool setDefaultRipple, STAmount const &amount, Account const &account)
Definition Env.cpp:261
Json::Value json(JsonValue &&jv, FN const &... fN)
Create JSON from parameters.
Definition Env.h:520
Converts to IOU Issue or STAmount.
Add a path.
Definition paths.h:37
Set Paths, SendMax on a JTx.
Definition paths.h:15
Sets the SendMax on a JTx.
Definition sendmax.h:13
Set the flags on a JTx.
Definition txflags.h:11
T get(T... args)
T is_same_v
Json::Value trust(Account const &account, STAmount const &amount, std::uint32_t flags)
Modify a trust line.
Definition trust.cpp:13
Json::Value rate(Account const &account, double multiplier)
Set a transfer rate.
Definition rate.cpp:13
XRP_t const XRP
Converts to XRP Issue or STAmount.
Definition amount.cpp:90
Json::Value pay(AccountID const &account, AccountID const &to, AnyAmount amount)
Create a payment.
Definition pay.cpp:11
FeatureBitset testable_amendments()
Definition Env.h:76
Json::Value offer(Account const &account, STAmount const &takerPays, STAmount const &takerGets, std::uint32_t flags)
Create an offer.
Definition offer.cpp:10
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
bool isXRP(AccountID const &c)
Definition AccountID.h:70
std::optional< AccountID > parseBase58(std::string const &s)
Parse AccountID from checked, base58 string.
std::pair< TER, std::vector< Strand > > toStrands(ReadView const &view, AccountID const &src, AccountID const &dst, Issue const &deliver, std::optional< Quality > const &limitQuality, std::optional< Issue > const &sendMax, STPathSet const &paths, bool addDefaultPath, bool ownerPaysTransferFee, OfferCrossing offerCrossing, AMMContext &ammContext, std::optional< uint256 > const &domainID, beast::Journal j)
Create a Strand for each specified path (including the default path, if indicated)
Definition PaySteps.cpp:398
STAmount amountFromJson(SField const &name, Json::Value const &v)
Definition STAmount.cpp:948
QualityDirection
Definition Steps.h:23
constexpr std::uint32_t tfNoRippleDirect
Definition TxFlags.h:87
@ tapNONE
Definition ApplyView.h:11
Issue const & noIssue()
Returns an asset specifier that represents no account and currency.
Definition Issue.h:105
constexpr std::uint32_t tfPartialPayment
Definition TxFlags.h:88
@ no
Definition Steps.h:25
bool to_currency(Currency &, std::string const &)
Tries to convert a string to a Currency, returns true on success.
Definition UintTypes.cpp:62
@ tesSUCCESS
Definition TER.h:225
T str(T... args)
T to_string(T... args)
T value_or(T... args)