xrpld
Loading...
Searching...
No Matches
BookChanges_test.cpp
1#include <test/jtx/Account.h>
2#include <test/jtx/Env.h>
3#include <test/jtx/WSClient.h>
4#include <test/jtx/amount.h>
5#include <test/jtx/domain.h>
6#include <test/jtx/offer.h>
7#include <test/jtx/paths.h>
8#include <test/jtx/pay.h>
9#include <test/jtx/permissioned_dex.h>
10#include <test/jtx/sendmax.h>
11
12#include <xrpld/rpc/BookChanges.h>
13
14#include <xrpl/basics/base_uint.h>
15#include <xrpl/basics/chrono.h>
16#include <xrpl/basics/contract.h>
17#include <xrpl/beast/hash/uhash.h>
18#include <xrpl/beast/unit_test/suite.h>
19#include <xrpl/json/json_value.h>
20#include <xrpl/json/to_string.h>
21#include <xrpl/ledger/Ledger.h>
22#include <xrpl/protocol/ErrorCodes.h>
23#include <xrpl/protocol/Feature.h>
24#include <xrpl/protocol/LedgerFormats.h>
25#include <xrpl/protocol/SField.h>
26#include <xrpl/protocol/STArray.h>
27#include <xrpl/protocol/STObject.h>
28#include <xrpl/protocol/STTx.h>
29#include <xrpl/protocol/Serializer.h>
30#include <xrpl/protocol/TxFormats.h>
31#include <xrpl/protocol/jss.h>
32
33#include <cstddef>
34#include <cstdint>
35#include <memory>
36#include <stdexcept>
37#include <string>
38#include <unordered_set>
39#include <utility>
40#include <vector>
41
42namespace xrpl::test {
43
45{
46public:
47 void
49 {
50 testcase("Specify well-known strings as ledger input");
51 jtx::Env env(*this);
52 json::Value params, resp;
53
54 // As per convention in XRPL, ledgers can be specified with strings
55 // "closed", "validated" or "current"
56 params["ledger"] = "validated";
57 resp = env.rpc("json", "book_changes", to_string(params));
58 BEAST_EXPECT(!resp[jss::result].isMember(jss::error));
59 BEAST_EXPECT(resp[jss::result][jss::status] == "success");
60 BEAST_EXPECT(resp[jss::result][jss::validated] == true);
61
62 params["ledger"] = "current";
63 resp = env.rpc("json", "book_changes", to_string(params));
64 BEAST_EXPECT(!resp[jss::result].isMember(jss::error));
65 BEAST_EXPECT(resp[jss::result][jss::status] == "success");
66 BEAST_EXPECT(resp[jss::result][jss::validated] == false);
67
68 params["ledger"] = "closed";
69 resp = env.rpc("json", "book_changes", to_string(params));
70 BEAST_EXPECT(!resp[jss::result].isMember(jss::error));
71 BEAST_EXPECT(resp[jss::result][jss::status] == "success");
72
73 // In the unit-test framework, requesting for "closed" ledgers appears
74 // to yield "validated" ledgers. This is not new behavior. It is also
75 // observed in the unit tests for the LedgerHeader class.
76 BEAST_EXPECT(resp[jss::result][jss::validated] == true);
77
78 // non-conventional ledger input should throw an error
79 params["ledger"] = "non_conventional_ledger_input";
80 resp = env.rpc("json", "book_changes", to_string(params));
81 BEAST_EXPECT(resp[jss::result][jss::status] == "error");
82 BEAST_EXPECT(resp[jss::result][jss::error] == "invalidParams");
83 BEAST_EXPECT(resp[jss::result][jss::error_code] == RpcInvalidParams);
84 BEAST_EXPECT(
85 resp[jss::result][jss::error_message] ==
86 "Invalid field 'ledger', not string or number.");
87 }
88
89 void
91 {
93 "If ledger_hash or ledger_index is not specified, the behavior "
94 "must default to the `current` ledger");
95 jtx::Env env(*this);
96
97 // As per convention in XRPL, ledgers can be specified with strings
98 // "closed", "validated" or "current"
99 json::Value const resp = env.rpc("json", "book_changes", to_string(json::Value{}));
100 BEAST_EXPECT(!resp[jss::result].isMember(jss::error));
101 BEAST_EXPECT(resp[jss::result][jss::status] == "success");
102
103 // I dislike asserting the below statement, because its dependent on the
104 // unit-test framework BEAST_EXPECT(resp[jss::result][jss::ledger_index]
105 // == 3);
106 }
107
108 void
110 {
111 testcase("Domain Offer");
112 using namespace jtx;
113
114 FeatureBitset const all{
115 jtx::testableAmendments() | featurePermissionedDomains | featureCredentials |
116 featurePermissionedDEX,
117 };
118
119 Env env(*this, all);
120 PermissionedDEX const permDex(env);
121 auto const& [gw, domainOwner, alice, bob, carol, usd, domainID, credType] = permDex;
122
123 auto wsc = makeWSClient(env.app().config());
124
125 env(offer(alice, XRP(10), usd(10)), Domain(domainID));
126 env.close();
127
128 env(pay(bob, carol, usd(10)), Path(~usd), Sendmax(XRP(10)), Domain(domainID));
129 env.close();
130
131 std::string const txHash{
132 env.tx()->getJson(JsonOptions::Values::None)[jss::hash].asString(),
133 };
134
135 json::Value const txResult = env.rpc("tx", txHash)[jss::result];
136 auto const ledgerIndex = txResult[jss::ledger_index].asInt();
137
138 json::Value jvParams;
139 jvParams[jss::ledger_index] = ledgerIndex;
140
141 auto jv = wsc->invoke("book_changes", jvParams);
142 auto jrr = jv[jss::result];
143
144 BEAST_EXPECT(jrr[jss::changes].size() == 1);
145 BEAST_EXPECT(jrr[jss::changes][0u][jss::domain].asString() == to_string(domainID));
146 }
147
148 void
150 {
151 testcase("book_changes skips overflowing rate");
152 using namespace jtx;
153
154 Env env(*this);
155 Account const gw{"gw"};
156 Account const iouGw{"iouGw"};
157
158 auto const big = MPT{gw.id(), 1};
159 auto const usd = iouGw["USD"];
160
161 // Metadata for a partial MPT/IOU offer fill. The rate is
162 // divide(deltaGets, deltaPays): 1.8e18 MPT over `pays` IOU.
163 auto const test = [&](std::unordered_set<uint256, beast::Uhash<>> const& features,
164 STAmount const& pays,
165 std::size_t expectedChanges) {
166 STObject finalFields = STObject::makeInnerObject(sfFinalFields);
167 finalFields.setFieldU32(sfSequence, 1);
168 finalFields.setFieldAmount(sfTakerGets, big(1'800'000'000'000'000'000ull));
169 finalFields.setFieldAmount(sfTakerPays, pays);
170
171 STObject previousFields = STObject::makeInnerObject(sfPreviousFields);
172 previousFields.setFieldU32(sfSequence, 1);
173 previousFields.setFieldAmount(sfTakerGets, big(3'600'000'000'000'000'000ull));
174 previousFields.setFieldAmount(sfTakerPays, pays + pays);
175
176 STObject modifiedOffer{sfModifiedNode};
177 modifiedOffer.setFieldU16(sfLedgerEntryType, ltOFFER);
178 modifiedOffer.setFieldObject(sfFinalFields, finalFields);
179 modifiedOffer.setFieldObject(sfPreviousFields, previousFields);
180
181 STArray affectedNodes{sfAffectedNodes};
182 affectedNodes.pushBack(std::move(modifiedOffer));
183
184 auto const metadata = std::make_shared<STObject>(sfTransactionMetaData);
185 metadata->setFieldArray(sfAffectedNodes, affectedNodes);
186
187 auto const tx = std::make_shared<STTx const>(ttOFFER_CREATE, [](STObject&) {});
188
189 auto const ledger = std::make_shared<Ledger>(
190 2,
192 Rules{features},
193 env.current()->fees(),
194 env.app().getNodeFamily());
195
196 auto const txSerializer = std::make_shared<Serializer>();
197 tx->add(*txSerializer);
198
199 auto const metaSerializer = std::make_shared<Serializer>();
200 metadata->add(*metaSerializer);
201
202 ledger->rawTxInsert(UInt256{1}, txSerializer, metaSerializer);
203 BEAST_EXPECT(ledger->setImmutable());
204 ledger->setValidated();
205
206 try
207 {
208 auto const result =
210 BEAST_EXPECT(result[jss::type] == "bookChanges");
211 BEAST_EXPECT(result[jss::changes].size() == expectedChanges);
212 }
213 catch (std::overflow_error const&)
214 {
215 fail("Overflowing book-change rate shouldn't throw");
216 }
217 };
218
219 // Over the smallest IOU the rate is beyond the IOU exponent range:
220 // the change is skipped.
221 STAmount const tiny{usd.issue(), STAmount::kMinValue, STAmount::kMinOffset};
222 // Over 9 USD the rate is 2e17. divide() used to overflow here; with
223 // Number arithmetic for MPT operands it is reported.
224 STAmount const nine = usd(9);
225
226 for (auto const& features : {
229 })
230 {
231 test(features, tiny, 0);
232 test(features, nine, 1);
233 }
234 }
235
236 // Build a ledger whose transactions are OfferCreates carrying the supplied
237 // consumed-offer deltas, then run computeBookChanges over it. Each pair is
238 // (TakerGets, TakerPays) fully consumed off a resting offer.
239 static json::Value
241 {
242 auto const ledger = std::make_shared<Ledger>(
243 2,
246 env.current()->fees(),
247 env.app().getNodeFamily());
248
249 std::uint32_t seq = 0;
250 for (auto const& [gets, pays] : crossings)
251 {
252 ++seq;
253
254 STObject finalFields = STObject::makeInnerObject(sfFinalFields);
255 finalFields.setFieldU32(sfSequence, seq);
256 finalFields.setFieldAmount(sfTakerGets, STAmount{gets.asset()});
257 finalFields.setFieldAmount(sfTakerPays, STAmount{pays.asset()});
258
259 STObject previousFields = STObject::makeInnerObject(sfPreviousFields);
260 previousFields.setFieldU32(sfSequence, seq);
261 previousFields.setFieldAmount(sfTakerGets, gets);
262 previousFields.setFieldAmount(sfTakerPays, pays);
263
264 STObject modifiedOffer{sfModifiedNode};
265 modifiedOffer.setFieldU16(sfLedgerEntryType, ltOFFER);
266 modifiedOffer.setFieldObject(sfFinalFields, finalFields);
267 modifiedOffer.setFieldObject(sfPreviousFields, previousFields);
268
269 STArray affectedNodes{sfAffectedNodes};
270 affectedNodes.pushBack(std::move(modifiedOffer));
271
272 auto const metadata = std::make_shared<STObject>(sfTransactionMetaData);
273 metadata->setFieldArray(sfAffectedNodes, affectedNodes);
274
275 STTx const tx{ttOFFER_CREATE, [](STObject&) {}};
276
277 auto const txSerializer = std::make_shared<Serializer>();
278 tx.add(*txSerializer);
279
280 auto const metaSerializer = std::make_shared<Serializer>();
281 metadata->add(*metaSerializer);
282
283 ledger->rawTxInsert(UInt256{seq}, txSerializer, metaSerializer);
284 }
285
286 // Thrown rather than asserted because a refusal leaves the ledger unusable, and this
287 // helper is static, so BEAST_EXPECT is out of reach.
288 if (!ledger->setImmutable())
289 {
290 Throw<std::runtime_error>("bookChangesFor: ledger could not be made immutable");
291 }
292 ledger->setValidated();
293
295 }
296
297 void
299 {
300 testcase("book_changes skips overflowing volume");
301 using namespace jtx;
302
303 Env env(*this);
304
305 // Two crossings in one book, accumulated by the `+=` in the tally's
306 // else branch. The rate is 1 either way, so the divide() guard is not
307 // what is under test here.
308 //
309 // MPT: kMaxMpTokenAmount is INT64_MAX, so two halves sum past it. The
310 // add is a raw int64 add, which wraps to a negative amount rather than
311 // throwing, and canonicalize() only bounds the magnitude -- so before
312 // the fix this reported a negative volume.
313 {
314 auto const mptA = MPT{Account{"gw"}.id(), 1};
315 auto const mptB = MPT{Account{"gw"}.id(), 2};
316 auto const half = 5'000'000'000'000'000'000ull; // 2 * half > INT64_MAX
317
318 auto const result =
319 bookChangesFor(env, {{mptA(half), mptB(half)}, {mptA(half), mptB(half)}});
320
321 BEAST_EXPECT(result[jss::type] == "bookChanges");
322 if (BEAST_EXPECT(result[jss::changes].size() == 1))
323 {
324 auto const& change = result[jss::changes][0u];
325 // The second crossing is dropped, so the first one's volume
326 // stands. Above all it must not be negative.
327 BEAST_EXPECT(change[jss::volume_a].asString() == std::to_string(half));
328 BEAST_EXPECT(change[jss::volume_b].asString() == std::to_string(half));
329 }
330 }
331
332 // IOU: the addition throws std::overflow_error once the summed
333 // exponent passes IOUAmount::kMaxExponent. Before the fix that
334 // escaped computeBookChanges entirely.
335 {
336 Account const gwA{"gwA"};
337 Account const gwB{"gwB"};
338 // Mantissa in range, exponent at the maximum: two of these sum to
339 // one exponent past it.
340 STAmount const bigA{gwA["USD"].issue(), UINT64_C(9'000'000'000'000'000), 80};
341 STAmount const bigB{gwB["EUR"].issue(), UINT64_C(9'000'000'000'000'000), 80};
342
343 try
344 {
345 auto const result = bookChangesFor(env, {{bigA, bigB}, {bigA, bigB}});
346 BEAST_EXPECT(result[jss::type] == "bookChanges");
347 BEAST_EXPECT(result[jss::changes].size() == 1);
348 }
349 catch (std::overflow_error const&)
350 {
351 fail("Overflowing book-change volume shouldn't throw");
352 }
353 }
354 }
355
356 void
357 run() override
358 {
361
365 // Note: Other aspects of the book_changes rpc are fertile grounds
366 // for unit-testing purposes. It can be included in future work
367 }
368};
369
371
372} // namespace xrpl::test
A testsuite class.
Definition suite.h:52
void fail(String const &reason, char const *file, int line)
Record a failure.
Definition suite.h:554
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
Represents a JSON value.
Definition json_value.h:121
Int asInt() const
virtual Config & config()=0
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
Rules controlling protocol behavior.
Definition Rules.h:40
static constexpr int kMinOffset
Definition STAmount.h:61
static constexpr std::uint64_t kMinValue
Definition STAmount.h:65
void pushBack(STObject const &object)
Definition STArray.h:212
void setFieldU32(SField const &field, std::uint32_t)
Definition STObject.cpp:743
void setFieldAmount(SField const &field, STAmount const &)
Definition STObject.cpp:803
void add(Serializer &s) const override
Definition STObject.cpp:123
void setFieldU16(SField const &field, std::uint16_t)
Definition STObject.cpp:737
static STObject makeInnerObject(SField const &name)
Definition STObject.cpp:79
void setFieldObject(SField const &field, STObject const &v)
Definition STObject.cpp:839
virtual Family & getNodeFamily()=0
static json::Value bookChangesFor(jtx::Env &env, std::vector< std::pair< STAmount, STAmount > > const &crossings)
void run() override
Runs the suite.
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
json::Value rpc(unsigned apiVersion, std::unordered_map< std::string, std::string > const &headers, std::string const &cmd, Args &&... args)
Execute an RPC command.
Definition Env.h:1058
std::shared_ptr< STTx const > tx() const
Return the tx data for the last JTx.
Definition Env.cpp:560
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Definition Env.h:377
Converts to MPT Issue or STAmount.
Add a path.
Definition paths.h:47
Sets the SendMax on a JTx.
Definition sendmax.h:16
T make_shared(T... args)
The api_version numbers this server serves.
Definition ApiVersion.h:26
json::Value computeBookChanges(std::shared_ptr< L const > const &lpAccepted)
Definition BookChanges.h:41
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 offer(Account const &account, STAmount const &takerPays, STAmount const &takerGets, std::uint32_t flags)
Create an offer.
Definition offer.cpp:14
BEAST_DEFINE_TESTSUITE(AMMClawback, app, xrpl)
std::unique_ptr< WSClient > makeWSClient(Config const &cfg, bool v2, unsigned rpcVersion, std::unordered_map< std::string, std::string > const &headers)
Returns a client operating through WebSockets/S.
Definition WSClient.cpp:373
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
@ RpcInvalidParams
Definition ErrorCodes.h:67
BaseUInt< 256 > Domain
Domain is a 256-bit hash representing a specific domain.
Definition UintTypes.h:59
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
BaseUInt< 256 > UInt256
Definition base_uint.h:581
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
T static_pointer_cast(T... args)
T to_string(T... args)