xrpld
Loading...
Searching...
No Matches
Subscribe_test.cpp
1#include <test/jtx/Env.h>
2#include <test/jtx/TestHelpers.h>
3#include <test/jtx/WSClient.h>
4#include <test/jtx/amount.h>
5#include <test/jtx/batch.h>
6#include <test/jtx/domain.h>
7#include <test/jtx/envconfig.h>
8#include <test/jtx/escrow.h>
9#include <test/jtx/fee.h>
10#include <test/jtx/mpt.h>
11#include <test/jtx/offer.h>
12#include <test/jtx/owners.h> // IWYU pragma: keep
13#include <test/jtx/paths.h>
14#include <test/jtx/pay.h>
15#include <test/jtx/permissioned_dex.h>
16#include <test/jtx/sendmax.h>
17#include <test/jtx/seq.h>
18#include <test/jtx/sig.h>
19#include <test/jtx/tags.h>
20#include <test/jtx/token.h>
21#include <test/jtx/txflags.h>
22
23#include <xrpld/app/main/LoadManager.h>
24#include <xrpld/core/Config.h>
25
26#include <xrpl/basics/UnorderedContainers.h>
27#include <xrpl/basics/base_uint.h>
28#include <xrpl/basics/strHex.h>
29#include <xrpl/beast/unit_test/suite.h>
30#include <xrpl/config/Constants.h>
31#include <xrpl/core/NetworkIDService.h>
32#include <xrpl/json/json_value.h>
33#include <xrpl/json/to_string.h>
34#include <xrpl/protocol/AccountID.h>
35#include <xrpl/protocol/ErrorCodes.h>
36#include <xrpl/protocol/Feature.h>
37#include <xrpl/protocol/Fees.h>
38#include <xrpl/protocol/Indexes.h>
39#include <xrpl/protocol/KeyType.h>
40#include <xrpl/protocol/PublicKey.h>
41#include <xrpl/protocol/SField.h>
42#include <xrpl/protocol/STValidation.h>
43#include <xrpl/protocol/SecretKey.h>
44#include <xrpl/protocol/Seed.h>
45#include <xrpl/protocol/SeqProxy.h>
46#include <xrpl/protocol/TxFlags.h>
47#include <xrpl/protocol/UintTypes.h>
48#include <xrpl/protocol/XRPAmount.h>
49#include <xrpl/protocol/jss.h>
50#include <xrpl/protocol/tokens.h>
51#include <xrpl/server/LoadFeeTrack.h>
52#include <xrpl/server/NetworkOPs.h>
53
54#include <algorithm>
55#include <array>
56#include <chrono>
57#include <cstddef>
58#include <cstdint>
59#include <initializer_list>
60#include <iterator>
61#include <memory>
62#include <optional>
63#include <string>
64#include <tuple>
65#include <utility>
66#include <vector>
67
68namespace xrpl::test {
69
71{
72public:
73 void
75 {
76 using namespace std::chrono_literals;
77 using namespace jtx;
78 Env env{*this, singleThreadIo(envconfig())};
79 auto wsc = makeWSClient(env.app().config());
80 json::Value stream;
81
82 {
83 // RPC subscribe to server stream
84 stream[jss::streams] = json::ValueType::Array;
85 stream[jss::streams].append("server");
86 auto jv = wsc->invoke("subscribe", stream);
87 if (wsc->version() == 2)
88 {
89 BEAST_EXPECT(hasEnvelope2(jv));
90 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
91 }
92 BEAST_EXPECT(jv[jss::status] == "success");
93 }
94
95 // here we forcibly stop the load manager because it can (rarely but
96 // every-so-often) cause fees to raise or lower AFTER we've called the
97 // first findMsg but BEFORE we unsubscribe, thus causing the final
98 // findMsg check to fail since there is one unprocessed ws msg created
99 // by the loadmanager
100 env.app().getLoadManager().stop();
101 {
102 // Raise fee to cause an update
103 auto& feeTrack = env.app().getFeeTrack();
104 for (int i = 0; i < 5; ++i)
105 feeTrack.raiseLocalFee();
106 env.app().getOPs().reportFeeChange();
107
108 // Check stream update
109 BEAST_EXPECT(
110 wsc->findMsg(5s, [&](auto const& jv) { return jv[jss::type] == "serverStatus"; }));
111 }
112
113 {
114 // RPC unsubscribe
115 auto jv = wsc->invoke("unsubscribe", stream);
116 if (wsc->version() == 2)
117 {
118 BEAST_EXPECT(hasEnvelope2(jv));
119 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
120 }
121 BEAST_EXPECT(jv[jss::status] == "success");
122 }
123
124 {
125 // Raise fee to cause an update
126 auto& feeTrack = env.app().getFeeTrack();
127 for (int i = 0; i < 5; ++i)
128 feeTrack.raiseLocalFee();
129 env.app().getOPs().reportFeeChange();
130
131 // Check stream update
132 auto jvo = wsc->getMsg(10ms);
133 BEAST_EXPECTS(!jvo, "getMsg: " + to_string(jvo.value()));
134 }
135 }
136
137 void
139 {
140 using namespace std::chrono_literals;
141 using namespace jtx;
142 Env env{*this, singleThreadIo(envconfig())};
143 auto wsc = makeWSClient(env.app().config());
144 json::Value stream;
145
146 {
147 // RPC subscribe to ledger stream
148 stream[jss::streams] = json::ValueType::Array;
149 stream[jss::streams].append("ledger");
150 auto jv = wsc->invoke("subscribe", stream);
151 if (wsc->version() == 2)
152 {
153 BEAST_EXPECT(hasEnvelope2(jv));
154 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
155 }
156 BEAST_EXPECT(jv[jss::result][jss::ledger_index] == 2);
157 BEAST_EXPECT(
158 jv[jss::result][jss::network_id] == env.app().getNetworkIDService().getNetworkID());
159 }
160
161 {
162 // Accept a ledger
163 BEAST_EXPECT(env.syncClose());
164
165 // Check stream update
166 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
167 return jv[jss::ledger_index] == 3 &&
168 jv[jss::network_id] == env.app().getNetworkIDService().getNetworkID();
169 }));
170 }
171
172 {
173 // Accept another ledger
174 BEAST_EXPECT(env.syncClose());
175
176 // Check stream update
177 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
178 return jv[jss::ledger_index] == 4 &&
179 jv[jss::network_id] == env.app().getNetworkIDService().getNetworkID();
180 }));
181 }
182
183 // RPC unsubscribe
184 auto jv = wsc->invoke("unsubscribe", stream);
185 if (wsc->version() == 2)
186 {
187 BEAST_EXPECT(hasEnvelope2(jv));
188 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
189 }
190 BEAST_EXPECT(jv[jss::status] == "success");
191 }
192
193 void
195 {
196 using namespace std::chrono_literals;
197 using namespace jtx;
198 Env env(*this, singleThreadIo(envconfig()));
199 auto baseFee = env.current()->fees().base.drops();
200 auto wsc = makeWSClient(env.app().config());
201 json::Value stream;
202
203 {
204 // RPC subscribe to transactions stream
205 stream[jss::streams] = json::ValueType::Array;
206 stream[jss::streams].append("transactions");
207 auto jv = wsc->invoke("subscribe", stream);
208 if (wsc->version() == 2)
209 {
210 BEAST_EXPECT(hasEnvelope2(jv));
211 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
212 }
213 BEAST_EXPECT(jv[jss::status] == "success");
214 }
215
216 {
217 env.fund(XRP(10000), "alice");
218 BEAST_EXPECT(env.syncClose());
219
220 // Check stream update for payment transaction
221 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
222 return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"]
223 [jss::Account] == Account("alice").human() &&
224 jv[jss::transaction][jss::TransactionType] == jss::Payment &&
225 jv[jss::transaction][jss::DeliverMax] ==
226 std::to_string(10000000000 + baseFee) &&
227 jv[jss::transaction][jss::Fee] == std::to_string(baseFee) &&
228 jv[jss::transaction][jss::Sequence] == 1;
229 }));
230
231 // Check stream update for accountset transaction
232 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
233 return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"]
234 [jss::Account] == Account("alice").human();
235 }));
236
237 env.fund(XRP(10000), "bob");
238 BEAST_EXPECT(env.syncClose());
239
240 // Check stream update for payment transaction
241 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
242 return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"]
243 [jss::Account] //
244 == Account("bob").human() &&
245 jv[jss::transaction][jss::TransactionType] //
246 == jss::Payment &&
247 jv[jss::transaction][jss::DeliverMax] //
248 == std::to_string(10000000000 + baseFee) &&
249 jv[jss::transaction][jss::Fee] //
250 == std::to_string(baseFee) &&
251 jv[jss::transaction][jss::Sequence] //
252 == 2;
253 }));
254
255 // Check stream update for accountset transaction
256 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
257 return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"]
258 [jss::Account] == Account("bob").human();
259 }));
260 }
261
262 {
263 // RPC unsubscribe
264 auto jv = wsc->invoke("unsubscribe", stream);
265 if (wsc->version() == 2)
266 {
267 BEAST_EXPECT(hasEnvelope2(jv));
268 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
269 }
270 BEAST_EXPECT(jv[jss::status] == "success");
271 }
272
273 {
274 // RPC subscribe to accounts stream
276 stream[jss::accounts] = json::ValueType::Array;
277 stream[jss::accounts].append(Account("alice").human());
278 auto jv = wsc->invoke("subscribe", stream);
279 if (wsc->version() == 2)
280 {
281 BEAST_EXPECT(hasEnvelope2(jv));
282 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
283 }
284 BEAST_EXPECT(jv[jss::status] == "success");
285 }
286
287 {
288 // Transaction that does not affect stream
289 env.fund(XRP(10000), "carol");
290 BEAST_EXPECT(env.syncClose());
291 BEAST_EXPECT(!wsc->getMsg(10ms));
292
293 // Transactions concerning alice
294 env.trust(Account("bob")["USD"](100), "alice");
295 BEAST_EXPECT(env.syncClose());
296
297 // Check stream updates
298 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
299 return jv[jss::meta]["AffectedNodes"][1u]["ModifiedNode"]["FinalFields"]
300 [jss::Account] == Account("alice").human();
301 }));
302
303 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
304 return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"]["LowLimit"]
305 [jss::issuer] == Account("alice").human();
306 }));
307 }
308
309 // RPC unsubscribe
310 auto jv = wsc->invoke("unsubscribe", stream);
311 if (wsc->version() == 2)
312 {
313 BEAST_EXPECT(hasEnvelope2(jv));
314 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
315 }
316 BEAST_EXPECT(jv[jss::status] == "success");
317 }
318
319 void
321 {
322 testcase("transactions API version 2");
323
324 using namespace std::chrono_literals;
325 using namespace jtx;
326 Env env(*this, envconfig([](std::unique_ptr<Config> cfg) {
327 cfg->fees.referenceFee = 10;
328 cfg = singleThreadIo(std::move(cfg));
329 return cfg;
330 }));
331 auto wsc = makeWSClient(env.app().config());
333
334 {
335 // RPC subscribe to transactions stream
336 stream[jss::api_version] = 2;
337 stream[jss::streams] = json::ValueType::Array;
338 stream[jss::streams].append("transactions");
339 auto jv = wsc->invoke("subscribe", stream);
340 if (wsc->version() == 2)
341 {
342 BEAST_EXPECT(hasEnvelope2(jv));
343 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
344 }
345 BEAST_EXPECT(jv[jss::status] == "success");
346 }
347
348 {
349 env.fund(XRP(10000), "alice");
350 BEAST_EXPECT(env.syncClose());
351
352 // Check stream update for payment transaction
353 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
354 return jv[jss::meta]["AffectedNodes"][1u]["CreatedNode"]["NewFields"]
355 [jss::Account] //
356 == Account("alice").human() &&
357 jv[jss::close_time_iso] //
358 == "2000-01-01T00:00:10Z" &&
359 jv[jss::validated] == true && //
360 jv[jss::ledger_hash] ==
361 "5CC95BD8BA54A009A4F5BA437867BBFCF18F5A9CFB7F68FE7816258D164C1516" && //
362 !jv[jss::inLedger] &&
363 jv[jss::ledger_index] == 3 && //
364 jv[jss::tx_json][jss::TransactionType] //
365 == jss::Payment &&
366 jv[jss::tx_json][jss::DeliverMax] //
367 == "10000000010" &&
368 !jv[jss::tx_json].isMember(jss::Amount) &&
369 jv[jss::tx_json][jss::Fee] //
370 == "10" &&
371 jv[jss::tx_json][jss::Sequence] //
372 == 1;
373 }));
374
375 // Check stream update for accountset transaction
376 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
377 return jv[jss::meta]["AffectedNodes"][0u]["ModifiedNode"]["FinalFields"]
378 [jss::Account] == Account("alice").human();
379 }));
380 }
381
382 {
383 // RPC unsubscribe
384 auto jv = wsc->invoke("unsubscribe", stream);
385 if (wsc->version() == 2)
386 {
387 BEAST_EXPECT(hasEnvelope2(jv));
388 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
389 }
390 BEAST_EXPECT(jv[jss::status] == "success");
391 }
392 }
393
394 void
396 {
397 using namespace jtx;
398 Env env(*this, singleThreadIo(envconfig()));
399 auto wsc = makeWSClient(env.app().config());
400 json::Value stream;
401
402 {
403 // RPC subscribe to manifests stream
404 stream[jss::streams] = json::ValueType::Array;
405 stream[jss::streams].append("manifests");
406 auto jv = wsc->invoke("subscribe", stream);
407 if (wsc->version() == 2)
408 {
409 BEAST_EXPECT(hasEnvelope2(jv));
410 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
411 }
412 BEAST_EXPECT(jv[jss::status] == "success");
413 }
414
415 // RPC unsubscribe
416 auto jv = wsc->invoke("unsubscribe", stream);
417 if (wsc->version() == 2)
418 {
419 BEAST_EXPECT(hasEnvelope2(jv));
420 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
421 }
422 BEAST_EXPECT(jv[jss::status] == "success");
423 }
424
425 void
427 {
428 using namespace jtx;
429
430 // doValidation only writes a fee field when its target differs from the
431 // ledger's current value, so a node with nothing to change emits
432 // nothing. Vote for limits other than the ones already in force, so
433 // the extension fields actually appear on the flag ledger.
434 auto const voteDifferentLimits = [](std::unique_ptr<Config> cfg) {
435 auto& voting = cfg->section(Sections::kVoting);
439
440 return cfg;
441 };
442 Env env{*this, singleThreadIo(voteDifferentLimits(envconfig(validator, ""))), features};
443 auto& cfg = env.app().config();
444 if (!BEAST_EXPECT(cfg.section(Sections::kValidationSeed).empty()))
445 return;
446 auto const parsedseed =
447 parseBase58<Seed>(cfg.section(Sections::kValidationSeed).values()[0]);
448 if (BEAST_EXPECT(parsedseed); not parsedseed.has_value())
449 return;
450
451 std::string const valPublicKey = toBase58(
455
456 auto wsc = makeWSClient(env.app().config());
457 json::Value stream;
458
459 {
460 // RPC subscribe to validations stream
461 stream[jss::streams] = json::ValueType::Array;
462 stream[jss::streams].append("validations");
463 auto jv = wsc->invoke("subscribe", stream);
464 if (wsc->version() == 2)
465 {
466 BEAST_EXPECT(hasEnvelope2(jv));
467 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
468 }
469 BEAST_EXPECT(jv[jss::status] == "success");
470 }
471
472 {
473 // Lambda to check ledger validations from the stream.
474 auto const validValidationFields = [&env, &valPublicKey](json::Value const& jv) {
475 if (jv[jss::type] != "validationReceived")
476 return false;
477
478 if (jv[jss::validation_public_key].asString() != valPublicKey)
479 return false;
480
481 if (jv[jss::ledger_hash] != to_string(env.closed()->header().hash))
482 return false;
483
484 if (jv[jss::ledger_index] != std::to_string(env.closed()->header().seq))
485 return false;
486
487 if (jv[jss::flags] != (kVfFullyCanonicalSig | kVfFullValidation))
488 return false;
489
490 if (jv[jss::full] != true)
491 return false;
492
493 if (jv.isMember(jss::load_fee))
494 return false;
495
496 if (!jv.isMember(jss::signature))
497 return false;
498
499 if (!jv.isMember(jss::signing_time))
500 return false;
501
502 if (!jv.isMember(jss::cookie))
503 return false;
504
505 if (!jv.isMember(jss::validated_hash))
506 return false;
507
508 uint32_t const netID = env.app().getNetworkIDService().getNetworkID();
509 if (!jv.isMember(jss::network_id) || jv[jss::network_id] != netID)
510 return false;
511
512 // Certain fields are only added on a flag ledger.
513 bool const isFlagLedger = (env.closed()->header().seq + 1) % 256 == 0;
514
515 if (jv.isMember(jss::server_version) != isFlagLedger)
516 return false;
517
518 if (jv.isMember(jss::reserve_base) != isFlagLedger)
519 return false;
520
521 if (jv.isMember(jss::reserve_inc) != isFlagLedger)
522 return false;
523
524 if (env.closed()->rules().enabled(featureSmartEscrow))
525 {
526 if (jv.isMember(jss::gas_limit) != isFlagLedger)
527 return false;
528
529 if (jv.isMember(jss::bytecode_size_limit) != isFlagLedger)
530 return false;
531
532 if (jv.isMember(jss::gas_price) != isFlagLedger)
533 return false;
534 }
535 else
536 {
537 if (jv.isMember(jss::gas_limit))
538 return false;
539
540 if (jv.isMember(jss::bytecode_size_limit))
541 return false;
542
543 if (jv.isMember(jss::gas_price))
544 return false;
545 }
546 return true;
547 };
548
549 // Check stream update. Look at enough stream entries so we see
550 // at least one flag ledger.
551 while (env.closed()->header().seq < 300)
552 {
553 BEAST_EXPECT(env.syncClose());
554 using namespace std::chrono_literals;
555 BEAST_EXPECT(wsc->findMsg(5s, validValidationFields));
556 }
557 }
558
559 // RPC unsubscribe
560 auto jv = wsc->invoke("unsubscribe", stream);
561 if (wsc->version() == 2)
562 {
563 BEAST_EXPECT(hasEnvelope2(jv));
564 BEAST_EXPECT(jv.isMember(jss::id) && jv[jss::id] == 5);
565 }
566 BEAST_EXPECT(jv[jss::status] == "success");
567 }
568
569 void
571 {
572 using namespace jtx;
573 testcase("Subscribe by url");
574 Env env{*this, singleThreadIo(envconfig())};
575
576 json::Value jv;
577 jv[jss::url] = "http://localhost/events";
578 jv[jss::url_username] = "admin";
579 jv[jss::url_password] = "password";
580 jv[jss::streams] = json::ValueType::Array;
581 jv[jss::streams][0u] = "validations";
582 auto jr = env.rpc("json", "subscribe", to_string(jv))[jss::result];
583 BEAST_EXPECT(jr[jss::status] == "success");
584
585 jv[jss::streams][0u] = "ledger";
586 jr = env.rpc("json", "subscribe", to_string(jv))[jss::result];
587 BEAST_EXPECT(jr[jss::status] == "success");
588 BEAST_EXPECT(jr[jss::network_id] == env.app().getNetworkIDService().getNetworkID());
589
590 jr = env.rpc("json", "unsubscribe", to_string(jv))[jss::result];
591 BEAST_EXPECT(jr[jss::status] == "success");
592
593 jv[jss::streams][0u] = "validations";
594 jr = env.rpc("json", "unsubscribe", to_string(jv))[jss::result];
595 BEAST_EXPECT(jr[jss::status] == "success");
596 }
597
598 void
599 testSubErrors(bool subscribe)
600 {
601 using namespace jtx;
602 auto const method = subscribe ? "subscribe" : "unsubscribe";
603 testcase << "Error cases for " << method;
604
605 Env env{*this, singleThreadIo(envconfig())};
606 auto wsc = makeWSClient(env.app().config());
607
608 {
609 auto const jr = env.rpc("json", method, "{}")[jss::result];
610 BEAST_EXPECT(jr[jss::error] == "invalidParams");
611 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
612 BEAST_EXPECT(jr[jss::error_message] == "Invalid parameters.");
613 }
614
615 {
616 json::Value jv;
617 jv[jss::url] = "not-a-url";
618 jv[jss::username] = "admin";
619 jv[jss::password] = "password";
620 auto const jr = env.rpc("json", method, to_string(jv))[jss::result];
621 if (subscribe)
622 {
623 BEAST_EXPECT(jr[jss::error] == "invalidParams");
624 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
625 BEAST_EXPECT(jr[jss::error_message] == "Failed to parse url.");
626 }
627 // else TODO: why isn't this an error for unsubscribe ?
628 // (findRpcSub returns null)
629 }
630
631 {
632 json::Value jv;
633 jv[jss::url] = "ftp://scheme.not.supported.tld";
634 auto const jr = env.rpc("json", method, to_string(jv))[jss::result];
635 if (subscribe)
636 {
637 BEAST_EXPECT(jr[jss::error] == "invalidParams");
638 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
639 BEAST_EXPECT(jr[jss::error_message] == "Only http and https is supported.");
640 }
641 }
642
643 {
644 Env envNonadmin{*this, singleThreadIo(noAdmin(envconfig()))};
645 json::Value jv;
646 jv[jss::url] = "no-url";
647 auto const jr = envNonadmin.rpc("json", method, to_string(jv))[jss::result];
648 BEAST_EXPECT(jr[jss::error] == "noPermission");
649 BEAST_EXPECT(jr[jss::error_code] == RpcNoPermission);
650 BEAST_EXPECT(jr[jss::error_message] == "You don't have permission for this command.");
651 }
652
658 "",
661 };
662
663 for (auto const& f : {jss::accounts_proposed, jss::accounts})
664 {
665 for (auto const& nonArray : nonArrays)
666 {
667 json::Value jv;
668 jv[f] = nonArray;
669 auto const jr = wsc->invoke(method, jv)[jss::result];
670 BEAST_EXPECT(jr[jss::error] == "invalidParams");
671 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
672 BEAST_EXPECT(jr[jss::error_message] == "Invalid parameters.");
673 }
674
675 {
676 json::Value jv;
678 auto const jr = wsc->invoke(method, jv)[jss::result];
679 BEAST_EXPECT(jr[jss::error] == "actMalformed");
680 BEAST_EXPECT(jr[jss::error_code] == RpcActMalformed);
681 BEAST_EXPECT(jr[jss::error_message] == "Account malformed.");
682 }
683 }
684
685 for (auto const& nonArray : nonArrays)
686 {
687 json::Value jv;
688 jv[jss::mpt_issuances] = nonArray;
689 auto jr = wsc->invoke(method, jv)[jss::result];
690 BEAST_EXPECT(jr[jss::error] == "invalidParams");
691 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
692 BEAST_EXPECT(jr[jss::error_message] == "Invalid parameters.");
693 }
694
695 {
696 json::Value jv;
697 jv[jss::mpt_issuances] = json::ValueType::Array;
698 jv[jss::mpt_issuances][0u] = 1;
699 auto jr = wsc->invoke(method, jv)[jss::result];
700 BEAST_EXPECT(jr[jss::error] == "invalidParams");
701 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
702 BEAST_EXPECT(jr[jss::error_message] == "Invalid parameters.");
703 }
704
705 {
706 json::Value jv;
707 jv[jss::mpt_issuances] = json::ValueType::Array;
708 jv[jss::mpt_issuances][0u] = "not-an-mpt-issuance-id";
709 auto jr = wsc->invoke(method, jv)[jss::result];
710 BEAST_EXPECT(jr[jss::error] == "invalidParams");
711 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
712 BEAST_EXPECT(jr[jss::error_message] == "Invalid parameters.");
713 }
714
715 {
716 json::Value jv;
717 jv[jss::mpt_issuances] = json::ValueType::Array;
718 jv[jss::mpt_issuances][0u] = "0123456789ABCDEF";
719 auto jr = wsc->invoke(method, jv)[jss::result];
720 BEAST_EXPECT(jr[jss::error] == "invalidParams");
721 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
722 BEAST_EXPECT(jr[jss::error_message] == "Invalid parameters.");
723 }
724
725 for (auto const& nonArray : nonArrays)
726 {
727 json::Value jv;
728 jv[jss::books] = nonArray;
729 auto const jr = wsc->invoke(method, jv)[jss::result];
730 BEAST_EXPECT(jr[jss::error] == "invalidParams");
731 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
732 BEAST_EXPECT(jr[jss::error_message] == "Invalid parameters.");
733 }
734
735 {
736 json::Value jv;
737 jv[jss::books] = json::ValueType::Array;
738 jv[jss::books][0u] = 1;
739 auto const jr = wsc->invoke(method, jv)[jss::result];
740 BEAST_EXPECT(jr[jss::error] == "invalidParams");
741 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
742 BEAST_EXPECT(jr[jss::error_message] == "Invalid parameters.");
743 }
744
745 {
746 json::Value jv;
747 jv[jss::books] = json::ValueType::Array;
748 jv[jss::books][0u] = json::ValueType::Object;
749 jv[jss::books][0u][jss::taker_gets] = json::ValueType::Object;
750 jv[jss::books][0u][jss::taker_pays] = json::ValueType::Object;
751 auto const jr = wsc->invoke(method, jv)[jss::result];
752
753 BEAST_EXPECT(jr[jss::error] == "srcCurMalformed");
754 BEAST_EXPECT(jr[jss::error_code] == RpcSrcCurMalformed);
755 BEAST_EXPECT(jr[jss::error_message] == "Source currency is malformed.");
756 }
757
758 {
759 json::Value jv;
760 jv[jss::books] = json::ValueType::Array;
761 jv[jss::books][0u] = json::ValueType::Object;
762 jv[jss::books][0u][jss::taker_gets] = json::ValueType::Object;
763 jv[jss::books][0u][jss::taker_pays] = json::ValueType::Object;
764 jv[jss::books][0u][jss::taker_pays][jss::currency] = "ZZZZ";
765 auto const jr = wsc->invoke(method, jv)[jss::result];
766 BEAST_EXPECT(jr[jss::error] == "srcCurMalformed");
767 BEAST_EXPECT(jr[jss::error_code] == RpcSrcCurMalformed);
768 BEAST_EXPECT(jr[jss::error_message] == "Source currency is malformed.");
769 }
770
771 {
772 json::Value jv;
773 jv[jss::books] = json::ValueType::Array;
774 jv[jss::books][0u] = json::ValueType::Object;
775 jv[jss::books][0u][jss::taker_gets] = json::ValueType::Object;
776 jv[jss::books][0u][jss::taker_pays] = json::ValueType::Object;
777 jv[jss::books][0u][jss::taker_pays][jss::currency] = "USD";
778 jv[jss::books][0u][jss::taker_pays][jss::issuer] = 1;
779 auto const jr = wsc->invoke(method, jv)[jss::result];
780 BEAST_EXPECT(jr[jss::error] == "srcIsrMalformed");
781 BEAST_EXPECT(jr[jss::error_code] == RpcSrcIsrMalformed);
782 BEAST_EXPECT(jr[jss::error_message] == "Source issuer is malformed.");
783 }
784
785 {
786 json::Value jv;
787 jv[jss::books] = json::ValueType::Array;
788 jv[jss::books][0u] = json::ValueType::Object;
789 jv[jss::books][0u][jss::taker_gets] = json::ValueType::Object;
790 jv[jss::books][0u][jss::taker_pays] = json::ValueType::Object;
791 jv[jss::books][0u][jss::taker_pays][jss::currency] = "USD";
792 jv[jss::books][0u][jss::taker_pays][jss::issuer] = Account{"gateway"}.human() + "DEAD";
793 auto const jr = wsc->invoke(method, jv)[jss::result];
794 BEAST_EXPECT(jr[jss::error] == "srcIsrMalformed");
795 BEAST_EXPECT(jr[jss::error_code] == RpcSrcIsrMalformed);
796 BEAST_EXPECT(jr[jss::error_message] == "Source issuer is malformed.");
797 }
798
799 {
800 json::Value jv;
801 jv[jss::books] = json::ValueType::Array;
802 jv[jss::books][0u] = json::ValueType::Object;
803 jv[jss::books][0u][jss::taker_pays] =
804 Account{"gateway"}["USD"](1).value().getJson(JsonOptions::Values::IncludeDate);
805 jv[jss::books][0u][jss::taker_gets] = json::ValueType::Object;
806 auto const jr = wsc->invoke(method, jv)[jss::result];
807 // NOTE: this error is slightly incongruous with the equivalent source currency error
808 BEAST_EXPECT(jr[jss::error] == "dstAmtMalformed");
809 BEAST_EXPECT(jr[jss::error_code] == RpcDstAmtMalformed);
810 BEAST_EXPECT(
811 jr[jss::error_message] == "Destination amount/currency/issuer is malformed.");
812 }
813
814 {
815 json::Value jv;
816 jv[jss::books] = json::ValueType::Array;
817 jv[jss::books][0u] = json::ValueType::Object;
818 jv[jss::books][0u][jss::taker_pays] =
819 Account{"gateway"}["USD"](1).value().getJson(JsonOptions::Values::IncludeDate);
820 jv[jss::books][0u][jss::taker_gets][jss::currency] = "ZZZZ";
821 auto const jr = wsc->invoke(method, jv)[jss::result];
822 // NOTE: this error is slightly incongruous with the
823 // equivalent source currency error
824 BEAST_EXPECT(jr[jss::error] == "dstAmtMalformed");
825 BEAST_EXPECT(jr[jss::error_code] == RpcDstAmtMalformed);
826 BEAST_EXPECT(
827 jr[jss::error_message] == "Destination amount/currency/issuer is malformed.");
828 }
829
830 {
831 json::Value jv;
832 jv[jss::books] = json::ValueType::Array;
833 jv[jss::books][0u] = json::ValueType::Object;
834 jv[jss::books][0u][jss::taker_pays] =
835 Account{"gateway"}["USD"](1).value().getJson(JsonOptions::Values::IncludeDate);
836 jv[jss::books][0u][jss::taker_gets][jss::currency] = "USD";
837 jv[jss::books][0u][jss::taker_gets][jss::issuer] = 1;
838 auto const jr = wsc->invoke(method, jv)[jss::result];
839 BEAST_EXPECT(jr[jss::error] == "dstIsrMalformed");
840 BEAST_EXPECT(jr[jss::error_code] == RpcDstIsrMalformed);
841 BEAST_EXPECT(jr[jss::error_message] == "Destination issuer is malformed.");
842 }
843
844 {
845 json::Value jv;
846 jv[jss::books] = json::ValueType::Array;
847 jv[jss::books][0u] = json::ValueType::Object;
848 jv[jss::books][0u][jss::taker_pays] =
849 Account{"gateway"}["USD"](1).value().getJson(JsonOptions::Values::IncludeDate);
850 jv[jss::books][0u][jss::taker_gets][jss::currency] = "USD";
851 jv[jss::books][0u][jss::taker_gets][jss::issuer] = Account{"gateway"}.human() + "DEAD";
852 auto const jr = wsc->invoke(method, jv)[jss::result];
853 BEAST_EXPECT(jr[jss::error] == "dstIsrMalformed");
854 BEAST_EXPECT(jr[jss::error_code] == RpcDstIsrMalformed);
855 BEAST_EXPECT(jr[jss::error_message] == "Destination issuer is malformed.");
856 }
857
858 {
859 json::Value jv;
860 jv[jss::books] = json::ValueType::Array;
861 jv[jss::books][0u] = json::ValueType::Object;
862 jv[jss::books][0u][jss::taker_pays] =
863 Account{"gateway"}["USD"](1).value().getJson(JsonOptions::Values::IncludeDate);
864 jv[jss::books][0u][jss::taker_gets] =
865 Account{"gateway"}["USD"](1).value().getJson(JsonOptions::Values::IncludeDate);
866 auto const jr = wsc->invoke(method, jv)[jss::result];
867 BEAST_EXPECT(jr[jss::error] == "badMarket");
868 BEAST_EXPECT(jr[jss::error_code] == RpcBadMarket);
869 BEAST_EXPECT(jr[jss::error_message] == "No such market.");
870 }
871
872 for (auto const& nonArray : nonArrays)
873 {
874 json::Value jv;
875 jv[jss::streams] = nonArray;
876 auto const jr = wsc->invoke(method, jv)[jss::result];
877 BEAST_EXPECT(jr[jss::error] == "invalidParams");
878 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
879 BEAST_EXPECT(jr[jss::error_message] == "Invalid parameters.");
880 }
881
882 {
883 json::Value jv;
884 jv[jss::streams] = json::ValueType::Array;
885 jv[jss::streams][0u] = 1;
886 auto const jr = wsc->invoke(method, jv)[jss::result];
887 BEAST_EXPECT(jr[jss::error] == "malformedStream");
888 BEAST_EXPECT(jr[jss::error_code] == RpcStreamMalformed);
889 BEAST_EXPECT(jr[jss::error_message] == "Stream malformed.");
890 }
891
892 {
893 json::Value jv;
894 jv[jss::streams] = json::ValueType::Array;
895 jv[jss::streams][0u] = "not_a_stream";
896 auto const jr = wsc->invoke(method, jv)[jss::result];
897 BEAST_EXPECT(jr[jss::error] == "malformedStream");
898 BEAST_EXPECT(jr[jss::error_code] == RpcStreamMalformed);
899 BEAST_EXPECT(jr[jss::error_message] == "Stream malformed.");
900 }
901
902 if (subscribe)
903 {
904 // invalid taker - not a string
905 {
906 json::Value jv;
907 jv[jss::books] = json::ValueType::Array;
908 jv[jss::books][0u] = json::ValueType::Object;
909 jv[jss::books][0u][jss::taker_pays] =
910 Account{"gateway"}["USD"](1).value().getJson(JsonOptions::Values::IncludeDate);
911 jv[jss::books][0u][jss::taker_gets][jss::currency] = "XRP";
912 jv[jss::books][0u][jss::taker] = 1;
913 auto const jr = wsc->invoke(method, jv)[jss::result];
914 BEAST_EXPECTS(jr[jss::error] == "actMalformed", jr.toStyledString());
915 BEAST_EXPECT(jr[jss::error_code] == RpcActMalformed);
916 BEAST_EXPECT(jr[jss::error_message] == "Account malformed.");
917 }
918
919 // invalid taker - malformed account string
920 {
921 json::Value jv;
922 jv[jss::books] = json::ValueType::Array;
923 jv[jss::books][0u] = json::ValueType::Object;
924 jv[jss::books][0u][jss::taker_pays] =
925 Account{"gateway"}["USD"](1).value().getJson(JsonOptions::Values::IncludeDate);
926 jv[jss::books][0u][jss::taker_gets][jss::currency] = "XRP";
927 jv[jss::books][0u][jss::taker] = "not_an_account";
928 auto const jr = wsc->invoke(method, jv)[jss::result];
929 BEAST_EXPECTS(jr[jss::error] == "actMalformed", jr.toStyledString());
930 BEAST_EXPECT(jr[jss::error_code] == RpcActMalformed);
931 BEAST_EXPECT(jr[jss::error_message] == "Account malformed.");
932 }
933
934 // invalid taker - account string with extra characters
935 {
936 json::Value jv;
937 jv[jss::books] = json::ValueType::Array;
938 jv[jss::books][0u] = json::ValueType::Object;
939 jv[jss::books][0u][jss::taker_pays] =
940 Account{"gateway"}["USD"](1).value().getJson(JsonOptions::Values::IncludeDate);
941 jv[jss::books][0u][jss::taker_gets][jss::currency] = "XRP";
942 jv[jss::books][0u][jss::taker] = Account{"alice"}.human() + "DEAD";
943 auto const jr = wsc->invoke(method, jv)[jss::result];
944 BEAST_EXPECTS(jr[jss::error] == "actMalformed", jr.toStyledString());
945 BEAST_EXPECT(jr[jss::error_code] == RpcActMalformed);
946 BEAST_EXPECT(jr[jss::error_message] == "Account malformed.");
947 }
948 }
949 }
950
951 void
953 {
954 testcase("HistoryTxStream");
955
956 using namespace std::chrono_literals;
957 using namespace jtx;
959
960 Account const alice("alice");
961 Account const bob("bob");
962 Account const carol("carol");
963 Account const david("david");
965
966 /*
967 * return true if the subscribe or unsubscribe result is a success
968 */
969 auto const goodSubRPC = [](json::Value const& subReply) -> bool {
970 return subReply.isMember(jss::result) && subReply[jss::result].isMember(jss::status) &&
971 subReply[jss::result][jss::status] == jss::success;
972 };
973
974 /*
975 * try to receive txns from the tx stream subscription via the WSClient.
976 * return {true, true} if received numReplies replies and also
977 * received a tx with the account_history_tx_first == true
978 */
979 auto const getTxHash = [](WSClient& wsc,
980 IdxHashVec& v,
981 int numReplies,
984 bool firstFlag = false;
985
986 for (int i = 0; i < numReplies; ++i)
987 {
988 std::uint32_t idx{0};
989 auto reply = wsc.getMsg(timeout);
990 if (reply)
991 {
992 auto r = *reply;
993 if (r.isMember(jss::account_history_tx_index))
994 idx = r[jss::account_history_tx_index].asInt();
995 if (r.isMember(jss::account_history_tx_first))
996 firstFlag = true;
997 bool const boundary = r.isMember(jss::account_history_boundary);
998 int const ledgerIdx = r[jss::ledger_index].asInt();
999 if (r.isMember(jss::transaction) && r[jss::transaction].isMember(jss::hash))
1000 {
1001 auto t{r[jss::transaction]};
1002 v.emplace_back(idx, t[jss::hash].asString(), boundary, ledgerIdx);
1003 continue;
1004 }
1005 }
1006 return {false, firstFlag};
1007 }
1008
1009 return {true, firstFlag};
1010 };
1011
1012 /*
1013 * send payments between the two accounts a and b,
1014 * and close ledgersToClose ledgers
1015 */
1016 auto sendPayments = [this](
1017 Env& env,
1018 Account const& a,
1019 Account const& b,
1020 int newTxns,
1021 std::uint32_t ledgersToClose,
1022 int numXRP = 10) {
1023 env.memoize(a);
1024 env.memoize(b);
1025 for (int i = 0; i < newTxns; ++i)
1026 {
1027 auto& from = (i % 2 == 0) ? a : b;
1028 auto& to = (i % 2 == 0) ? b : a;
1029 env(pay(from, to, jtx::XRP(numXRP)),
1033 }
1034 for (int i = 0; i < ledgersToClose; ++i)
1035 BEAST_EXPECT(env.syncClose());
1036 return newTxns;
1037 };
1038
1039 /*
1040 * Check if txHistoryVec has every item of accountVec,
1041 * and in the same order.
1042 * If sizeCompare is false, txHistoryVec is allowed to be larger.
1043 */
1044 auto const hashCompare = [](IdxHashVec const& accountVec,
1045 IdxHashVec const& txHistoryVec,
1046 bool sizeCompare) -> bool {
1047 if (accountVec.empty() || txHistoryVec.empty())
1048 return false;
1049 if (sizeCompare && accountVec.size() != txHistoryVec.size())
1050 return false;
1051
1052 HashMap<std::string, int> txHistoryMap;
1053 for (auto const& tx : txHistoryVec)
1054 {
1055 txHistoryMap.emplace(std::get<1>(tx), std::get<0>(tx));
1056 }
1057
1058 auto const getHistoryIndex = [&](std::size_t i) -> std::optional<int> {
1059 if (i >= accountVec.size())
1060 return {};
1061 auto const it = txHistoryMap.find(std::get<1>(accountVec[i]));
1062 if (it == txHistoryMap.end())
1063 return {};
1064 return it->second;
1065 };
1066
1067 auto firstHistoryIndex = getHistoryIndex(0);
1068 if (!firstHistoryIndex)
1069 return false;
1070 for (std::size_t i = 1; i < accountVec.size(); ++i)
1071 {
1072 if (auto idx = getHistoryIndex(i); !idx || *idx != *firstHistoryIndex + i)
1073 return false;
1074 }
1075 return true;
1076 };
1077
1078 // example of vector created from the return of `subscribe` rpc
1079 // with jss::accounts
1080 // boundary == true on last tx of ledger
1081 // ------------------------------------------------------------
1082 // (0, "E5B8B...", false, 4
1083 // (0, "39E1C...", false, 4
1084 // (0, "14EF1...", false, 4
1085 // (0, "386E6...", false, 4
1086 // (0, "00F3B...", true, 4
1087 // (0, "1DCDC...", false, 5
1088 // (0, "BD02A...", false, 5
1089 // (0, "D3E16...", false, 5
1090 // (0, "CB593...", false, 5
1091 // (0, "8F28B...", true, 5
1092 //
1093 // example of vector created from the return of `subscribe` rpc
1094 // with jss::account_history_tx_stream.
1095 // boundary == true on first tx of ledger
1096 // ------------------------------------------------------------
1097 // (-1, "8F28B...", false, 5
1098 // (-2, "CB593...", false, 5
1099 // (-3, "D3E16...", false, 5
1100 // (-4, "BD02A...", false, 5
1101 // (-5, "1DCDC...", true, 5
1102 // (-6, "00F3B...", false, 4
1103 // (-7, "386E6...", false, 4
1104 // (-8, "14EF1...", false, 4
1105 // (-9, "39E1C...", false, 4
1106 // (-10, "E5B8B...", true, 4
1107
1108 auto const checkBoundary = [](IdxHashVec const& vec, bool /* forward */) {
1109 size_t const numTx = vec.size();
1110 for (size_t i = 0; i < numTx; ++i)
1111 {
1112 auto [idx, hash, boundary, ledger] = vec[i];
1113 if ((i + 1 == numTx || ledger != std::get<3>(vec[i + 1])) != boundary)
1114 return false;
1115 }
1116 return true;
1117 };
1118
1120
1121 {
1122 /*
1123 * subscribe to an account twice with same WS client,
1124 * the second should fail
1125 *
1126 * also test subscribe to the account before it is created
1127 */
1128 Env env(*this, singleThreadIo(envconfig()));
1129 auto wscTxHistory = makeWSClient(env.app().config());
1130 json::Value request;
1131 request[jss::account_history_tx_stream] = json::ValueType::Object;
1132 request[jss::account_history_tx_stream][jss::account] = alice.human();
1133 auto jv = wscTxHistory->invoke("subscribe", request);
1134 if (!BEAST_EXPECT(goodSubRPC(jv)))
1135 return;
1136
1137 jv = wscTxHistory->invoke("subscribe", request);
1138 BEAST_EXPECT(!goodSubRPC(jv));
1139
1140 /*
1141 * unsubscribe history only, future txns should still be streamed
1142 */
1143 request[jss::account_history_tx_stream][jss::stop_history_tx_only] = true;
1144 jv = wscTxHistory->invoke("unsubscribe", request);
1145 if (!BEAST_EXPECT(goodSubRPC(jv)))
1146 return;
1147
1148 sendPayments(env, env.master, alice, 1, 1, 123456);
1149
1150 IdxHashVec vec;
1151 auto r = getTxHash(*wscTxHistory, vec, 1);
1152 if (!BEAST_EXPECT(r.first && r.second))
1153 return;
1154
1155 /*
1156 * unsubscribe, future txns should not be streamed
1157 */
1158 request[jss::account_history_tx_stream][jss::stop_history_tx_only] = false;
1159 jv = wscTxHistory->invoke("unsubscribe", request);
1160 BEAST_EXPECT(goodSubRPC(jv));
1161
1162 sendPayments(env, env.master, alice, 1, 1);
1163 r = getTxHash(*wscTxHistory, vec, 1, 10ms);
1164 BEAST_EXPECT(!r.first);
1165 }
1166 {
1167 /*
1168 * subscribe genesis account tx history without txns
1169 * subscribe to bob's account after it is created
1170 */
1171 Env env(*this, singleThreadIo(envconfig()));
1172 auto wscTxHistory = makeWSClient(env.app().config());
1173 json::Value request;
1174 request[jss::account_history_tx_stream] = json::ValueType::Object;
1175 request[jss::account_history_tx_stream][jss::account] =
1176 "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh";
1177 auto jv = wscTxHistory->invoke("subscribe", request);
1178 if (!BEAST_EXPECT(goodSubRPC(jv)))
1179 return;
1180 IdxHashVec genesisFullHistoryVec;
1181 BEAST_EXPECT(env.syncClose());
1182 if (!BEAST_EXPECT(!getTxHash(*wscTxHistory, genesisFullHistoryVec, 1, 10ms).first))
1183 return;
1184
1185 /*
1186 * create bob's account with one tx
1187 * the two subscriptions should both stream it
1188 */
1189 sendPayments(env, env.master, bob, 1, 1, 654321);
1190
1191 auto r = getTxHash(*wscTxHistory, genesisFullHistoryVec, 1);
1192 if (!BEAST_EXPECT(r.first && r.second))
1193 return;
1194
1195 request[jss::account_history_tx_stream][jss::account] = bob.human();
1196 jv = wscTxHistory->invoke("subscribe", request);
1197 if (!BEAST_EXPECT(goodSubRPC(jv)))
1198 return;
1199 IdxHashVec bobFullHistoryVec;
1200 BEAST_EXPECT(env.syncClose());
1201 r = getTxHash(*wscTxHistory, bobFullHistoryVec, 1);
1202 if (!BEAST_EXPECT(r.first && r.second))
1203 return;
1204 BEAST_EXPECT(
1205 std::get<1>(bobFullHistoryVec.back()) == std::get<1>(genesisFullHistoryVec.back()));
1206
1207 /*
1208 * unsubscribe to prepare next test
1209 */
1210 jv = wscTxHistory->invoke("unsubscribe", request);
1211 if (!BEAST_EXPECT(goodSubRPC(jv)))
1212 return;
1213 request[jss::account_history_tx_stream][jss::account] =
1214 "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh";
1215 jv = wscTxHistory->invoke("unsubscribe", request);
1216 BEAST_EXPECT(goodSubRPC(jv));
1217
1218 /*
1219 * add more txns, then subscribe bob tx history and
1220 * genesis account tx history. Their earliest txns should match.
1221 */
1222 sendPayments(env, env.master, bob, 30, 300);
1223 wscTxHistory = makeWSClient(env.app().config());
1224 request[jss::account_history_tx_stream][jss::account] = bob.human();
1225 jv = wscTxHistory->invoke("subscribe", request);
1226
1227 bobFullHistoryVec.clear();
1228 BEAST_EXPECT(getTxHash(*wscTxHistory, bobFullHistoryVec, 31).second);
1229 jv = wscTxHistory->invoke("unsubscribe", request);
1230
1231 request[jss::account_history_tx_stream][jss::account] =
1232 "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh";
1233 jv = wscTxHistory->invoke("subscribe", request);
1234 genesisFullHistoryVec.clear();
1235 BEAST_EXPECT(env.syncClose());
1236 BEAST_EXPECT(getTxHash(*wscTxHistory, genesisFullHistoryVec, 31).second);
1237 jv = wscTxHistory->invoke("unsubscribe", request);
1238
1239 BEAST_EXPECT(
1240 std::get<1>(bobFullHistoryVec.back()) == std::get<1>(genesisFullHistoryVec.back()));
1241 }
1242
1243 {
1244 /*
1245 * subscribe account and subscribe account tx history
1246 * and compare txns streamed
1247 */
1248 Env env(*this, singleThreadIo(envconfig()));
1249 auto wscAccount = makeWSClient(env.app().config());
1250 auto wscTxHistory = makeWSClient(env.app().config());
1251
1252 std::array<Account, 2> const accounts = {alice, bob};
1253 env.fund(XRP(222222), accounts);
1254 BEAST_EXPECT(env.syncClose());
1255
1256 // subscribe account
1258 stream[jss::accounts] = json::ValueType::Array;
1259 stream[jss::accounts].append(alice.human());
1260 auto jv = wscAccount->invoke("subscribe", stream);
1261
1262 sendPayments(env, alice, bob, 5, 1);
1263 sendPayments(env, alice, bob, 5, 1);
1264 IdxHashVec accountVec;
1265 if (!BEAST_EXPECT(getTxHash(*wscAccount, accountVec, 10).first))
1266 return;
1267
1268 // subscribe account tx history
1269 json::Value request;
1270 request[jss::account_history_tx_stream] = json::ValueType::Object;
1271 request[jss::account_history_tx_stream][jss::account] = alice.human();
1272 jv = wscTxHistory->invoke("subscribe", request);
1273
1274 // compare historical txns
1275 IdxHashVec txHistoryVec;
1276 if (!BEAST_EXPECT(getTxHash(*wscTxHistory, txHistoryVec, 10).first))
1277 return;
1278 if (!BEAST_EXPECT(hashCompare(accountVec, txHistoryVec, true)))
1279 return;
1280
1281 // check boundary tags
1282 // only account_history_tx_stream has ledger boundary information.
1283 if (!BEAST_EXPECT(checkBoundary(txHistoryVec, false)))
1284 return;
1285
1286 {
1287 // take out all history txns from stream to prepare next test
1288 IdxHashVec initFundTxns;
1289 if (!BEAST_EXPECT(getTxHash(*wscTxHistory, initFundTxns, 10).second) ||
1290 !BEAST_EXPECT(checkBoundary(initFundTxns, false)))
1291 return;
1292 }
1293
1294 // compare future txns
1295 sendPayments(env, alice, bob, 10, 1);
1296 if (!BEAST_EXPECT(getTxHash(*wscAccount, accountVec, 10).first))
1297 return;
1298 if (!BEAST_EXPECT(getTxHash(*wscTxHistory, txHistoryVec, 10).first))
1299 return;
1300 if (!BEAST_EXPECT(hashCompare(accountVec, txHistoryVec, true)))
1301 return;
1302
1303 // check boundary tags
1304 // only account_history_tx_stream has ledger boundary information.
1305 if (!BEAST_EXPECT(checkBoundary(txHistoryVec, false)))
1306 return;
1307
1308 wscTxHistory->invoke("unsubscribe", request);
1309 wscAccount->invoke("unsubscribe", stream);
1310 }
1311
1312 {
1313 /*
1314 * alice issues USD to carol
1315 * mix USD and XRP payments
1316 */
1317 Env env(*this, singleThreadIo(envconfig()));
1318 auto const usdA = alice["USD"];
1319
1320 std::array<Account, 2> const accounts = {alice, carol};
1321 env.fund(XRP(333333), accounts);
1322 env.trust(usdA(20000), carol);
1323 BEAST_EXPECT(env.syncClose());
1324
1325 auto const mixedPayments = [&] -> int {
1326 sendPayments(env, alice, carol, 1, 0);
1327 env(pay(alice, carol, usdA(100)));
1328 BEAST_EXPECT(env.syncClose());
1329 return 2;
1330 };
1331
1332 // subscribe
1333 json::Value request;
1334 request[jss::account_history_tx_stream] = json::ValueType::Object;
1335 request[jss::account_history_tx_stream][jss::account] = carol.human();
1336 auto ws = makeWSClient(env.app().config());
1337 auto const jv = ws->invoke("subscribe", request);
1338 BEAST_EXPECT(env.syncClose());
1339 {
1340 // take out existing txns from the stream
1341 IdxHashVec tempVec;
1342 getTxHash(*ws, tempVec, 100, 1000ms);
1343 }
1344
1345 auto const count = mixedPayments();
1346 IdxHashVec vec1;
1347 if (!BEAST_EXPECT(getTxHash(*ws, vec1, count).first))
1348 return;
1349 ws->invoke("unsubscribe", request);
1350 }
1351
1352 {
1353 /*
1354 * long transaction history
1355 */
1356 Env env(*this, singleThreadIo(envconfig()));
1357 std::array<Account, 2> const accounts = {alice, carol};
1358 env.fund(XRP(444444), accounts);
1359 BEAST_EXPECT(env.syncClose());
1360
1361 // many payments, and close lots of ledgers
1362 auto const oneRound = [&](int numPayments) {
1363 return sendPayments(env, alice, carol, numPayments, 300);
1364 };
1365
1366 // subscribe
1367 json::Value request;
1368 request[jss::account_history_tx_stream] = json::ValueType::Object;
1369 request[jss::account_history_tx_stream][jss::account] = carol.human();
1370 auto wscLong = makeWSClient(env.app().config());
1371 auto const jv = wscLong->invoke("subscribe", request);
1372 BEAST_EXPECT(env.syncClose());
1373 {
1374 // take out existing txns from the stream
1375 IdxHashVec tempVec;
1376 getTxHash(*wscLong, tempVec, 100, 1000ms);
1377 }
1378
1379 // repeat the payments many rounds
1380 for (int kk = 2; kk < 10; ++kk)
1381 {
1382 auto const count = oneRound(kk);
1383 IdxHashVec vec1;
1384 if (!BEAST_EXPECT(getTxHash(*wscLong, vec1, count).first))
1385 return;
1386
1387 // another subscribe, only for this round
1388 auto wscShort = makeWSClient(env.app().config());
1389 auto const jv = wscShort->invoke("subscribe", request);
1390 IdxHashVec vec2;
1391 if (!BEAST_EXPECT(getTxHash(*wscShort, vec2, count).first))
1392 return;
1393 if (!BEAST_EXPECT(hashCompare(vec1, vec2, true)))
1394 return;
1395 wscShort->invoke("unsubscribe", request);
1396 }
1397 }
1398 }
1399
1400 void
1402 {
1403 testcase("SubBookChanges");
1404 using namespace jtx;
1405 using namespace std::chrono_literals;
1406 FeatureBitset const all{
1407 jtx::testableAmendments() | featurePermissionedDomains | featureCredentials |
1408 featurePermissionedDEX,
1409 };
1410
1411 Env env(*this, singleThreadIo(envconfig()), all);
1412 PermissionedDEX const permDex(env);
1413 auto const alice = permDex.alice;
1414 auto const bob = permDex.bob;
1415 auto const carol = permDex.carol;
1416 auto const domainID = permDex.domainID;
1417 auto const gw = permDex.gw;
1418 auto const usd = permDex.usd;
1419
1420 auto wsc = makeWSClient(env.app().config());
1421
1422 json::Value streams;
1423 streams[jss::streams] = json::ValueType::Array;
1424 streams[jss::streams][0u] = "book_changes";
1425
1426 auto jv = wsc->invoke("subscribe", streams);
1427 if (!BEAST_EXPECT(jv[jss::status] == "success"))
1428 return;
1429 env(offer(alice, XRP(10), usd(10)), Domain(domainID), Txflags(tfHybrid));
1430 BEAST_EXPECT(env.syncClose());
1431
1432 env(pay(bob, carol, usd(5)), Path(~usd), Sendmax(XRP(5)), Domain(domainID));
1433 BEAST_EXPECT(env.syncClose());
1434
1435 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
1436 if (jv[jss::changes].size() != 1)
1437 return false;
1438
1439 auto const jrOffer = jv[jss::changes][0u];
1440 return (jv[jss::changes][0u][jss::domain]).asString() == strHex(domainID) &&
1441 jrOffer[jss::currency_a].asString() == "XRP_drops" &&
1442 jrOffer[jss::volume_a].asString() == "5000000" &&
1443 jrOffer[jss::currency_b].asString() == "rHUKYAZyUFn8PCZWbPfwHfbVQXTYrYKkHb/USD" &&
1444 jrOffer[jss::volume_b].asString() == "5";
1445 }));
1446 }
1447
1448 void
1450 {
1451 // `nftoken_id` is added for `transaction` stream in the `subscribe`
1452 // response for NFTokenMint and NFTokenAcceptOffer.
1453 //
1454 // `nftoken_ids` is added for `transaction` stream in the `subscribe`
1455 // response for NFTokenCancelOffer
1456 //
1457 // `offer_id` is added for `transaction` stream in the `subscribe`
1458 // response for NFTokenCreateOffer
1459 //
1460 // The values of these fields are dependent on the NFTokenID/OfferID
1461 // changed in its corresponding transaction. We want to validate each
1462 // response to make sure the synthetic fields hold the right values.
1463
1464 testcase("Test synthetic fields from Subscribe response");
1465
1466 using namespace test::jtx;
1467 using namespace std::chrono_literals;
1468
1469 Account const alice{"alice"};
1470 Account const bob{"bob"};
1471 Account const broker{"broker"};
1472
1473 Env env{*this, singleThreadIo(envconfig()), features};
1474 env.fund(XRP(10000), alice, bob, broker);
1475 BEAST_EXPECT(env.syncClose());
1476
1477 auto wsc = test::makeWSClient(env.app().config());
1478 json::Value stream;
1479 stream[jss::streams] = json::ValueType::Array;
1480 stream[jss::streams].append("transactions");
1481 auto const jv = wsc->invoke("subscribe", stream);
1482
1483 // Verify `nftoken_id` value equals to the NFTokenID that was
1484 // changed in the most recent NFTokenMint or NFTokenAcceptOffer
1485 // transaction
1486 auto const verifyNFTokenID = [&](UInt256 const& actualNftID) {
1487 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
1488 UInt256 nftID;
1489 BEAST_EXPECT(nftID.parseHex(jv[jss::meta][jss::nftoken_id].asString()));
1490 return nftID == actualNftID;
1491 }));
1492 };
1493
1494 // Verify `nftoken_ids` value equals to the NFTokenIDs that were
1495 // changed in the most recent NFTokenCancelOffer transaction
1496 auto const verifyNFTokenIDsInCancelOffer = [&](std::vector<UInt256> actualNftIDs) {
1497 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
1498 std::vector<UInt256> metaIDs;
1499 std::transform(
1500 jv[jss::meta][jss::nftoken_ids].begin(),
1501 jv[jss::meta][jss::nftoken_ids].end(),
1502 std::back_inserter(metaIDs),
1503 [this](json::Value id) {
1504 UInt256 nftID;
1505 BEAST_EXPECT(nftID.parseHex(id.asString()));
1506 return nftID;
1507 });
1508 // Sort both array to prepare for comparison
1509 std::ranges::sort(metaIDs);
1510 std::ranges::sort(actualNftIDs);
1511
1512 // Make sure the expect number of NFTs is correct
1513 BEAST_EXPECT(metaIDs.size() == actualNftIDs.size());
1514
1515 // Check the value of NFT ID in the meta with the
1516 // actual values
1517 for (size_t i = 0; i < metaIDs.size(); ++i)
1518 {
1519 BEAST_EXPECT(metaIDs[i] == actualNftIDs[i]);
1520 }
1521 return true;
1522 }));
1523 };
1524
1525 // Verify `offer_id` value equals to the offerID that was
1526 // changed in the most recent NFTokenCreateOffer tx
1527 auto const verifyNFTokenOfferID = [&](UInt256 const& offerID) {
1528 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
1529 UInt256 metaOfferID;
1530 BEAST_EXPECT(metaOfferID.parseHex(jv[jss::meta][jss::offer_id].asString()));
1531 return metaOfferID == offerID;
1532 }));
1533 };
1534
1535 // Check new fields in tx meta when for all NFTtransactions
1536 {
1537 // Alice mints 2 NFTs
1538 // Verify the NFTokenIDs are correct in the NFTokenMint tx meta
1539 UInt256 const nftId1{token::getNextID(env, alice, 0u, tfTransferable)};
1540 env(token::mint(alice, 0u), Txflags(tfTransferable));
1541 BEAST_EXPECT(env.syncClose());
1542 verifyNFTokenID(nftId1);
1543
1544 UInt256 const nftId2{token::getNextID(env, alice, 0u, tfTransferable)};
1545 env(token::mint(alice, 0u), Txflags(tfTransferable));
1546 BEAST_EXPECT(env.syncClose());
1547 verifyNFTokenID(nftId2);
1548
1549 // Alice creates one sell offer for each NFT
1550 // Verify the offer indexes are correct in the NFTokenCreateOffer tx
1551 // meta
1552 UInt256 const aliceOfferIndex1 =
1553 keylet::nftokenOffer(alice, SeqProxy::rawSequence(env.seq(alice))).key;
1554 env(token::createOffer(alice, nftId1, drops(1)), Txflags(tfSellNFToken));
1555 BEAST_EXPECT(env.syncClose());
1556 verifyNFTokenOfferID(aliceOfferIndex1);
1557
1558 UInt256 const aliceOfferIndex2 =
1559 keylet::nftokenOffer(alice, SeqProxy::rawSequence(env.seq(alice))).key;
1560 env(token::createOffer(alice, nftId2, drops(1)), Txflags(tfSellNFToken));
1561 BEAST_EXPECT(env.syncClose());
1562 verifyNFTokenOfferID(aliceOfferIndex2);
1563
1564 // Alice cancels two offers she created
1565 // Verify the NFTokenIDs are correct in the NFTokenCancelOffer tx
1566 // meta
1567 env(token::cancelOffer(alice, {aliceOfferIndex1, aliceOfferIndex2}));
1568 BEAST_EXPECT(env.syncClose());
1569 verifyNFTokenIDsInCancelOffer({nftId1, nftId2});
1570
1571 // Bobs creates a buy offer for nftId1
1572 // Verify the offer id is correct in the NFTokenCreateOffer tx meta
1573 auto const bobBuyOfferIndex =
1575 env(token::createOffer(bob, nftId1, drops(1)), token::Owner(alice));
1576 BEAST_EXPECT(env.syncClose());
1577 verifyNFTokenOfferID(bobBuyOfferIndex);
1578
1579 // Alice accepts bob's buy offer
1580 // Verify the NFTokenID is correct in the NFTokenAcceptOffer tx meta
1581 env(token::acceptBuyOffer(alice, bobBuyOfferIndex));
1582 BEAST_EXPECT(env.syncClose());
1583 verifyNFTokenID(nftId1);
1584 }
1585
1586 // Check `nftoken_ids` in brokered mode
1587 {
1588 // Alice mints a NFT
1589 UInt256 const nftId{token::getNextID(env, alice, 0u, tfTransferable)};
1590 env(token::mint(alice, 0u), Txflags(tfTransferable));
1591 BEAST_EXPECT(env.syncClose());
1592 verifyNFTokenID(nftId);
1593
1594 // Alice creates sell offer and set broker as destination
1595 UInt256 const offerAliceToBroker =
1596 keylet::nftokenOffer(alice, SeqProxy::rawSequence(env.seq(alice))).key;
1597 env(token::createOffer(alice, nftId, drops(1)),
1598 token::Destination(broker),
1599 Txflags(tfSellNFToken));
1600 BEAST_EXPECT(env.syncClose());
1601 verifyNFTokenOfferID(offerAliceToBroker);
1602
1603 // Bob creates buy offer
1604 UInt256 const offerBobToBroker =
1606 env(token::createOffer(bob, nftId, drops(1)), token::Owner(alice));
1607 BEAST_EXPECT(env.syncClose());
1608 verifyNFTokenOfferID(offerBobToBroker);
1609
1610 // Check NFTokenID meta for NFTokenAcceptOffer in brokered mode
1611 env(token::brokerOffers(broker, offerBobToBroker, offerAliceToBroker));
1612 BEAST_EXPECT(env.syncClose());
1613 verifyNFTokenID(nftId);
1614 }
1615
1616 // Check if there are no duplicate nft id in Cancel transactions where
1617 // multiple offers are cancelled for the same NFT
1618 {
1619 // Alice mints a NFT
1620 UInt256 const nftId{token::getNextID(env, alice, 0u, tfTransferable)};
1621 env(token::mint(alice, 0u), Txflags(tfTransferable));
1622 BEAST_EXPECT(env.syncClose());
1623 verifyNFTokenID(nftId);
1624
1625 // Alice creates 2 sell offers for the same NFT
1626 UInt256 const aliceOfferIndex1 =
1627 keylet::nftokenOffer(alice, SeqProxy::rawSequence(env.seq(alice))).key;
1628 env(token::createOffer(alice, nftId, drops(1)), Txflags(tfSellNFToken));
1629 BEAST_EXPECT(env.syncClose());
1630 verifyNFTokenOfferID(aliceOfferIndex1);
1631
1632 UInt256 const aliceOfferIndex2 =
1633 keylet::nftokenOffer(alice, SeqProxy::rawSequence(env.seq(alice))).key;
1634 env(token::createOffer(alice, nftId, drops(1)), Txflags(tfSellNFToken));
1635 BEAST_EXPECT(env.syncClose());
1636 verifyNFTokenOfferID(aliceOfferIndex2);
1637
1638 // Make sure the metadata only has 1 nft id, since both offers are
1639 // for the same nft
1640 env(token::cancelOffer(alice, {aliceOfferIndex1, aliceOfferIndex2}));
1641 BEAST_EXPECT(env.syncClose());
1642 verifyNFTokenIDsInCancelOffer({nftId});
1643 }
1644
1645 if (features[featureNFTokenMintOffer])
1646 {
1647 UInt256 const aliceMintWithOfferIndex1 =
1648 keylet::nftokenOffer(alice, SeqProxy::rawSequence(env.seq(alice))).key;
1649 env(token::mint(alice), token::Amount(XRP(0)));
1650 BEAST_EXPECT(env.syncClose());
1651 verifyNFTokenOfferID(aliceMintWithOfferIndex1);
1652 }
1653 }
1654
1655 // ----- Subscription limit / teardown verification ----------------------
1656 //
1657 // The helpers and tests below exercise:
1658 // * the per-connection subscription cap + proportional charge enforced
1659 // in doSubscribe (Subscribe.cpp), and
1660 // * the asynchronous, chunked teardown of a disconnecting connection's
1661 // account subscriptions (~InfoSub -> scheduleAccountCleanup -> JobQueue).
1662 //
1663 // The cap-exceeded error is rpcINVALID_PARAMS with the message "Too many
1664 // subscriptions for this connection."; the tests assert that exactly.
1665 //
1666 // There is no public accessor for the server-side per-connection count, so
1667 // the async cleanup is verified behaviorally: publishing still flows to a
1668 // live subscriber, rather than by reading a count to zero.
1669
1670 // Build `count` distinct, valid, base58-encoded account strings cheaply by
1671 // incrementing an AccountID. parseAccountIds dedups into a HashSet, so the
1672 // strings MUST be distinct for the cap arithmetic to be exact; incrementing
1673 // guarantees distinctness without deriving `count` keypairs.
1674 static std::vector<std::string>
1676 {
1678 out.reserve(count);
1679 // Start at `seed` so separate calls produce non-overlapping ranges,
1680 // letting a test subscribe disjoint batches across requests.
1681 AccountID id{static_cast<std::uint64_t>(seed)};
1682 for (std::size_t i = 0; i < count; ++i)
1683 {
1684 out.push_back(toBase58(id));
1685 ++id;
1686 }
1687 return out;
1688 }
1689
1690 // Append the given account strings as a jss::accounts array onto a fresh
1691 // subscribe request object.
1692 static json::Value
1694 {
1696 jv[jss::accounts] = json::ValueType::Array;
1697 for (auto const& a : accts)
1698 jv[jss::accounts].append(a);
1699 return jv;
1700 }
1701
1702 // Append the given account strings as a jss::accounts_proposed array onto a
1703 // fresh subscribe request object.
1704 static json::Value
1706 {
1708 jv[jss::accounts_proposed] = json::ValueType::Array;
1709 for (auto const& a : accts)
1710 jv[jss::accounts_proposed].append(a);
1711 return jv;
1712 }
1713
1714 // Build `count` distinct, valid MPT issuance id strings the same cheap way
1715 // as makeAccountStrings: by incrementing an MPTID. doSubscribe only parses
1716 // these (it does not require the issuances to exist in the ledger), and
1717 // parseMPTIssuanceIDs dedups into a HashSet, so distinctness is what makes
1718 // the cap arithmetic exact.
1721 {
1723 out.reserve(count);
1724 // Start at `seed` so separate calls produce non-overlapping ranges.
1725 MPTID id{static_cast<std::uint64_t>(seed)};
1726 for (std::size_t i = 0; i < count; ++i)
1727 {
1728 out.push_back(to_string(id));
1729 ++id;
1730 }
1731 return out;
1732 }
1733
1734 // Append the given issuance ids as a jss::mpt_issuances array onto a fresh
1735 // subscribe request object.
1736 static json::Value
1738 {
1740 jv[jss::mpt_issuances] = json::ValueType::Array;
1741 for (auto const& id : mptIDs)
1742 jv[jss::mpt_issuances].append(id);
1743 return jv;
1744 }
1745
1746 // A single, valid XRP/USD order book request, as one entry of a
1747 // jss::books array.
1748 static json::Value
1750 {
1751 using namespace jtx;
1753 jv[jss::books] = json::ValueType::Array;
1754 json::Value& book = jv[jss::books][0u];
1755 book[jss::taker_gets] = json::ValueType::Object;
1756 book[jss::taker_gets][jss::currency] = "XRP";
1757 book[jss::taker_pays] = json::ValueType::Object;
1758 book[jss::taker_pays][jss::currency] = "USD";
1759 book[jss::taker_pays][jss::issuer] = Account("alice").human();
1760 return jv;
1761 }
1762
1763 // A single account_history_tx_stream subscribe request for `acct`.
1764 static json::Value
1766 {
1768 jv[jss::account_history_tx_stream] = json::ValueType::Object;
1769 jv[jss::account_history_tx_stream][jss::account] = acct;
1770 return jv;
1771 }
1772
1773 // An envconfig modifier that lowers the per-connection subscription cap to
1774 // `cap`, so the cap logic in doSubscribe can be driven without subscribing
1775 // the production default (100'000) entries. (Env is non-movable, so this
1776 // returns the config modifier rather than a ready-made Env.)
1777 static auto
1779 {
1780 return [cap](std::unique_ptr<Config> cfg) {
1781 cfg->maxSubscriptionsPerConnection = cap;
1782 return jtx::singleThreadIo(std::move(cfg));
1783 };
1784 }
1785
1786 void
1788 {
1789 // A request that alone exceeds the cap is rejected with the exact
1790 // cap error, before any state is recorded. Baseline negative path.
1791 testcase("subscription cap rejects an over-cap request");
1792
1793 using namespace jtx;
1794 Env env{*this, envconfig(cappedConfig(5))};
1795 auto wsc = makeWSClient(env.app().config());
1796
1797 // Six accounts against a cap of five: rejected.
1798 auto const jr =
1799 wsc->invoke("subscribe", accountsRequest(makeAccountStrings(6)))[jss::result];
1800 BEAST_EXPECT(jr[jss::error] == "invalidParams");
1801 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
1802 BEAST_EXPECT(jr[jss::error_message] == "Too many subscriptions for this connection.");
1803 }
1804
1805 void
1807 {
1808 // Re-subscribing accounts already held by this connection adds no new
1809 // tracked state, so it must be admitted even at the cap. The cap check
1810 // must count only NET-NEW accounts, not the raw request size.
1811 testcase("re-subscribe at the cap is not over-counted");
1812
1813 using namespace jtx;
1814 Env env{*this, envconfig(cappedConfig(5))};
1815 auto wsc = makeWSClient(env.app().config());
1816
1817 // Fill the cap exactly with five distinct accounts.
1818 auto const five = makeAccountStrings(5);
1819 {
1820 auto const r = wsc->invoke("subscribe", accountsRequest(five));
1821 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
1822 }
1823
1824 // Re-subscribe the same five: net-new is zero, so it stays within the
1825 // cap and must succeed. (Pre-fix this was wrongly rejected.)
1826 {
1827 auto const r = wsc->invoke("subscribe", accountsRequest(five));
1828 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
1829 }
1830 }
1831
1832 void
1834 {
1835 // Book subscriptions are tracked separately (OrderBookDB) and are not
1836 // part of totalSubscriptionCount(). An account set at the cap must not
1837 // block an unrelated book subscription.
1838 testcase("books cap is independent of account count");
1839
1840 using namespace jtx;
1841 Env env{*this, envconfig(cappedConfig(5))};
1842 Account const alice{"alice"};
1843 env.fund(XRP(10000), alice);
1844 BEAST_EXPECT(env.syncClose());
1845
1846 auto wsc = makeWSClient(env.app().config());
1847
1848 // Fill the account cap exactly.
1849 {
1850 auto const r = wsc->invoke("subscribe", accountsRequest(makeAccountStrings(5)));
1851 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
1852 }
1853
1854 // A single book subscription must still be admitted: it does not count
1855 // against the account cap. (Pre-fix this was wrongly rejected.)
1856 {
1857 auto const r = wsc->invoke("subscribe", oneBookRequest());
1858 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
1859 }
1860 }
1861
1862 void
1864 {
1865 // A single request mixing fields must be all-or-nothing: if a later
1866 // field trips the cap, an earlier field must NOT have subscribed. The
1867 // leak is detected through the cap arithmetic itself - a follow-up
1868 // request succeeds only if no state leaked from the rejected one.
1869 testcase("multi-field subscribe does not partially subscribe");
1870
1871 using namespace jtx;
1872 Env env{*this, envconfig(cappedConfig(5))};
1873 auto wsc = makeWSClient(env.app().config());
1874
1875 // accounts_proposed (3, evaluated first, would subscribe) +
1876 // accounts (3): combined 6 exceeds the cap of 5, so the request is
1877 // rejected. The proposed branch must not have leaked its 3 entries.
1879 for (auto const& a : makeAccountStrings(3, 100))
1880 req[jss::accounts].append(a);
1881 {
1882 auto const jr = wsc->invoke("subscribe", req)[jss::result];
1883 BEAST_EXPECT(jr[jss::error] == "invalidParams");
1884 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
1885 BEAST_EXPECT(jr[jss::error_message] == "Too many subscriptions for this connection.");
1886 }
1887
1888 // If the rejected request leaked its 3 proposed subscriptions, the
1889 // connection's count is already 3 and this 3-account request would be
1890 // rejected (3 + 3 > 5). With no leak the count is 0 and it succeeds.
1891 {
1892 auto const r = wsc->invoke("subscribe", accountsRequest(makeAccountStrings(3, 200)));
1893 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
1894 }
1895 }
1896
1897 void
1899 {
1900 // An account_history_tx_stream subscribe is charged against the cap only
1901 // when it is net-new, matching the account branches. Re-subscribing an
1902 // account-history already held on this connection adds no tracked entry,
1903 // so it must NOT be rejected at the cap. The two rejection causes are
1904 // told apart by their exact error_message: the cap check yields "Too
1905 // many subscriptions for this connection."; a duplicate that gets past
1906 // the cap and is rejected downstream by subAccountHistory yields the
1907 // generic "Invalid parameters.".
1908 testcase("account_history re-subscribe at the cap is not over-counted");
1909
1910 using namespace jtx;
1911 Env env{*this, envconfig(cappedConfig(1))};
1912 Account const alice{"alice"};
1913 env.fund(XRP(10000), alice);
1914 BEAST_EXPECT(env.syncClose());
1915
1916 auto wsc = makeWSClient(env.app().config());
1917
1918 // First account-history subscribe is net-new: charge 1 fills the cap of
1919 // 1 exactly, so it is admitted. Positive path.
1920 {
1921 auto const r = wsc->invoke("subscribe", accountHistoryRequest(alice.human()));
1922 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
1923 }
1924
1925 // Re-subscribe the same account-history while sitting exactly at the
1926 // cap. Net-new is zero, so the cap check must pass; the request is then
1927 // rejected by subAccountHistory as a duplicate, NOT by the cap. Proven
1928 // by the exact message: it is the duplicate error, not the cap error.
1929 // (Pre-fix, the flat charge of 1 made the cap check reject this with the
1930 // cap message instead.)
1931 {
1932 auto const jr =
1933 wsc->invoke("subscribe", accountHistoryRequest(alice.human()))[jss::result];
1934 BEAST_EXPECT(jr[jss::error] == "invalidParams");
1935 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
1936 BEAST_EXPECT(jr[jss::error_message] == "Invalid parameters.");
1937 BEAST_EXPECT(jr[jss::error_message] != "Too many subscriptions for this connection.");
1938 }
1939 }
1940
1941 void
1943 {
1944 // A genuinely net-new account-history subscribe on a connection already
1945 // at the cap IS rejected, with the cap error. Negative path, and the
1946 // counterpart to testHistoryReSubscribeNotOvercounted: it confirms the
1947 // net-new charge still rejects when the entry really is new.
1948 testcase("account_history net-new subscribe is rejected at the cap");
1949
1950 using namespace jtx;
1951 Env env{*this, envconfig(cappedConfig(1))};
1952 Account const alice{"alice"};
1953 Account const bob{"bob"};
1954 env.fund(XRP(10000), alice, bob);
1955 BEAST_EXPECT(env.syncClose());
1956
1957 auto wsc = makeWSClient(env.app().config());
1958
1959 // Fill the cap of 1 with alice's account-history.
1960 {
1961 auto const r = wsc->invoke("subscribe", accountHistoryRequest(alice.human()));
1962 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
1963 }
1964
1965 // A different account-history (bob) is net-new: charge 1 over a cap of 1
1966 // already full, so it is rejected with the cap error.
1967 {
1968 auto const jr =
1969 wsc->invoke("subscribe", accountHistoryRequest(bob.human()))[jss::result];
1970 BEAST_EXPECT(jr[jss::error] == "invalidParams");
1971 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
1972 BEAST_EXPECT(jr[jss::error_message] == "Too many subscriptions for this connection.");
1973 }
1974 }
1975
1976 void
1978 {
1979 // MPT issuance subscriptions are per-connection tracked state, so they
1980 // are bounded by the same cap as the account branches. A request that
1981 // alone exceeds the cap is rejected with the cap error, and nothing is
1982 // recorded. (Pre-fix the mpt_issuances branch skipped the cap check
1983 // entirely, so a client could hold unbounded issuance subscriptions.)
1984 testcase("mpt_issuances cap rejects an over-cap request");
1985
1986 using namespace jtx;
1987 Env env{*this, envconfig(cappedConfig(5))};
1988 auto wsc = makeWSClient(env.app().config());
1989
1990 // Six issuances against a cap of five: rejected.
1991 {
1992 auto const jr = wsc->invoke(
1993 "subscribe", mptIssuancesRequest(makeMPTIssuanceStrings(6)))[jss::result];
1994 BEAST_EXPECT(jr[jss::error] == "invalidParams");
1995 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
1996 BEAST_EXPECT(jr[jss::error_message] == "Too many subscriptions for this connection.");
1997 }
1998
1999 // The rejected request reserved nothing: a five-issuance request (the
2000 // cap exactly) still fits. If the rejected one had leaked entries this
2001 // would be rejected too.
2002 {
2003 auto const r = wsc->invoke("subscribe", mptIssuancesRequest(makeMPTIssuanceStrings(5)));
2004 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2005 }
2006 }
2007
2008 void
2010 {
2011 // Like the account branches, the MPT charge counts only NET-NEW
2012 // issuances: re-subscribing issuances already held adds no tracked
2013 // state, so it must be admitted even sitting exactly at the cap.
2014 testcase("mpt_issuances re-subscribe at the cap is not over-counted");
2015
2016 using namespace jtx;
2017 Env env{*this, envconfig(cappedConfig(5))};
2018 auto wsc = makeWSClient(env.app().config());
2019
2020 // Fill the cap exactly with five distinct issuances.
2021 auto const five = makeMPTIssuanceStrings(5);
2022 {
2023 auto const r = wsc->invoke("subscribe", mptIssuancesRequest(five));
2024 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2025 }
2026
2027 // Re-subscribe the same five: net-new is zero, so it stays within the
2028 // cap and must succeed.
2029 {
2030 auto const r = wsc->invoke("subscribe", mptIssuancesRequest(five));
2031 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2032 }
2033
2034 // A single net-new issuance on top of a full cap IS rejected.
2035 {
2036 auto const jr = wsc->invoke(
2037 "subscribe", mptIssuancesRequest(makeMPTIssuanceStrings(1, 100)))[jss::result];
2038 BEAST_EXPECT(jr[jss::error] == "invalidParams");
2039 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
2040 BEAST_EXPECT(jr[jss::error_message] == "Too many subscriptions for this connection.");
2041 }
2042 }
2043
2044 void
2046 {
2047 // The cap is one budget over all tracked kinds, so MPT issuances and
2048 // accounts consume the same allowance in either order.
2049 testcase("mpt_issuances and accounts share one cap");
2050
2051 using namespace jtx;
2052
2053 // Accounts first, then MPTs: 3 + 3 over a cap of 5 is rejected.
2054 {
2055 Env env{*this, envconfig(cappedConfig(5))};
2056 auto wsc = makeWSClient(env.app().config());
2057
2058 auto const r = wsc->invoke("subscribe", accountsRequest(makeAccountStrings(3)));
2059 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2060
2061 auto const jr = wsc->invoke(
2062 "subscribe", mptIssuancesRequest(makeMPTIssuanceStrings(3)))[jss::result];
2063 BEAST_EXPECT(jr[jss::error] == "invalidParams");
2064 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
2065 BEAST_EXPECT(jr[jss::error_message] == "Too many subscriptions for this connection.");
2066
2067 // Two more issuances do fit the remaining allowance.
2068 auto const r2 =
2069 wsc->invoke("subscribe", mptIssuancesRequest(makeMPTIssuanceStrings(2)));
2070 BEAST_EXPECTS(r2[jss::status] == "success", to_string(r2));
2071 }
2072
2073 // MPTs first, then accounts: the tally MPTs contribute is what rejects
2074 // the accounts, proving mptSubscriptions_ is part of the count and not
2075 // just checked against it.
2076 {
2077 Env env{*this, envconfig(cappedConfig(5))};
2078 auto wsc = makeWSClient(env.app().config());
2079
2080 auto const r = wsc->invoke("subscribe", mptIssuancesRequest(makeMPTIssuanceStrings(5)));
2081 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2082
2083 auto const jr =
2084 wsc->invoke("subscribe", accountsRequest(makeAccountStrings(1)))[jss::result];
2085 BEAST_EXPECT(jr[jss::error] == "invalidParams");
2086 BEAST_EXPECT(jr[jss::error_code] == RpcInvalidParams);
2087 BEAST_EXPECT(jr[jss::error_message] == "Too many subscriptions for this connection.");
2088 }
2089 }
2090
2091 void
2093 {
2094 // Unsubscribing releases the allowance: after dropping the issuances,
2095 // the same connection can subscribe a fresh batch. Guards against a
2096 // reserve that is never given back (which would turn the cap into a
2097 // permanent per-connection budget).
2098 testcase("mpt_issuances unsubscribe frees cap allowance");
2099
2100 using namespace jtx;
2101 Env env{*this, envconfig(cappedConfig(5))};
2102 auto wsc = makeWSClient(env.app().config());
2103
2104 auto const five = makeMPTIssuanceStrings(5);
2105 {
2106 auto const r = wsc->invoke("subscribe", mptIssuancesRequest(five));
2107 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2108 }
2109
2110 {
2111 auto const r = wsc->invoke("unsubscribe", mptIssuancesRequest(five));
2112 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2113 }
2114
2115 // The cap is free again, so a disjoint batch of five is admitted.
2116 {
2117 auto const r =
2118 wsc->invoke("subscribe", mptIssuancesRequest(makeMPTIssuanceStrings(5, 100)));
2119 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2120 }
2121 }
2122
2123 void
2125 {
2126 // Test C (core regression): disconnecting a connection with many
2127 // account subscriptions must NOT block subsequent operations or
2128 // publishing. The teardown is now posted to a JobQueue job
2129 // (scheduleAccountCleanup), so it runs off the disconnect thread.
2130 testcase("async teardown does not stall publishing");
2131
2132 using namespace std::chrono_literals;
2133 using namespace jtx;
2134 Env env{*this, singleThreadIo(envconfig())};
2135
2136 Account const alice{"alice"};
2137 env.fund(XRP(10000), alice);
2138 BEAST_EXPECT(env.syncClose());
2139
2140 // A second, long-lived subscriber to alice that must keep receiving
2141 // publishes after the first connection disconnects.
2142 auto wscLive = makeWSClient(env.app().config());
2143 {
2145 jv[jss::accounts] = json::ValueType::Array;
2146 jv[jss::accounts].append(alice.human());
2147 auto const r = wscLive->invoke("subscribe", jv);
2148 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2149 }
2150
2151 // A connection that subscribes to many accounts, then disconnects. A
2152 // few thousand entries is enough to be a real teardown while still
2153 // running fast in CI.
2154 constexpr std::size_t kBulk = 3000;
2155 {
2156 auto wscBulk = makeWSClient(env.app().config());
2157 auto const r =
2158 wscBulk->invoke("subscribe", accountsRequest(makeAccountStrings(kBulk, 10)));
2159 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2160 // Destroying the client closes the WS connection, which destroys
2161 // the server-side InfoSub and posts the chunked async cleanup job.
2162 // WSClient exposes no explicit close(); resetting the owning
2163 // unique_ptr is the disconnect path.
2164 wscBulk.reset();
2165 }
2166
2167 // Immediately after the disconnect, an unrelated operation completes
2168 // promptly (it would block for seconds with inline teardown). This is a
2169 // cheap liveness check; the publish assertion below is the real proof.
2170 {
2171 auto const info = env.app().getOPs().getServerInfo(false, true, false);
2172 BEAST_EXPECT(info.isMember(jss::server_state));
2173 }
2174
2175 // The live subscriber still receives a published transaction for alice
2176 // within a short timeout, proving account-publishing was not stalled by
2177 // the concurrent teardown.
2178 {
2179 env(pay(env.master, alice, XRP(100)));
2180 BEAST_EXPECT(env.syncClose());
2181 BEAST_EXPECT(wscLive->findMsg(5s, [&](auto const& jv) {
2182 return jv.isMember(jss::transaction) &&
2183 jv[jss::transaction][jss::TransactionType] == jss::Payment &&
2184 jv[jss::transaction][jss::Destination] == alice.human();
2185 }));
2186 }
2187
2188 wscLive->invoke("unsubscribe", accountsRequest({alice.human()}));
2189 }
2190
2191 void
2193 {
2194 // Test D (Phase 3 correctness): connection A subscribes to account X
2195 // and disconnects (async cleanup pending, keyed on A's seq). A new
2196 // connection B subscribes to X and MUST still receive publishes for X -
2197 // A's deferred, seq-keyed cleanup must not remove B's subscription.
2198 testcase("re-subscribe after disconnect still delivers");
2199
2200 using namespace std::chrono_literals;
2201 using namespace jtx;
2202 Env env{*this, singleThreadIo(envconfig())};
2203
2204 Account const alice{"alice"};
2205 env.fund(XRP(10000), alice);
2206 BEAST_EXPECT(env.syncClose());
2207
2208 // Connection A subscribes to alice, then disconnects. A also subscribes
2209 // to a bulk set so its deferred cleanup is non-trivial and races with B.
2210 {
2211 auto wscA = makeWSClient(env.app().config());
2212 auto bulk = makeAccountStrings(2000, 10);
2213 bulk.push_back(alice.human());
2214 auto const r = wscA->invoke("subscribe", accountsRequest(bulk));
2215 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2216 // Disconnect A by destroying its client (no explicit close()).
2217 wscA.reset();
2218 }
2219
2220 // Connection B (a new InfoSub with a distinct seq) subscribes to alice.
2221 auto wscB = makeWSClient(env.app().config());
2222 {
2224 jv[jss::accounts] = json::ValueType::Array;
2225 jv[jss::accounts].append(alice.human());
2226 auto const r = wscB->invoke("subscribe", jv);
2227 BEAST_EXPECTS(r[jss::status] == "success", to_string(r));
2228 }
2229
2230 // A publish for alice must reach B. If A's seq-keyed cleanup had wrongly
2231 // removed the shared alice entry, B would receive nothing.
2232 {
2233 env(pay(env.master, alice, XRP(100)));
2234 BEAST_EXPECT(env.syncClose());
2235 BEAST_EXPECT(wscB->findMsg(5s, [&](auto const& jv) {
2236 return jv.isMember(jss::transaction) &&
2237 jv[jss::transaction][jss::TransactionType] == jss::Payment &&
2238 jv[jss::transaction][jss::Destination] == alice.human();
2239 }));
2240 }
2241
2242 wscB->invoke("unsubscribe", accountsRequest({alice.human()}));
2243 }
2244
2245 void
2247 {
2248 // subscribe to multiple MPTs
2249 testcase("SubMPT");
2250 using namespace jtx;
2251 using namespace std::chrono_literals;
2252
2253 Env env(*this);
2254
2255 Account const alice{"alice"};
2256 Account const bob{"bob"};
2257 Account const carol{"carol"};
2258 Account const dan{"dan"};
2259
2260 auto wsc = makeWSClient(env.app().config());
2261
2262 MPTTester mptAlice(env, alice, {.holders = {bob}});
2263 MPTTester mptCarol(env, carol, {.holders = {dan}});
2264
2265 // Transfer fee is 10%
2266 mptAlice.create(
2267 {.transferFee = 10'000, .ownerCount = 1, .flags = tfMPTCanTransfer | tfMPTCanLock});
2268 mptCarol.create({.ownerCount = 1, .flags = tfMPTCanTransfer});
2269
2270 json::Value stream;
2271 stream = json::ValueType::Object;
2272 stream[jss::mpt_issuances] = json::ValueType::Array;
2273 stream[jss::mpt_issuances].append(to_string(mptAlice.issuanceID()));
2274 stream[jss::mpt_issuances].append(to_string(mptCarol.issuanceID()));
2275 auto jv = wsc->invoke("subscribe", stream);
2276 BEAST_EXPECT(jv[jss::status] == "success");
2277
2278 // bob create MPToken
2279 mptAlice.authorize({.account = bob});
2280 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
2281 return jv[jss::engine_result] == "tesSUCCESS" &&
2282 jv[jss::transaction][jss::Account] == bob.human() &&
2283 jv[jss::transaction][jss::Flags] == 0 &&
2284 jv[jss::transaction][sfMPTokenIssuanceID.jsonName] ==
2285 to_string(mptAlice.issuanceID()) &&
2286 jv[jss::transaction][jss::TransactionType] == "MPTokenAuthorize" &&
2287 jv[jss::type] == "transaction";
2288 }));
2289
2290 // dan create MPToken
2291 mptCarol.authorize({.account = dan});
2292 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
2293 return jv[jss::engine_result] == "tesSUCCESS" &&
2294 jv[jss::transaction][jss::Account] == dan.human() &&
2295 jv[jss::transaction][jss::Flags] == 0 &&
2296 jv[jss::transaction][sfMPTokenIssuanceID.jsonName] ==
2297 to_string(mptCarol.issuanceID()) &&
2298 jv[jss::transaction][jss::Sequence] == 5 &&
2299 jv[jss::transaction][jss::TransactionType] == "MPTokenAuthorize" &&
2300 jv[jss::type] == "transaction";
2301 }));
2302
2303 // subscribe stream sees alice's MPT
2304 mptAlice.pay(alice, bob, 2000);
2305 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
2306 return jv[jss::engine_result] == "tesSUCCESS" &&
2307 jv[jss::transaction][jss::Account] == alice.human() &&
2308 jv[jss::transaction][jss::Amount][jss::mpt_issuance_id] ==
2309 to_string(mptAlice.issuanceID()) &&
2310 jv[jss::transaction][jss::Amount][jss::value] == "2000" &&
2311 jv[jss::transaction][jss::DeliverMax][jss::mpt_issuance_id] ==
2312 to_string(mptAlice.issuanceID()) &&
2313 jv[jss::transaction][jss::DeliverMax][jss::value] == "2000" &&
2314 jv[jss::transaction][jss::Destination] == bob.human() &&
2315 jv[jss::transaction][jss::Flags] == tfFullyCanonicalSig &&
2316 jv[jss::transaction][jss::TransactionType] == "Payment" &&
2317 jv[jss::type] == "transaction";
2318 }));
2319
2320 // subscribe stream sees carol's MPT
2321 mptCarol.pay(carol, dan, 1000);
2322 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
2323 return jv[jss::engine_result] == "tesSUCCESS" &&
2324 jv[jss::transaction][jss::Account] == carol.human() &&
2325 jv[jss::transaction][jss::Amount][jss::mpt_issuance_id] ==
2326 to_string(mptCarol.issuanceID()) &&
2327 jv[jss::transaction][jss::Amount][jss::value] == "1000" &&
2328 jv[jss::transaction][jss::DeliverMax][jss::mpt_issuance_id] ==
2329 to_string(mptCarol.issuanceID()) &&
2330 jv[jss::transaction][jss::DeliverMax][jss::value] == "1000" &&
2331 jv[jss::transaction][jss::Destination] == dan.human() &&
2332 jv[jss::transaction][jss::Flags] == tfFullyCanonicalSig &&
2333 jv[jss::transaction][jss::Sequence] == 6 &&
2334 jv[jss::transaction][jss::TransactionType] == "Payment" &&
2335 jv[jss::type] == "transaction";
2336 }));
2337
2338 // subscribe stream sees alice's MPT lock
2339 mptAlice.set({.account = alice, .flags = tfMPTLock});
2340 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
2341 return jv[jss::engine_result] == "tesSUCCESS" &&
2342 jv[jss::transaction][jss::Account] == alice.human() &&
2343 jv[jss::transaction][jss::Flags] == tfMPTLock &&
2344 jv[jss::transaction][sfMPTokenIssuanceID.jsonName] ==
2345 to_string(mptAlice.issuanceID()) &&
2346 jv[jss::transaction][jss::TransactionType] == "MPTokenIssuanceSet" &&
2347 jv[jss::type] == "transaction";
2348 }));
2349
2350 // subscribe stream sees alice's MPT unlock
2351 mptAlice.set({.account = alice, .flags = tfMPTUnlock});
2352 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
2353 return jv[jss::engine_result] == "tesSUCCESS" &&
2354 jv[jss::transaction][jss::Account] == alice.human() &&
2355 jv[jss::transaction][jss::Flags] == tfMPTUnlock &&
2356 jv[jss::transaction][sfMPTokenIssuanceID.jsonName] ==
2357 to_string(mptAlice.issuanceID()) &&
2358 jv[jss::transaction][jss::TransactionType] == "MPTokenIssuanceSet" &&
2359 jv[jss::type] == "transaction";
2360 }));
2361
2362 // unsub alice's MPT from the stream
2363 json::Value unsubStream;
2364 unsubStream = json::ValueType::Object;
2365 unsubStream[jss::mpt_issuances] = json::ValueType::Array;
2366 unsubStream[jss::mpt_issuances].append(to_string(mptAlice.issuanceID()));
2367 auto unsubJv = wsc->invoke("unsubscribe", unsubStream);
2368 BEAST_EXPECT(unsubJv[jss::status] == "success");
2369
2370 // bob pays alice, this txn should no longer be sent by the stream
2371 mptAlice.pay(bob, alice, 500);
2372
2373 // we don't expect to find alice's mpt in the stream
2374 BEAST_EXPECT(!wsc->findMsg(5s, [&](auto const& jv) {
2375 return jv[jss::transaction][jss::Amount][jss::mpt_issuance_id] ==
2376 to_string(mptAlice.issuanceID()) &&
2377 jv[jss::transaction][jss::Amount][jss::value] == "500";
2378 }));
2379
2380 // this txn should be seen
2381 mptCarol.pay(dan, carol, 100);
2382
2383 // only carol's MPT txn will be seen
2384 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
2385 return jv[jss::engine_result] == "tesSUCCESS" &&
2386 jv[jss::transaction][jss::Account] == dan.human() &&
2387 jv[jss::transaction][jss::Amount][jss::mpt_issuance_id] ==
2388 to_string(mptCarol.issuanceID()) &&
2389 jv[jss::transaction][jss::Amount][jss::value] == "100" &&
2390 jv[jss::transaction][jss::DeliverMax][jss::mpt_issuance_id] ==
2391 to_string(mptCarol.issuanceID()) &&
2392 jv[jss::transaction][jss::DeliverMax][jss::value] == "100" &&
2393 jv[jss::transaction][jss::Destination] == carol.human() &&
2394 jv[jss::transaction][jss::Flags] == tfFullyCanonicalSig &&
2395 jv[jss::transaction][jss::TransactionType] == "Payment" &&
2396 jv[jss::type] == "transaction";
2397 }));
2398 }
2399
2400 void
2402 {
2403 // MPTs destroyed by the inner transactions of a Batch are still seen by
2404 // the stream. An MPTokenIssuance entry does not carry its own issuance
2405 // id, so this exercises deriving the id from the metadata.
2406 testcase("SubMPT batch");
2407 using namespace jtx;
2408 using namespace std::chrono_literals;
2409
2410 Env env(*this);
2411
2412 Account const alice{"alice"};
2413
2414 auto wsc = makeWSClient(env.app().config());
2415
2416 // A Batch requires at least two inner transactions, so destroy two
2417 // issuances at once.
2418 MPTTester mptAlice1(env, alice, MPTInit{});
2419 mptAlice1.create({.ownerCount = 1});
2420 auto const mptID1 = mptAlice1.issuanceID();
2421
2422 MPTTester mptAlice2(env, alice, MPTInit{.fund = false});
2423 mptAlice2.create({.ownerCount = 2});
2424 auto const mptID2 = mptAlice2.issuanceID();
2425
2426 json::Value stream;
2427 stream = json::ValueType::Object;
2428 stream[jss::mpt_issuances] = json::ValueType::Array;
2429 stream[jss::mpt_issuances].append(to_string(mptID1));
2430 stream[jss::mpt_issuances].append(to_string(mptID2));
2431 auto const jv = wsc->invoke("subscribe", stream);
2432 BEAST_EXPECT(jv[jss::status] == "success");
2433
2434 // destroy both issuances from inside a Batch
2435 auto const seq = env.seq(alice);
2436 auto const batchFee = batch::calcBatchFee(env, 0, 2);
2437 env(batch::outer(alice, seq, batchFee, tfAllOrNothing),
2438 batch::Inner(mptAlice1.destroyJV({.issuer = alice, .id = mptID1}), seq + 1),
2439 batch::Inner(mptAlice2.destroyJV({.issuer = alice, .id = mptID2}), seq + 2));
2440 env.close();
2441
2442 // each inner transaction is published on the stream for its own issuance
2443 for (auto const& mptID : {mptID1, mptID2})
2444 {
2445 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
2446 return jv[jss::engine_result] == "tesSUCCESS" &&
2447 jv[jss::transaction][jss::Account] == alice.human() &&
2448 jv[jss::transaction][sfMPTokenIssuanceID.jsonName] == to_string(mptID) &&
2449 jv[jss::transaction][jss::TransactionType] == "MPTokenIssuanceDestroy" &&
2450 jv[jss::type] == "transaction";
2451 }));
2452 }
2453
2454 // the outer Batch transaction is not itself published on the stream;
2455 // only the inner transactions touch the issuances
2456 BEAST_EXPECT(!wsc->findMsg(1s, [](auto const& jv) {
2457 return jv[jss::transaction][jss::TransactionType] == "Batch";
2458 }));
2459
2460 json::Value unsubStream;
2461 unsubStream = json::ValueType::Object;
2462 unsubStream[jss::mpt_issuances] = json::ValueType::Array;
2463 unsubStream[jss::mpt_issuances].append(to_string(mptID1));
2464 unsubStream[jss::mpt_issuances].append(to_string(mptID2));
2465 BEAST_EXPECT(wsc->invoke("unsubscribe", unsubStream)[jss::status] == "success");
2466 }
2467
2468 void
2470 {
2471 testcase("SubMPT amount fields");
2472 using namespace jtx;
2473 using namespace std::chrono_literals;
2474
2475 Env env(*this);
2476 Account const alice{"alice"};
2477 Account const bob{"bob"};
2478 Account const carol{"carol"};
2479
2480 MPTTester mpt(env, alice, {.holders = {bob, carol}});
2481 mpt.create({.pay = {{{bob}, 100}}, .flags = kMptDexFlags | tfMPTCanEscrow});
2482
2483 auto wsc = makeWSClient(env.app().config());
2484 auto const subscribed =
2485 wsc->invoke("subscribe", mptIssuancesRequest({to_string(mpt.issuanceID())}));
2486 BEAST_EXPECT(subscribed[jss::status] == "success");
2487
2488 auto const expectTransaction = [&](std::string const& type) {
2489 BEAST_EXPECT(wsc->findMsg(5s, [&](auto const& jv) {
2490 return jv[jss::engine_result] == "tesSUCCESS" &&
2491 jv[jss::transaction][jss::TransactionType] == type &&
2492 jv[jss::type] == "transaction";
2493 }));
2494 };
2495
2496 // Created offers carry the issuance only inside their amount fields.
2497 env(offer(bob, XRP(10), mpt(10)));
2498 env.close();
2499 expectTransaction("OfferCreate");
2500
2501 env(offer(carol, mpt(5), XRP(10)));
2502 env.close();
2503 expectTransaction("OfferCreate");
2504
2505 // Escrow entries similarly carry the issuance in sfAmount.
2506 auto const baseFee = env.current()->fees().base;
2507 env(escrow::create(bob, carol, mpt(10)),
2508 escrow::kFinishTime(env.now() + 1s),
2509 Fee(baseFee * 150));
2510 env.close();
2511 expectTransaction("EscrowCreate");
2512 }
2513
2514 void
2550};
2551
2553
2554} // namespace xrpl::test
A testsuite class.
Definition suite.h:52
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
Represents a JSON value.
Definition json_value.h:121
Value & append(Value const &value)
Append value to array at the end.
void clear()
Remove all object members and array elements.
virtual Config & config()=0
virtual std::uint32_t getNetworkID() const noexcept=0
Get the configured network ID.
virtual json::Value getServerInfo(bool human, bool admin, bool counters)=0
virtual void reportFeeChange()=0
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
virtual NetworkOPs & getOPs()=0
virtual LoadManager & getLoadManager()=0
virtual NetworkIDService & getNetworkIDService()=0
virtual LoadFeeTrack & getFeeTrack()=0
static json::Value oneBookRequest()
void run() override
Runs the suite.
static std::vector< std::string > makeAccountStrings(std::size_t count, std::uint32_t seed=1)
static json::Value accountsRequest(std::vector< std::string > const &accts)
static json::Value accountHistoryRequest(std::string const &acct)
void testValidations(FeatureBitset features=test::jtx::testableAmendments())
static auto cappedConfig(std::size_t cap)
void testNFToken(FeatureBitset features)
static std::vector< std::string > makeMPTIssuanceStrings(std::size_t count, std::uint32_t seed=1)
static json::Value accountsProposedRequest(std::vector< std::string > const &accts)
void testSubErrors(bool subscribe)
static json::Value mptIssuancesRequest(std::vector< std::string > const &mptIDs)
virtual std::optional< json::Value > getMsg(std::chrono::milliseconds const &timeout=std::chrono::milliseconds{0})=0
Retrieve a message.
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
std::string const & human() const
Returns the human readable public key.
A transaction testing environment.
Definition Env.h:161
Application & app()
Definition Env.h:300
bool syncClose(std::chrono::steady_clock::duration timeout=std::chrono::seconds{1})
Close and advance the ledger, then synchronize with the server's io_context to ensure all async opera...
Definition Env.h:479
bool close(NetClock::time_point closeTime, std::optional< std::chrono::milliseconds > consensusDelay=std::nullopt)
Close and advance the ledger.
Definition Env.cpp:133
std::shared_ptr< ReadView const > closed()
Returns the last closed ledger.
Definition Env.cpp:127
void fund(bool setDefaultRipple, STAmount const &amount, Account const &account)
Definition Env.cpp:323
std::uint32_t seq(Account const &account) const
Returns the next sequence number on account.
Definition Env.cpp:302
Account const & master
Definition Env.h:165
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
void trust(STAmount const &amount, Account const &account)
Establish trust lines.
Definition Env.cpp:354
void memoize(Account const &account)
Associate AccountID with account.
Definition Env.cpp:174
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Definition Env.h:377
NetClock::time_point now()
Returns the current network time.
Definition Env.h:326
Set the fee on a JTx.
Definition fee.h:20
Test helper for creating, mutating, and asserting MPT and confidential MPT ledger state.
Definition mpt.h:512
void create(MPTCreate const &arg=MPTCreate{}, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:346
Add a path.
Definition paths.h:47
Sets the SendMax on a JTx.
Definition sendmax.h:16
Set the regular signature on a JTx.
Definition sig.h:19
Set the flags on a JTx.
Definition txflags.h:14
Adds an inner Batch transaction to a JTx and autofills it.
Definition batch.h:91
T clear(T... args)
T emplace(T... args)
T end(T... args)
T find(T... args)
@ UInt
unsigned integer value
Definition json_value.h:28
@ Int
signed integer value
Definition json_value.h:27
@ Boolean
bool value
Definition json_value.h:31
@ Array
array value (ordered list)
Definition json_value.h:32
@ Object
object value (collection of name/value pairs).
Definition json_value.h:33
@ Real
double value
Definition json_value.h:29
@ Null
'null' value
Definition json_value.h:26
Keylet nftokenOffer(AccountID const &owner, SeqProxy const &seq)
An offer from an account to buy or sell an NFT.
Definition Indexes.cpp:465
The api_version numbers this server serves.
Definition ApiVersion.h:26
json::Value outer(jtx::Account const &account, uint32_t seq, STAmount const &fee, std::uint32_t flags)
Build an outer Batch transaction JSON object.
Definition batch.cpp:55
XRPAmount calcBatchFee(jtx::Env const &env, uint32_t const &numSigners, uint32_t const &txns=0)
Calculate the expected outer Batch transaction fee.
Definition batch.cpp:37
json::Value create(AccountID const &account, AccountID const &to, STAmount const &amount)
Definition escrow.cpp:24
auto const kFinishTime
Set the "FinishAfter" time tag on a JTx.
Definition escrow.h:93
json::Value mint(jtx::Account const &account, std::uint32_t nfTokenTaxon)
Mint an NFToken.
Definition token.cpp:23
json::Value brokerOffers(jtx::Account const &account, UInt256 const &buyOfferIndex, UInt256 const &sellOfferIndex)
Broker two NFToken offers.
Definition token.cpp:179
json::Value createOffer(jtx::Account const &account, UInt256 const &nftokenID, STAmount const &amount)
Create an NFTokenOffer.
Definition token.cpp:96
json::Value cancelOffer(jtx::Account const &account, std::initializer_list< UInt256 > const &nftokenOffers)
Cancel NFTokenOffers.
Definition token.cpp:141
UInt256 getNextID(jtx::Env const &env, jtx::Account const &issuer, std::uint32_t nfTokenTaxon, std::uint16_t flags, std::uint16_t xferFee)
Get the next NFTokenID that will be issued.
Definition token.cpp:57
json::Value acceptBuyOffer(jtx::Account const &account, UInt256 const &offerIndex)
Accept an NFToken buy offer.
Definition token.cpp:159
auto const kMptDexFlags
Definition mpt.h:47
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
bool hasEnvelope2(json::Value const &reply)
Reports whether reply carries the version 2 envelope: jsonrpc equal to rpc::kJsonRpcVersion and rippl...
FeatureBitset testableAmendments()
Definition Env.h:92
std::unique_ptr< Config > singleThreadIo(std::unique_ptr< Config >)
json::Value offer(Account const &account, STAmount const &takerPays, STAmount const &takerGets, std::uint32_t flags)
Create an offer.
Definition offer.cpp:14
std::unique_ptr< Config > envconfig()
creates and initializes a default configuration for jtx::Env
Definition envconfig.h:38
std::unique_ptr< Config > noAdmin(std::unique_ptr< Config >)
adjust config so no admin ports are enabled
Definition envconfig.cpp:76
static AutofillT const kAutofill
Definition tags.h:15
PrettyAmount drops(Integer i)
Returns an XRP PrettyAmount, which is trivially convertible to STAmount.
std::unique_ptr< Config > validator(std::unique_ptr< Config >, std::string const &)
adjust configuration with params needed to be a validator
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
@ RpcDstAmtMalformed
Definition ErrorCodes.h:89
@ RpcStreamMalformed
Definition ErrorCodes.h:109
@ RpcBadMarket
Definition ErrorCodes.h:80
@ RpcActMalformed
Definition ErrorCodes.h:73
@ RpcSrcCurMalformed
Definition ErrorCodes.h:107
@ RpcInvalidParams
Definition ErrorCodes.h:67
@ RpcSrcIsrMalformed
Definition ErrorCodes.h:108
@ RpcDstIsrMalformed
Definition ErrorCodes.h:91
@ RpcNoPermission
Definition ErrorCodes.h:36
PublicKey derivePublicKey(KeyType type, SecretKey const &sk)
Derive the public key from a secret key.
constexpr std::uint32_t kDefaultGasLimit
bool isFlagLedger(LedgerIndex seq)
Returns true if the given ledgerIndex is a flag ledgerIndex.
Definition Protocol.cpp:11
std::optional< AccountID > parseBase58(std::string const &s)
Parse AccountID from checked, base58 string.
BaseUInt< 256 > Domain
Domain is a 256-bit hash representing a specific domain.
Definition UintTypes.h:59
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
Definition AccountID.cpp:95
SecretKey generateSecretKey(KeyType type, Seed const &seed)
Generate a new secret key deterministically.
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
BaseUInt< 256 > UInt256
Definition base_uint.h:581
BaseUInt< 192 > MPTID
MPTID is a 192-bit value representing MPT Issuance ID, which is a concatenation of a 32-bit sequence ...
Definition UintTypes.h:54
constexpr std::uint32_t kDefaultGasPrice
constexpr std::uint32_t kVfFullValidation
constexpr std::uint32_t kDefaultBytecodeSizeLimit
constexpr std::uint32_t kVfFullyCanonicalSig
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
std::unordered_map< Key, Value, Hash, Pred, Allocator > HashMap
T push_back(T... args)
T reserve(T... args)
T sort(T... args)
UInt256 key
Definition Keylet.h:21
static constexpr auto kGasLimit
Definition Constants.h:112
static constexpr auto kBytecodeSizeLimit
Definition Constants.h:97
static constexpr auto kGasPrice
Definition Constants.h:113
static constexpr auto kValidationSeed
Definition Constants.h:67
static constexpr auto kVoting
Definition Constants.h:78
Arguments for initializing funded MPT test accounts and issuance.
Definition mpt.h:189
Set the sequence number on a JTx.
Definition seq.h:16
T to_string(T... args)