xrpld
Loading...
Searching...
No Matches
ConfidentialTransfer_test.cpp
1#include <test/jtx/Account.h>
2#include <test/jtx/ConfidentialTransfer.h>
3#include <test/jtx/Env.h>
4#include <test/jtx/amount.h>
5#include <test/jtx/flags.h>
6#include <test/jtx/mpt.h>
7#include <test/jtx/pay.h>
8#include <test/jtx/ter.h>
9#include <test/jtx/vault.h>
10
11#include <xrpl/basics/Buffer.h>
12#include <xrpl/basics/Slice.h>
13#include <xrpl/basics/base_uint.h>
14#include <xrpl/basics/contract.h>
15#include <xrpl/basics/strHex.h>
16#include <xrpl/beast/unit_test/suite.h>
17#include <xrpl/beast/utility/Journal.h>
18#include <xrpl/core/ServiceRegistry.h>
19#include <xrpl/json/json_value.h>
20#include <xrpl/ledger/ApplyView.h>
21#include <xrpl/ledger/OpenView.h>
22#include <xrpl/protocol/AccountID.h>
23#include <xrpl/protocol/ConfidentialTransfer.h>
24#include <xrpl/protocol/Feature.h>
25#include <xrpl/protocol/Indexes.h>
26#include <xrpl/protocol/LedgerFormats.h>
27#include <xrpl/protocol/Protocol.h>
28#include <xrpl/protocol/SField.h>
29#include <xrpl/protocol/STObject.h>
30#include <xrpl/protocol/Serializer.h>
31#include <xrpl/protocol/TER.h>
32#include <xrpl/protocol/TxFlags.h>
33#include <xrpl/protocol/UintTypes.h>
34#include <xrpl/protocol/jss.h>
35#include <xrpl/tx/apply.h>
36
37#include <openssl/evp.h>
38#include <utility/mpt_utility.h>
39
40#include <secp256k1.h>
41#include <secp256k1_mpt.h>
42
43#include <algorithm>
44#include <array>
45#include <cstddef>
46#include <cstdint>
47#include <cstring>
48#include <functional>
49#include <initializer_list>
50#include <limits>
51#include <memory>
52#include <optional>
53#include <stdexcept>
54#include <string>
55#include <utility>
56
57namespace xrpl {
58
60{
61 void
63 {
64 testcase("Convert");
65 using namespace test::jtx;
66
67 // Basic convert test
68 {
69 Env env{*this, features};
70 Account const alice("alice");
71 Account const bob("bob");
72 MPTTester mptAlice(env, alice, {.holders = {bob}});
73
74 mptAlice.create({
75 .ownerCount = 1,
76 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
77 });
78
79 mptAlice.authorize({
80 .account = bob,
81 });
82 mptAlice.pay(alice, bob, 100);
83
84 mptAlice.generateKeyPair(alice);
85
86 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
87
88 mptAlice.generateKeyPair(bob);
89
90 mptAlice.convert({
91 .account = bob,
92 .amt = 0,
93 .holderPubKey = mptAlice.getPubKey(bob),
94 });
95
96 mptAlice.convert({
97 .account = bob,
98 .amt = 20,
99 });
100
101 mptAlice.convert({
102 .account = bob,
103 .amt = 40,
104 });
105
106 mptAlice.convert({
107 .account = bob,
108 .amt = 40,
109 });
110 }
111
112 // Edge case: minimum amount (1)
113 {
114 Env env{*this, features};
115 Account const alice("alice");
116 Account const bob("bob");
117 MPTTester mptAlice(env, alice, {.holders = {bob}});
118
119 mptAlice.create({
120 .ownerCount = 1,
121 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
122 });
123
124 mptAlice.authorize({
125 .account = bob,
126 });
127 mptAlice.pay(alice, bob, 1);
128
129 mptAlice.generateKeyPair(alice);
130 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
131
132 mptAlice.generateKeyPair(bob);
133 mptAlice.convert({
134 .account = bob,
135 .amt = 0,
136 .holderPubKey = mptAlice.getPubKey(bob),
137 });
138
139 mptAlice.convert({
140 .account = bob,
141 .amt = 1,
142 });
143 }
144
145 // Edge case: kMaxMpTokenAmount
146 // Using raw JSON to avoid automatic decryption checks in MPTTester
147 // which don't work for very large amounts (brute-force decryption is slow)
148 {
149 Env env{*this, features};
150 Account const alice("alice");
151 Account const bob("bob");
152 MPTTester mptAlice(env, alice, {.holders = {bob}});
153
154 mptAlice.create({
155 .ownerCount = 1,
156 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
157 });
158
159 mptAlice.authorize({
160 .account = bob,
161 });
162 mptAlice.pay(alice, bob, kMaxMpTokenAmount);
163
164 mptAlice.generateKeyPair(alice);
165 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
166
167 mptAlice.generateKeyPair(bob);
168
169 // First convert with amt=0 to register public key (uses MPTTester)
170 mptAlice.convert({
171 .account = bob,
172 .amt = 0,
173 .holderPubKey = mptAlice.getPubKey(bob),
174 });
175
176 // Second convert with kMaxMpTokenAmount using raw JSON
177 Buffer const blindingFactor = generateBlindingFactor();
178 auto const holderCiphertext =
179 mptAlice.encryptAmount(bob, kMaxMpTokenAmount, blindingFactor);
180 auto const issuerCiphertext =
181 mptAlice.encryptAmount(alice, kMaxMpTokenAmount, blindingFactor);
182
183 json::Value jv;
184 jv[jss::Account] = bob.human();
185 jv[jss::TransactionType] = jss::ConfidentialMPTConvert;
186 jv[sfMPTokenIssuanceID] = to_string(mptAlice.issuanceID());
187 jv[sfMPTAmount.jsonName] = std::to_string(kMaxMpTokenAmount);
188 jv[sfHolderEncryptedAmount.jsonName] = strHex(holderCiphertext);
189 jv[sfIssuerEncryptedAmount.jsonName] = strHex(issuerCiphertext);
190 jv[sfBlindingFactor.jsonName] = strHex(blindingFactor);
191
192 env(jv, Ter(tesSUCCESS));
193
194 // Verify the public balance was reduced
195 env.require(MptBalance(mptAlice, bob, 0));
196 }
197 }
198
199 void
201 {
202 testcase("Convert with auditor");
203 using namespace test::jtx;
204
205 Env env{*this, features};
206 Account const alice("alice");
207 Account const bob("bob");
208 Account const auditor("auditor");
209 MPTTester mptAlice(
210 env,
211 alice,
212 {
213 .holders = {bob},
214 .auditor = auditor,
215 });
216
217 mptAlice.create({
218 .ownerCount = 1,
219 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
220 });
221
222 mptAlice.authorize({
223 .account = bob,
224 });
225 mptAlice.pay(alice, bob, 100);
226
227 mptAlice.generateKeyPair(alice);
228 mptAlice.generateKeyPair(auditor);
229
230 mptAlice.set({
231 .account = alice,
232 .issuerPubKey = mptAlice.getPubKey(alice),
233 .auditorPubKey = mptAlice.getPubKey(auditor),
234 });
235
236 mptAlice.generateKeyPair(bob);
237
238 mptAlice.convert({
239 .account = bob,
240 .amt = 0,
241 .holderPubKey = mptAlice.getPubKey(bob),
242 });
243
244 mptAlice.convert({
245 .account = bob,
246 .amt = 20,
247 });
248
249 mptAlice.convert({
250 .account = bob,
251 .amt = 30,
252 });
253 }
254
255 void
257 {
258 testcase("Convert preflight");
259 using namespace test::jtx;
260
261 // Alice (issuer) tries to convert her own tokens - should fail
262 {
263 Env env{*this, features};
264 Account const alice("alice");
265 MPTTester mptAlice(env, alice);
266
267 mptAlice.create({
268 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
269 });
270 mptAlice.generateKeyPair(alice);
271
272 mptAlice.convert({
273 .account = alice,
274 .amt = 10,
275 .holderPubKey = mptAlice.getPubKey(alice),
276 .err = temMALFORMED,
277 });
278 }
279
280 {
281 Env env{*this, features - featureConfidentialTransfer};
282 Account const alice("alice");
283 Account const bob("bob");
284 MPTTester mptAlice(env, alice, {.holders = {bob}});
285
286 mptAlice.create({
287 .ownerCount = 1,
288 .flags = tfMPTCanTransfer | tfMPTCanLock,
289 });
290
291 mptAlice.authorize({
292 .account = bob,
293 });
294 mptAlice.pay(alice, bob, 100);
295
296 mptAlice.generateKeyPair(alice);
297 mptAlice.generateKeyPair(bob);
298
299 mptAlice.set({
300 .account = alice,
301 .issuerPubKey = mptAlice.getPubKey(alice),
302 .err = temDISABLED,
303 });
304
305 mptAlice.convert({
306 .account = bob,
307 .amt = 10,
308 .holderPubKey = mptAlice.getPubKey(bob),
309 .err = temDISABLED,
310 });
311 }
312
313 {
314 Env env{*this, features};
315 Account const alice("alice");
316 Account const bob("bob");
317 MPTTester mptAlice(env, alice, {.holders = {bob}});
318
319 mptAlice.create({
320 .ownerCount = 1,
321 .flags = tfMPTCanTransfer | tfMPTCanLock,
322 });
323
324 mptAlice.authorize({
325 .account = bob,
326 });
327 mptAlice.pay(alice, bob, 100);
328
329 mptAlice.generateKeyPair(alice);
330 mptAlice.generateKeyPair(bob);
331
332 mptAlice.convert({
333 .account = alice,
334 .amt = 10,
335 .holderPubKey = mptAlice.getPubKey(bob),
336 .err = temMALFORMED,
337 });
338
339 // Holder encrypted amount is empty (length 0)
340 mptAlice.convert({
341 .account = bob,
342 .amt = 10,
343 .holderPubKey = mptAlice.getPubKey(bob),
344 .holderEncryptedAmt = Buffer{},
345 .err = temBAD_CIPHERTEXT,
346 });
347
348 // Issuer encrypted amount is empty (length 0)
349 mptAlice.convert({
350 .account = bob,
351 .amt = 10,
352 .holderPubKey = mptAlice.getPubKey(bob),
353 .issuerEncryptedAmt = Buffer{},
354 .err = temBAD_CIPHERTEXT,
355 });
356
357 // Auditor encrypted amount has invalid length (must be 66 bytes)
358 mptAlice.convert({
359 .account = bob,
360 .amt = 10,
361 .holderPubKey = mptAlice.getPubKey(bob),
362 .auditorEncryptedAmt = gMakeZeroBuffer(10),
363 .err = temBAD_CIPHERTEXT,
364 });
365
366 // Auditor encrypted amount has correct length but invalid data
367 mptAlice.convert({
368 .account = bob,
369 .amt = 10,
370 .holderPubKey = mptAlice.getPubKey(bob),
371 .auditorEncryptedAmt = getBadCiphertext(),
372 .err = temBAD_CIPHERTEXT,
373 });
374
375 // Amount exceeds maximum allowed MPT amount
376 mptAlice.convert({
377 .account = bob,
378 .amt = kMaxMpTokenAmount + 1,
379 .holderPubKey = mptAlice.getPubKey(bob),
380 .err = temBAD_AMOUNT,
381 });
382
383 // Holder encrypted amount has correct length but invalid data
384 mptAlice.convert({
385 .account = bob,
386 .amt = 1,
387 .holderPubKey = mptAlice.getPubKey(bob),
388 .holderEncryptedAmt = getBadCiphertext(),
389 .err = temBAD_CIPHERTEXT,
390 });
391
392 // Issuer encrypted amount has correct length but invalid data (not
393 // a valid EC point)
394 mptAlice.convert({
395 .account = bob,
396 .amt = 1,
397 .holderPubKey = mptAlice.getPubKey(bob),
398 .issuerEncryptedAmt = getBadCiphertext(),
399 .err = temBAD_CIPHERTEXT,
400 });
401
402 // Holder public key is invalid (empty buffer)
403 mptAlice.convert({
404 .account = bob,
405 .amt = 10,
406 .holderPubKey = Buffer{},
407 .err = temMALFORMED,
408 });
409
410 // Holder public key has correct length but invalid EC point data
411 mptAlice.convert({
412 .account = bob,
413 .amt = 10,
414 .holderPubKey = gMakeZeroBuffer(kEcPubKeyLength),
415 .err = temMALFORMED,
416 });
417 }
418
419 // when registering holder pub key, the transaction must include a
420 // Schnorr proof of knowledge for the corresponding secret key
421 {
422 Env env{*this, features};
423 Account const alice("alice");
424 Account const bob("bob");
425 MPTTester mptAlice(env, alice, {.holders = {bob}});
426
427 mptAlice.create({
428 .ownerCount = 1,
429 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
430 });
431
432 mptAlice.authorize({
433 .account = bob,
434 });
435 mptAlice.pay(alice, bob, 100);
436
437 mptAlice.generateKeyPair(alice);
438 mptAlice.generateKeyPair(bob);
439
440 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
441
442 mptAlice.convert({
443 .account = bob,
444 .amt = 10,
445 .fillSchnorrProof = false,
446 .holderPubKey = mptAlice.getPubKey(bob),
447 .err = temMALFORMED,
448 });
449
450 mptAlice.convert({
451 .account = bob,
452 .amt = 0,
453 .fillSchnorrProof = false,
454 .holderPubKey = mptAlice.getPubKey(bob),
455 .err = temMALFORMED,
456 });
457
458 // proof length is invalid
459 mptAlice.convert({
460 .account = bob,
461 .amt = 10,
462 .proof = std::string(10, 'A'),
463 .holderPubKey = mptAlice.getPubKey(bob),
464 .err = temMALFORMED,
465 });
466 }
467
468 // when holder pub key already registered, Schnorr proof must not be
469 // provided
470 {
471 Env env{*this, features};
472 Account const alice("alice");
473 Account const bob("bob");
474 MPTTester mptAlice(env, alice, {.holders = {bob}});
475
476 mptAlice.create({
477 .ownerCount = 1,
478 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
479 });
480
481 mptAlice.authorize({
482 .account = bob,
483 });
484 mptAlice.pay(alice, bob, 100);
485
486 mptAlice.generateKeyPair(alice);
487 mptAlice.generateKeyPair(bob);
488
489 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
490
491 // this will register bob's pub key,
492 // and convert 10 to confidential balance
493 mptAlice.convert({
494 .account = bob,
495 .amt = 10,
496 .holderPubKey = mptAlice.getPubKey(bob),
497 });
498
499 // proof must not be provided after pub key was registered
500 mptAlice.convert({
501 .account = bob,
502 .amt = 20,
503 .fillSchnorrProof = true,
504 .err = temMALFORMED,
505 });
506 }
507 }
508
509 void
511 {
512 testcase("Convert proof context binding");
513 using namespace test::jtx;
514
515 auto const runBadProof = [&](auto makeContextHash) {
516 Env env{*this, features};
517 Account const alice("alice");
518 Account const bob("bob");
519 Account const carol("carol");
520 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
521
522 mptAlice.create({
523 .ownerCount = 1,
524 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
525 });
526 mptAlice.authorize({.account = bob});
527 mptAlice.authorize({.account = carol});
528 mptAlice.pay(alice, bob, 100);
529
530 mptAlice.generateKeyPair(alice);
531 mptAlice.generateKeyPair(bob);
532 mptAlice.generateKeyPair(carol);
533 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
534
535 auto const proof =
536 mptAlice.getSchnorrProof(bob, makeContextHash(env, mptAlice, alice, bob, carol));
537 if (!BEAST_EXPECT(proof.has_value()))
538 return;
539
540 mptAlice.convert({
541 .account = bob,
542 .amt = 10,
543 .proof = strHex(requireOptional(proof, "Missing proof")),
544 .holderPubKey = mptAlice.getPubKey(bob),
545 .err = tecBAD_PROOF,
546 });
547 };
548
549 // Wrong account in the proof context.
550 runBadProof([&](Env& env,
551 MPTTester const& mpt,
552 Account const&,
553 Account const& bob,
554 Account const& carol) {
555 return getConvertContextHash(carol.id(), mpt.issuanceID(), env.seq(bob));
556 });
557
558 // Wrong issuance ID in the proof context.
559 runBadProof([&](Env& env,
560 MPTTester const&,
561 Account const& alice,
562 Account const& bob,
563 Account const&) {
565 bob.id(), makeMptID(env.seq(alice) + 100, alice), env.seq(bob));
566 });
567
568 // Wrong transaction sequence in the proof context.
569 runBadProof([&](Env& env,
570 MPTTester const& mpt,
571 Account const&,
572 Account const& bob,
573 Account const&) {
574 return getConvertContextHash(bob.id(), mpt.issuanceID(), env.seq(bob) + 1);
575 });
576 }
577
578 void
580 {
581 testcase("Set");
582 using namespace test::jtx;
583
584 // Set keys on issuance that already has confidential amounts enabled
585 {
586 Env env{*this, features};
587 Account const alice("alice");
588 Account const auditor("auditor");
589 MPTTester mptAlice(env, alice, {.holders = {}, .auditor = auditor});
590
591 mptAlice.create({
592 .ownerCount = 1,
593 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
594 });
595
596 mptAlice.generateKeyPair(alice);
597 mptAlice.generateKeyPair(auditor);
598
599 mptAlice.set({
600 .account = alice,
601 .issuerPubKey = mptAlice.getPubKey(alice),
602 .auditorPubKey = mptAlice.getPubKey(auditor),
603 });
604 }
605
606 // Enable confidential amounts flag only (no keys)
607 {
608 Env env{*this, features};
609 Account const alice("alice");
610 MPTTester mptAlice(env, alice, {.holders = {}});
611
612 mptAlice.create({
613 .ownerCount = 1,
614 .flags = tfMPTCanTransfer | tfMPTCanLock,
615 });
616
617 mptAlice.set({
618 .account = alice,
619 .flags = tfMPTSetCanHoldConfidentialBalance,
620 });
621 }
622
623 // Set keys when enabling confidential amounts in the same tx
624 {
625 Env env{*this, features};
626 Account const alice("alice");
627 Account const auditor("auditor");
628 MPTTester mptAlice(env, alice, {.holders = {}, .auditor = auditor});
629
630 mptAlice.create({
631 .ownerCount = 1,
632 .flags = tfMPTCanTransfer | tfMPTCanLock,
633 });
634
635 mptAlice.generateKeyPair(alice);
636 mptAlice.generateKeyPair(auditor);
637
638 mptAlice.set({
639 .account = alice,
640 .flags = tfMPTSetCanHoldConfidentialBalance,
641 .issuerPubKey = mptAlice.getPubKey(alice),
642 .auditorPubKey = mptAlice.getPubKey(auditor),
643 });
644
645 // Verify lsfMPTCanHoldConfidentialBalance flag is set
646 BEAST_EXPECT(mptAlice.checkFlags(
647 lsfMPTCanTransfer | lsfMPTCanLock | lsfMPTCanHoldConfidentialBalance));
648
649 // Verify keys are persisted on the issuance
650 auto const sle = env.le(keylet::mptokenIssuance(mptAlice.issuanceID()));
651 BEAST_EXPECT(sle);
652 BEAST_EXPECT(sle->isFieldPresent(sfIssuerEncryptionKey));
653 BEAST_EXPECT(sle->isFieldPresent(sfAuditorEncryptionKey));
654 }
655 }
656
657 void
659 {
660 testcase("Set preflight");
661 using namespace test::jtx;
662
663 {
664 Env env{*this, features - featureConfidentialTransfer};
665 Account const alice("alice");
666 Account const bob("bob");
667 MPTTester mptAlice(env, alice, {.holders = {bob}});
668
669 mptAlice.create({
670 .ownerCount = 1,
671 .flags = tfMPTCanTransfer | tfMPTCanLock,
672 });
673
674 mptAlice.authorize({
675 .account = bob,
676 });
677 mptAlice.pay(alice, bob, 100);
678
679 mptAlice.generateKeyPair(alice);
680 mptAlice.generateKeyPair(bob);
681
682 mptAlice.set({
683 .account = alice,
684 .issuerPubKey = mptAlice.getPubKey(alice),
685 .err = temDISABLED,
686 });
687 }
688
689 // pub key is invalid
690 {
691 Env env{*this, features};
692 Account const alice("alice");
693 Account const bob("bob");
694 MPTTester mptAlice(env, alice, {.holders = {bob}});
695
696 mptAlice.create({
697 .ownerCount = 1,
698 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
699 });
700
701 mptAlice.authorize({
702 .account = bob,
703 });
704 mptAlice.pay(alice, bob, 100);
705
706 mptAlice.generateKeyPair(alice);
707 mptAlice.generateKeyPair(bob);
708
709 // Issuer pub key is invalid (empty)
710 mptAlice.set({
711 .account = alice,
712 .issuerPubKey = Buffer{},
713 .err = temMALFORMED,
714 });
715
716 // Issuer pub key has correct length but invalid EC point data
717 mptAlice.set({
718 .account = alice,
719 .issuerPubKey = gMakeZeroBuffer(kEcPubKeyLength),
720 .err = temMALFORMED,
721 });
722
723 // Auditor key is invalid length
724 mptAlice.set({
725 .account = alice,
726 .issuerPubKey = mptAlice.getPubKey(alice),
727 .auditorPubKey = gMakeZeroBuffer(10),
728 .err = temMALFORMED,
729 });
730
731 // Auditor key has correct length but invalid EC point data
732 mptAlice.set({
733 .account = alice,
734 .issuerPubKey = mptAlice.getPubKey(alice),
735 .auditorPubKey = gMakeZeroBuffer(kEcPubKeyLength),
736 .err = temMALFORMED,
737 });
738
739 // Note: "auditor key without issuer key" (temMALFORMED before
740 // ConfidentialMPTKeyRotation) is covered in ConfidentialMPTKeyRotation_test
741
742 // Cannot set Holder and issuer Keys in the same transaction
743 mptAlice.set({
744 .account = alice,
745 .holder = bob,
746 .issuerPubKey = mptAlice.getPubKey(alice),
747 .err = temMALFORMED,
748 });
749
750 // Cannot set Holder and auditor Keys in the same transaction
751 mptAlice.set({
752 .account = alice,
753 .holder = bob,
754 .auditorPubKey = mptAlice.getPubKey(alice),
755 .err = temMALFORMED,
756 });
757 }
758 }
759
760 void
762 {
763 testcase("Set preclaim");
764 using namespace test::jtx;
765
766 // Cannot set issuer key if confidential amounts not enabled
767 {
768 Env env{*this, features};
769 Account const alice("alice");
770 MPTTester mptAlice(env, alice, {.holders = {}});
771
772 mptAlice.create({
773 .ownerCount = 1,
774 .flags = tfMPTCanTransfer | tfMPTCanLock,
775 });
776
777 mptAlice.generateKeyPair(alice);
778
779 mptAlice.set({
780 .account = alice,
781 .issuerPubKey = mptAlice.getPubKey(alice),
782 .err = tecNO_PERMISSION,
783 });
784 }
785
786 // Cannot update issuer public key once set (pre-ConfidentialMPTKeyRotation behavior)
787 {
788 Env env{*this, features - featureConfidentialMPTKeyRotation};
789 Account const alice("alice");
790 Account const bob("bob");
791 MPTTester mptAlice(env, alice, {.holders = {bob}});
792
793 mptAlice.create({
794 .ownerCount = 1,
795 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
796 });
797
798 mptAlice.generateKeyPair(alice);
799 mptAlice.generateKeyPair(bob);
800
801 // First set issuer key - should succeed
802 mptAlice.set({
803 .account = alice,
804 .issuerPubKey = mptAlice.getPubKey(alice),
805 });
806
807 // Try to update issuer key - should fail
808 mptAlice.set({
809 .account = alice,
810 .issuerPubKey = mptAlice.getPubKey(bob),
811 .err = tecNO_PERMISSION,
812 });
813 }
814
815 // Cannot update issuer and auditor public keys once set
816 // Note: trying to set only auditor key fails in preflight (temMALFORMED)
817 // so we must provide both keys, which fails on issuer key check first
818 // (pre-ConfidentialMPTKeyRotation behavior)
819 {
820 Env env{*this, features - featureConfidentialMPTKeyRotation};
821 Account const alice("alice");
822 Account const bob("bob");
823 Account const auditor("auditor");
824 MPTTester mptAlice(env, alice, {.holders = {bob}, .auditor = auditor});
825
826 mptAlice.create({
827 .ownerCount = 1,
828 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
829 });
830
831 mptAlice.generateKeyPair(alice);
832 mptAlice.generateKeyPair(bob);
833 mptAlice.generateKeyPair(auditor);
834
835 // Set issuer and auditor keys - should succeed
836 mptAlice.set({
837 .account = alice,
838 .issuerPubKey = mptAlice.getPubKey(alice),
839 .auditorPubKey = mptAlice.getPubKey(auditor),
840 });
841
842 // Try to update both keys - fails on issuer key check first
843 mptAlice.set({
844 .account = alice,
845 .issuerPubKey = mptAlice.getPubKey(bob),
846 .auditorPubKey = mptAlice.getPubKey(alice),
847 .err = tecNO_PERMISSION,
848 });
849 }
850
851 // Cannot set auditor key if confidential amounts not enabled
852 {
853 Env env{*this, features};
854 Account const alice("alice");
855 Account const auditor("auditor");
856 MPTTester mptAlice(env, alice, {.holders = {}, .auditor = auditor});
857
858 mptAlice.create({
859 .ownerCount = 1,
860 .flags = tfMPTCanTransfer | tfMPTCanLock,
861 });
862
863 mptAlice.generateKeyPair(alice);
864 mptAlice.generateKeyPair(auditor);
865
866 mptAlice.set({
867 .account = alice,
868 .issuerPubKey = mptAlice.getPubKey(alice),
869 .auditorPubKey = mptAlice.getPubKey(auditor),
870 .err = tecNO_PERMISSION,
871 });
872 }
873
874 // Cannot set keys when mutation of canConfidentialAmount is disallowed
875 {
876 Env env{*this, features};
877 Account const alice("alice");
878 MPTTester mptAlice(env, alice, {.holders = {}});
879
880 // Create with tifMPTCanHoldConfidentialBalance
881 mptAlice.create({
882 .ownerCount = 1,
883 .flags = tfMPTCanTransfer | tfMPTCanLock,
884 .immutableFlags = tifMPTCanHoldConfidentialBalance,
885 });
886
887 mptAlice.generateKeyPair(alice);
888
889 // Trying to enable confidential amounts and set keys fails
890 // because the issuance cannot mutate canConfidentialAmount
891 mptAlice.set({
892 .account = alice,
893 .flags = tfMPTSetCanHoldConfidentialBalance,
894 .issuerPubKey = mptAlice.getPubKey(alice),
895 .err = tecNO_PERMISSION,
896 });
897 }
898
899 // Set issuer key first, then auditor key in a separate tx
900 // (pre-ConfidentialMPTKeyRotation behavior)
901 {
902 Env env{*this, features - featureConfidentialMPTKeyRotation};
903 Account const alice("alice");
904 Account const auditor("auditor");
905 MPTTester mptAlice(env, alice, {.holders = {}, .auditor = auditor});
906
907 mptAlice.create({
908 .ownerCount = 1,
909 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
910 });
911
912 mptAlice.generateKeyPair(alice);
913 mptAlice.generateKeyPair(auditor);
914
915 // Set issuer key only
916 mptAlice.set({
917 .account = alice,
918 .issuerPubKey = mptAlice.getPubKey(alice),
919 });
920
921 // Set auditor key in a separate tx - requires issuer key in tx
922 // (preflight enforces auditor key requires issuer key)
923 // This fails because issuer key is already set on ledger
924 mptAlice.set({
925 .account = alice,
926 .issuerPubKey = mptAlice.getPubKey(alice),
927 .auditorPubKey = mptAlice.getPubKey(auditor),
928 .err = tecNO_PERMISSION,
929 });
930 }
931 }
932
933 void
935 {
936 testcase("test transfer fee");
937 using namespace test::jtx;
938
939 // MPTokenIssuanceCreate: cannot create with both TransferFee > 0 and
940 // tfMPTCanHoldConfidentialBalance
941 {
942 Env env{*this, features};
943 Account const alice("alice");
944 MPTTester mptAlice(env, alice, {.holders = {}});
945
946 mptAlice.create({
947 .transferFee = 100,
948 .flags = tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance,
949 .err = temBAD_TRANSFER_FEE,
950 });
951
952 // transferFee being 0 is allowed, even with tfMPTCanHoldConfidentialBalance
953 mptAlice.create({
954 .transferFee = 0,
955 .flags = tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance,
956 });
957 }
958
959 // MPTokenIssuanceSet (preflight): cannot enable confidential amounts and
960 // set TransferFee > 0 in the same transaction
961 {
962 Env env{*this, features};
963 Account const alice("alice");
964 MPTTester mptAlice(env, alice, {.holders = {}});
965
966 mptAlice.create({.ownerCount = 1, .flags = tfMPTCanTransfer | tfMPTCanLock});
967
968 mptAlice.set({
969 .account = alice,
970 .flags = tfMPTSetCanHoldConfidentialBalance,
971 .transferFee = 100,
972 .err = temBAD_TRANSFER_FEE,
973 });
974 }
975
976 // MPTokenIssuanceSet (preclaim): cannot enable confidential amounts on
977 // an issuance that already has a non-zero TransferFee
978 {
979 Env env{*this, features};
980 Account const alice("alice");
981 MPTTester mptAlice(env, alice, {.holders = {}});
982
983 mptAlice.create(
984 {.transferFee = 100, .ownerCount = 1, .flags = tfMPTCanTransfer | tfMPTCanLock});
985
986 mptAlice.set({
987 .account = alice,
988 .flags = tfMPTSetCanHoldConfidentialBalance,
989 .err = tecNO_PERMISSION,
990 });
991 }
992
993 // MPTokenIssuanceSet (preclaim): cannot set TransferFee > 0 on an
994 // issuance that already has lsfMPTCanHoldConfidentialBalance
995 {
996 Env env{*this, features};
997 Account const alice("alice");
998 MPTTester mptAlice(env, alice, {.holders = {}});
999
1000 mptAlice.create({
1001 .ownerCount = 1,
1002 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1003 });
1004
1005 mptAlice.set({
1006 .account = alice,
1007 .transferFee = 100,
1008 .err = tecNO_PERMISSION,
1009 });
1010
1011 // Setting transfer fee to 0 is allowed, but have no effect.
1012 mptAlice.set({
1013 .account = alice,
1014 .transferFee = 0,
1015 });
1016 }
1017 }
1018
1019 void
1021 {
1022 testcase("Convert preclaim");
1023 using namespace test::jtx;
1024
1025 // tfMPTCanHoldConfidentialBalance is not set on issuance
1026 {
1027 Env env{*this, features};
1028 Account const alice("alice");
1029 Account const bob("bob");
1030 MPTTester mptAlice(env, alice, {.holders = {bob}});
1031
1032 mptAlice.create({
1033 .ownerCount = 1,
1034 .flags = tfMPTCanTransfer | tfMPTCanLock,
1035 });
1036
1037 mptAlice.authorize({
1038 .account = bob,
1039 });
1040 mptAlice.pay(alice, bob, 100);
1041
1042 mptAlice.generateKeyPair(alice);
1043 mptAlice.generateKeyPair(bob);
1044
1045 mptAlice.convert({
1046 .account = bob,
1047 .amt = 10,
1048 .holderPubKey = mptAlice.getPubKey(bob),
1049 .err = tecNO_PERMISSION,
1050 });
1051 }
1052
1053 // issuer has not uploaded their sfIssuerEncryptionKey
1054 {
1055 Env env{*this, features};
1056 Account const alice("alice");
1057 Account const bob("bob");
1058 MPTTester mptAlice(env, alice, {.holders = {bob}});
1059
1060 mptAlice.create({
1061 .ownerCount = 1,
1062 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1063 });
1064
1065 mptAlice.authorize({
1066 .account = bob,
1067 });
1068 mptAlice.pay(alice, bob, 100);
1069
1070 mptAlice.generateKeyPair(alice);
1071 mptAlice.generateKeyPair(bob);
1072
1073 mptAlice.convert({
1074 .account = bob,
1075 .amt = 10,
1076 .holderPubKey = mptAlice.getPubKey(bob),
1077 .err = tecNO_PERMISSION,
1078 });
1079 }
1080
1081 // issuance does not exist
1082 {
1083 Env env{*this, features};
1084 Account const alice("alice");
1085 Account const bob("bob");
1086 MPTTester mptAlice(env, alice, {.holders = {bob}});
1087
1088 mptAlice.create({
1089 .ownerCount = 1,
1090 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1091 });
1092
1093 mptAlice.authorize({
1094 .account = bob,
1095 });
1096 mptAlice.generateKeyPair(alice);
1097
1098 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1099
1100 mptAlice.destroy();
1101 mptAlice.generateKeyPair(bob);
1102
1103 mptAlice.convert({
1104 .account = bob,
1105 .amt = 10,
1106 .holderPubKey = mptAlice.getPubKey(bob),
1107 .err = tecOBJECT_NOT_FOUND,
1108 });
1109 }
1110
1111 // bob has not created MPToken
1112 {
1113 Env env{*this, features};
1114 Account const alice("alice");
1115 Account const bob("bob");
1116 MPTTester mptAlice(env, alice, {.holders = {bob}});
1117
1118 mptAlice.create({
1119 .ownerCount = 1,
1120 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1121 });
1122
1123 mptAlice.generateKeyPair(alice);
1124 mptAlice.generateKeyPair(bob);
1125
1126 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1127
1128 mptAlice.convert({
1129 .account = bob,
1130 .amt = 10,
1131 .holderPubKey = mptAlice.getPubKey(bob),
1132 .err = tecOBJECT_NOT_FOUND,
1133 });
1134 }
1135
1136 // Verification of Issuer and and holder ciphertexts
1137 {
1138 Env env{*this, features};
1139 Account const alice("alice");
1140 Account const bob("bob");
1141 Account const carol("carol");
1142 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
1143
1144 mptAlice.create({
1145 .ownerCount = 1,
1146 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1147 });
1148
1149 mptAlice.authorize({
1150 .account = bob,
1151 });
1152 mptAlice.pay(alice, bob, 100);
1153
1154 mptAlice.generateKeyPair(alice);
1155 mptAlice.generateKeyPair(bob);
1156 mptAlice.generateKeyPair(carol);
1157
1158 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1159
1160 mptAlice.convert({
1161 .account = bob,
1162 .amt = 10,
1163 .holderPubKey = mptAlice.getPubKey(bob),
1164 .holderEncryptedAmt = getTrivialCiphertext(),
1165 .err = tecBAD_PROOF,
1166 });
1167
1168 mptAlice.convert({
1169 .account = bob,
1170 .amt = 10,
1171 .holderPubKey = mptAlice.getPubKey(bob),
1172 .issuerEncryptedAmt = getTrivialCiphertext(),
1173 .err = tecBAD_PROOF,
1174 });
1175
1176 std::uint64_t const amount = 10;
1177 Buffer const blindingFactor = generateBlindingFactor();
1178 Buffer const holderCiphertext = mptAlice.encryptAmount(bob, amount, blindingFactor);
1179
1180 // Holder ciphertext is valid for the amount and
1181 // blinding factor, but the issuer ciphertext is encrypted under a
1182 // different public key than the registered issuer key.
1183 Buffer const wrongIssuerCiphertext =
1184 mptAlice.encryptAmount(carol, amount, blindingFactor);
1185
1186 mptAlice.convert({
1187 .account = bob,
1188 .amt = amount,
1189 .holderPubKey = mptAlice.getPubKey(bob),
1190 .holderEncryptedAmt = holderCiphertext,
1191 .issuerEncryptedAmt = wrongIssuerCiphertext,
1192 .blindingFactor = blindingFactor,
1193 .err = tecBAD_PROOF,
1194 });
1195 }
1196
1197 // trying to convert more than what bob has
1198 {
1199 Env env{*this, features};
1200 Account const alice("alice");
1201 Account const bob("bob");
1202 MPTTester mptAlice(env, alice, {.holders = {bob}});
1203
1204 mptAlice.create({
1205 .ownerCount = 1,
1206 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1207 });
1208
1209 mptAlice.authorize({
1210 .account = bob,
1211 });
1212 mptAlice.pay(alice, bob, 100);
1213
1214 mptAlice.generateKeyPair(alice);
1215
1216 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1217
1218 mptAlice.generateKeyPair(bob);
1219
1220 mptAlice.convert({
1221 .account = bob,
1222 .amt = 200,
1223 .holderPubKey = mptAlice.getPubKey(bob),
1224 .err = tecINSUFFICIENT_FUNDS,
1225 });
1226 }
1227
1228 // holder cannot upload pk again
1229 {
1230 Env env{*this, features};
1231 Account const alice("alice");
1232 Account const bob("bob");
1233 MPTTester mptAlice(env, alice, {.holders = {bob}});
1234
1235 mptAlice.create({
1236 .ownerCount = 1,
1237 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1238 });
1239
1240 mptAlice.authorize({
1241 .account = bob,
1242 });
1243 mptAlice.pay(alice, bob, 100);
1244
1245 mptAlice.generateKeyPair(alice);
1246
1247 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1248
1249 mptAlice.generateKeyPair(bob);
1250
1251 mptAlice.convert({.account = bob, .amt = 10, .holderPubKey = mptAlice.getPubKey(bob)});
1252
1253 // cannot upload pk again
1254 mptAlice.convert({
1255 .account = bob,
1256 .amt = 10,
1257 .holderPubKey = mptAlice.getPubKey(bob),
1258 .err = tecDUPLICATE,
1259 });
1260 }
1261
1262 // cannot convert if locked
1263 {
1264 Env env{*this, features};
1265 Account const alice("alice");
1266 Account const bob("bob");
1267 MPTTester mptAlice(env, alice, {.holders = {bob}});
1268
1269 mptAlice.create({
1270 .ownerCount = 1,
1271 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1272 });
1273
1274 mptAlice.authorize({
1275 .account = bob,
1276 });
1277 mptAlice.pay(alice, bob, 100);
1278
1279 mptAlice.generateKeyPair(alice);
1280
1281 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1282
1283 mptAlice.set({
1284 .account = alice,
1285 .holder = bob,
1286 .flags = tfMPTLock,
1287 });
1288
1289 mptAlice.generateKeyPair(bob);
1290
1291 mptAlice.convert({
1292 .account = bob,
1293 .amt = 10,
1294 .holderPubKey = mptAlice.getPubKey(bob),
1295 .err = tecLOCKED,
1296 });
1297
1298 mptAlice.set({
1299 .account = alice,
1300 .holder = bob,
1301 .flags = tfMPTUnlock,
1302 });
1303
1304 mptAlice.convert({
1305 .account = bob,
1306 .amt = 10,
1307 .holderPubKey = mptAlice.getPubKey(bob),
1308 });
1309 }
1310
1311 // cannot convert if unauth
1312 {
1313 Env env{*this, features};
1314 Account const alice("alice");
1315 Account const bob("bob");
1316 MPTTester mptAlice(env, alice, {.holders = {bob}});
1317
1318 mptAlice.create({
1319 .ownerCount = 1,
1320 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTRequireAuth |
1321 tfMPTCanHoldConfidentialBalance,
1322 });
1323
1324 mptAlice.authorize({
1325 .account = bob,
1326 });
1327 mptAlice.authorize({
1328 .account = alice,
1329 .holder = bob,
1330 });
1331 mptAlice.pay(alice, bob, 100);
1332
1333 mptAlice.generateKeyPair(alice);
1334
1335 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1336
1337 mptAlice.generateKeyPair(bob);
1338
1339 // Unauthorize bob
1340 mptAlice.authorize({
1341 .account = alice,
1342 .holder = bob,
1343 .flags = tfMPTUnauthorize,
1344 });
1345
1346 mptAlice.convert({
1347 .account = bob,
1348 .amt = 10,
1349 .holderPubKey = mptAlice.getPubKey(bob),
1350 .err = tecNO_AUTH,
1351 });
1352
1353 // auth bob
1354 mptAlice.authorize({
1355 .account = alice,
1356 .holder = bob,
1357 });
1358
1359 mptAlice.convert({
1360 .account = bob,
1361 .amt = 10,
1362 .holderPubKey = mptAlice.getPubKey(bob),
1363 });
1364 }
1365
1366 // frozen account cannot bypass freeze check with amount=0
1367 {
1368 Env env{*this, features};
1369 Account const alice("alice");
1370 Account const bob("bob");
1371 MPTTester mptAlice(env, alice, {.holders = {bob}});
1372
1373 mptAlice.create({
1374 .ownerCount = 1,
1375 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1376 });
1377
1378 mptAlice.authorize({
1379 .account = bob,
1380 });
1381 mptAlice.pay(alice, bob, 100);
1382
1383 mptAlice.generateKeyPair(alice);
1384
1385 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1386
1387 // lock bob
1388 mptAlice.set({
1389 .account = alice,
1390 .holder = bob,
1391 .flags = tfMPTLock,
1392 });
1393
1394 mptAlice.generateKeyPair(bob);
1395
1396 // amount=0 should still be rejected when locked
1397 mptAlice.convert({
1398 .account = bob,
1399 .amt = 0,
1400 .holderPubKey = mptAlice.getPubKey(bob),
1401 .err = tecLOCKED,
1402 });
1403 }
1404
1405 // unauthorized account cannot bypass auth check with amount=0
1406 {
1407 Env env{*this, features};
1408 Account const alice("alice");
1409 Account const bob("bob");
1410 MPTTester mptAlice(env, alice, {.holders = {bob}});
1411
1412 mptAlice.create({
1413 .ownerCount = 1,
1414 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTRequireAuth |
1415 tfMPTCanHoldConfidentialBalance,
1416 });
1417
1418 mptAlice.authorize({
1419 .account = bob,
1420 });
1421 mptAlice.authorize({
1422 .account = alice,
1423 .holder = bob,
1424 });
1425 mptAlice.pay(alice, bob, 100);
1426
1427 mptAlice.generateKeyPair(alice);
1428
1429 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1430
1431 mptAlice.generateKeyPair(bob);
1432
1433 // Unauthorize bob
1434 mptAlice.authorize({
1435 .account = alice,
1436 .holder = bob,
1437 .flags = tfMPTUnauthorize,
1438 });
1439
1440 // amount=0 should still be rejected when unauthorized
1441 mptAlice.convert({
1442 .account = bob,
1443 .amt = 0,
1444 .holderPubKey = mptAlice.getPubKey(bob),
1445 .err = tecNO_AUTH,
1446 });
1447 }
1448
1449 // cannot convert if auditor key is set, but auditor amount is not
1450 // provided
1451 {
1452 Env env{*this, features};
1453 Account const alice("alice");
1454 Account const bob("bob");
1455 Account const auditor("auditor");
1456 MPTTester mptAlice(
1457 env,
1458 alice,
1459 {
1460 .holders = {bob},
1461 .auditor = auditor,
1462 });
1463
1464 mptAlice.create({
1465 .ownerCount = 1,
1466 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1467 });
1468
1469 mptAlice.authorize({
1470 .account = bob,
1471 });
1472 mptAlice.pay(alice, bob, 100);
1473
1474 mptAlice.generateKeyPair(alice);
1475 mptAlice.generateKeyPair(bob);
1476 mptAlice.generateKeyPair(auditor);
1477
1478 mptAlice.set({
1479 .account = alice,
1480 .issuerPubKey = mptAlice.getPubKey(alice),
1481 .auditorPubKey = mptAlice.getPubKey(auditor),
1482 });
1483
1484 // no auditor encrypted amt provided
1485 mptAlice.convert({
1486 .account = bob,
1487 .amt = 10,
1488 .fillAuditorEncryptedAmt = false,
1489 .holderPubKey = mptAlice.getPubKey(bob),
1490 .err = tecNO_PERMISSION,
1491 });
1492 }
1493
1494 // cannot convert if tx include auditor ciphertext, but does not have
1495 // auditing enabled
1496 {
1497 Env env{*this, features};
1498 Account const alice("alice");
1499 Account const bob("bob");
1500 MPTTester mptAlice(env, alice, {.holders = {bob}});
1501
1502 mptAlice.create({
1503 .ownerCount = 1,
1504 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1505 });
1506
1507 mptAlice.authorize({
1508 .account = bob,
1509 });
1510 mptAlice.pay(alice, bob, 100);
1511
1512 mptAlice.generateKeyPair(alice);
1513 mptAlice.generateKeyPair(bob);
1514
1515 // there is no auditor key set
1516 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1517
1518 mptAlice.convert({
1519 .account = bob,
1520 .amt = 10,
1521 .holderPubKey = mptAlice.getPubKey(bob),
1522 .auditorEncryptedAmt = getTrivialCiphertext(),
1523 .err = tecNO_PERMISSION,
1524 });
1525 }
1526
1527 // Auditor key set successfully, auditor ciphertext mathematically
1528 // correct, but contains invalid data (mismatching amount).
1529 {
1530 Env env{*this, features};
1531 Account const alice("alice");
1532 Account const bob("bob");
1533 Account const auditor("auditor");
1534 MPTTester mptAlice(
1535 env,
1536 alice,
1537 {
1538 .holders = {bob},
1539 .auditor = auditor,
1540 });
1541
1542 mptAlice.create({
1543 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1544 });
1545
1546 mptAlice.authorize({
1547 .account = bob,
1548 });
1549 mptAlice.pay(alice, bob, 100);
1550
1551 mptAlice.generateKeyPair(alice);
1552 mptAlice.generateKeyPair(bob);
1553 mptAlice.generateKeyPair(auditor);
1554
1555 mptAlice.set({
1556 .account = alice,
1557 .issuerPubKey = mptAlice.getPubKey(alice),
1558 .auditorPubKey = mptAlice.getPubKey(auditor),
1559 });
1560
1561 mptAlice.convert({
1562 .account = bob,
1563 .amt = 10,
1564 .holderPubKey = mptAlice.getPubKey(bob),
1565 .auditorEncryptedAmt = getTrivialCiphertext(),
1566 .err = tecBAD_PROOF,
1567 });
1568 }
1569
1570 // invalid proof when registering holder pub key
1571 {
1572 Env env{*this, features};
1573 Account const alice("alice");
1574 Account const bob("bob");
1575 MPTTester mptAlice(env, alice, {.holders = {bob}});
1576
1577 mptAlice.create({
1578 .ownerCount = 1,
1579 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1580 });
1581
1582 mptAlice.authorize({
1583 .account = bob,
1584 });
1585 mptAlice.pay(alice, bob, 100);
1586
1587 mptAlice.generateKeyPair(alice);
1588 mptAlice.generateKeyPair(bob);
1589
1590 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1591
1592 mptAlice.convert({
1593 .account = bob,
1594 .amt = 10,
1595 .proof = std::string(kEcSchnorrProofLength * 2, 'A'),
1596 .holderPubKey = mptAlice.getPubKey(bob),
1597 .err = tecBAD_PROOF,
1598 });
1599 }
1600
1601 // no holder key on ledger and no key in tx
1602 {
1603 Env env{*this, features};
1604 Account const alice("alice");
1605 Account const bob("bob");
1606 MPTTester mptAlice(env, alice, {.holders = {bob}});
1607
1608 mptAlice.create({
1609 .ownerCount = 1,
1610 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1611 });
1612
1613 mptAlice.authorize({
1614 .account = bob,
1615 });
1616 mptAlice.pay(alice, bob, 100);
1617
1618 mptAlice.generateKeyPair(alice);
1619 mptAlice.generateKeyPair(bob);
1620
1621 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1622
1623 // bob has not registered a holder key, and doesn't provide one
1624 mptAlice.convert({
1625 .account = bob,
1626 .amt = 10,
1627 .err = tecNO_PERMISSION,
1628 });
1629 }
1630
1631 // all public balance already converted, try to convert more
1632 {
1633 Env env{*this, features};
1634 Account const alice("alice");
1635 Account const bob("bob");
1636 MPTTester mptAlice(env, alice, {.holders = {bob}});
1637
1638 mptAlice.create({
1639 .ownerCount = 1,
1640 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1641 });
1642
1643 mptAlice.authorize({
1644 .account = bob,
1645 });
1646 mptAlice.pay(alice, bob, 100);
1647
1648 mptAlice.generateKeyPair(alice);
1649
1650 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1651
1652 mptAlice.generateKeyPair(bob);
1653
1654 // convert entire public balance
1655 mptAlice.convert({
1656 .account = bob,
1657 .amt = 100,
1658 .holderPubKey = mptAlice.getPubKey(bob),
1659 });
1660
1661 env.require(MptBalance(mptAlice, bob, 0));
1662
1663 // try to convert 1 more — no public balance left
1664 mptAlice.convert({
1665 .account = bob,
1666 .amt = 1,
1667 .err = tecINSUFFICIENT_FUNDS,
1668 });
1669 }
1670 }
1671
1672 void
1674 {
1675 testcase("Merge inbox");
1676 using namespace test::jtx;
1677
1678 // Merge with an empty inbox should succeed as a no-op.
1679 {
1680 Env env{*this, features};
1681 Account const alice("alice");
1682 Account const bob("bob");
1683 MPTTester mptAlice(env, alice, {.holders = {bob}});
1684
1685 mptAlice.create({
1686 .ownerCount = 1,
1687 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1688 });
1689 mptAlice.authorize({.account = bob});
1690 mptAlice.pay(alice, bob, 100);
1691
1692 mptAlice.generateKeyPair(alice);
1693 mptAlice.generateKeyPair(bob);
1694 mptAlice.set({
1695 .account = alice,
1696 .issuerPubKey = mptAlice.getPubKey(alice),
1697 });
1698
1699 mptAlice.convert({
1700 .account = bob,
1701 .amt = 40,
1702 .holderPubKey = mptAlice.getPubKey(bob),
1703 });
1704
1705 mptAlice.mergeInbox({.account = bob});
1706 // Inbox is empty after the first merge; the second merge is a no-op.
1707 mptAlice.mergeInbox({.account = bob});
1708 }
1709
1710 // Makes sure if merge inbox version is UINT32_MAX, the next merge wraps
1711 // the version back to 0.
1712 {
1713 Env env{*this, features};
1714 Account const alice("alice");
1715 Account const bob("bob");
1716 MPTTester mptAlice(env, alice, {.holders = {bob}});
1717
1718 mptAlice.create({
1719 .ownerCount = 1,
1720 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1721 });
1722 mptAlice.authorize({.account = bob});
1723 mptAlice.pay(alice, bob, 100);
1724
1725 mptAlice.generateKeyPair(alice);
1726 mptAlice.generateKeyPair(bob);
1727 mptAlice.set({
1728 .account = alice,
1729 .issuerPubKey = mptAlice.getPubKey(alice),
1730 });
1731
1732 mptAlice.convert({
1733 .account = bob,
1734 .amt = 40,
1735 .holderPubKey = mptAlice.getPubKey(bob),
1736 });
1737
1738 // Force the on-ledger version to UINT32_MAX, then apply a merge and
1739 // confirm the version wraps around to 0.
1740 auto const wrappedFrom = std::numeric_limits<std::uint32_t>::max();
1741 auto const jt = env.jt(mptAlice.mergeInboxJV({.account = bob}));
1742 BEAST_EXPECT(env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal) {
1743 auto const sle = std::const_pointer_cast<SLE>(
1744 view.read(keylet::mptoken(mptAlice.issuanceID(), bob.id())));
1745 if (!sle)
1746 return false;
1747
1748 (*sle)[sfConfidentialBalanceVersion] = wrappedFrom;
1749 view.rawReplace(sle);
1750
1751 auto const result = xrpl::apply(env.app(), view, *jt.stx, TapNone, env.journal);
1752 BEAST_EXPECT(result.ter == tesSUCCESS);
1753 return result.applied;
1754 }));
1755
1756 BEAST_EXPECT(mptAlice.getMPTokenVersion(bob) == 0);
1757 }
1758 }
1759
1760 void
1762 {
1763 testcase("Merge inbox preflight");
1764 using namespace test::jtx;
1765 Env env{*this, features};
1766 Account const alice("alice");
1767 Account const bob("bob");
1768 MPTTester mptAlice(env, alice, {.holders = {bob}});
1769
1770 mptAlice.create({
1771 .ownerCount = 1,
1772 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1773 });
1774
1775 mptAlice.authorize({
1776 .account = bob,
1777 });
1778 mptAlice.pay(alice, bob, 100);
1779
1780 mptAlice.generateKeyPair(alice);
1781
1782 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1783
1784 mptAlice.generateKeyPair(bob);
1785
1786 mptAlice.convert({
1787 .account = bob,
1788 .amt = 40,
1789 .holderPubKey = mptAlice.getPubKey(bob),
1790 });
1791
1792 mptAlice.mergeInbox({
1793 .account = alice,
1794 .err = temMALFORMED,
1795 });
1796
1797 env.disableFeature(featureConfidentialTransfer);
1798 env.close();
1799
1800 mptAlice.mergeInbox({
1801 .account = bob,
1802 .err = temDISABLED,
1803 });
1804 }
1805
1806 void
1808 {
1809 testcase("Merge inbox preclaim");
1810 using namespace test::jtx;
1811
1812 // issuance does not exist
1813 {
1814 Env env{*this, features};
1815 Account const alice("alice");
1816 Account const bob("bob");
1817 MPTTester mptAlice(env, alice, {.holders = {bob}});
1818
1819 mptAlice.create({
1820 .ownerCount = 1,
1821 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1822 });
1823
1824 mptAlice.authorize({
1825 .account = bob,
1826 });
1827 mptAlice.generateKeyPair(alice);
1828
1829 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1830
1831 mptAlice.destroy();
1832 mptAlice.generateKeyPair(bob);
1833
1834 mptAlice.mergeInbox({
1835 .account = bob,
1836 .err = tecOBJECT_NOT_FOUND,
1837 });
1838 }
1839
1840 // tfMPTCanHoldConfidentialBalance is not set on issuance
1841 {
1842 Env env{*this, features};
1843 Account const alice("alice");
1844 Account const bob("bob");
1845 MPTTester mptAlice(env, alice, {.holders = {bob}});
1846
1847 mptAlice.create({
1848 .ownerCount = 1,
1849 .flags = tfMPTCanTransfer | tfMPTCanLock,
1850 });
1851
1852 mptAlice.authorize({
1853 .account = bob,
1854 });
1855 mptAlice.pay(alice, bob, 100);
1856
1857 mptAlice.generateKeyPair(alice);
1858 mptAlice.generateKeyPair(bob);
1859
1860 mptAlice.mergeInbox({
1861 .account = bob,
1862 .err = tecNO_PERMISSION,
1863 });
1864 }
1865
1866 // no mptoken
1867 {
1868 Env env{*this, features};
1869 Account const alice("alice");
1870 Account const bob("bob");
1871 MPTTester mptAlice(env, alice, {.holders = {bob}});
1872
1873 mptAlice.create({
1874 .ownerCount = 1,
1875 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1876 });
1877
1878 mptAlice.generateKeyPair(alice);
1879
1880 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1881
1882 mptAlice.mergeInbox({
1883 .account = bob,
1884 .err = tecOBJECT_NOT_FOUND,
1885 });
1886 }
1887
1888 // bob doesn't have encrypted balances
1889 {
1890 Env env{*this, features};
1891 Account const alice("alice");
1892 Account const bob("bob");
1893 MPTTester mptAlice(env, alice, {.holders = {bob}});
1894
1895 mptAlice.create({
1896 .ownerCount = 1,
1897 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1898 });
1899
1900 mptAlice.authorize({
1901 .account = bob,
1902 });
1903 mptAlice.pay(alice, bob, 100);
1904
1905 mptAlice.generateKeyPair(alice);
1906
1907 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1908
1909 mptAlice.generateKeyPair(bob);
1910
1911 mptAlice.mergeInbox({
1912 .account = bob,
1913 .err = tecNO_PERMISSION,
1914 });
1915 }
1916
1917 // holder is locked
1918 {
1919 Env env{*this, features};
1920 Account const alice("alice");
1921 Account const bob("bob");
1922 MPTTester mptAlice(env, alice, {.holders = {bob}});
1923
1924 mptAlice.create({
1925 .ownerCount = 1,
1926 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
1927 });
1928
1929 mptAlice.authorize({
1930 .account = bob,
1931 });
1932 mptAlice.pay(alice, bob, 100);
1933
1934 mptAlice.generateKeyPair(alice);
1935 mptAlice.generateKeyPair(bob);
1936
1937 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1938
1939 mptAlice.convert({
1940 .account = bob,
1941 .amt = 50,
1942 .holderPubKey = mptAlice.getPubKey(bob),
1943 });
1944
1945 // lock bob
1946 mptAlice.set({
1947 .account = alice,
1948 .holder = bob,
1949 .flags = tfMPTLock,
1950 });
1951
1952 mptAlice.mergeInbox({
1953 .account = bob,
1954 .err = tecLOCKED,
1955 });
1956
1957 // unlock bob
1958 mptAlice.set({
1959 .account = alice,
1960 .holder = bob,
1961 .flags = tfMPTUnlock,
1962 });
1963
1964 // should succeed now
1965 mptAlice.mergeInbox({
1966 .account = bob,
1967 });
1968 }
1969
1970 // holder not authorized
1971 {
1972 Env env{*this, features};
1973 Account const alice("alice");
1974 Account const bob("bob");
1975 MPTTester mptAlice(env, alice, {.holders = {bob}});
1976
1977 mptAlice.create({
1978 .ownerCount = 1,
1979 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance |
1980 tfMPTRequireAuth,
1981 });
1982
1983 mptAlice.authorize({
1984 .account = bob,
1985 });
1986 mptAlice.authorize({
1987 .account = alice,
1988 .holder = bob,
1989 });
1990 mptAlice.pay(alice, bob, 100);
1991
1992 mptAlice.generateKeyPair(alice);
1993 mptAlice.generateKeyPair(bob);
1994
1995 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
1996
1997 mptAlice.convert({
1998 .account = bob,
1999 .amt = 50,
2000 .holderPubKey = mptAlice.getPubKey(bob),
2001 });
2002
2003 // unauthorize bob
2004 mptAlice.authorize({
2005 .account = alice,
2006 .holder = bob,
2007 .flags = tfMPTUnauthorize,
2008 });
2009
2010 mptAlice.mergeInbox({
2011 .account = bob,
2012 .err = tecNO_AUTH,
2013 });
2014
2015 // authorize bob again
2016 mptAlice.authorize({
2017 .account = alice,
2018 .holder = bob,
2019 });
2020
2021 // should succeed now
2022 mptAlice.mergeInbox({
2023 .account = bob,
2024 });
2025 }
2026 }
2027
2028 void
2030 {
2031 testcase("test confidential send");
2032 using namespace test::jtx;
2033 Env env{*this, features};
2034 Account const alice("alice"), bob("bob"), carol("carol");
2035 ConfidentialEnv confEnv{
2036 env,
2037 alice,
2038 {
2039 {.account = bob, .payAmount = 100, .convertAmount = 60},
2040 {.account = carol, .payAmount = 50, .convertAmount = 20},
2041 }};
2042 auto& mptAlice = confEnv.mpt;
2043
2044 // bob sends 10 to carol
2045 mptAlice.send({
2046 .account = bob,
2047 .dest = carol,
2048 .amt = 10,
2049 });
2050
2051 // bob sends 1 to carol again
2052 mptAlice.send({
2053 .account = bob,
2054 .dest = carol,
2055 .amt = 1,
2056 });
2057
2058 mptAlice.mergeInbox({
2059 .account = carol,
2060 });
2061
2062 // carol sends 15 back to bob
2063 mptAlice.send({
2064 .account = carol,
2065 .dest = bob,
2066 .amt = 15,
2067 });
2068 }
2069
2070 void
2072 {
2073 testcase("test confidential send with auditor");
2074 using namespace test::jtx;
2075 Env env{*this, features};
2076 Account const alice("alice");
2077 Account const bob("bob");
2078 Account const carol("carol");
2079 Account const auditor("auditor");
2080 ConfidentialEnv confEnv{
2081 env,
2082 alice,
2083 {
2084 {.account = bob, .payAmount = 100, .convertAmount = 60},
2085 {.account = carol, .payAmount = 50, .convertAmount = 20},
2086 },
2087 tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
2088 auditor};
2089 auto& mptAlice = confEnv.mpt;
2090
2091 // bob sends 10 to carol
2092 mptAlice.send({
2093 .account = bob,
2094 .dest = carol,
2095 .amt = 10,
2096 });
2097
2098 // bob sends 1 to carol again
2099 mptAlice.send({
2100 .account = bob,
2101 .dest = carol,
2102 .amt = 1,
2103 });
2104
2105 mptAlice.mergeInbox({
2106 .account = carol,
2107 });
2108
2109 // carol sends 15 back to bob
2110 mptAlice.send({
2111 .account = carol,
2112 .dest = bob,
2113 .amt = 15,
2114 });
2115 }
2116
2117 void
2119 {
2120 testcase("test ConfidentialMPTSend Preflight");
2121 using namespace test::jtx;
2122
2123 // test disabled
2124 {
2125 Env env{*this, features - featureConfidentialTransfer};
2126 Account const alice("alice");
2127 Account const bob("bob");
2128 Account const carol("carol");
2129 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
2130
2131 mptAlice.create();
2132 mptAlice.authorize({
2133 .account = bob,
2134 });
2135 mptAlice.authorize({
2136 .account = carol,
2137 });
2138
2139 mptAlice.send({
2140 .account = bob,
2141 .dest = carol,
2142 .amt = 10,
2143 .senderEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength),
2144 .destEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength),
2145 .issuerEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength),
2146 .err = temDISABLED,
2147 });
2148 }
2149
2150 // test malformed
2151 {
2152 Env env{*this, features};
2153 Account const alice("alice");
2154 Account const bob("bob");
2155 Account const carol("carol");
2156 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
2157
2158 mptAlice.create({
2159 .ownerCount = 1,
2160 .flags = tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance,
2161 });
2162
2163 mptAlice.authorize({
2164 .account = bob,
2165 });
2166 mptAlice.authorize({
2167 .account = carol,
2168 });
2169 mptAlice.generateKeyPair(alice);
2170 mptAlice.generateKeyPair(bob);
2171 mptAlice.generateKeyPair(carol);
2172 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
2173 mptAlice.pay(alice, bob, 100);
2174 mptAlice.pay(alice, carol, 50);
2175
2176 mptAlice.convert({
2177 .account = bob,
2178 .amt = 50,
2179 .holderPubKey = mptAlice.getPubKey(bob),
2180 });
2181
2182 mptAlice.convert({
2183 .account = carol,
2184 .amt = 40,
2185 .holderPubKey = mptAlice.getPubKey(carol),
2186 });
2187
2188 // issuer can not be the same as sender
2189 mptAlice.send({
2190 .account = alice,
2191 .dest = carol,
2192 .amt = 10,
2193 .err = temMALFORMED,
2194 });
2195
2196 // can not send to self
2197 mptAlice.send({
2198 .account = bob,
2199 .dest = bob,
2200 .amt = 10,
2201 .proof = getTrivialSendProofHex(),
2202 .err = temMALFORMED,
2203 });
2204
2205 // can not send to issuer
2206 mptAlice.send({
2207 .account = bob,
2208 .dest = alice,
2209 .amt = 10,
2210 .err = temMALFORMED,
2211 });
2212
2213 // sender encrypted amount wrong length
2214 mptAlice.send({
2215 .account = bob,
2216 .dest = carol,
2217 .amt = 10,
2218 .senderEncryptedAmt = gMakeZeroBuffer(10),
2219 .err = temBAD_CIPHERTEXT,
2220 });
2221
2222 // dest encrypted amount wrong length
2223 mptAlice.send({
2224 .account = bob,
2225 .dest = carol,
2226 .amt = 10,
2227 .destEncryptedAmt = gMakeZeroBuffer(10),
2228 .err = temBAD_CIPHERTEXT,
2229 });
2230
2231 // issuer encrypted amount wrong length
2232 mptAlice.send({
2233 .account = bob,
2234 .dest = carol,
2235 .amt = 10,
2236 .issuerEncryptedAmt = gMakeZeroBuffer(10),
2237 .err = temBAD_CIPHERTEXT,
2238 });
2239
2240 // sender encrypted amount malformed
2241 mptAlice.send({
2242 .account = bob,
2243 .dest = carol,
2244 .amt = 10,
2245 .proof = getTrivialSendProofHex(),
2246 .senderEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength),
2247 .amountCommitment = getTrivialCommitment(),
2248 .balanceCommitment = getTrivialCommitment(),
2249 .err = temBAD_CIPHERTEXT,
2250 });
2251
2252 // dest encrypted amount malformed
2253 mptAlice.send({
2254 .account = bob,
2255 .dest = carol,
2256 .amt = 10,
2257 .proof = getTrivialSendProofHex(),
2258 .destEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength),
2259 .amountCommitment = getTrivialCommitment(),
2260 .balanceCommitment = getTrivialCommitment(),
2261 .err = temBAD_CIPHERTEXT,
2262 });
2263
2264 // issuer encrypted amount malformed
2265 mptAlice.send({
2266 .account = bob,
2267 .dest = carol,
2268 .amt = 10,
2269 .proof = getTrivialSendProofHex(),
2270 .issuerEncryptedAmt = gMakeZeroBuffer(kEcGamalEncryptedTotalLength),
2271 .amountCommitment = getTrivialCommitment(),
2272 .balanceCommitment = getTrivialCommitment(),
2273 .err = temBAD_CIPHERTEXT,
2274 });
2275
2276 // invalid proof length
2277 mptAlice.send({
2278 .account = bob,
2279 .dest = carol,
2280 .amt = 10,
2281 .proof = std::string(10, 'A'),
2282 .amountCommitment = getTrivialCommitment(),
2283 .balanceCommitment = getTrivialCommitment(),
2284 .err = temMALFORMED,
2285 });
2286
2287 // invalid amount Pedersen commitment length
2288 mptAlice.send({
2289 .account = bob,
2290 .dest = carol,
2291 .amt = 10,
2292 .proof = getTrivialSendProofHex(),
2293 .amountCommitment = gMakeZeroBuffer(100),
2294 .balanceCommitment = getTrivialCommitment(),
2295 .err = temMALFORMED,
2296 });
2297
2298 // invalid balance Pedersen commitment length
2299 mptAlice.send({
2300 .account = bob,
2301 .dest = carol,
2302 .amt = 10,
2303 .proof = getTrivialSendProofHex(),
2304 .amountCommitment = getTrivialCommitment(),
2305 .balanceCommitment = gMakeZeroBuffer(100),
2306 .err = temMALFORMED,
2307 });
2308
2309 // amount Pedersen commitment has correct length but invalid EC point data
2310 mptAlice.send({
2311 .account = bob,
2312 .dest = carol,
2313 .amt = 10,
2314 .proof = getTrivialSendProofHex(),
2315 .amountCommitment = gMakeZeroBuffer(kEcPedersenCommitmentLength),
2316 .balanceCommitment = getTrivialCommitment(),
2317 .err = temMALFORMED,
2318 });
2319
2320 // balance Pedersen commitment has correct length but invalid EC point data
2321 mptAlice.send({
2322 .account = bob,
2323 .dest = carol,
2324 .amt = 10,
2325 .proof = getTrivialSendProofHex(),
2326 .amountCommitment = getTrivialCommitment(),
2327 .balanceCommitment = gMakeZeroBuffer(kEcPedersenCommitmentLength),
2328 .err = temMALFORMED,
2329 });
2330 }
2331
2332 // test bad ciphertext
2333 {
2334 Env env{*this, features};
2335 Account const alice("alice");
2336 Account const bob("bob");
2337 Account const carol("carol");
2338 Account const auditor("auditor");
2339 MPTTester mptAlice(
2340 env,
2341 alice,
2342 {
2343 .holders = {bob, carol},
2344 .auditor = auditor,
2345 });
2346
2347 mptAlice.create({
2348 .ownerCount = 1,
2349 .flags = tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance,
2350 });
2351
2352 mptAlice.authorize({
2353 .account = bob,
2354 });
2355 mptAlice.authorize({
2356 .account = carol,
2357 });
2358 mptAlice.generateKeyPair(alice);
2359 mptAlice.generateKeyPair(bob);
2360 mptAlice.generateKeyPair(carol);
2361 mptAlice.generateKeyPair(auditor);
2362
2363 mptAlice.set({
2364 .account = alice,
2365 .issuerPubKey = mptAlice.getPubKey(alice),
2366 .auditorPubKey = mptAlice.getPubKey(auditor),
2367 });
2368 mptAlice.pay(alice, bob, 100);
2369 mptAlice.pay(alice, carol, 50);
2370
2371 mptAlice.convert({
2372 .account = bob,
2373 .amt = 50,
2374 .holderPubKey = mptAlice.getPubKey(bob),
2375 });
2376
2377 mptAlice.convert({
2378 .account = carol,
2379 .amt = 40,
2380 .holderPubKey = mptAlice.getPubKey(carol),
2381 });
2382
2383 // auditor encrypted amount wrong length
2384 mptAlice.send({
2385 .account = bob,
2386 .dest = carol,
2387 .amt = 10,
2388 .proof = getTrivialSendProofHex(),
2389 .auditorEncryptedAmt = gMakeZeroBuffer(10),
2390 .amountCommitment = getTrivialCommitment(),
2391 .balanceCommitment = getTrivialCommitment(),
2392 .err = temBAD_CIPHERTEXT,
2393 });
2394
2395 // auditor encrypted amount (correct length, invalid data)
2396 mptAlice.send({
2397 .account = bob,
2398 .dest = carol,
2399 .amt = 10,
2400 .proof = getTrivialSendProofHex(),
2401 .auditorEncryptedAmt = getBadCiphertext(),
2402 .amountCommitment = getTrivialCommitment(),
2403 .balanceCommitment = getTrivialCommitment(),
2404 .err = temBAD_CIPHERTEXT,
2405 });
2406 }
2407 }
2408
2409 void
2411 {
2412 testcase("test ConfidentialMPTSend Preclaim");
2413
2414 using namespace test::jtx;
2415 Env env{*this, features};
2416 Account const alice("alice");
2417 Account const bob("bob");
2418 Account const carol("carol");
2419 Account const dave("dave");
2420 Account const eve("eve");
2421 MPTTester mptAlice(env, alice, {.holders = {bob, carol, dave, eve}});
2422
2423 // authorize bob, carol, dave (not eve)
2424 mptAlice.create({
2425 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTRequireAuth |
2426 tfMPTCanHoldConfidentialBalance,
2427 });
2428 mptAlice.authorize({
2429 .account = bob,
2430 });
2431 mptAlice.authorize({
2432 .account = alice,
2433 .holder = bob,
2434 });
2435 mptAlice.authorize({
2436 .account = carol,
2437 });
2438 mptAlice.authorize({
2439 .account = alice,
2440 .holder = carol,
2441 });
2442 mptAlice.authorize({
2443 .account = dave,
2444 });
2445 mptAlice.authorize({
2446 .account = alice,
2447 .holder = dave,
2448 });
2449
2450 // fund bob, carol (not dave or eve)
2451 mptAlice.pay(alice, bob, 100);
2452 mptAlice.pay(alice, carol, 50);
2453
2454 mptAlice.generateKeyPair(alice);
2455 mptAlice.generateKeyPair(bob);
2456 mptAlice.generateKeyPair(carol);
2457 mptAlice.generateKeyPair(dave);
2458 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
2459
2460 // bob and carol convert some funds to confidential
2461 mptAlice.convert({
2462 .account = bob,
2463 .amt = 60,
2464 .holderPubKey = mptAlice.getPubKey(bob),
2465 .err = tesSUCCESS,
2466 });
2467 mptAlice.convert({
2468 .account = carol,
2469 .amt = 20,
2470 .holderPubKey = mptAlice.getPubKey(carol),
2471 .err = tesSUCCESS,
2472 });
2473
2474 // bob and carol merge inbox
2475 mptAlice.mergeInbox({
2476 .account = bob,
2477 });
2478 mptAlice.mergeInbox({
2479 .account = carol,
2480 });
2481
2482 // issuance not found
2483 {
2484 Env env{*this, features};
2485 Account const alice("alice");
2486 Account const bob("bob");
2487 Account const carol("carol");
2488 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
2489
2490 mptAlice.create({
2491 .flags = tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance,
2492 });
2493 mptAlice.authorize({
2494 .account = bob,
2495 });
2496 mptAlice.authorize({
2497 .account = carol,
2498 });
2499 mptAlice.generateKeyPair(alice);
2500 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
2501
2502 // destroy the issuance
2503 mptAlice.destroy();
2504
2505 json::Value jv;
2506 jv[jss::Account] = bob.human();
2507 jv[jss::Destination] = carol.human();
2508 jv[jss::TransactionType] = jss::ConfidentialMPTSend;
2509 jv[sfMPTokenIssuanceID] = to_string(mptAlice.issuanceID());
2510 jv[sfSenderEncryptedAmount] = strHex(getTrivialCiphertext());
2511 jv[sfDestinationEncryptedAmount] = strHex(getTrivialCiphertext());
2512 jv[sfIssuerEncryptedAmount] = strHex(getTrivialCiphertext());
2513 jv[sfAmountCommitment] = strHex(getTrivialCommitment());
2514 jv[sfBalanceCommitment] = strHex(getTrivialCommitment());
2515 jv[sfZKProof] = getTrivialSendProofHex();
2516
2517 env(jv, Ter(tecOBJECT_NOT_FOUND));
2518 }
2519
2520 // destination does not exist
2521 {
2522 Account const unknown("unknown");
2523 mptAlice.send({
2524 .account = bob,
2525 .dest = unknown,
2526 .amt = 10,
2527 .proof = getTrivialSendProofHex(),
2528 .senderEncryptedAmt = getTrivialCiphertext(),
2529 .destEncryptedAmt = getTrivialCiphertext(),
2530 .issuerEncryptedAmt = getTrivialCiphertext(),
2531 .amountCommitment = getTrivialCommitment(),
2532 .balanceCommitment = getTrivialCommitment(),
2533 .err = tecNO_TARGET,
2534 });
2535 }
2536
2537 // destination requires destination tag but none provided
2538 {
2539 env(fset(carol, asfRequireDest));
2540 env.close();
2541
2542 mptAlice.send({
2543 .account = bob,
2544 .dest = carol,
2545 .amt = 10,
2546 .proof = getTrivialSendProofHex(),
2547 .senderEncryptedAmt = getTrivialCiphertext(),
2548 .destEncryptedAmt = getTrivialCiphertext(),
2549 .issuerEncryptedAmt = getTrivialCiphertext(),
2550 .amountCommitment = getTrivialCommitment(),
2551 .balanceCommitment = getTrivialCommitment(),
2552 .err = tecDST_TAG_NEEDED,
2553 });
2554
2555 env(fclear(carol, asfRequireDest));
2556 env.close();
2557 }
2558
2559 // dave exists, but has no confidential fields (never converted)
2560 {
2561 mptAlice.send({
2562 .account = bob,
2563 .dest = dave,
2564 .amt = 10,
2565 .proof = getTrivialSendProofHex(),
2566 .senderEncryptedAmt = getTrivialCiphertext(),
2567 .destEncryptedAmt = getTrivialCiphertext(),
2568 .issuerEncryptedAmt = getTrivialCiphertext(),
2569 .amountCommitment = getTrivialCommitment(),
2570 .balanceCommitment = getTrivialCommitment(),
2571 .err = tecNO_PERMISSION,
2572 });
2573 mptAlice.send({
2574 .account = dave,
2575 .dest = carol,
2576 .amt = 10,
2577 .proof = getTrivialSendProofHex(),
2578 .senderEncryptedAmt = getTrivialCiphertext(),
2579 .destEncryptedAmt = getTrivialCiphertext(),
2580 .issuerEncryptedAmt = getTrivialCiphertext(),
2581 .amountCommitment = getTrivialCommitment(),
2582 .balanceCommitment = getTrivialCommitment(),
2583 .err = tecNO_PERMISSION,
2584 });
2585 }
2586
2587 // destination exists but has no MPT object.
2588 {
2589 mptAlice.send({
2590 .account = bob,
2591 .dest = eve,
2592 .amt = 10,
2593 .proof = getTrivialSendProofHex(),
2594 .senderEncryptedAmt = getTrivialCiphertext(),
2595 .destEncryptedAmt = getTrivialCiphertext(),
2596 .issuerEncryptedAmt = getTrivialCiphertext(),
2597 .amountCommitment = getTrivialCommitment(),
2598 .balanceCommitment = getTrivialCommitment(),
2599 .err = tecOBJECT_NOT_FOUND,
2600 });
2601 }
2602
2603 // issuance is locked globally
2604 {
2605 // lock issuance
2606 mptAlice.set({
2607 .account = alice,
2608 .flags = tfMPTLock,
2609 });
2610 mptAlice.send({
2611 .account = bob,
2612 .dest = carol,
2613 .amt = 10,
2614 .err = tecLOCKED,
2615 });
2616 // unlock issuance
2617 mptAlice.set({
2618 .account = alice,
2619 .flags = tfMPTUnlock,
2620 });
2621 // now can send
2622 mptAlice.send({
2623 .account = bob,
2624 .dest = carol,
2625 .amt = 1,
2626 });
2627 }
2628
2629 // sender is locked
2630 {
2631 // lock bob
2632 mptAlice.set({
2633 .account = alice,
2634 .holder = bob,
2635 .flags = tfMPTLock,
2636 });
2637 mptAlice.send({
2638 .account = bob,
2639 .dest = carol,
2640 .amt = 10,
2641 .err = tecLOCKED,
2642 });
2643 // unlock bob
2644 mptAlice.set({
2645 .account = alice,
2646 .holder = bob,
2647 .flags = tfMPTUnlock,
2648 });
2649 // now can send
2650 mptAlice.send({
2651 .account = bob,
2652 .dest = carol,
2653 .amt = 2,
2654 });
2655 }
2656
2657 // destination is locked
2658 {
2659 // lock carol
2660 mptAlice.set({
2661 .account = alice,
2662 .holder = carol,
2663 .flags = tfMPTLock,
2664 });
2665 mptAlice.send({
2666 .account = bob,
2667 .dest = carol,
2668 .amt = 10,
2669 .err = tecLOCKED,
2670 });
2671 // unlock carol
2672 mptAlice.set({
2673 .account = alice,
2674 .holder = carol,
2675 .flags = tfMPTUnlock,
2676 });
2677 // now can send
2678 mptAlice.send({
2679 .account = bob,
2680 .dest = carol,
2681 .amt = 3,
2682 });
2683 }
2684
2685 // sender not authorized
2686 {
2687 // unauthorize bob
2688 mptAlice.authorize({
2689 .account = alice,
2690 .holder = bob,
2691 .flags = tfMPTUnauthorize,
2692 });
2693 mptAlice.send({
2694 .account = bob,
2695 .dest = carol,
2696 .amt = 10,
2697 .err = tecNO_AUTH,
2698 });
2699 // authorize bob again
2700 mptAlice.authorize({
2701 .account = alice,
2702 .holder = bob,
2703 });
2704 // now can send
2705 mptAlice.send({
2706 .account = bob,
2707 .dest = carol,
2708 .amt = 4,
2709 });
2710 }
2711
2712 // destination not authorized
2713 {
2714 // unauthorize carol
2715 mptAlice.authorize({
2716 .account = alice,
2717 .holder = carol,
2718 .flags = tfMPTUnauthorize,
2719 });
2720 mptAlice.send({
2721 .account = bob,
2722 .dest = carol,
2723 .amt = 10,
2724 .err = tecNO_AUTH,
2725 });
2726 // authorize carol again
2727 mptAlice.authorize({
2728 .account = alice,
2729 .holder = carol,
2730 });
2731 // now can send
2732 mptAlice.send({
2733 .account = bob,
2734 .dest = carol,
2735 .amt = 5,
2736 });
2737 }
2738
2739 // cannot send when MPTCanTransfer is not set
2740 {
2741 Env env{*this, features};
2742 Account const alice("alice");
2743 Account const bob("bob");
2744 Account const carol("carol");
2745 ConfidentialEnv confEnv{
2746 env,
2747 alice,
2748 {
2749 {.account = bob, .payAmount = 100, .convertAmount = 60},
2750 {.account = carol, .payAmount = 50, .convertAmount = 20},
2751 },
2752 tfMPTCanLock | tfMPTCanHoldConfidentialBalance};
2753 auto& mptAlice = confEnv.mpt;
2754
2755 // bob sends 10 to carol
2756 mptAlice.send({
2757 .account = bob,
2758 .dest = carol,
2759 .amt = 10, // will be encrypted internally
2760 .err = tecNO_AUTH,
2761 });
2762 }
2763
2764 // Confidential MPTs should not have a transfer fee. Force malformed
2765 // ledger state to cover the defensive preclaim check.
2766 {
2767 Env env{*this, features};
2768 Account const alice("alice");
2769 Account const bob("bob");
2770 Account const carol("carol");
2771 ConfidentialEnv confEnv{
2772 env,
2773 alice,
2774 {
2775 {.account = bob, .payAmount = 100, .convertAmount = 60},
2776 {.account = carol, .payAmount = 50, .convertAmount = 20},
2777 }};
2778 auto& mptAlice = confEnv.mpt;
2779
2780 BEAST_EXPECT(env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal) {
2781 auto const issuance = std::const_pointer_cast<SLE>(
2782 view.read(keylet::mptokenIssuance(mptAlice.issuanceID())));
2783 if (!issuance)
2784 return false;
2785
2786 issuance->setFieldU16(sfTransferFee, 1);
2787 view.rawReplace(issuance);
2788 return true;
2789 }));
2790
2791 mptAlice.send({
2792 .account = bob,
2793 .dest = carol,
2794 .amt = 10,
2795 .proof = getTrivialSendProofHex(),
2796 .err = tecNO_PERMISSION,
2797 });
2798 }
2799
2800 // bad proof
2801 {
2802 Env env{*this, features};
2803 Account const alice("alice");
2804 Account const bob("bob");
2805 Account const carol("carol");
2806 ConfidentialEnv confEnv{
2807 env,
2808 alice,
2809 {
2810 {.account = bob, .payAmount = 100, .convertAmount = 60},
2811 {.account = carol, .payAmount = 50, .convertAmount = 20},
2812 }};
2813 auto& mptAlice = confEnv.mpt;
2814
2815 mptAlice.send({
2816 .account = bob,
2817 .dest = carol,
2818 .amt = 10,
2819 .proof = getTrivialSendProofHex(),
2820 .err = tecBAD_PROOF,
2821 });
2822 }
2823
2824 // No Auditor key set, but auditor encrypted amt provided
2825 {
2826 mptAlice.send({
2827 .account = bob,
2828 .dest = carol,
2829 .amt = 10,
2830 .proof = getTrivialSendProofHex(),
2831 .auditorEncryptedAmt = getTrivialCiphertext(),
2832 .err = tecNO_PERMISSION,
2833 });
2834 }
2835
2836 // Auditor CipherText is Valid, but does not match the Txn Amount
2837 {
2838 Env env{*this, features};
2839 Account const alice("alice");
2840 Account const bob("bob");
2841 Account const carol("carol");
2842 Account const auditor("auditor");
2843 MPTTester mptAlice(
2844 env,
2845 alice,
2846 {
2847 .holders = {bob, carol},
2848 .auditor = auditor,
2849 });
2850
2851 mptAlice.create({
2852 .ownerCount = 1,
2853 .flags = tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance,
2854 });
2855
2856 mptAlice.authorize({
2857 .account = bob,
2858 });
2859 mptAlice.authorize({
2860 .account = carol,
2861 });
2862 mptAlice.generateKeyPair(alice);
2863 mptAlice.generateKeyPair(bob);
2864 mptAlice.generateKeyPair(carol);
2865 mptAlice.generateKeyPair(auditor);
2866
2867 mptAlice.set({
2868 .account = alice,
2869 .issuerPubKey = mptAlice.getPubKey(alice),
2870 .auditorPubKey = mptAlice.getPubKey(auditor),
2871 });
2872 mptAlice.pay(alice, bob, 100);
2873 mptAlice.pay(alice, carol, 50);
2874
2875 mptAlice.convert({
2876 .account = bob,
2877 .amt = 50,
2878 .holderPubKey = mptAlice.getPubKey(bob),
2879 });
2880
2881 mptAlice.convert({
2882 .account = carol,
2883 .amt = 40,
2884 .holderPubKey = mptAlice.getPubKey(carol),
2885 });
2886
2887 mptAlice.send({
2888 .account = bob,
2889 .dest = carol,
2890 .amt = 10,
2891 .proof = getTrivialSendProofHex(),
2892 .auditorEncryptedAmt = getTrivialCiphertext(),
2893 .amountCommitment = getTrivialCommitment(),
2894 .balanceCommitment = getTrivialCommitment(),
2895 .err = tecBAD_PROOF,
2896 });
2897 }
2898 }
2899
2900 void
2902 {
2903 testcase("test ConfidentialMPTSend Range Proof");
2904
2905 using namespace test::jtx;
2906 Env env{*this, features};
2907 Account const alice("alice"), bob("bob"), carol("carol");
2908 ConfidentialEnv confEnv{
2909 env,
2910 alice,
2911 {
2912 {.account = bob, .payAmount = 1000, .convertAmount = 60},
2913 {.account = carol, .payAmount = 1000, .convertAmount = 50},
2914 }};
2915 auto& mptAlice = confEnv.mpt;
2916
2917 {
2918 // Bob has 60, sends 60. Remainder is exactly 0. Valid remaining balance.
2919 mptAlice.send({
2920 .account = bob,
2921 .dest = carol,
2922 .amt = 60,
2923 .err = tesSUCCESS,
2924 });
2925 }
2926
2927 {
2928 // Bob converts 100.
2929 mptAlice.convert({
2930 .account = bob,
2931 .amt = 100,
2932 });
2933 mptAlice.mergeInbox({
2934 .account = bob,
2935 });
2936
2937 // Bob has 100, tries to send 2^64-1. Invalid remaining balance.
2938 {
2939 ConfidentialSendSetup const setup(
2940 mptAlice, bob, carol, alice, std::numeric_limits<std::uint64_t>::max());
2941 auto const forged = getForgedSendProof(mptAlice, env, bob, carol, setup);
2942 mptAlice.send(setup.sendArgs(bob, carol, forged, tecBAD_PROOF));
2943 }
2944
2945 // Bob sends 1, remaining 99.
2946 mptAlice.send({
2947 .account = bob,
2948 .dest = carol,
2949 .amt = 1,
2950 .err = tesSUCCESS,
2951 });
2952 }
2953
2954 // send when spending balance is 0 (key registered, inbox merged, but nothing converted)
2955 {
2956 // Register keys only (amt=0) for both parties — spending stays 0.
2957 Env env2{*this, features};
2958 Account const alice2("alice"), bob2("bob"), carol2("carol");
2959 ConfidentialEnv zeroEnv{
2960 env2,
2961 alice2,
2962 {
2963 {.account = bob2, .payAmount = 100, .convertAmount = 0},
2964 {.account = carol2, .payAmount = 50, .convertAmount = 0},
2965 }};
2966 auto& mptAlice2 = zeroEnv.mpt;
2967
2968 // Trying to send any amount with 0 spending balance must fail:
2969 // the range proof for < 0 is invalid.
2970 ConfidentialSendSetup const setup(mptAlice2, bob2, carol2, alice2, 1);
2971 auto const forged = getForgedSendProof(mptAlice2, env2, bob2, carol2, setup);
2972 mptAlice2.send(setup.sendArgs(bob2, carol2, forged, tecBAD_PROOF));
2973
2974 BEAST_EXPECT(
2975 mptAlice2.getDecryptedBalance(bob2, MPTTester::holderEncryptedSpending) == 0);
2976 }
2977 }
2978
2979 /* The equality proof library and range proof library do not
2980 * support generating proofs for amt=0 (they require a positive witness).
2981 * To test the VERIFIER without crashing the helper, we bypass normal proof
2982 * generation by supplying explicit ciphertexts, commitments, and a dummy
2983 * (all-zero) proof. The preflight has no temBAD_AMOUNT guard for
2984 * ConfidentialMPTSend, so all validation occurs in verifySendProofs.
2985 */
2986 void
2988 {
2989 testcase("Send: zero amount — equality and range proof verifier behavior");
2990 using namespace test::jtx;
2991
2992 Env env{*this, features};
2993 Account const alice("alice");
2994 Account const bob("bob");
2995 Account const carol("carol");
2996 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
2997
2998 mptAlice.create({
2999 .ownerCount = 1,
3000 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
3001 });
3002 mptAlice.authorize({.account = bob});
3003 mptAlice.authorize({.account = carol});
3004 mptAlice.pay(alice, bob, 100);
3005 mptAlice.pay(alice, carol, 50);
3006
3007 mptAlice.generateKeyPair(alice);
3008 mptAlice.generateKeyPair(bob);
3009 mptAlice.generateKeyPair(carol);
3010
3011 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
3012
3013 mptAlice.convert({.account = bob, .amt = 100, .holderPubKey = mptAlice.getPubKey(bob)});
3014 mptAlice.mergeInbox({.account = bob});
3015
3016 mptAlice.convert({.account = carol, .amt = 50, .holderPubKey = mptAlice.getPubKey(carol)});
3017 mptAlice.mergeInbox({.account = carol});
3018
3019 Buffer const bf = generateBlindingFactor();
3020
3021 // equality proof verification for amt=0.
3022 // Encrypt 0 under each participant's key. The amount commitment is
3023 // getTrivialCommitment() — a valid EC point that passes preflight's
3024 // isValidCompressedECPoint check but is not the true PC for amt=0.
3025 // The dummy ZKProof's equality component must be rejected by
3026 // verifyMultiCiphertextEqualityProof.
3027 mptAlice.send({
3028 .account = bob,
3029 .dest = carol,
3030 .amt = 0,
3031 .proof = getTrivialSendProofHex(),
3032 .senderEncryptedAmt = mptAlice.encryptAmount(bob, 0, bf),
3033 .destEncryptedAmt = mptAlice.encryptAmount(carol, 0, bf),
3034 .issuerEncryptedAmt = mptAlice.encryptAmount(alice, 0, bf),
3035 .amountCommitment = getTrivialCommitment(),
3036 .balanceCommitment = getTrivialCommitment(),
3037 .err = tecBAD_PROOF,
3038 });
3039
3040 // range proof verification for amt=0.
3041 // Identical construction; focuses on the bulletproof range check
3042 // embedded in ZKProof. The range proof for amount=0 with a dummy
3043 // (all-zero) proof must also be rejected.
3044 Buffer const bf2 = generateBlindingFactor();
3045 mptAlice.send({
3046 .account = bob,
3047 .dest = carol,
3048 .amt = 0,
3049 .proof = getTrivialSendProofHex(),
3050 .senderEncryptedAmt = mptAlice.encryptAmount(bob, 0, bf2),
3051 .destEncryptedAmt = mptAlice.encryptAmount(carol, 0, bf2),
3052 .issuerEncryptedAmt = mptAlice.encryptAmount(alice, 0, bf2),
3053 .amountCommitment = getTrivialCommitment(),
3054 .balanceCommitment = getTrivialCommitment(),
3055 .err = tecBAD_PROOF,
3056 });
3057
3058 // All rejected sends must leave balances unchanged.
3059 BEAST_EXPECT(mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending) == 100);
3060 BEAST_EXPECT(mptAlice.getDecryptedBalance(carol, MPTTester::holderEncryptedInbox) == 0);
3061 }
3062
3063 void
3065 {
3066 testcase("Delete");
3067 using namespace test::jtx;
3068
3069 // cannot delete mptoken where it has encrypted balance
3070 {
3071 Env env{*this, features};
3072 Account const alice("alice");
3073 Account const bob("bob");
3074 MPTTester mptAlice(env, alice, {.holders = {bob}});
3075
3076 mptAlice.create({
3077 .ownerCount = 1,
3078 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
3079 });
3080
3081 mptAlice.authorize({
3082 .account = bob,
3083 });
3084 mptAlice.pay(alice, bob, 100);
3085
3086 mptAlice.generateKeyPair(alice);
3087
3088 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
3089
3090 mptAlice.generateKeyPair(bob);
3091
3092 mptAlice.convert({
3093 .account = bob,
3094 .amt = 100,
3095 .holderPubKey = mptAlice.getPubKey(bob),
3096 });
3097
3098 mptAlice.authorize({
3099 .account = bob,
3100 .flags = tfMPTUnauthorize,
3101 .err = tecHAS_OBLIGATIONS,
3102 });
3103 }
3104
3105 // cannot delete mptoken where it has encrypted balance
3106 {
3107 Env env{*this, features};
3108 Account const alice("alice");
3109 Account const bob("bob");
3110 Account const carol("carol");
3111 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
3112
3113 mptAlice.create({
3114 .ownerCount = 1,
3115 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
3116 });
3117
3118 mptAlice.authorize({
3119 .account = bob,
3120 });
3121 mptAlice.authorize({
3122 .account = carol,
3123 });
3124 mptAlice.pay(alice, bob, 100);
3125
3126 mptAlice.generateKeyPair(alice);
3127
3128 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
3129
3130 mptAlice.generateKeyPair(bob);
3131 mptAlice.generateKeyPair(carol);
3132
3133 mptAlice.convert({
3134 .account = bob,
3135 .amt = 100,
3136 .holderPubKey = mptAlice.getPubKey(bob),
3137 });
3138
3139 mptAlice.convert({
3140 .account = carol,
3141 .amt = 0,
3142 .holderPubKey = mptAlice.getPubKey(carol),
3143 });
3144
3145 // carol cannot delete even if he has encrypted zero amount
3146 mptAlice.authorize({
3147 .account = carol,
3148 .flags = tfMPTUnauthorize,
3149 .err = tecHAS_OBLIGATIONS,
3150 });
3151 }
3152
3153 // can delete mptoken if outstanding confidential balance is zero
3154 {
3155 Env env{*this, features};
3156 Account const alice("alice");
3157 Account const bob("bob");
3158 MPTTester mptAlice(env, alice, {.holders = {bob}});
3159
3160 mptAlice.create({
3161 .ownerCount = 1,
3162 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
3163 });
3164
3165 mptAlice.authorize({
3166 .account = bob,
3167 });
3168 mptAlice.generateKeyPair(alice);
3169
3170 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
3171
3172 mptAlice.generateKeyPair(bob);
3173
3174 mptAlice.convert({
3175 .account = bob,
3176 .amt = 0,
3177 .holderPubKey = mptAlice.getPubKey(bob),
3178 });
3179
3180 mptAlice.authorize({
3181 .account = bob,
3182 .flags = tfMPTUnauthorize,
3183 });
3184 }
3185
3186 // can delete mptoken if issuance has been destroyed and has
3187 // encrypted zero balance
3188 {
3189 Env env{*this, features};
3190 Account const alice("alice");
3191 Account const bob("bob");
3192 MPTTester mptAlice(env, alice, {.holders = {bob}});
3193
3194 mptAlice.create({
3195 .ownerCount = 1,
3196 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
3197 });
3198
3199 mptAlice.authorize({
3200 .account = bob,
3201 });
3202 mptAlice.generateKeyPair(alice);
3203
3204 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
3205
3206 mptAlice.generateKeyPair(bob);
3207
3208 mptAlice.convert({
3209 .account = bob,
3210 .amt = 0,
3211 .holderPubKey = mptAlice.getPubKey(bob),
3212 });
3213
3214 mptAlice.destroy();
3215
3216 mptAlice.authorize({
3217 .account = bob,
3218 .flags = tfMPTUnauthorize,
3219 });
3220 }
3221 // test with convert back and delete
3222 // can delete mptoken if converted back (COA returns to zero)
3223 {
3224 Env env{*this, features};
3225 Account const alice("alice");
3226 Account const bob("bob");
3227 ConfidentialEnv confEnv{
3228 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 100}}};
3229 auto& mptAlice = confEnv.mpt;
3230
3231 mptAlice.convertBack({
3232 .account = bob,
3233 .amt = 100,
3234 });
3235
3236 mptAlice.pay(bob, alice, 100);
3237
3238 // Should be able to delete as Confidential Outstanding amount is 0
3239 mptAlice.authorize({
3240 .account = bob,
3241 .flags = tfMPTUnauthorize,
3242 });
3243 }
3244
3245 // removeEmptyHolding: vault share MPToken with confidential balance
3246 // fields should not be deleted on VaultWithdraw
3247 {
3248 Env env{*this, features | featureSingleAssetVault};
3249 Account const issuer("issuer");
3250 Account const owner("owner");
3251 Account const depositor("depositor");
3252
3253 MPTTester mptt{env, issuer, {.holders = {owner, depositor}}};
3254 mptt.create({
3255 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanClawback,
3256 });
3257 PrettyAsset const asset = mptt.issuanceID();
3258 mptt.authorize({.account = owner});
3259 mptt.authorize({.account = depositor});
3260 env(pay(issuer, depositor, asset(1000)));
3261 env.close();
3262
3263 test::jtx::Vault const vault{env};
3264 auto [tx, vaultKeylet] = vault.create({.owner = owner, .asset = asset});
3265 env(tx);
3266 env.close();
3267
3268 // Get the share MPTID from vault
3269 auto const vaultSle = env.le(vaultKeylet);
3270 BEAST_EXPECT(vaultSle != nullptr);
3271 auto const share = vaultSle->at(sfShareMPTID);
3272
3273 // Depositor deposits into vault
3274 tx = vault.deposit(
3275 {.depositor = depositor, .id = vaultKeylet.key, .amount = asset(100)});
3276 env(tx);
3277 env.close();
3278
3279 // Verify depositor has share tokens
3280 auto shareMpt = env.le(keylet::mptoken(share, depositor.id()));
3281 BEAST_EXPECT(shareMpt != nullptr);
3282
3283 // Inject confidential balance fields on the share MPToken
3284 // to simulate a scenario where vault shares somehow have
3285 // confidential balances
3286 env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal) {
3287 // Set lsfMPTCanHoldConfidentialBalance on the share issuance
3288 // so the invariant allows encrypted fields on the MPToken
3289 auto const issuance =
3291 if (!issuance)
3292 return false;
3293 issuance->setFlag(lsfMPTCanHoldConfidentialBalance);
3294 view.rawReplace(issuance);
3295
3296 auto const k = keylet::mptoken(share, depositor.id());
3297 auto const sle = std::const_pointer_cast<SLE>(view.read(k));
3298 if (!sle)
3299 return false;
3300 // Inject dummy confidential balance fields
3301 Buffer dummyCiphertext(kEcGamalEncryptedTotalLength);
3302 std::memset(dummyCiphertext.data(), 0, kEcGamalEncryptedTotalLength);
3303 dummyCiphertext.data()[0] = kEcCompressedPrefixEvenY;
3305 dummyCiphertext.data()[kEcCiphertextComponentLength - 1] = 0x01;
3306 dummyCiphertext.data()[kEcGamalEncryptedTotalLength - 1] = 0x01;
3307 sle->setFieldVL(sfConfidentialBalanceSpending, dummyCiphertext);
3308 sle->setFieldVL(sfConfidentialBalanceInbox, dummyCiphertext);
3309 sle->setFieldVL(sfIssuerEncryptedBalance, dummyCiphertext);
3310 view.rawReplace(sle);
3311 return true;
3312 });
3313
3314 // Withdraw everything - which should fail because of the confidential balance fields
3315 tx = vault.withdraw(
3316 {.depositor = depositor, .id = vaultKeylet.key, .amount = asset(100)});
3317 env(tx);
3318
3319 // The share MPToken should still exist because the
3320 // withdrawal failed due to confidential balance obligations
3321 shareMpt = env.le(keylet::mptoken(share, depositor.id()));
3322 BEAST_EXPECT(shareMpt != nullptr);
3323 }
3324 }
3325
3326 void
3328 {
3329 testcase("Convert back");
3330 using namespace test::jtx;
3331
3332 // Basic convert back test
3333 {
3334 Env env{*this, features};
3335 Account const alice("alice");
3336 Account const bob("bob");
3337 ConfidentialEnv confEnv{
3338 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 40}}};
3339 auto& mptAlice = confEnv.mpt;
3340
3341 mptAlice.convertBack({
3342 .account = bob,
3343 .amt = 30,
3344 });
3345
3346 mptAlice.convertBack({
3347 .account = bob,
3348 .amt = 10,
3349 });
3350 }
3351
3352 // Edge case: minimum amount (1)
3353 {
3354 Env env{*this, features};
3355 Account const alice("alice");
3356 Account const bob("bob");
3357 ConfidentialEnv confEnv{
3358 env, alice, {{.account = bob, .payAmount = 2, .convertAmount = 2}}};
3359 auto& mptAlice = confEnv.mpt;
3360
3361 mptAlice.convertBack({
3362 .account = bob,
3363 .amt = 1,
3364 });
3365 }
3366
3367 // Edge case: kMaxMpTokenAmount
3368 // Using raw JSON to avoid automatic decryption checks in MPTTester
3369 // which don't work for very large amounts (brute-force decryption is slow)
3370 // TODO: improve this test once there is bounded decryption or optimized decryption for
3371 // large amounts
3372 {
3373 Env env{*this, features};
3374 Account const alice("alice");
3375 Account const bob("bob");
3376 MPTTester mptAlice(env, alice, {.holders = {bob}});
3377
3378 mptAlice.create({
3379 .ownerCount = 1,
3380 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
3381 });
3382
3383 mptAlice.authorize({
3384 .account = bob,
3385 });
3386 mptAlice.pay(alice, bob, kMaxMpTokenAmount);
3387
3388 mptAlice.generateKeyPair(alice);
3389 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
3390
3391 mptAlice.generateKeyPair(bob);
3392
3393 // Convert kMaxMpTokenAmount to confidential using raw JSON
3394 Buffer const convertBlindingFactor = generateBlindingFactor();
3395 auto const convertHolderCiphertext =
3396 mptAlice.encryptAmount(bob, kMaxMpTokenAmount, convertBlindingFactor);
3397 auto const convertIssuerCiphertext =
3398 mptAlice.encryptAmount(alice, kMaxMpTokenAmount, convertBlindingFactor);
3399 auto const convertContextHash =
3400 getConvertContextHash(bob.id(), mptAlice.issuanceID(), env.seq(bob));
3401 auto const schnorrProof = requireOptional(
3402 mptAlice.getSchnorrProof(bob, convertContextHash), "Missing schnorr proof");
3403
3404 {
3405 json::Value jv;
3406 jv[jss::Account] = bob.human();
3407 jv[jss::TransactionType] = jss::ConfidentialMPTConvert;
3408 jv[sfMPTokenIssuanceID] = to_string(mptAlice.issuanceID());
3409 jv[sfMPTAmount.jsonName] = std::to_string(kMaxMpTokenAmount);
3410 jv[sfHolderEncryptionKey.jsonName] =
3411 strHex(requireOptional(mptAlice.getPubKey(bob), "Missing holder public key"));
3412 jv[sfHolderEncryptedAmount.jsonName] = strHex(convertHolderCiphertext);
3413 jv[sfIssuerEncryptedAmount.jsonName] = strHex(convertIssuerCiphertext);
3414 jv[sfBlindingFactor.jsonName] = strHex(convertBlindingFactor);
3415 jv[sfZKProof.jsonName] = strHex(schnorrProof);
3416
3417 env(jv, Ter(tesSUCCESS));
3418 }
3419
3420 // Merge inbox using raw JSON - moves funds from inbox to spending balance
3421 {
3422 json::Value jv;
3423 jv[jss::Account] = bob.human();
3424 jv[jss::TransactionType] = jss::ConfidentialMPTMergeInbox;
3425 jv[sfMPTokenIssuanceID] = to_string(mptAlice.issuanceID());
3426
3427 env(jv, Ter(tesSUCCESS));
3428 }
3429
3430 // ConvertBack kMaxMpTokenAmount - 1 using raw JSON
3431 // After convert + merge, spending balance = kMaxMpTokenAmount
3432 // We convert back kMaxMpTokenAmount - 1 to leave remainder of 1
3433 std::uint64_t const convertBackAmt = kMaxMpTokenAmount - 1;
3434
3435 Buffer const convertBackBlindingFactor = generateBlindingFactor();
3436 auto const convertBackHolderCiphertext =
3437 mptAlice.encryptAmount(bob, convertBackAmt, convertBackBlindingFactor);
3438 auto const convertBackIssuerCiphertext =
3439 mptAlice.encryptAmount(alice, convertBackAmt, convertBackBlindingFactor);
3440
3441 // Get the encrypted spending balance from ledger (no decryption needed)
3442 auto const encryptedSpendingBalance = requireOptional(
3443 mptAlice.getEncryptedBalance(bob, MPTTester::holderEncryptedSpending),
3444 "Missing encrypted spending balance");
3445
3446 // Generate pedersen commitment for the known spending balance
3447 Buffer const pcBlindingFactor = generateBlindingFactor();
3448 Buffer const pedersenCommitment =
3449 mptAlice.getPedersenCommitment(kMaxMpTokenAmount, pcBlindingFactor);
3450
3451 // Generate the proof using known spending balance value
3452 auto const version = mptAlice.getMPTokenVersion(bob);
3453 UInt256 const convertBackContextHash =
3454 getConvertBackContextHash(bob.id(), mptAlice.issuanceID(), env.seq(bob), version);
3455
3456 auto const proof = mptAlice.getConvertBackProof(
3457 bob,
3458 convertBackAmt,
3459 convertBackContextHash,
3460 {
3461 .pedersenCommitment = pedersenCommitment,
3462 .amt = kMaxMpTokenAmount,
3463 .encryptedAmt = encryptedSpendingBalance,
3464 .blindingFactor = pcBlindingFactor,
3465 });
3466 if (!BEAST_EXPECT(proof.has_value()))
3467 return;
3468
3469 {
3470 json::Value jv;
3471 jv[jss::Account] = bob.human();
3472 jv[jss::TransactionType] = jss::ConfidentialMPTConvertBack;
3473 jv[sfMPTokenIssuanceID] = to_string(mptAlice.issuanceID());
3474 jv[sfMPTAmount.jsonName] = std::to_string(convertBackAmt);
3475 jv[sfHolderEncryptedAmount.jsonName] = strHex(convertBackHolderCiphertext);
3476 jv[sfIssuerEncryptedAmount.jsonName] = strHex(convertBackIssuerCiphertext);
3477 jv[sfBlindingFactor.jsonName] = strHex(convertBackBlindingFactor);
3478 jv[sfBalanceCommitment.jsonName] = strHex(pedersenCommitment);
3479 jv[sfZKProof.jsonName] = strHex(requireOptionalRef(proof, "Missing proof"));
3480
3481 env(jv, Ter(tesSUCCESS));
3482 }
3483
3484 // Verify the public balance was restored (minus 1 remaining in confidential)
3485 env.require(MptBalance(mptAlice, bob, convertBackAmt));
3486 }
3487 }
3488
3489 void
3491 {
3492 testcase("Convert back with auditor");
3493 using namespace test::jtx;
3494
3495 Env env{*this, features};
3496 Account const alice("alice");
3497 Account const bob("bob");
3498 Account const auditor("auditor");
3499 ConfidentialEnv confEnv{
3500 env,
3501 alice,
3502 {{.account = bob, .payAmount = 100, .convertAmount = 40}},
3503 tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
3504 auditor};
3505 auto& mptAlice = confEnv.mpt;
3506
3507 mptAlice.convertBack({
3508 .account = bob,
3509 .amt = 30,
3510 });
3511 }
3512
3513 void
3515 {
3516 testcase("Convert back preflight");
3517 using namespace test::jtx;
3518
3519 {
3520 Env env{*this, features - featureConfidentialTransfer};
3521 Account const alice("alice");
3522 Account const bob("bob");
3523 MPTTester mptAlice(env, alice, {.holders = {bob}});
3524
3525 mptAlice.create({
3526 .ownerCount = 1,
3527 .flags = tfMPTCanTransfer | tfMPTCanLock,
3528 });
3529
3530 mptAlice.authorize({
3531 .account = bob,
3532 });
3533 mptAlice.pay(alice, bob, 100);
3534
3535 mptAlice.generateKeyPair(alice);
3536 mptAlice.generateKeyPair(bob);
3537
3538 mptAlice.convertBack({
3539 .account = bob,
3540 .amt = 30,
3541 .err = temDISABLED,
3542 });
3543 }
3544
3545 {
3546 Env env{*this, features};
3547 Account const alice("alice");
3548 Account const bob("bob");
3549 ConfidentialEnv confEnv{
3550 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 40}}};
3551 auto& mptAlice = confEnv.mpt;
3552
3553 mptAlice.convertBack({
3554 .account = alice,
3555 .amt = 30,
3556 .err = temMALFORMED,
3557 });
3558
3559 mptAlice.convertBack({
3560 .account = bob,
3561 .amt = 0,
3562 .err = temBAD_AMOUNT,
3563 });
3564
3565 mptAlice.convertBack({
3566 .account = bob,
3567 .amt = kMaxMpTokenAmount + 1,
3568 .err = temBAD_AMOUNT,
3569 });
3570
3571 // Balance commitment has correct length but invalid EC point data
3572 mptAlice.convertBack({
3573 .account = bob,
3574 .amt = 30,
3575 .pedersenCommitment = gMakeZeroBuffer(kEcPedersenCommitmentLength),
3576 .err = temMALFORMED,
3577 });
3578
3579 mptAlice.convertBack({
3580 .account = bob,
3581 .amt = 30,
3582 .holderEncryptedAmt = Buffer{},
3583 .err = temBAD_CIPHERTEXT,
3584 });
3585
3586 mptAlice.convertBack({
3587 .account = bob,
3588 .amt = 30,
3589 .issuerEncryptedAmt = Buffer{},
3590 .err = temBAD_CIPHERTEXT,
3591 });
3592
3593 mptAlice.convertBack({
3594 .account = bob,
3595 .amt = 30,
3596 .holderEncryptedAmt = getBadCiphertext(),
3597 .err = temBAD_CIPHERTEXT,
3598 });
3599
3600 mptAlice.convertBack({
3601 .account = bob,
3602 .amt = 30,
3603 .issuerEncryptedAmt = getBadCiphertext(),
3604 .err = temBAD_CIPHERTEXT,
3605 });
3606
3607 mptAlice.convertBack({
3608 .account = bob,
3609 .amt = 30,
3610 .auditorEncryptedAmt = gMakeZeroBuffer(10),
3611 .err = temBAD_CIPHERTEXT,
3612 });
3613
3614 mptAlice.convertBack({
3615 .account = bob,
3616 .amt = 30,
3617 .auditorEncryptedAmt = getBadCiphertext(),
3618 .err = temBAD_CIPHERTEXT,
3619 });
3620
3621 // invalid proof length
3622 mptAlice.convertBack({
3623 .account = bob,
3624 .amt = 30,
3625 .proof = Buffer{},
3626 .err = temMALFORMED,
3627 });
3628
3629 mptAlice.convertBack({
3630 .account = bob,
3631 .amt = 30,
3632 .proof = gMakeZeroBuffer(100),
3633 .err = temMALFORMED,
3634 });
3635 }
3636 }
3637
3638 void
3640 {
3641 testcase("Convert back preclaim");
3642 using namespace test::jtx;
3643
3644 // issuance does not exist
3645 {
3646 Env env{*this, features};
3647 Account const alice("alice");
3648 Account const bob("bob");
3649 MPTTester mptAlice(env, alice, {.holders = {bob}});
3650
3651 mptAlice.create({
3652 .ownerCount = 1,
3653 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
3654 });
3655
3656 mptAlice.authorize({
3657 .account = bob,
3658 });
3659 mptAlice.generateKeyPair(alice);
3660
3661 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
3662
3663 mptAlice.destroy();
3664 mptAlice.generateKeyPair(bob);
3665
3666 mptAlice.convertBack({
3667 .account = bob,
3668 .amt = 30,
3669 .err = tecOBJECT_NOT_FOUND,
3670 });
3671 }
3672
3673 // tfMPTCanHoldConfidentialBalance is not set on issuance
3674 {
3675 Env env{*this, features};
3676 Account const alice("alice");
3677 Account const bob("bob");
3678 MPTTester mptAlice(env, alice, {.holders = {bob}});
3679
3680 mptAlice.create({
3681 .ownerCount = 1,
3682 .flags = tfMPTCanTransfer | tfMPTCanLock,
3683 });
3684
3685 mptAlice.authorize({
3686 .account = bob,
3687 });
3688 mptAlice.pay(alice, bob, 100);
3689
3690 mptAlice.generateKeyPair(alice);
3691 mptAlice.generateKeyPair(bob);
3692
3693 mptAlice.convertBack({
3694 .account = bob,
3695 .amt = 30,
3696 .err = tecNO_PERMISSION,
3697 });
3698 }
3699
3700 // no mptoken
3701 {
3702 Env env{*this, features};
3703 Account const alice("alice");
3704 Account const bob("bob");
3705 MPTTester mptAlice(env, alice, {.holders = {bob}});
3706
3707 mptAlice.create({
3708 .ownerCount = 1,
3709 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
3710 });
3711
3712 mptAlice.generateKeyPair(alice);
3713 mptAlice.generateKeyPair(bob);
3714
3715 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
3716
3717 mptAlice.convertBack({
3718 .account = bob,
3719 .amt = 30,
3720 .err = tecOBJECT_NOT_FOUND,
3721 });
3722 }
3723
3724 // mptoken exists but lacks confidential fields
3725 {
3726 Env env{*this, features};
3727 Account const alice("alice");
3728 Account const bob("bob");
3729 MPTTester mptAlice(env, alice, {.holders = {bob}});
3730
3731 mptAlice.create({
3732 .ownerCount = 1,
3733 .flags = tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance,
3734 });
3735
3736 mptAlice.authorize({
3737 .account = bob,
3738 });
3739
3740 mptAlice.pay(alice, bob, 100);
3741 mptAlice.generateKeyPair(alice);
3742 mptAlice.generateKeyPair(bob);
3743 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
3744
3745 // Bob's MPToken lacks the confidential fields
3746 auto const sleBobMpt = env.le(keylet::mptoken(mptAlice.issuanceID(), bob.id()));
3747 BEAST_EXPECT(sleBobMpt);
3748 BEAST_EXPECT(!sleBobMpt->isFieldPresent(sfHolderEncryptionKey));
3749 BEAST_EXPECT(!sleBobMpt->isFieldPresent(sfConfidentialBalanceSpending));
3750 BEAST_EXPECT(!sleBobMpt->isFieldPresent(sfIssuerEncryptedBalance));
3751
3752 mptAlice.convertBack({
3753 .account = bob,
3754 .amt = 30,
3755 .err = tecNO_PERMISSION,
3756 });
3757 }
3758
3759 // bob tries to convert back more than COA
3760 {
3761 Env env{*this, features};
3762 Account const alice("alice");
3763 Account const bob("bob");
3764 Account const carol("carol");
3765 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
3766
3767 mptAlice.create({
3768 .ownerCount = 1,
3769 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
3770 });
3771
3772 mptAlice.authorize({
3773 .account = bob,
3774 });
3775 mptAlice.authorize({
3776 .account = carol,
3777 });
3778 mptAlice.pay(alice, bob, 100);
3779 mptAlice.pay(alice, carol, 100);
3780
3781 mptAlice.generateKeyPair(alice);
3782
3783 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
3784
3785 mptAlice.generateKeyPair(bob);
3786 mptAlice.generateKeyPair(carol);
3787
3788 mptAlice.convert({
3789 .account = bob,
3790 .amt = 40,
3791 .holderPubKey = mptAlice.getPubKey(bob),
3792 });
3793
3794 mptAlice.mergeInbox({
3795 .account = bob,
3796 });
3797
3798 mptAlice.convert({
3799 .account = carol,
3800 .amt = 40,
3801 .holderPubKey = mptAlice.getPubKey(carol),
3802 });
3803
3804 mptAlice.convertBack({
3805 .account = bob,
3806 .amt = 300,
3807 .err = tecINSUFFICIENT_FUNDS,
3808 });
3809 }
3810
3811 // cannot convert if locked or unauth
3812 {
3813 Env env{*this, features};
3814 Account const alice("alice");
3815 Account const bob("bob");
3816 MPTTester mptAlice(env, alice, {.holders = {bob}});
3817
3818 mptAlice.create({
3819 .ownerCount = 1,
3820 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTRequireAuth |
3821 tfMPTCanHoldConfidentialBalance,
3822 });
3823
3824 mptAlice.authorize({
3825 .account = bob,
3826 });
3827 mptAlice.authorize({
3828 .account = alice,
3829 .holder = bob,
3830 });
3831 mptAlice.pay(alice, bob, 100);
3832
3833 mptAlice.generateKeyPair(alice);
3834
3835 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
3836
3837 mptAlice.generateKeyPair(bob);
3838
3839 mptAlice.convert({
3840 .account = bob,
3841 .amt = 40,
3842 .holderPubKey = mptAlice.getPubKey(bob),
3843 });
3844
3845 mptAlice.mergeInbox({
3846 .account = bob,
3847 });
3848
3849 mptAlice.set({
3850 .account = alice,
3851 .holder = bob,
3852 .flags = tfMPTLock,
3853 });
3854
3855 mptAlice.convertBack({
3856 .account = bob,
3857 .amt = 10,
3858 .err = tecLOCKED,
3859 });
3860
3861 mptAlice.set({
3862 .account = alice,
3863 .holder = bob,
3864 .flags = tfMPTUnlock,
3865 });
3866
3867 mptAlice.convertBack({
3868 .account = bob,
3869 .amt = 10,
3870 });
3871
3872 mptAlice.authorize({
3873 .account = alice,
3874 .holder = bob,
3875 .flags = tfMPTUnauthorize,
3876 });
3877
3878 mptAlice.convertBack({
3879 .account = bob,
3880 .amt = 10,
3881 .err = tecNO_AUTH,
3882 });
3883
3884 mptAlice.authorize({
3885 .account = alice,
3886 .holder = bob,
3887 });
3888
3889 mptAlice.convertBack({
3890 .account = bob,
3891 .amt = 10,
3892 });
3893 }
3894
3895 // Verification of holder and issuer ciphertexts during convertBack
3896 {
3897 Env env{*this, features};
3898 Account const alice("alice");
3899 Account const bob("bob");
3900 ConfidentialEnv confEnv{
3901 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 50}}};
3902 auto& mptAlice = confEnv.mpt;
3903
3904 // Holder encrypted amount is valid format but mathematically incorrect for this
3905 // convertBack
3906 mptAlice.convertBack({
3907 .account = bob,
3908 .amt = 10,
3909 .holderEncryptedAmt = getTrivialCiphertext(),
3910 .err = tecBAD_PROOF,
3911 });
3912
3913 // Issuer encrypted amount is valid format but mathematically incorrect for this
3914 // convertBack
3915 mptAlice.convertBack({
3916 .account = bob,
3917 .amt = 10,
3918 .issuerEncryptedAmt = getTrivialCiphertext(),
3919 .err = tecBAD_PROOF,
3920 });
3921 }
3922
3923 // Alice has NOT set an auditor key, but Bob provides
3924 // auditorEncryptedAmt
3925 {
3926 Env env{*this, features};
3927 Account const alice("alice");
3928 Account const bob("bob");
3929 ConfidentialEnv confEnv{
3930 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 50}}};
3931 auto& mptAlice = confEnv.mpt;
3932
3933 mptAlice.convertBack({
3934 .account = bob,
3935 .amt = 10,
3936 // Provide valid ciphertext to pass preflight
3937 .auditorEncryptedAmt = getTrivialCiphertext(),
3938 .err = tecNO_PERMISSION,
3939 });
3940 }
3941
3942 // we set the auditor key, but convertBack omits auditorEncryptedAmt
3943 {
3944 Env env{*this, features};
3945 Account const alice("alice");
3946 Account const bob("bob");
3947 Account const auditor("auditor");
3948 ConfidentialEnv confEnv{
3949 env,
3950 alice,
3951 {{.account = bob, .payAmount = 100, .convertAmount = 50}},
3952 tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
3953 auditor};
3954 auto& mptAlice = confEnv.mpt;
3955
3956 // ConvertBack WITHOUT auditorEncryptedAmt
3957 mptAlice.convertBack({
3958 .account = bob,
3959 .amt = 10,
3960 .fillAuditorEncryptedAmt = false,
3961 .err = tecNO_PERMISSION,
3962 });
3963
3964 // ConvertBack where auditor ciphertext mathematically
3965 // correct, but contains invalid data (mismatching amount).
3966 mptAlice.convertBack({
3967 .account = bob,
3968 .amt = 10,
3969 .auditorEncryptedAmt = getTrivialCiphertext(),
3970 .err = tecBAD_PROOF,
3971 });
3972 }
3973 }
3974
3975 void
3977 {
3978 testcase("test ConfidentialMPTClawback");
3979 using namespace test::jtx;
3980
3981 Env env{*this, features};
3982 Account const alice("alice");
3983 Account const bob("bob");
3984 Account const carol("carol");
3985 Account const dave("dave");
3986 MPTTester mptAlice(env, alice, {.holders = {bob, carol, dave}});
3987
3988 mptAlice.create({
3989 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanClawback |
3990 tfMPTCanHoldConfidentialBalance,
3991 });
3992 mptAlice.authorize({
3993 .account = bob,
3994 });
3995 mptAlice.pay(alice, bob, 100);
3996 mptAlice.authorize({
3997 .account = carol,
3998 });
3999 mptAlice.pay(alice, carol, 200);
4000 mptAlice.authorize({
4001 .account = dave,
4002 });
4003 mptAlice.pay(alice, dave, 300);
4004
4005 mptAlice.generateKeyPair(alice);
4006 mptAlice.generateKeyPair(bob);
4007 mptAlice.generateKeyPair(carol);
4008 mptAlice.generateKeyPair(dave);
4009 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
4010
4011 // setup bob.
4012 // after setup, bob's spending balance is 60, inbox balance is 0.
4013 {
4014 // bob converts 60 to confidential
4015 mptAlice.convert({.account = bob, .amt = 60, .holderPubKey = mptAlice.getPubKey(bob)});
4016
4017 // bob merge inbox
4018 mptAlice.mergeInbox({
4019 .account = bob,
4020 });
4021 }
4022
4023 // setup carol.
4024 // after setup, carol's spending balance is 120, inbox balance is 0.
4025 {
4026 // carol converts 120 to confidential
4027 mptAlice.convert(
4028 {.account = carol, .amt = 120, .holderPubKey = mptAlice.getPubKey(carol)});
4029
4030 // carol merge inbox
4031 mptAlice.mergeInbox({
4032 .account = carol,
4033 });
4034 }
4035
4036 // setup dave.
4037 // dave will not merge inbox.
4038 // after setup, dave's inbox balance is 200, spending balance is 0.
4039 mptAlice.convert({.account = dave, .amt = 200, .holderPubKey = mptAlice.getPubKey(dave)});
4040
4041 // setup: carol confidential send 50 to bob.
4042 // after send, bob's inbox balance is 50, spending balance
4043 // remains 60. carol's inbox balance remains 0, spending balance
4044 // drops to 70.
4045 mptAlice.send({
4046 .account = carol,
4047 .dest = bob,
4048 .amt = 50,
4049 });
4050
4051 // Confidential clawback is burn/reduce outstanding amount.
4052 // The holder public balance is unchanged, and OA/COA decrease.
4053 auto const preBobPublicBalance = mptAlice.getBalance(bob);
4054 auto const preOutstandingAmount = mptAlice.getIssuanceOutstandingBalance();
4055 auto const preConfidentialOutstandingAmount = mptAlice.getIssuanceConfidentialBalance();
4056 BEAST_EXPECT(!env.le(keylet::mptoken(mptAlice.issuanceID(), alice.id())));
4057
4058 // alice clawback all confidential balance from bob, 110 in total.
4059 // bob has balance in both inbox and spending. These balances should
4060 // become zero after clawback, which is verified in the
4061 // confidentialClaw function.
4062 mptAlice.confidentialClaw({
4063 .account = alice,
4064 .holder = bob,
4065 .amt = 110,
4066 });
4067 BEAST_EXPECT(mptAlice.getBalance(bob) == preBobPublicBalance);
4068 auto const postOutstandingAmount = mptAlice.getIssuanceOutstandingBalance();
4069 BEAST_EXPECT(
4070 preOutstandingAmount && postOutstandingAmount &&
4071 *postOutstandingAmount == *preOutstandingAmount - 110);
4072 BEAST_EXPECT(
4073 mptAlice.getIssuanceConfidentialBalance() == preConfidentialOutstandingAmount - 110);
4074 BEAST_EXPECT(!env.le(keylet::mptoken(mptAlice.issuanceID(), alice.id())));
4075
4076 // alice clawback all confidential balance from carol, which is 70.
4077 // carol only has balance in spending.
4078 mptAlice.confidentialClaw({
4079 .account = alice,
4080 .holder = carol,
4081 .amt = 70,
4082 });
4083
4084 // alice clawback all confidential balance from dave, which is 200.
4085 // dave only has balance in inbox.
4086 mptAlice.confidentialClaw({
4087 .account = alice,
4088 .holder = dave,
4089 .amt = 200,
4090 });
4091 }
4092
4093 void
4095 {
4096 testcase("test ConfidentialMPTClawback with auditor");
4097 using namespace test::jtx;
4098
4099 Env env{*this, features};
4100 Account const alice("alice");
4101 Account const bob("bob");
4102 Account const carol("carol");
4103 Account const dave("dave");
4104 Account const auditor("auditor");
4105 MPTTester mptAlice(
4106 env,
4107 alice,
4108 {
4109 .holders = {bob, carol, dave},
4110 .auditor = auditor,
4111 });
4112
4113 mptAlice.create({
4114 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanClawback |
4115 tfMPTCanHoldConfidentialBalance,
4116 });
4117 mptAlice.authorize({
4118 .account = bob,
4119 });
4120 mptAlice.pay(alice, bob, 100);
4121 mptAlice.authorize({
4122 .account = carol,
4123 });
4124 mptAlice.pay(alice, carol, 200);
4125 mptAlice.authorize({
4126 .account = dave,
4127 });
4128 mptAlice.pay(alice, dave, 300);
4129
4130 mptAlice.generateKeyPair(alice);
4131 mptAlice.generateKeyPair(bob);
4132 mptAlice.generateKeyPair(carol);
4133 mptAlice.generateKeyPair(dave);
4134 mptAlice.generateKeyPair(auditor);
4135 mptAlice.set({
4136 .account = alice,
4137 .issuerPubKey = mptAlice.getPubKey(alice),
4138 .auditorPubKey = mptAlice.getPubKey(auditor),
4139 });
4140
4141 // setup bob.
4142 // after setup, bob's spending balance is 60, inbox balance is 0.
4143 {
4144 // bob converts 60 to confidential
4145 mptAlice.convert({.account = bob, .amt = 60, .holderPubKey = mptAlice.getPubKey(bob)});
4146
4147 // bob merge inbox
4148 mptAlice.mergeInbox({
4149 .account = bob,
4150 });
4151 }
4152
4153 // setup carol.
4154 // after setup, carol's spending balance is 120, inbox balance is 0.
4155 {
4156 // carol converts 120 to confidential
4157 mptAlice.convert(
4158 {.account = carol, .amt = 120, .holderPubKey = mptAlice.getPubKey(carol)});
4159
4160 // carol merge inbox
4161 mptAlice.mergeInbox({
4162 .account = carol,
4163 });
4164 }
4165
4166 // setup dave.
4167 // dave will not merge inbox.
4168 // after setup, dave's inbox balance is 200, spending balance is 0.
4169 mptAlice.convert({.account = dave, .amt = 200, .holderPubKey = mptAlice.getPubKey(dave)});
4170
4171 // setup: carol confidential send 50 to bob.
4172 // after send, bob's inbox balance is 50, spending balance
4173 // remains 60. carol's inbox balance remains 0, spending balance
4174 // drops to 70.
4175 mptAlice.send({
4176 .account = carol,
4177 .dest = bob,
4178 .amt = 50,
4179 });
4180
4181 // alice clawback all confidential balance from bob, 110 in total.
4182 // bob has balance in both inbox and spending. These balances should
4183 // become zero after clawback, which is verified in the
4184 // confidentialClaw function.
4185 mptAlice.confidentialClaw({
4186 .account = alice,
4187 .holder = bob,
4188 .amt = 110,
4189 });
4190
4191 // alice clawback all confidential balance from carol, which is 70.
4192 // carol only has balance in spending.
4193 mptAlice.confidentialClaw({
4194 .account = alice,
4195 .holder = carol,
4196 .amt = 70,
4197 });
4198
4199 // alice clawback all confidential balance from dave, which is 200.
4200 // dave only has balance in inbox.
4201 mptAlice.confidentialClaw({
4202 .account = alice,
4203 .holder = dave,
4204 .amt = 200,
4205 });
4206 }
4207
4208 void
4210 {
4211 testcase("ConfidentialMPTClawback context binding");
4212 using namespace test::jtx;
4213
4214 auto const runBadProof = [&](auto makeContextHash) {
4215 Env env{*this, features};
4216 Account const alice("alice");
4217 Account const bob("bob");
4218 Account const carol("carol");
4219 ConfidentialEnv confEnv{
4220 env,
4221 alice,
4222 {{.account = bob, .payAmount = 100, .convertAmount = 60}},
4223 tfMPTCanTransfer | tfMPTCanLock | tfMPTCanClawback |
4224 tfMPTCanHoldConfidentialBalance};
4225 auto& mptAlice = confEnv.mpt;
4226
4227 auto const privKey = mptAlice.getPrivKey(alice);
4228 if (!BEAST_EXPECT(privKey.has_value()))
4229 return;
4230
4231 auto const proof = mptAlice.getClawbackProof(
4232 bob,
4233 60,
4234 requireOptionalRef(privKey, "Missing private key"),
4235 makeContextHash(env, mptAlice, alice, bob, carol));
4236 if (!BEAST_EXPECT(proof.has_value()))
4237 return;
4238
4239 mptAlice.confidentialClaw({
4240 .account = alice,
4241 .holder = bob,
4242 .amt = 60,
4243 .proof = strHex(requireOptional(proof, "Missing proof")),
4244 .err = tecBAD_PROOF,
4245 });
4246 };
4247
4248 // Wrong account (issuer) in the proof context.
4249 runBadProof([&](Env& env,
4250 MPTTester const& mpt,
4251 Account const& alice,
4252 Account const& bob,
4253 Account const& carol) {
4254 return getClawbackContextHash(carol.id(), mpt.issuanceID(), env.seq(alice), bob.id());
4255 });
4256
4257 // Wrong issuance ID in the proof context.
4258 runBadProof([&](Env& env,
4259 MPTTester const&,
4260 Account const& alice,
4261 Account const& bob,
4262 Account const&) {
4264 alice.id(), makeMptID(env.seq(alice) + 100, alice), env.seq(alice), bob.id());
4265 });
4266
4267 // Wrong transaction sequence in the proof context.
4268 runBadProof([&](Env& env,
4269 MPTTester const& mpt,
4270 Account const& alice,
4271 Account const& bob,
4272 Account const&) {
4274 alice.id(), mpt.issuanceID(), env.seq(alice) + 1, bob.id());
4275 });
4276
4277 // Wrong holder in the proof context.
4278 runBadProof([&](Env& env,
4279 MPTTester const& mpt,
4280 Account const& alice,
4281 Account const&,
4282 Account const& carol) {
4283 return getClawbackContextHash(alice.id(), mpt.issuanceID(), env.seq(alice), carol.id());
4284 });
4285 }
4286
4287 // Bob creates the AMM, but Bob is not the MPT holder checked below.
4288 // The AMM has its own pseudo-account (`ammHolder`) that can hold the
4289 // public MPT pool balance. That pseudo-account cannot normally
4290 // initialize confidential state because the confidential txn's must be
4291 // signed by sfAccount, and the AMM pseudo-account has no signing key.
4292 // So this is a construction/impossibility test: public AMM MPT state exists
4293 // but the corresponding confidential AMM clawback flow is not normally reachable.
4294 void
4296 {
4297 testcase("test ConfidentialMPTClawback Preflight");
4298 using namespace test::jtx;
4299
4300 // test feature disabled
4301 {
4302 Env env{*this, features - featureConfidentialTransfer};
4303 Account const alice("alice");
4304 Account const bob("bob");
4305 MPTTester mptAlice(env, alice, {.holders = {bob}});
4306
4307 mptAlice.create();
4308 mptAlice.authorize({
4309 .account = bob,
4310 });
4311
4312 mptAlice.confidentialClaw({
4313 .account = alice,
4314 .holder = bob,
4315 .amt = 10,
4316 .proof = "123",
4317 .err = temDISABLED,
4318 });
4319 }
4320
4321 // test malformed
4322 {
4323 // set up
4324 Env env{*this, features};
4325 Account const alice("alice");
4326 Account const bob("bob");
4327 Account const carol("carol");
4328 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
4329
4330 mptAlice.create({
4331 .ownerCount = 1,
4332 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
4333 });
4334
4335 mptAlice.authorize({
4336 .account = bob,
4337 });
4338 mptAlice.authorize({
4339 .account = carol,
4340 });
4341 mptAlice.generateKeyPair(alice);
4342 mptAlice.generateKeyPair(bob);
4343 mptAlice.generateKeyPair(carol);
4344 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
4345 mptAlice.pay(alice, bob, 100);
4346 mptAlice.pay(alice, carol, 50);
4347
4348 // only issuer can clawback
4349 mptAlice.confidentialClaw({
4350 .account = carol,
4351 .holder = bob,
4352 .amt = 10,
4353 .err = temMALFORMED,
4354 });
4355
4356 // invalid issuance ID, whose issuer is not alice
4357 {
4358 json::Value jv;
4359 jv[jss::Account] = alice.human();
4360 jv[sfHolder] = bob.human();
4361 jv[jss::TransactionType] = jss::ConfidentialMPTClawback;
4362 jv[sfMPTAmount] = std::to_string(10);
4363 jv[sfZKProof] = "123";
4364
4365 // wrong issuance ID
4366 jv[sfMPTokenIssuanceID] = "00000004AE123A8556F3CF91154711376AFB0F894F832B3E";
4367
4368 env(jv, Ter(temMALFORMED));
4369 }
4370
4371 // issuer cannot clawback from self
4372 mptAlice.confidentialClaw({
4373 .account = alice,
4374 .holder = alice,
4375 .amt = 10,
4376 .err = temMALFORMED,
4377 });
4378
4379 // invalid amount
4380 mptAlice.confidentialClaw({
4381 .account = alice,
4382 .holder = bob,
4383 .amt = 0,
4384 .err = temBAD_AMOUNT,
4385 });
4386
4387 // invalid proof length
4388 mptAlice.confidentialClaw({
4389 .account = alice,
4390 .holder = bob,
4391 .amt = 10,
4392 .proof = "123",
4393 .err = temMALFORMED,
4394 });
4395 }
4396 }
4397
4398 void
4400 {
4401 testcase("Clawback Preclaim Errors");
4402 using namespace test::jtx;
4403
4404 {
4405 // set up, alice is the issuer, bob and carol are authorized
4406 // holders. dave is not authorized. bob has confidential
4407 // balance, carol does not.
4408 Env env{*this, features};
4409 Account const alice("alice");
4410 Account const bob("bob");
4411 Account const carol("carol");
4412 Account const dave("dave");
4413 MPTTester mptAlice(env, alice, {.holders = {bob, carol, dave}});
4414
4415 mptAlice.create({
4416 .flags = tfMPTCanTransfer | tfMPTCanClawback | tfMPTRequireAuth |
4417 tfMPTCanHoldConfidentialBalance,
4418 });
4419 mptAlice.authorize({
4420 .account = bob,
4421 });
4422 mptAlice.authorize({
4423 .account = alice,
4424 .holder = bob,
4425 });
4426 mptAlice.authorize({
4427 .account = carol,
4428 });
4429 mptAlice.authorize({
4430 .account = alice,
4431 .holder = carol,
4432 });
4433
4434 mptAlice.pay(alice, bob, 100);
4435 mptAlice.pay(alice, carol, 50);
4436 mptAlice.generateKeyPair(alice);
4437 mptAlice.generateKeyPair(bob);
4438 mptAlice.generateKeyPair(carol);
4439 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
4440
4441 mptAlice.convert({
4442 .account = bob,
4443 .amt = 60,
4444 .holderPubKey = mptAlice.getPubKey(bob),
4445 });
4446 mptAlice.mergeInbox({
4447 .account = bob,
4448 });
4449
4450 // holder does not exist
4451 {
4452 Account const unknown("unknown");
4453 mptAlice.confidentialClaw({
4454 .account = alice,
4455 .holder = unknown,
4456 .amt = 10,
4457 .err = tecNO_TARGET,
4458 });
4459 }
4460
4461 // dave does not hold mpt at all, no MPT object
4462 {
4463 mptAlice.confidentialClaw({
4464 .account = alice,
4465 .holder = dave,
4466 .amt = 10,
4467 .err = tecOBJECT_NOT_FOUND,
4468 });
4469 }
4470
4471 // carol has no confidential balance
4472 {
4473 mptAlice.confidentialClaw({
4474 .account = alice,
4475 .holder = carol,
4476 .amt = 10,
4477 .err = tecNO_PERMISSION,
4478 });
4479 }
4480 }
4481
4482 // lsfMPTCanClawback not set
4483 {
4484 Env env{*this, features};
4485 Account const alice("alice");
4486 Account const bob("bob");
4487 MPTTester mptAlice(env, alice, {.holders = {bob}});
4488
4489 mptAlice.create({
4490 .flags = tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance,
4491 });
4492 mptAlice.authorize({
4493 .account = bob,
4494 });
4495 mptAlice.generateKeyPair(alice);
4496 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
4497
4498 mptAlice.confidentialClaw({
4499 .account = alice,
4500 .holder = bob,
4501 .amt = 10,
4502 .err = tecNO_PERMISSION,
4503 });
4504 }
4505
4506 // no issuer key
4507 {
4508 Env env{*this, features};
4509 Account const alice("alice");
4510 Account const bob("bob");
4511 MPTTester mptAlice(env, alice, {.holders = {bob}});
4512 mptAlice.create({
4513 .flags = tfMPTCanClawback | tfMPTCanHoldConfidentialBalance,
4514 });
4515 mptAlice.authorize({
4516 .account = bob,
4517 });
4518 mptAlice.generateKeyPair(alice);
4519
4520 mptAlice.confidentialClaw({
4521 .account = alice,
4522 .holder = bob,
4523 .amt = 10,
4524 .err = tecNO_PERMISSION,
4525 });
4526 }
4527
4528 // issuance not found
4529 {
4530 Env env{*this, features};
4531 Account const alice("alice");
4532 Account const bob("bob");
4533 MPTTester mptAlice(env, alice, {.holders = {bob}});
4534 mptAlice.create({
4535 .flags = tfMPTCanClawback | tfMPTCanHoldConfidentialBalance,
4536 });
4537 mptAlice.authorize({
4538 .account = bob,
4539 });
4540 mptAlice.generateKeyPair(alice);
4541 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
4542
4543 // destroy the issuance
4544 mptAlice.destroy();
4545
4546 json::Value jv;
4547 jv[jss::Account] = alice.human();
4548 jv[sfHolder] = bob.human();
4549 jv[jss::TransactionType] = jss::ConfidentialMPTClawback;
4550 jv[sfMPTAmount] = std::to_string(10);
4551 std::string const dummyProof(kEcClawbackProofLength * 2, '0');
4552 jv[sfZKProof] = dummyProof;
4553 jv[sfMPTokenIssuanceID] = to_string(mptAlice.issuanceID());
4554
4555 env(jv, Ter(tecOBJECT_NOT_FOUND));
4556 }
4557
4558 // After setup, bob has confidential balance 60 in spending.
4559 std::uint32_t const setupFlags = tfMPTCanTransfer | tfMPTCanClawback | tfMPTRequireAuth |
4560 tfMPTCanLock | tfMPTCanHoldConfidentialBalance;
4561 std::string const dummyClawbackProof(kEcClawbackProofLength * 2, '0');
4562
4563 auto const removeMPTokenField =
4564 [&](Env& env, MPTTester const& mpt, Account const& holder, SField const& field) {
4565 BEAST_EXPECT(env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal) {
4566 auto const sle = std::const_pointer_cast<SLE>(
4567 view.read(keylet::mptoken(mpt.issuanceID(), holder.id())));
4568 if (!sle)
4569 return false;
4570
4571 sle->makeFieldAbsent(field);
4572 view.rawReplace(sle);
4573 return true;
4574 }));
4575 };
4576
4577 // After global COA is drained to zero, a further confidential clawback
4578 // fails because the amount exceeds the remaining confidential
4579 // outstanding amount.
4580 {
4581 Env env{*this, features};
4582 Account const alice("alice");
4583 Account const bob("bob");
4584 ConfidentialEnv confEnv{
4585 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 60}}, setupFlags};
4586 auto& mptAlice = confEnv.mpt;
4587
4588 mptAlice.confidentialClaw({
4589 .account = alice,
4590 .holder = bob,
4591 .amt = 60,
4592 });
4593
4594 mptAlice.confidentialClaw({
4595 .account = alice,
4596 .holder = bob,
4597 .amt = 1,
4598 .proof = dummyClawbackProof,
4599 .err = tecINSUFFICIENT_FUNDS,
4600 });
4601 }
4602
4603 // Missing issuer encrypted balance should fail before proof
4604 // verification.
4605 {
4606 Env env{*this, features};
4607 Account const alice("alice");
4608 Account const bob("bob");
4609 ConfidentialEnv confEnv{
4610 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 60}}, setupFlags};
4611 auto& mptAlice = confEnv.mpt;
4612
4613 removeMPTokenField(env, mptAlice, bob, sfIssuerEncryptedBalance);
4614 mptAlice.confidentialClaw({
4615 .account = alice,
4616 .holder = bob,
4617 .amt = 60,
4618 .proof = dummyClawbackProof,
4619 .err = tecNO_PERMISSION,
4620 });
4621 }
4622
4623 // Missing holder encryption key should fail before proof verification.
4624 {
4625 Env env{*this, features};
4626 Account const alice("alice");
4627 Account const bob("bob");
4628 ConfidentialEnv confEnv{
4629 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 60}}, setupFlags};
4630 auto& mptAlice = confEnv.mpt;
4631
4632 removeMPTokenField(env, mptAlice, bob, sfHolderEncryptionKey);
4633 mptAlice.confidentialClaw({
4634 .account = alice,
4635 .holder = bob,
4636 .amt = 60,
4637 .proof = dummyClawbackProof,
4638 .err = tecNO_PERMISSION,
4639 });
4640 }
4641
4642 // lock should not block clawback. lock bob individually
4643 {
4644 Env env{*this, features};
4645 Account const alice("alice");
4646 Account const bob("bob");
4647 ConfidentialEnv confEnv{
4648 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 60}}, setupFlags};
4649 auto& mptAlice = confEnv.mpt;
4650 mptAlice.set({
4651 .account = alice,
4652 .holder = bob,
4653 .flags = tfMPTLock,
4654 });
4655
4656 // clawback should still work
4657 mptAlice.confidentialClaw({
4658 .account = alice,
4659 .holder = bob,
4660 .amt = 60,
4661 });
4662 }
4663
4664 // lock globally
4665 {
4666 Env env{*this, features};
4667 Account const alice("alice");
4668 Account const bob("bob");
4669 ConfidentialEnv confEnv{
4670 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 60}}, setupFlags};
4671 auto& mptAlice = confEnv.mpt;
4672 mptAlice.set({
4673 .account = alice,
4674 .flags = tfMPTLock,
4675 });
4676
4677 // clawback should still work
4678 mptAlice.confidentialClaw({
4679 .account = alice,
4680 .holder = bob,
4681 .amt = 60,
4682 });
4683 }
4684
4685 // unauthorize should not block clawback
4686 {
4687 Env env{*this, features};
4688 Account const alice("alice");
4689 Account const bob("bob");
4690 ConfidentialEnv confEnv{
4691 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 60}}, setupFlags};
4692 auto& mptAlice = confEnv.mpt;
4693
4694 // unauthorize bob
4695 mptAlice.authorize({
4696 .account = alice,
4697 .holder = bob,
4698 .flags = tfMPTUnauthorize,
4699 });
4700 // clawback should still work
4701 mptAlice.confidentialClaw({
4702 .account = alice,
4703 .holder = bob,
4704 .amt = 60,
4705 });
4706 }
4707
4708 // insufficient funds, clawback amount exceeding confidential
4709 // outstanding amount
4710 {
4711 Env env{*this, features};
4712 Account const alice("alice");
4713 Account const bob("bob");
4714 ConfidentialEnv confEnv{
4715 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 60}}, setupFlags};
4716 auto& mptAlice = confEnv.mpt;
4717
4718 mptAlice.confidentialClaw({
4719 .account = alice,
4720 .holder = bob,
4721 .amt = 10000,
4722 .err = tecINSUFFICIENT_FUNDS,
4723 });
4724 }
4725 }
4726
4727 void
4729 {
4730 testcase("ConfidentialMPTClawback Proof");
4731 using namespace test::jtx;
4732
4733 Account const alice("alice");
4734 Account const bob("bob");
4735 Account const carol("carol");
4736
4737 // lambda function to set up MPT with alice as issuer, bob and carol
4738 // as authorized holders, and fund 1000 mpt to bob and 2000 mpt to
4739 // carol.
4740 auto const setupEnv = [&](Env& env) -> MPTTester {
4741 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
4742
4743 mptAlice.create({
4744 .flags = tfMPTCanTransfer | tfMPTCanClawback | tfMPTCanHoldConfidentialBalance,
4745 });
4746
4747 for (auto const& [acct, amt] : {std::pair{bob, 1000}, {carol, 2000}})
4748 {
4749 mptAlice.authorize({
4750 .account = acct,
4751 });
4752 mptAlice.pay(alice, acct, amt);
4753 mptAlice.generateKeyPair(acct);
4754 }
4755
4756 mptAlice.generateKeyPair(alice);
4757 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
4758
4759 return mptAlice;
4760 };
4761
4762 // lambda function to test a set of bad clawback amounts that should
4763 // return tecBAD_PROOF
4764 auto const checkBadProofs =
4765 [&](MPTTester& mpt, Account const& holder, std::initializer_list<uint64_t> amts) {
4766 for (auto const badAmt : amts)
4767 {
4768 mpt.confidentialClaw({
4769 .account = alice,
4770 .holder = holder,
4771 .amt = badAmt,
4772 .err = tecBAD_PROOF,
4773 });
4774 }
4775 };
4776
4777 // SCENARIO 1: clawback from inbox only or spending only balances.
4778 // bob converts 500 and merge inbox,
4779 // carol converts 1000, but not merge inbox.
4780 // after setup, bob has 500 in spending, carol has 1000 in inbox.
4781 {
4782 Env env{*this, features};
4783 auto mptAlice = setupEnv(env);
4784
4785 // bob converts and merges
4786 mptAlice.convert({.account = bob, .amt = 500, .holderPubKey = mptAlice.getPubKey(bob)});
4787 mptAlice.mergeInbox({
4788 .account = bob,
4789 });
4790 // carol converts without merge
4791 mptAlice.convert(
4792 {.account = carol, .amt = 1000, .holderPubKey = mptAlice.getPubKey(carol)});
4793
4794 // verify proof fails with invalid clawback amount
4795 // bob: 500 in Spending, 0 in Inbox
4796 checkBadProofs(
4797 mptAlice,
4798 bob,
4799 {
4800 1,
4801 10,
4802 70,
4803 100,
4804 110,
4805 200,
4806 499,
4807 501,
4808 600,
4809 });
4810
4811 // carol: 1000 in Inbox, 0 in Spending
4812 checkBadProofs(
4813 mptAlice,
4814 carol,
4815 {
4816 1,
4817 10,
4818 50,
4819 500,
4820 777,
4821 850,
4822 999,
4823 1001,
4824 1200,
4825 });
4826
4827 // clawback with correct amount that passes proof verification
4828 mptAlice.confidentialClaw({
4829 .account = alice,
4830 .holder = bob,
4831 .amt = 500,
4832 });
4833 mptAlice.confidentialClaw({
4834 .account = alice,
4835 .holder = carol,
4836 .amt = 1000,
4837 });
4838 }
4839
4840 // SCENARIO 2: clawback from mixed inbox and spending balances.
4841 // bob converts 300 to confidential and merge inbox,
4842 // carol converts 400 to confidential and merge inbox,
4843 // bob sends 100 to carol, carol sends 100 to bob.
4844 // After setup, bob has 100 in inbox and 200 in spending;
4845 // carol has 100 in inbox and 300 in spending.
4846 {
4847 Env env{*this, features};
4848 auto mptAlice = setupEnv(env);
4849
4850 mptAlice.convert({.account = bob, .amt = 300, .holderPubKey = mptAlice.getPubKey(bob)});
4851 mptAlice.mergeInbox({
4852 .account = bob,
4853 });
4854 mptAlice.convert(
4855 {.account = carol, .amt = 400, .holderPubKey = mptAlice.getPubKey(carol)});
4856 mptAlice.mergeInbox({
4857 .account = carol,
4858 });
4859 mptAlice.send({
4860 .account = bob,
4861 .dest = carol,
4862 .amt = 100,
4863 });
4864 mptAlice.send({
4865 .account = carol,
4866 .dest = bob,
4867 .amt = 100,
4868 });
4869
4870 // verify proof fails with invalid clawback amount
4871 // bob: 100 in inbox, 200 in spending
4872 checkBadProofs(
4873 mptAlice,
4874 bob,
4875 {
4876 1,
4877 10,
4878 50,
4879 100,
4880 200,
4881 299,
4882 301,
4883 400,
4884 });
4885
4886 // proof failure for incorrect amount when clawbacking from
4887 // carol carol: 100 in inbox, 300 in spending
4888 checkBadProofs(
4889 mptAlice,
4890 carol,
4891 {
4892 1,
4893 10,
4894 50,
4895 100,
4896 300,
4897 399,
4898 401,
4899 501,
4900 });
4901
4902 // clawback with correct amount that passes proof verification
4903 mptAlice.confidentialClaw({
4904 .account = alice,
4905 .holder = bob,
4906 .amt = 300,
4907 });
4908 mptAlice.confidentialClaw({
4909 .account = alice,
4910 .holder = carol,
4911 .amt = 400,
4912 });
4913 }
4914
4915 // SCENARIO 3: the clawback proof omits the holder's confidential
4916 // balance version. A proof generated before the version advances is
4917 // still accepted, because getClawbackContextHash has no version
4918 // component.
4919 {
4920 Env env{*this, features};
4921 auto mptAlice = setupEnv(env);
4922
4923 mptAlice.convert({.account = bob, .amt = 500, .holderPubKey = mptAlice.getPubKey(bob)});
4924 mptAlice.mergeInbox({
4925 .account = bob,
4926 });
4927
4928 auto const privKey = mptAlice.getPrivKey(alice);
4929 if (!BEAST_EXPECT(privKey.has_value()))
4930 return;
4931
4932 auto const proof = mptAlice.getClawbackProof(
4933 bob,
4934 500,
4935 requireOptionalRef(privKey, "Missing private key"),
4937 alice.id(), mptAlice.issuanceID(), env.seq(alice), bob.id()));
4938 if (!BEAST_EXPECT(proof.has_value()))
4939 return;
4940
4941 // Advance bob's balance version after the proof is generated. An
4942 // empty-inbox merge leaves the balance unchanged but still bumps
4943 // sfConfidentialBalanceVersion.
4944 auto const versionBefore = mptAlice.getMPTokenVersion(bob);
4945 mptAlice.mergeInbox({.account = bob});
4946 BEAST_EXPECT(mptAlice.getMPTokenVersion(bob) != versionBefore);
4947
4948 // The stale-version proof is still accepted.
4949 mptAlice.confidentialClaw({
4950 .account = alice,
4951 .holder = bob,
4952 .amt = 500,
4953 .proof = strHex(requireOptional(proof, "Missing proof")),
4954 });
4955 }
4956 }
4957
4958 void
4960 {
4961 testcase("Public transfers after clearing Confidential Flag");
4962 using namespace test::jtx;
4963
4964 Account const alice("alice");
4965 Account const bob("bob");
4966 Account const carol("carol");
4967
4968 // After clearing the confidential flag, all four public MPT operations
4969 // must succeed regardless of which confidential path left encrypted-zero
4970 // fields on bob's MPToken.
4971 auto const runPublicPayments = [&](MPTTester& mpt) {
4972 mpt.pay(bob, carol, 10);
4973 mpt.pay(carol, bob, 5);
4974 mpt.pay(alice, bob, 1);
4975 mpt.pay(carol, alice, 5);
4976 };
4977
4978 auto const drainAndDeleteBobMPToken = [&](Env& env, MPTTester& mpt) {
4979 auto const bobBalance = mpt.getBalance(bob);
4980 BEAST_EXPECT(bobBalance > 0);
4981
4982 mpt.pay(bob, alice, bobBalance);
4983 BEAST_EXPECT(mpt.getBalance(bob) == 0);
4984
4985 mpt.authorize({.account = bob, .flags = tfMPTUnauthorize});
4986 BEAST_EXPECT(!env.le(keylet::mptoken(mpt.issuanceID(), bob.id())));
4987 };
4988
4989 // Alice pays Bob 100 public, Bob converts 50 confidential
4990 // Bob converts 50 back to public, and make sure can receive public payments
4991 {
4992 Env env{*this, features};
4993 ConfidentialEnv ct{
4994 env,
4995 alice,
4996 {{.account = bob, .payAmount = 100, .convertAmount = 50}},
4997 tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance};
4998
4999 env.fund(XRP(1'000), carol);
5000 ct.mpt.authorize({.account = carol});
5001 ct.mpt.pay(alice, carol, 50);
5002
5003 ct.mpt.convertBack({.account = bob, .amt = 50});
5004
5005 runPublicPayments(ct.mpt);
5006 drainAndDeleteBobMPToken(env, ct.mpt);
5007 }
5008
5009 // Same path as above but with Auditor
5010 {
5011 Env env{*this, features};
5012 Account const auditor("auditor");
5013 MPTTester mptAlice(env, alice, {.holders = {bob, carol}, .auditor = auditor});
5014
5015 mptAlice.create({
5016 .ownerCount = 1,
5017 .flags = tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance,
5018 });
5019
5020 mptAlice.authorize({.account = bob});
5021 mptAlice.authorize({.account = carol});
5022 mptAlice.pay(alice, bob, 100);
5023 mptAlice.pay(alice, carol, 50);
5024
5025 mptAlice.generateKeyPair(alice);
5026 mptAlice.generateKeyPair(bob);
5027 mptAlice.generateKeyPair(auditor);
5028 mptAlice.set({
5029 .account = alice,
5030 .issuerPubKey = mptAlice.getPubKey(alice),
5031 .auditorPubKey = mptAlice.getPubKey(auditor),
5032 });
5033
5034 mptAlice.convert({
5035 .account = bob,
5036 .amt = 50,
5037 .holderPubKey = mptAlice.getPubKey(bob),
5038 });
5039 mptAlice.mergeInbox({.account = bob});
5040 mptAlice.convertBack({.account = bob, .amt = 50});
5041
5042 runPublicPayments(mptAlice);
5043 drainAndDeleteBobMPToken(env, mptAlice);
5044 }
5045
5046 // Confidential clawback leaves encrypted-zero fields;
5047 // the public balance remaining after the clawback must stay usable.
5048 {
5049 Env env{*this, features};
5050 ConfidentialEnv ct{
5051 env,
5052 alice,
5053 {{.account = bob, .payAmount = 100, .convertAmount = 50}},
5054 tfMPTCanTransfer | tfMPTCanClawback | tfMPTCanHoldConfidentialBalance};
5055
5056 env.fund(XRP(1'000), carol);
5057 ct.mpt.authorize({.account = carol});
5058 ct.mpt.pay(alice, carol, 50);
5059
5060 ct.mpt.confidentialClaw({.account = alice, .holder = bob, .amt = 50});
5061
5062 runPublicPayments(ct.mpt);
5063 drainAndDeleteBobMPToken(env, ct.mpt);
5064 }
5065 }
5066
5067 void
5069 {
5070 testcase("mutate lsfMPTCanHoldConfidentialBalance");
5071 using namespace test::jtx;
5072
5073 // can not create mpt issuance with tifMPTCanHoldConfidentialBalance
5074 // when featureDynamicMPT is disabled
5075 {
5076 Env env{*this, features - featureDynamicMPT};
5077 Account const alice("alice");
5078 Account const bob("bob");
5079 MPTTester mptAlice(env, alice, {.holders = {bob}});
5080
5081 mptAlice.create({
5082 .ownerCount = 0,
5083 .immutableFlags = tifMPTCanHoldConfidentialBalance,
5084 .err = temDISABLED,
5085 });
5086 }
5087
5088 // can not create mpt issuance with tifMPTCanHoldConfidentialBalance when
5089 // featureConfidentialTransfer is disabled
5090 {
5091 Env env{*this, features - featureConfidentialTransfer};
5092 Account const alice("alice");
5093 Account const bob("bob");
5094 MPTTester mptAlice(env, alice, {.holders = {bob}});
5095
5096 mptAlice.create({
5097 .ownerCount = 0,
5098 .immutableFlags = tifMPTCanHoldConfidentialBalance,
5099 .err = temDISABLED,
5100 });
5101 }
5102
5103 // if lsifMPTCanHoldConfidentialBalance is set, can not set/clear
5104 // lsfMPTCanHoldConfidentialBalance
5105 {
5106 Env env{*this, features};
5107 Account const alice("alice");
5108 Account const bob("bob");
5109 MPTTester mptAlice(env, alice, {.holders = {bob}});
5110
5111 mptAlice.create({
5112 .ownerCount = 1,
5113 .flags = tfMPTCanTransfer,
5114 .immutableFlags = tifMPTCanHoldConfidentialBalance,
5115 });
5116
5117 mptAlice.set({
5118 .account = alice,
5119 .flags = tfMPTSetCanHoldConfidentialBalance,
5120 .err = tecNO_PERMISSION,
5121 });
5122 }
5123
5124 // Toggle lsfMPTCanHoldConfidentialBalance
5125 {
5126 Env env{*this, features};
5127 Account const alice("alice");
5128 Account const bob("bob");
5129 MPTTester mptAlice(env, alice, {.holders = {bob}});
5130
5131 mptAlice.create({
5132 .ownerCount = 1,
5133 .flags = tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance,
5134 .immutableFlags = tifMPTCanLock,
5135 });
5136
5137 mptAlice.authorize({
5138 .account = bob,
5139 });
5140 mptAlice.pay(alice, bob, 100);
5141
5142 mptAlice.generateKeyPair(alice);
5143 mptAlice.generateKeyPair(bob);
5144 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
5145
5146 auto holderPubKeySet = false;
5147 auto const verifyToggle = [&](TER expectedResult, uint64_t amt) {
5148 if (!holderPubKeySet)
5149 {
5150 mptAlice.convert({
5151 .account = bob,
5152 .amt = amt,
5153 .holderPubKey = mptAlice.getPubKey(bob),
5154 .err = expectedResult,
5155 });
5156 }
5157 else
5158 {
5159 mptAlice.convert({
5160 .account = bob,
5161 .amt = amt,
5162 .err = expectedResult,
5163 });
5164 }
5165
5166 if (expectedResult == tesSUCCESS)
5167 {
5168 holderPubKeySet = true;
5169 mptAlice.mergeInbox({
5170 .account = bob,
5171 });
5172
5173 // make sure there's no confidential outstanding balance
5174 // for the next toggle test
5175 mptAlice.convertBack({
5176 .account = bob,
5177 .amt = amt,
5178 });
5179 }
5180 };
5181
5182 // set lsfMPTCanHoldConfidentialBalance, but no effect because
5183 // lsfMPTCanHoldConfidentialBalance was already set
5184 mptAlice.set({
5185 .account = alice,
5186 .flags = tfMPTSetCanHoldConfidentialBalance,
5187 });
5188 verifyToggle(tesSUCCESS, 10);
5189
5190 // set tfMPTSetCanHoldConfidentialBalance again
5191 mptAlice.set({
5192 .account = alice,
5193 .flags = tfMPTSetCanHoldConfidentialBalance,
5194 });
5195 verifyToggle(tesSUCCESS, 30);
5196 }
5197
5198 // can not mutate lsfPrivacy when there's confidential
5199 // outstanding amount
5200 {
5201 Env env{*this, features};
5202 Account const alice("alice");
5203 Account const bob("bob");
5204 MPTTester mptAlice(env, alice, {.holders = {bob}});
5205
5206 // lsifMPTCanHoldConfidentialBalance is false by default,
5207 // so that lsfMPTCanHoldConfidentialBalance can be mutated
5208 mptAlice.create({
5209 .ownerCount = 1,
5210 .flags = tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance,
5211 });
5212
5213 mptAlice.authorize({
5214 .account = bob,
5215 });
5216 mptAlice.pay(alice, bob, 100);
5217
5218 mptAlice.generateKeyPair(alice);
5219 mptAlice.generateKeyPair(bob);
5220 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
5221
5222 // bob convert 50 to confidential
5223 mptAlice.convert({.account = bob, .amt = 50, .holderPubKey = mptAlice.getPubKey(bob)});
5224
5225 // set lsfMPTCanHoldConfidentialBalance should fail because of
5226 // confidential outstanding balance
5227 mptAlice.set({
5228 .account = alice,
5229 .flags = tfMPTSetCanHoldConfidentialBalance,
5230 .err = tecNO_PERMISSION,
5231 });
5232 }
5233 }
5234
5235 void
5237 {
5238 testcase("Convert back pedersen proof");
5239 using namespace test::jtx;
5240
5241 Env env{*this, features};
5242 Account const alice("alice");
5243 Account const bob("bob");
5244 ConfidentialEnv confEnv{
5245 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 40}}};
5246 auto& mptAlice = confEnv.mpt;
5247
5248 // for ease of understanding, generate all the fields here instead of
5249 // autofilling
5250 uint64_t const amt = 10;
5251 Buffer const blindingFactor = generateBlindingFactor();
5252 Buffer const pcBlindingFactor = generateBlindingFactor();
5253
5254 auto const spendingBalance = requireOptional(
5255 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending),
5256 "Missing spending balance");
5257 auto const encryptedSpendingBalance = requireOptional(
5258 mptAlice.getEncryptedBalance(bob, MPTTester::holderEncryptedSpending),
5259 "Missing encrypted spending balance");
5260 BEAST_EXPECT(!encryptedSpendingBalance.empty());
5261
5262 Buffer const pedersenCommitment =
5263 mptAlice.getPedersenCommitment(spendingBalance, pcBlindingFactor);
5264 Buffer const issuerCiphertext = mptAlice.encryptAmount(alice, amt, blindingFactor);
5265 Buffer const bobCiphertext = mptAlice.encryptAmount(bob, amt, blindingFactor);
5266 auto const version = mptAlice.getMPTokenVersion(bob);
5267
5268 // These tests verify that the compact ConvertBack proof validation
5269 // correctly rejects proofs generated with incorrect parameters.
5270 // The compact proof simultaneously verifies balance ownership,
5271 // commitment linkage, and that remaining balance is non-negative.
5272
5273 // Test 1: Proof generated with wrong pedersen commitment value.
5274 // The proof uses PC(1, rho) but the transaction submits PC(balance, rho).
5275 // Verification fails because the proof doesn't match the submitted commitment.
5276 {
5277 UInt256 const contextHash =
5278 getConvertBackContextHash(bob, mptAlice.issuanceID(), env.seq(bob), version);
5279 Buffer const badPedersenCommitment =
5280 mptAlice.getPedersenCommitment(1, pcBlindingFactor);
5281 auto const proof = mptAlice.getConvertBackProof(
5282 bob,
5283 amt,
5284 contextHash,
5285 {
5286 .pedersenCommitment = badPedersenCommitment, // wrong pedersen commitment
5287 .amt = spendingBalance,
5288 .encryptedAmt = encryptedSpendingBalance,
5289 .blindingFactor = pcBlindingFactor,
5290 });
5291 if (!BEAST_EXPECT(proof.has_value()))
5292 return;
5293
5294 mptAlice.convertBack({
5295 .account = bob,
5296 .amt = amt,
5297 .proof = proof,
5298 .holderEncryptedAmt = bobCiphertext,
5299 .issuerEncryptedAmt = issuerCiphertext,
5300 .blindingFactor = blindingFactor,
5301 .pedersenCommitment = pedersenCommitment,
5302 .err = tecBAD_PROOF,
5303 });
5304 }
5305
5306 // Test 2: Proof generated with wrong blinding factor (rho).
5307 // The pedersen commitment PC = balance*G + rho*H requires the same rho
5308 // used in proof generation. Using a different rho breaks the linkage.
5309 {
5310 UInt256 const contextHash =
5311 getConvertBackContextHash(bob, mptAlice.issuanceID(), env.seq(bob), version);
5312
5313 auto const proof = mptAlice.getConvertBackProof(
5314 bob,
5315 amt,
5316 contextHash,
5317 {
5318 .pedersenCommitment = pedersenCommitment,
5319 .amt = spendingBalance,
5320 .encryptedAmt = encryptedSpendingBalance,
5321 .blindingFactor = generateBlindingFactor(), // wrong blinding factor
5322 });
5323 if (!BEAST_EXPECT(proof.has_value()))
5324 return;
5325
5326 mptAlice.convertBack({
5327 .account = bob,
5328 .amt = amt,
5329 .proof = proof,
5330 .holderEncryptedAmt = bobCiphertext,
5331 .issuerEncryptedAmt = issuerCiphertext,
5332 .blindingFactor = blindingFactor,
5333 .pedersenCommitment = pedersenCommitment,
5334 .err = tecBAD_PROOF,
5335 });
5336 }
5337
5338 // Test 3: Proof generated with wrong balance value.
5339 // The sigma proof claims balance=20 but the pedersen commitment and
5340 // encrypted spending balance were built for the actual balance (40).
5341 // we cannot call mpt_get_convert_back_proof because it has client-side
5342 // verification.
5343 {
5344 UInt256 const contextHash =
5345 getConvertBackContextHash(bob, mptAlice.issuanceID(), env.seq(bob), version);
5346
5347 uint64_t constexpr claimedBalance = 20; // wrong: real balance is 40
5348
5349 auto const proof = getForgedConvertBackProof(
5350 mptAlice,
5351 bob,
5352 claimedBalance,
5353 spendingBalance,
5354 amt,
5355 pedersenCommitment,
5356 encryptedSpendingBalance,
5357 pcBlindingFactor,
5358 contextHash);
5359
5360 mptAlice.convertBack({
5361 .account = bob,
5362 .amt = amt,
5363 .proof = proof,
5364 .holderEncryptedAmt = bobCiphertext,
5365 .issuerEncryptedAmt = issuerCiphertext,
5366 .blindingFactor = blindingFactor,
5367 .pedersenCommitment = pedersenCommitment,
5368 .err = tecBAD_PROOF,
5369 });
5370 }
5371
5372 // Test 4: Correct proof but wrong pedersen commitment in transaction.
5373 // The proof is generated correctly, but the transaction submits a
5374 // different pedersen commitment. Verification fails because the
5375 // submitted commitment doesn't match what the proof was generated for.
5376 {
5377 UInt256 const contextHash =
5378 getConvertBackContextHash(bob, mptAlice.issuanceID(), env.seq(bob), version);
5379 Buffer const badPedersenCommitment =
5380 mptAlice.getPedersenCommitment(1, pcBlindingFactor);
5381 auto const proof = mptAlice.getConvertBackProof(
5382 bob,
5383 amt,
5384 contextHash,
5385 {
5386 .pedersenCommitment = pedersenCommitment,
5387 .amt = spendingBalance,
5388 .encryptedAmt = encryptedSpendingBalance,
5389 .blindingFactor = pcBlindingFactor,
5390 });
5391 if (!BEAST_EXPECT(proof.has_value()))
5392 return;
5393
5394 mptAlice.convertBack({
5395 .account = bob,
5396 .amt = amt,
5397 .proof = proof,
5398 .holderEncryptedAmt = bobCiphertext,
5399 .issuerEncryptedAmt = issuerCiphertext,
5400 .blindingFactor = blindingFactor,
5401 .pedersenCommitment = badPedersenCommitment, // wrong pedersen commitment
5402 .err = tecBAD_PROOF,
5403 });
5404 }
5405
5406 // Test 5: Proof generated with wrong context hash.
5407 // The context hash binds the proof to a specific transaction (account,
5408 // sequence, issuanceID, amount, version). Using a different context hash
5409 // makes the proof invalid for this transaction, preventing replay attacks.
5410 {
5411 UInt256 const badContextHash{1};
5412
5413 auto const proof = mptAlice.getConvertBackProof(
5414 bob,
5415 amt,
5416 badContextHash, // wrong context hash
5417 {
5418 .pedersenCommitment = pedersenCommitment,
5419 .amt = spendingBalance,
5420 .encryptedAmt = encryptedSpendingBalance,
5421 .blindingFactor = pcBlindingFactor,
5422 });
5423 if (!BEAST_EXPECT(proof.has_value()))
5424 return;
5425
5426 mptAlice.convertBack({
5427 .account = bob,
5428 .amt = amt,
5429 .proof = proof,
5430 .holderEncryptedAmt = bobCiphertext,
5431 .issuerEncryptedAmt = issuerCiphertext,
5432 .blindingFactor = blindingFactor,
5433 .pedersenCommitment = pedersenCommitment,
5434 .err = tecBAD_PROOF,
5435 });
5436 }
5437
5438 // Test 6: Correct proof to verify the test setup is valid.
5439 // All parameters are correct, so the transaction should succeed.
5440 {
5441 UInt256 const contextHash =
5442 getConvertBackContextHash(bob, mptAlice.issuanceID(), env.seq(bob), version);
5443
5444 auto const proof = mptAlice.getConvertBackProof(
5445 bob,
5446 amt,
5447 contextHash,
5448 {
5449 .pedersenCommitment = pedersenCommitment,
5450 .amt = spendingBalance,
5451 .encryptedAmt = encryptedSpendingBalance,
5452 .blindingFactor = pcBlindingFactor,
5453 });
5454 if (!BEAST_EXPECT(proof.has_value()))
5455 return;
5456
5457 mptAlice.convertBack({
5458 .account = bob,
5459 .amt = amt,
5460 .proof = proof,
5461 .holderEncryptedAmt = bobCiphertext,
5462 .issuerEncryptedAmt = issuerCiphertext,
5463 .blindingFactor = blindingFactor,
5464 .pedersenCommitment = pedersenCommitment,
5465 });
5466 }
5467 }
5468
5469 void
5471 {
5472 uint64_t const balance = 100;
5473 testSendOverdraftBulletproofImpl(features, balance, balance); // SUCCEED
5474 testSendOverdraftBulletproofImpl(features, balance, balance + 1); // FAIL
5475 }
5476
5477 void
5478 testSendOverdraftBulletproofImpl(FeatureBitset features, unsigned balance, unsigned amt)
5479 {
5480 testcase("Send: overdraft prevention via bulletproof");
5481 using namespace test::jtx;
5482
5483 // Attack scenario: Alice has 100 tokens, tries to send 101 to Bob.
5484 // The client-side check in mpt-crypto:mpt_utility.cpp:743 prevents honest
5485 // clients from creating this proof. We bypass it by manually
5486 // constructing a forged proof to demonstrate that the ledger's
5487 // range proof verification catches the overdraft.
5488
5489 Env env{*this, features};
5490 Account const alice("alice"), bob("bob"), issuer("issuer");
5491
5492 uint64_t const aliceBalance = balance;
5493 uint64_t const aliceAmount = amt;
5494 uint64_t const aliceRemaining = aliceBalance - aliceAmount;
5495
5496 // Setup: Alice has 100 tokens converted to confidential
5497 ConfidentialEnv confEnv{
5498 env,
5499 issuer,
5500 {
5501 {.account = alice, .payAmount = 1000, .convertAmount = aliceBalance},
5502 {.account = bob, .payAmount = 1000, .convertAmount = 30},
5503 }};
5504 auto& mptIssuer = confEnv.mpt;
5505
5506 std::pair<int, TER> errors = aliceAmount > aliceBalance
5509
5510 unsigned const numParticipants = 3;
5511
5512 // Verify Alice's actual balance before attack
5513 {
5514 auto const balance = requireOptional(
5515 mptIssuer.getDecryptedBalance(alice, MPTTester::holderEncryptedSpending),
5516 "Missing Alice's balance");
5517 BEAST_EXPECT(balance == aliceBalance);
5518 }
5519
5520 // We cannot use ConfidentialSendSetup directly because it would
5521 // call mpt_get_confidential_send_proof which has a client-side
5522 // check (amount > balance) at line 743 in mpt_utility.cpp.
5523 // Instead, we manually construct the transaction components.
5524
5525 Buffer const randomElgamal = generateBlindingFactor();
5526 Buffer const randomBalance = generateBlindingFactor();
5527
5528 // Create encrypted amounts (using the OVERDRAFT amount)
5529 Buffer const aliceEncAmt = mptIssuer.encryptAmount(alice, aliceAmount, randomElgamal);
5530 Buffer const bobEncAmt = mptIssuer.encryptAmount(bob, aliceAmount, randomElgamal);
5531 Buffer const issuerEncAmt = mptIssuer.encryptAmount(issuer, aliceAmount, randomElgamal);
5532
5533 // Create commitments
5534 // IMPORTANT: Amount commitment uses same randomness as ElGamal encryption!
5535 Buffer const amtCommit = mptIssuer.getPedersenCommitment(aliceAmount, randomElgamal);
5536 Buffer const balanceCommit = mptIssuer.getPedersenCommitment(aliceBalance, randomBalance);
5537
5538 // Get Alice's current encrypted spending balance
5539 Buffer const aliceEncBalance = requireOptional(
5540 mptIssuer.getEncryptedBalance(alice, MPTTester::holderEncryptedSpending),
5541 "Missing Alice's encrypted spending balance");
5542
5543 uint32_t const version = mptIssuer.getMPTokenVersion(alice);
5544 auto const ctxHash = getSendContextHash(
5545 alice.id(), mptIssuer.issuanceID(), env.seq(alice), bob.id(), version);
5546
5547 // Now we need to manually generate the sigma proof part.
5548 // The sigma proof verifies ciphertext consistency and commitments,
5549 // but doesn't check the range. We'll construct it with the overdraft
5550 // amount to bypass the client-side check.
5551
5552 // Generate the sigma proof manually using the lower-level secp256k1 API
5553 auto const* ctx = mpt_secp256k1_context();
5554 Buffer sigmaProof(SECP256K1_COMPACT_STANDARD_PROOF_SIZE);
5555
5556 // Parse all public keys and ciphertexts
5557 secp256k1_pubkey c1, c2Alice, c2Bob, c2Issuer;
5558 // Parse sender's ciphertext C1 (first 33(kCompressedEcPointLength) bytes)
5559 auto x = secp256k1_ec_pubkey_parse(ctx, &c1, aliceEncAmt.data(), kCompressedEcPointLength);
5560 if (!BEAST_EXPECTS(x == 1, "Failed to parse C1"))
5561 return;
5562 // Parse C2 components for all recipients
5563 x = secp256k1_ec_pubkey_parse(
5564 ctx, &c2Alice, aliceEncAmt.data() + kCompressedEcPointLength, kCompressedEcPointLength);
5565 auto y = secp256k1_ec_pubkey_parse(
5566 ctx, &c2Bob, bobEncAmt.data() + kCompressedEcPointLength, kCompressedEcPointLength);
5567 auto z = secp256k1_ec_pubkey_parse(
5568 ctx,
5569 &c2Issuer,
5570 issuerEncAmt.data() + kCompressedEcPointLength,
5572 if (!BEAST_EXPECTS(x == 1 && y == 1 && z == 1, "Failed to parse C2 components"))
5573 return;
5574 secp256k1_pubkey c2Vec[] = {c2Alice, c2Bob, c2Issuer};
5575
5576 // Parse public keys
5577 secp256k1_pubkey pkAlice, pkBob, pkIssuer;
5578 auto alicePubKey = requireOptional(mptIssuer.getPubKey(alice), "Missing alice pubkey");
5579 auto bobPubKey = requireOptional(mptIssuer.getPubKey(bob), "Missing bob pubkey");
5580 auto issuerPubKey = requireOptional(mptIssuer.getPubKey(issuer), "Missing issuer pubkey");
5581 x = secp256k1_ec_pubkey_parse(ctx, &pkAlice, alicePubKey.data(), kCompressedEcPointLength);
5582 y = secp256k1_ec_pubkey_parse(ctx, &pkBob, bobPubKey.data(), kCompressedEcPointLength);
5583 z = secp256k1_ec_pubkey_parse(
5584 ctx, &pkIssuer, issuerPubKey.data(), kCompressedEcPointLength);
5585 if (!BEAST_EXPECTS(x == 1 && y == 1 && z == 1, "Failed to parse public keys"))
5586 return;
5587 secp256k1_pubkey pkVec[] = {pkAlice, pkBob, pkIssuer};
5588
5589 // Parse commitments
5590 secp256k1_pubkey pcAmount, pcBalance, b1, b2;
5591 x = secp256k1_ec_pubkey_parse(ctx, &pcAmount, amtCommit.data(), kCompressedEcPointLength);
5592 y = secp256k1_ec_pubkey_parse(
5593 ctx, &pcBalance, balanceCommit.data(), kCompressedEcPointLength);
5594 if (!BEAST_EXPECTS(x == 1 && y == 1, "Failed to parse commitments"))
5595 return;
5596 // Parse balance ciphertext
5597 x = secp256k1_ec_pubkey_parse(ctx, &b1, aliceEncBalance.data(), kCompressedEcPointLength);
5598 y = secp256k1_ec_pubkey_parse(
5599 ctx, &b2, aliceEncBalance.data() + kCompressedEcPointLength, kCompressedEcPointLength);
5600 if (!BEAST_EXPECTS(x == 1 && y == 1, "Failed to parse balance ciphertext"))
5601 return;
5602
5603 // Get Alice's private key
5604 auto alicePrivKey = requireOptional(mptIssuer.getPrivKey(alice), "Missing alice privkey");
5605
5606 // Generate the compact sigma proof (part of mpt_get_confidential_send_proof)
5607 // This will succeed because sigma proof doesn't check amount vs balance
5608 x = secp256k1_compact_standard_prove(
5609 ctx,
5610 sigmaProof.data(),
5611 aliceAmount,
5612 aliceBalance,
5613 randomElgamal.data(),
5614 alicePrivKey.data(),
5615 randomBalance.data(),
5616 numParticipants,
5617 &c1,
5618 c2Vec,
5619 pkVec,
5620 &pcAmount,
5621 &pkAlice,
5622 &pcBalance,
5623 &b1,
5624 &b2,
5625 ctxHash.data());
5626 if (!BEAST_EXPECTS(x == 1, "Failed to generate sigma proof"))
5627 return;
5628
5629 // Direct verification
5630 x = secp256k1_compact_standard_verify(
5631 ctx,
5632 sigmaProof.data(),
5633 numParticipants,
5634 &c1,
5635 c2Vec,
5636 pkVec,
5637 &pcAmount,
5638 &pkAlice,
5639 &pcBalance,
5640 &b1,
5641 &b2,
5642 ctxHash.data());
5643 if (!BEAST_EXPECTS(x == 1, "Sigma verification failed"))
5644 return;
5645
5646 // Compute the remaining blinding factor: r_remaining = r_balance - r_amount
5647 // This is required because the ledger homomorphically computes:
5648 // C_remaining = C_balance - C_amount = Commit(remaining, r_balance - r_amount)
5649 Buffer randomRemaining(kEcBlindingFactorLength);
5650 Buffer negRandomElgamal(kEcBlindingFactorLength);
5651 secp256k1_mpt_scalar_negate(negRandomElgamal.data(), randomElgamal.data());
5652 secp256k1_mpt_scalar_add(
5653 randomRemaining.data(), randomBalance.data(), negRandomElgamal.data());
5654
5655 // Now forge the bulletproof claiming
5656 auto const forgedBulletproof = getForgedBulletproof(
5657 {aliceAmount, aliceRemaining}, {randomElgamal, randomRemaining}, ctxHash);
5658
5659 // Combine sigma proof + forged bulletproof
5660 Buffer combinedProof(SECP256K1_COMPACT_STANDARD_PROOF_SIZE + kEcDoubleBulletproofLength);
5661 std::memcpy(combinedProof.data(), sigmaProof.data(), SECP256K1_COMPACT_STANDARD_PROOF_SIZE);
5663 combinedProof.data() + SECP256K1_COMPACT_STANDARD_PROOF_SIZE,
5664 forgedBulletproof.data(),
5666
5667 // Direct verification
5668 x = mpt_verify_send_range_proof(
5669 combinedProof.data() + SECP256K1_COMPACT_STANDARD_PROOF_SIZE,
5670 amtCommit.data(),
5671 balanceCommit.data(),
5672 ctxHash.data());
5673 if (!BEAST_EXPECTS(x == errors.first, "Forged proof passed validation"))
5674 return;
5675
5676 // Attempt the transaction with forged proof
5677 // Expected to FAIL with tecBAD_PROOF
5678 mptIssuer.send({
5679 .account = alice,
5680 .dest = bob,
5681 .amt = aliceAmount,
5682 .proof = strHex(combinedProof),
5683 .senderEncryptedAmt = aliceEncAmt,
5684 .destEncryptedAmt = bobEncAmt,
5685 .issuerEncryptedAmt = issuerEncAmt,
5686 .amountCommitment = amtCommit,
5687 .balanceCommitment = balanceCommit,
5688 .err = errors.second,
5689 });
5690
5691 // Verify Alice's balance unchanged (attack prevented!)
5692 {
5693 auto const balance = requireOptional(
5694 mptIssuer.getDecryptedBalance(alice, MPTTester::holderEncryptedSpending),
5695 "Missing post-attack balance");
5696 if (aliceAmount > aliceBalance)
5697 {
5698 BEAST_EXPECT(balance == aliceBalance);
5699 }
5700 else
5701 {
5702 BEAST_EXPECT(balance < aliceBalance);
5703 }
5704 }
5705 }
5706
5707 void
5709 {
5710 uint64_t const balance = 100;
5711 testConvertBackOverdraftBulletproofImpl(features, balance, balance); // SUCCEED
5712 testConvertBackOverdraftBulletproofImpl(features, balance, balance + 1); // FAIL
5713 }
5714
5715 void
5716 testConvertBackOverdraftBulletproofImpl(FeatureBitset features, uint64_t balance, uint64_t amt)
5717 {
5718 testcase("Convert back: overdraft prevention via bulletproof");
5719 using namespace test::jtx;
5720
5721 // Attack scenario: Bob has 100 confidential tokens, tries to convert back 101.
5722 // The client-side check in mpt_get_convert_back_proof would prevent honest
5723 // clients from creating this proof. We bypass it by manually constructing
5724 // a forged proof to demonstrate that the ledger's bulletproof verification
5725 // catches the overdraft.
5726
5727 Env env{*this, features};
5728 Account const alice("alice"), bob("bob"), carol("carol");
5729
5730 uint64_t const bobBalance = balance;
5731 uint64_t const convertAmount = amt;
5732 uint64_t const bobRemaining = bobBalance - convertAmount;
5733
5734 // Setup: Bob and Carol both have confidential balance
5735 // Carol ensures outstanding amount >= convertAmount (bypass preclaim check)
5736 // This allows us to test the bulletproof specifically
5737 ConfidentialEnv confEnv{
5738 env,
5739 alice,
5740 {
5741 {.account = bob, .payAmount = 1000, .convertAmount = bobBalance},
5742 {
5743 .account = carol,
5744 .payAmount = 1000,
5745 .convertAmount = std::max(convertAmount, bobBalance + 1),
5746 },
5747 }};
5748 auto& mptAlice = confEnv.mpt;
5749
5750 std::pair<int, TER> errors = convertAmount > bobBalance
5753
5754 // Verify Bob's actual balance before attack
5755 {
5756 auto const balance = requireOptional(
5757 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending),
5758 "Missing Bob's balance");
5759 BEAST_EXPECT(balance == bobBalance);
5760 }
5761
5762 // We cannot use the standard getConvertBackProof because it calls
5763 // mpt_get_convert_back_proof which has client-side validation.
5764 // Instead, we manually construct the sigma proof and forge the bulletproof.
5765
5766 Buffer const blindingFactor = generateBlindingFactor();
5767 Buffer const pcBlindingFactor = generateBlindingFactor();
5768
5769 // Create encrypted amounts for the conversion
5770 Buffer const bobEncAmt = mptAlice.encryptAmount(bob, convertAmount, blindingFactor);
5771 Buffer const issuerEncAmt = mptAlice.encryptAmount(alice, convertAmount, blindingFactor);
5772
5773 // Create Pedersen commitment to the current balance
5774 Buffer const balanceCommit = mptAlice.getPedersenCommitment(bobBalance, pcBlindingFactor);
5775
5776 // Get Bob's current encrypted spending balance
5777 Buffer const bobEncBalance = requireOptional(
5778 mptAlice.getEncryptedBalance(bob, MPTTester::holderEncryptedSpending),
5779 "Missing Bob's encrypted spending balance");
5780
5781 uint32_t const version = mptAlice.getMPTokenVersion(bob);
5782 auto const ctxHash =
5783 getConvertBackContextHash(bob.id(), mptAlice.issuanceID(), env.seq(bob), version);
5784
5785 // Now manually generate the compact sigma proof for ConvertBack
5786 auto const* ctx = mpt_secp256k1_context();
5787 Buffer sigmaProof(SECP256K1_COMPACT_CONVERTBACK_PROOF_SIZE);
5788
5789 // Parse the holder's public key
5790 secp256k1_pubkey pkBob;
5791 auto bobPubKey = requireOptional(mptAlice.getPubKey(bob), "Missing bob pubkey");
5792 auto x = secp256k1_ec_pubkey_parse(ctx, &pkBob, bobPubKey.data(), kCompressedEcPointLength);
5793 if (!BEAST_EXPECTS(x == 1, "Failed to parse Bob's public key"))
5794 return;
5795
5796 // Parse balance commitment
5797 secp256k1_pubkey pcBalance;
5798 x = secp256k1_ec_pubkey_parse(
5799 ctx, &pcBalance, balanceCommit.data(), kCompressedEcPointLength);
5800 if (!BEAST_EXPECTS(x == 1, "Failed to parse balance commitment"))
5801 return;
5802
5803 // Parse balance ciphertext (B1, B2)
5804 secp256k1_pubkey b1, b2;
5805 x = secp256k1_ec_pubkey_parse(ctx, &b1, bobEncBalance.data(), kCompressedEcPointLength);
5806 auto const y = secp256k1_ec_pubkey_parse(
5807 ctx, &b2, bobEncBalance.data() + kCompressedEcPointLength, kCompressedEcPointLength);
5808 if (!BEAST_EXPECTS(x == 1 && y == 1, "Failed to parse balance ciphertext"))
5809 return;
5810
5811 // Get Bob's private key
5812 auto bobPrivKey = requireOptional(mptAlice.getPrivKey(bob), "Missing bob privkey");
5813
5814 // Generate the compact sigma proof for ConvertBack
5815 // This verifies balance ownership and commitment linkage
5816 x = secp256k1_compact_convertback_prove(
5817 ctx,
5818 sigmaProof.data(),
5819 bobBalance,
5820 bobPrivKey.data(),
5821 pcBlindingFactor.data(),
5822 &pkBob,
5823 &b1,
5824 &b2,
5825 &pcBalance,
5826 ctxHash.data());
5827 if (!BEAST_EXPECTS(x == 1, "Failed to generate convertback sigma proof"))
5828 return;
5829
5830 // Verify the sigma proof passes (it doesn't check range)
5831 x = secp256k1_compact_convertback_verify(
5832 ctx, sigmaProof.data(), &pkBob, &b1, &b2, &pcBalance, ctxHash.data());
5833 if (!BEAST_EXPECTS(x == 1, "Sigma verification failed"))
5834 return;
5835
5836 // Now forge the single bulletproof claiming the remaining balance is valid
5837 // For ConvertBack, we need to prove: (balance - convertAmount) >= 0
5838 // We create a commitment to the remainder and generate a bulletproof for it
5839
5840 // The bulletproof needs the blinding factor for the remainder commitment
5841 // The ledger computes: C_remainder = C_balance - convertAmount*G
5842 // So the blinding factor is just pcBlindingFactor (no randomness in convertAmount*G)
5843
5844 auto const forgedBulletproof =
5845 getForgedSingleBulletproof(bobRemaining, pcBlindingFactor, ctxHash);
5846
5847 // Combine sigma proof + forged bulletproof
5848 Buffer combinedProof(kEcConvertBackProofLength);
5850 combinedProof.data(), sigmaProof.data(), SECP256K1_COMPACT_CONVERTBACK_PROOF_SIZE);
5852 combinedProof.data() + SECP256K1_COMPACT_CONVERTBACK_PROOF_SIZE,
5853 forgedBulletproof.data(),
5855
5856 // Direct verification of the full proof
5857 x = mpt_verify_convert_back_proof(
5858 combinedProof.data(),
5859 bobPubKey.data(),
5860 bobEncBalance.data(),
5861 balanceCommit.data(),
5863 ctxHash.data());
5864 if (!BEAST_EXPECTS(x == errors.first, "Forged proof verification mismatch"))
5865 return;
5866
5867 // Attempt the transaction with forged proof
5868 // Expected to FAIL with tecBAD_PROOF when convertAmount > bobBalance
5869 mptAlice.convertBack({
5870 .account = bob,
5871 .amt = convertAmount,
5872 .proof = combinedProof,
5873 .holderEncryptedAmt = bobEncAmt,
5874 .issuerEncryptedAmt = issuerEncAmt,
5875 .blindingFactor = blindingFactor,
5876 .pedersenCommitment = balanceCommit,
5877 .err = errors.second,
5878 });
5879
5880 // Verify Bob's balance unchanged (attack prevented!)
5881 {
5882 auto const postBalance = requireOptional(
5883 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending),
5884 "Missing post-attack balance");
5885 if (convertAmount > bobBalance)
5886 {
5887 BEAST_EXPECT(postBalance == bobBalance);
5888 }
5889 else
5890 {
5891 BEAST_EXPECT(postBalance < bobBalance);
5892 }
5893 }
5894 }
5895
5896 void
5898 {
5899 testcase("Convert back bulletproof");
5900 using namespace test::jtx;
5901
5902 Env env{*this, features};
5903 Account const alice("alice");
5904 Account const bob("bob");
5905 ConfidentialEnv confEnv{
5906 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 40}}};
5907 auto& mptAlice = confEnv.mpt;
5908
5909 // for ease of understanding, generate all the fields here instead of
5910 // autofilling
5911 uint64_t const amt = 10;
5912 Buffer const blindingFactor = generateBlindingFactor();
5913 Buffer const pcBlindingFactor = generateBlindingFactor();
5914
5915 auto const spendingBalance = requireOptional(
5916 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending),
5917 "Missing spending balance");
5918 auto const encryptedSpendingBalance = requireOptional(
5919 mptAlice.getEncryptedBalance(bob, MPTTester::holderEncryptedSpending),
5920 "Missing encrypted spending balance");
5921 BEAST_EXPECT(!encryptedSpendingBalance.empty());
5922
5923 Buffer const pedersenCommitment =
5924 mptAlice.getPedersenCommitment(spendingBalance, pcBlindingFactor);
5925 Buffer const issuerCiphertext = mptAlice.encryptAmount(alice, amt, blindingFactor);
5926 Buffer const bobCiphertext = mptAlice.encryptAmount(bob, amt, blindingFactor);
5927 auto const version = mptAlice.getMPTokenVersion(bob);
5928
5929 // These tests verify that the compact ConvertBack proof (sigma + bulletproof)
5930 // correctly rejects proofs generated with incorrect parameters.
5931 // The compact proof simultaneously verifies balance ownership, commitment
5932 // linkage, and that the remaining balance is non-negative.
5933
5934 // Test 1: Proof generated with wrong balance value.
5935 // The sigma proof claims balance=20 but the pedersen commitment and
5936 // encrypted spending balance were built for the actual balance (40).
5937 // we cannot call mpt_get_convert_back_proof because it has client-side
5938 // verification.
5939 {
5940 UInt256 const contextHash =
5941 getConvertBackContextHash(bob, mptAlice.issuanceID(), env.seq(bob), version);
5942
5943 uint64_t constexpr claimedBalance = 20; // wrong: real balance is 40
5944
5945 auto const proof = getForgedConvertBackProof(
5946 mptAlice,
5947 bob,
5948 claimedBalance,
5949 spendingBalance,
5950 amt,
5951 pedersenCommitment,
5952 encryptedSpendingBalance,
5953 pcBlindingFactor,
5954 contextHash);
5955
5956 mptAlice.convertBack({
5957 .account = bob,
5958 .amt = amt,
5959 .proof = proof,
5960 .holderEncryptedAmt = bobCiphertext,
5961 .issuerEncryptedAmt = issuerCiphertext,
5962 .blindingFactor = blindingFactor,
5963 .pedersenCommitment = pedersenCommitment,
5964 .err = tecBAD_PROOF,
5965 });
5966 }
5967
5968 // Test 2: Proof generated with wrong blinding factor (rho).
5969 // The compact sigma proof must use the same blinding factor (rho) as the
5970 // Pedersen commitment PC = balance*G + rho*H. Using a different rho
5971 // creates an inconsistency the verifier detects.
5972 {
5973 UInt256 const contextHash =
5974 getConvertBackContextHash(bob, mptAlice.issuanceID(), env.seq(bob), version);
5975
5976 auto const proof = mptAlice.getConvertBackProof(
5977 bob,
5978 amt,
5979 contextHash,
5980 {
5981 .pedersenCommitment = pedersenCommitment,
5982 .amt = spendingBalance,
5983 .encryptedAmt = encryptedSpendingBalance,
5984 .blindingFactor = generateBlindingFactor(), // wrong blinding factor
5985 });
5986 if (!BEAST_EXPECT(proof.has_value()))
5987 return;
5988
5989 mptAlice.convertBack({
5990 .account = bob,
5991 .amt = amt,
5992 .proof = proof,
5993 .holderEncryptedAmt = bobCiphertext,
5994 .issuerEncryptedAmt = issuerCiphertext,
5995 .blindingFactor = blindingFactor,
5996 .pedersenCommitment = pedersenCommitment,
5997 .err = tecBAD_PROOF,
5998 });
5999 }
6000
6001 // Test 3: Proof generated with wrong context hash.
6002 // The context hash binds the proof to a specific transaction (account,
6003 // sequence, issuanceID, amount, version). Using a different context hash
6004 // makes the proof invalid for this transaction, preventing replay attacks.
6005 {
6006 UInt256 const badContextHash{1};
6007 auto const proof = mptAlice.getConvertBackProof(
6008 bob,
6009 amt,
6010 badContextHash, // wrong context hash
6011 {
6012 .pedersenCommitment = pedersenCommitment,
6013 .amt = spendingBalance,
6014 .encryptedAmt = encryptedSpendingBalance,
6015 .blindingFactor = pcBlindingFactor,
6016 });
6017 if (!BEAST_EXPECT(proof.has_value()))
6018 return;
6019
6020 mptAlice.convertBack({
6021 .account = bob,
6022 .amt = amt,
6023 .proof = proof,
6024 .holderEncryptedAmt = bobCiphertext,
6025 .issuerEncryptedAmt = issuerCiphertext,
6026 .blindingFactor = blindingFactor,
6027 .pedersenCommitment = pedersenCommitment,
6028 .err = tecBAD_PROOF,
6029 });
6030 }
6031
6032 // Test 4: Correct proof to verify the test setup is valid.
6033 // All parameters are correct, so the transaction should succeed.
6034 {
6035 UInt256 const contextHash =
6036 getConvertBackContextHash(bob, mptAlice.issuanceID(), env.seq(bob), version);
6037
6038 auto const proof = mptAlice.getConvertBackProof(
6039 bob,
6040 amt,
6041 contextHash,
6042 {
6043 .pedersenCommitment = pedersenCommitment,
6044 .amt = spendingBalance,
6045 .encryptedAmt = encryptedSpendingBalance,
6046 .blindingFactor = pcBlindingFactor,
6047 });
6048 if (!BEAST_EXPECT(proof.has_value()))
6049 return;
6050
6051 mptAlice.convertBack({
6052 .account = bob,
6053 .amt = amt,
6054 .proof = proof,
6055 .holderEncryptedAmt = bobCiphertext,
6056 .issuerEncryptedAmt = issuerCiphertext,
6057 .blindingFactor = blindingFactor,
6058 .pedersenCommitment = pedersenCommitment,
6059 });
6060 }
6061 }
6062
6063 // A convert-back proof is bound to (account, issuance, sequence, version) via
6064 // the Fiat-Shamir context hash. Crafting a proof against any single wrong
6065 // variable and submitting it with the real parameters must be rejected
6066 // with tecBAD_PROOF
6067 void
6069 {
6070 testcase("ConvertBack proof context binding");
6071 using namespace test::jtx;
6072
6073 auto const runBadProof = [&](auto makeContextHash) {
6074 Env env{*this, features};
6075 Account const alice("alice");
6076 Account const bob("bob");
6077 Account const carol("carol");
6078 ConfidentialEnv confEnv{
6079 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 40}}};
6080 auto& mptAlice = confEnv.mpt;
6081
6082 std::uint64_t const amt = 10;
6083 Buffer const blindingFactor = generateBlindingFactor();
6084 Buffer const pcBlindingFactor = generateBlindingFactor();
6085
6086 auto const spendingBalance =
6087 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending);
6088 auto const encryptedSpendingBalance =
6089 mptAlice.getEncryptedBalance(bob, MPTTester::holderEncryptedSpending);
6090 if (!BEAST_EXPECT(spendingBalance && encryptedSpendingBalance))
6091 return;
6092
6093 Buffer const pedersenCommitment = mptAlice.getPedersenCommitment(
6094 requireOptional(spendingBalance, "Missing spending balance"), pcBlindingFactor);
6095 Buffer const issuerCiphertext = mptAlice.encryptAmount(alice, amt, blindingFactor);
6096 Buffer const bobCiphertext = mptAlice.encryptAmount(bob, amt, blindingFactor);
6097 auto const version = mptAlice.getMPTokenVersion(bob);
6098
6099 auto const proof = mptAlice.getConvertBackProof(
6100 bob,
6101 amt,
6102 makeContextHash(env, mptAlice, alice, bob, carol, version),
6103 {
6104 .pedersenCommitment = pedersenCommitment,
6105 .amt = requireOptional(spendingBalance, "Missing spending balance"),
6106 .encryptedAmt = requireOptionalRef(
6107 encryptedSpendingBalance, "Missing encrypted spending balance"),
6108 .blindingFactor = pcBlindingFactor,
6109 });
6110 if (!BEAST_EXPECT(proof.has_value()))
6111 return;
6112
6113 mptAlice.convertBack({
6114 .account = bob,
6115 .amt = amt,
6116 .proof = proof,
6117 .holderEncryptedAmt = bobCiphertext,
6118 .issuerEncryptedAmt = issuerCiphertext,
6119 .blindingFactor = blindingFactor,
6120 .pedersenCommitment = pedersenCommitment,
6121 .err = tecBAD_PROOF,
6122 });
6123 };
6124
6125 // Wrong account in the proof context.
6126 runBadProof([&](Env& env,
6127 MPTTester const& mpt,
6128 Account const&,
6129 Account const& bob,
6130 Account const& carol,
6131 std::uint32_t version) {
6132 return getConvertBackContextHash(carol.id(), mpt.issuanceID(), env.seq(bob), version);
6133 });
6134
6135 // Wrong issuance ID in the proof context.
6136 runBadProof([&](Env& env,
6137 MPTTester const&,
6138 Account const& alice,
6139 Account const& bob,
6140 Account const&,
6141 std::uint32_t version) {
6143 bob.id(), makeMptID(env.seq(alice) + 100, alice), env.seq(bob), version);
6144 });
6145
6146 // Wrong transaction sequence in the proof context.
6147 runBadProof([&](Env& env,
6148 MPTTester const& mpt,
6149 Account const&,
6150 Account const& bob,
6151 Account const&,
6152 std::uint32_t version) {
6153 return getConvertBackContextHash(bob.id(), mpt.issuanceID(), env.seq(bob) + 1, version);
6154 });
6155
6156 // Wrong balance version in the proof context.
6157 runBadProof([&](Env& env,
6158 MPTTester const& mpt,
6159 Account const&,
6160 Account const& bob,
6161 Account const&,
6162 std::uint32_t version) {
6163 return getConvertBackContextHash(bob.id(), mpt.issuanceID(), env.seq(bob), version + 1);
6164 });
6165 }
6166
6167 // This test simulates a valid proof π extracted from a transaction
6168 // for amount m1 is reused in a new transaction for a different
6169 // amount m2 with different ciphertexts. It confirms the context hash
6170 // recomputation fails due to the ciphertext binding mismatch, resulting
6171 // in tecBAD_PROOF.
6172 void
6174 {
6175 testcase("ConvertBack: proof ciphertext binding");
6176 using namespace test::jtx;
6177
6178 Env env{*this, features};
6179 Account const alice("alice"), bob("bob");
6180 ConfidentialEnv confEnv{
6181 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 50}}};
6182 auto& mptAlice = confEnv.mpt;
6183
6184 auto const spendingBalance = requireOptional(
6185 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending),
6186 "Missing spending balance");
6187 auto const encryptedSpendingBalance = requireOptional(
6188 mptAlice.getEncryptedBalance(bob, MPTTester::holderEncryptedSpending),
6189 "Missing encrypted spending balance");
6190 auto const version = mptAlice.getMPTokenVersion(bob);
6191 Buffer const pcBlindingFactor = generateBlindingFactor();
6192 Buffer const pedersenCommitment =
6193 mptAlice.getPedersenCommitment(spendingBalance, pcBlindingFactor);
6194
6195 // Generate a valid proof pi for Amount m1 = 10
6196 uint64_t const amtA = 10;
6197 uint32_t const currentSeq = env.seq(bob);
6198 UInt256 const contextHashA =
6199 getConvertBackContextHash(bob, mptAlice.issuanceID(), currentSeq, version);
6200
6201 auto const proofA = mptAlice.getConvertBackProof(
6202 bob,
6203 amtA,
6204 contextHashA,
6205 {
6206 .pedersenCommitment = pedersenCommitment,
6207 .amt = spendingBalance,
6208 .encryptedAmt = encryptedSpendingBalance,
6209 .blindingFactor = pcBlindingFactor,
6210 });
6211 if (!BEAST_EXPECT(proofA.has_value()))
6212 return;
6213
6214 // Construct Transaction B with Amount m2 = 20 and attach Proof pi
6215 uint64_t const amtB = 20;
6216 Buffer const blindingFactorB = generateBlindingFactor();
6217 Buffer const bobCiphertextB = mptAlice.encryptAmount(bob, amtB, blindingFactorB);
6218 Buffer const issuerCiphertextB = mptAlice.encryptAmount(alice, amtB, blindingFactorB);
6219
6220 // We attempt to verify the proof pi (for amt 10) against the new ciphertexts (for amt 20).
6221 mptAlice.convertBack({
6222 .account = bob,
6223 .amt = amtB,
6224 .proof = proofA, // Extracted/Reused proof from Transaction A
6225 .holderEncryptedAmt = bobCiphertextB,
6226 .issuerEncryptedAmt = issuerCiphertextB,
6227 .blindingFactor = blindingFactorB,
6228 .pedersenCommitment = pedersenCommitment,
6229 .err = tecBAD_PROOF, // Expected failure
6230 });
6231 }
6232
6233 // This test simulates a valid proof π and ciphertext are
6234 // tied to version v, but are reused after an inbox merge has incremented
6235 // the CBS version to v+1. It confirms the validator rejects the transaction
6236 // before acceptance due to the ContextID mismatch.
6237 void
6239 {
6240 testcase("ConvertBack: proof version mismatch");
6241 using namespace test::jtx;
6242
6243 Env env{*this, features};
6244 Account const alice("alice"), bob("bob");
6245 ConfidentialEnv confEnv{
6246 env, alice, {{.account = bob, .payAmount = 1000, .convertAmount = 100}}};
6247 auto& mptAlice = confEnv.mpt;
6248
6249 auto const versionV = mptAlice.getMPTokenVersion(bob);
6250 auto const spendingBalanceV = requireOptional(
6251 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending),
6252 "Missing spending balance");
6253 auto const encryptedSpendingBalanceV = requireOptional(
6254 mptAlice.getEncryptedBalance(bob, MPTTester::holderEncryptedSpending),
6255 "Missing encrypted spending balance");
6256
6257 // Parameters for the intended ConvertBack transaction
6258 uint64_t const amt = 10;
6259 Buffer const blindingFactor = generateBlindingFactor();
6260 Buffer const pcBlindingFactor = generateBlindingFactor();
6261 Buffer const pedersenCommitment =
6262 mptAlice.getPedersenCommitment(spendingBalanceV, pcBlindingFactor);
6263 Buffer const issuerCiphertext = mptAlice.encryptAmount(alice, amt, blindingFactor);
6264 Buffer const bobCiphertext = mptAlice.encryptAmount(bob, amt, blindingFactor);
6265
6266 // State Change: Increment version to v+1
6267 // Converting more funds and merging increments the sfConfidentialBalanceVersion
6268 mptAlice.convert({
6269 .account = bob,
6270 .amt = 50,
6271 });
6272 mptAlice.mergeInbox({
6273 .account = bob,
6274 });
6275
6276 BEAST_EXPECT(mptAlice.getMPTokenVersion(bob) > versionV);
6277
6278 // Attack: Attempt to reuse proof tied to Version v at ledger Version v+1
6279 uint32_t const currentSeq = env.seq(bob);
6280 // Proof is explicitly generated using the outdated Version v
6281 UInt256 const oldContextHash =
6282 getConvertBackContextHash(bob, mptAlice.issuanceID(), currentSeq, versionV);
6283
6284 auto const oldProof = mptAlice.getConvertBackProof(
6285 bob,
6286 amt,
6287 oldContextHash,
6288 {
6289 .pedersenCommitment = pedersenCommitment,
6290 .amt = spendingBalanceV,
6291 .encryptedAmt = encryptedSpendingBalanceV,
6292 .blindingFactor = pcBlindingFactor,
6293 });
6294 if (!BEAST_EXPECT(oldProof.has_value()))
6295 return;
6296
6297 // Submit and verify failure
6298 mptAlice.convertBack({
6299 .account = bob,
6300 .amt = amt,
6301 .proof = oldProof,
6302 .holderEncryptedAmt = bobCiphertext,
6303 .issuerEncryptedAmt = issuerCiphertext,
6304 .blindingFactor = blindingFactor,
6305 .pedersenCommitment = pedersenCommitment,
6306 .err = tecBAD_PROOF, // Fails because TransactionContextID differs
6307 });
6308 }
6309
6310 /* This test simulates an attack where the holder ciphertext is modified
6311 * via homomorphic addition (adding Encrypted_amt(1)) while leaving the issuer
6312 * ciphertext unchanged. It confirms that the validator detects the
6313 * mismatch between the re-computed ciphertexts and the submitted ones,
6314 * resulting in tecBAD_PROOF. */
6315 void
6317 {
6318 testcase("ConvertBack: homomorphic ciphertext modification");
6319 using namespace test::jtx;
6320
6321 Env env{*this, features};
6322 Account const alice("alice"), bob("bob");
6323 ConfidentialEnv confEnv{
6324 env, alice, {{.account = bob, .payAmount = 100, .convertAmount = 50}}};
6325 auto& mptAlice = confEnv.mpt;
6326
6327 // Prepare valid parameters for a ConvertBack of 10
6328 uint64_t const amt = 10;
6329 Buffer const bf = generateBlindingFactor();
6330
6331 auto const holderCipherText = mptAlice.encryptAmount(bob, amt, bf);
6332 auto const issuerCipherText = mptAlice.encryptAmount(alice, amt, bf);
6333
6334 // Generate a "Delta" ciphertext (Encrypting 1)
6335 // We use Bob's key because we are tampering with Bob's (Holder's) field
6336 Buffer const deltaBf = generateBlindingFactor();
6337 auto const deltaCipherText = mptAlice.encryptAmount(bob, 1, deltaBf);
6338
6339 // Homomorphically add Delta to HolderCipherText: Tampered = Enc(10) + Enc(1) = Enc(11)
6340 Buffer tamperedHolderCipherText = requireOptional(
6341 homomorphicAdd(holderCipherText, deltaCipherText), "Missing tampered ciphertext");
6342
6343 // Generate a valid proof for the ORIGINAL amount (10)
6344 auto const spendingBal = requireOptional(
6345 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending),
6346 "Missing spending balance");
6347 auto const spendingBalEnc = requireOptional(
6348 mptAlice.getEncryptedBalance(bob, MPTTester::holderEncryptedSpending),
6349 "Missing encrypted spending balance");
6350 Buffer const pcBf = generateBlindingFactor();
6351 auto const pedersenCommitment = mptAlice.getPedersenCommitment(spendingBal, pcBf);
6352
6353 auto const currentVersion = mptAlice.getMPTokenVersion(bob);
6354 // Uses the new signature: Account, IssuanceID, Sequence, Version
6355 UInt256 const contextHash =
6356 getConvertBackContextHash(bob, mptAlice.issuanceID(), env.seq(bob), currentVersion);
6357
6358 auto const proof = mptAlice.getConvertBackProof(
6359 bob,
6360 amt,
6361 contextHash,
6362 {
6363 .pedersenCommitment = pedersenCommitment,
6364 .amt = spendingBal,
6365 .encryptedAmt = spendingBalEnc,
6366 .blindingFactor = pcBf,
6367 });
6368 if (!BEAST_EXPECT(proof.has_value()))
6369 return;
6370
6371 // Submit transaction with Divergent Ciphertexts
6372 // Holder Ciphertext encrypts 11. Issuer Ciphertext encrypts 10.
6373 // The consistency check (re-encryption of `amt` with `bf`) will match Issuer but FAIL for
6374 // Holder.
6375 mptAlice.convertBack({
6376 .account = bob,
6377 .amt = amt,
6378 .proof = proof,
6379 .holderEncryptedAmt = tamperedHolderCipherText, // Tampered (11)
6380 .issuerEncryptedAmt = issuerCipherText, // Original (10)
6381 .blindingFactor = bf,
6382 .pedersenCommitment = pedersenCommitment,
6383 .err = tecBAD_PROOF,
6384 });
6385 }
6386
6387 /* This test verifies that xrpld correctly rejects attempts to
6388 * overflow the maximum allowable token amount via homomorphic manipulation.
6389 * It simulates an attack where an individual takes a valid ciphertext encrypting
6390 * the maximum amount (kMaxMpTokenAmount) and homomorphically adds an encryption of
6391 * 1 to it, producing a ciphertext for MAX+1. The test confirms that the Bulletproof
6392 * range proof or inner-product constraints detect this overflow and invalidate the
6393 * transaction, preserving the supply invariant. */
6394 void
6396 {
6397 testcase("Send: homomorphic overflow attack via Enc(MAX) + Enc(1)");
6398 using namespace test::jtx;
6399
6400 Env env{*this, features};
6401 Account const alice("alice"), bob("bob"), carol("carol");
6402 ConfidentialEnv confEnv{
6403 env,
6404 alice,
6405 {
6406 {.account = bob, .payAmount = 100, .convertAmount = 100},
6407 {.account = carol, .payAmount = 50, .convertAmount = 50},
6408 }};
6409 auto& mptAlice = confEnv.mpt;
6410
6411 // Bob sends 10 to carol. The send amount (10) and Bob's remaining balance
6412 // (90) are both within [0, kMaxMpTokenAmount]. Range proof passes.
6413 mptAlice.send({.account = bob, .dest = carol, .amt = 10});
6414
6415 // Bob's spending balance is 90 after the baseline send.
6416 auto const bobSpendingBefore =
6417 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending);
6418 BEAST_EXPECT(bobSpendingBefore == 90);
6419
6420 // Construct Enc(kMaxMpTokenAmount) with Bob's public key.
6421 Buffer const bf1 = generateBlindingFactor();
6422 Buffer const encMax = mptAlice.encryptAmount(bob, kMaxMpTokenAmount, bf1);
6423
6424 // Construct Enc(1) with a separate blinding factor.
6425 Buffer const bf2 = generateBlindingFactor();
6426 Buffer const encOne = mptAlice.encryptAmount(bob, 1, bf2);
6427
6428 // Homomorphically add to produce CB_S_holder' = Enc(MAX) + Enc(1)
6429 Buffer overflowedCt =
6430 requireOptional(homomorphicAdd(encMax, encOne), "Missing overflowed ciphertext");
6431
6432 // Submit the send transaction with the tampered ciphertext.
6433 // Setting amt = kMaxMpTokenAmount + 1 drives proof generation for the
6434 // overflowed value. The bulletproof range check [0, kMaxMpTokenAmount]
6435 // rejects MAX+1; the validator must return tecBAD_PROOF.
6436 mptAlice.send({
6437 .account = bob,
6438 .dest = carol,
6439 .amt = kMaxMpTokenAmount + 1,
6440 .senderEncryptedAmt = overflowedCt,
6441 .err = tecBAD_PROOF,
6442 });
6443
6444 auto const bobSpendingAfter =
6445 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending);
6446 BEAST_EXPECT(bobSpendingBefore == bobSpendingAfter);
6447 }
6448
6449 /* This test ensures that the system prevents underflow attacks where a user
6450 * attempts to create a negative balance through homomorphic subtraction. It
6451 * simulates a scenario where an attacker takes a ciphertext encrypting zero
6452 * and subtracts an encryption of 1, resulting in a value of -1.
6453 * The test asserts that the range proof verification fails because the resulting
6454 * value falls outside the valid non-negative range [0, kMaxMpTokenAmount],
6455 * causing the validator to reject the transaction with tecBAD_PROOF. */
6456 void
6458 {
6459 testcase("ConvertBack: homomorphic underflow attack via Enc(0) - Enc(1)");
6460 using namespace test::jtx;
6461
6462 Env env{*this, features};
6463 Account const alice("alice"), bob("bob");
6464 ConfidentialEnv confEnv{
6465 env, alice, {{.account = bob, .payAmount = 10, .convertAmount = 10}}};
6466 auto& mptAlice = confEnv.mpt;
6467
6468 // Converting back 1 from 10 leaves remaining balance = 9 (non-negative).
6469 // Range proof [0, kMaxMpTokenAmount] passes.
6470 mptAlice.convertBack({.account = bob, .amt = 1});
6471
6472 // Bob's spending balance is now 9; public balance is 1.
6473 auto const bobSpendingBefore =
6474 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending);
6475 BEAST_EXPECT(bobSpendingBefore == 9);
6476 auto const bobPublicBefore = mptAlice.getBalance(bob);
6477 BEAST_EXPECT(bobPublicBefore == 1);
6478
6479 // Construct Enc(0) — the zero encrypted balance using Bob's key.
6480 Buffer const bf1 = generateBlindingFactor();
6481 Buffer const encZero = mptAlice.encryptAmount(bob, 0, bf1);
6482
6483 // Construct Enc(1) with a separate blinding factor.
6484 Buffer const bf2 = generateBlindingFactor();
6485 Buffer const encOne = mptAlice.encryptAmount(bob, 1, bf2);
6486
6487 // Homomorphically subtract to produce CB_S_holder' = Enc(0) − Enc(1)
6488 // = Enc(−1), which lies below [0, kMaxMpTokenAmount].
6489 Buffer underflowedCt =
6490 requireOptional(homomorphicSubtract(encZero, encOne), "Missing underflowed ciphertext");
6491
6492 // The underflowed value as uint64_t: 0 - 1 wraps to 0xFFFFFFFFFFFFFFFF.
6493 // Generate a real proof using this wrapped value. The validator must still reject it
6494 // because 0xFFFFFFFFFFFFFFFE (remaining balance) is outside [0, kMaxMpTokenAmount].
6495 constexpr std::uint64_t kUnderflowedAmt =
6496 static_cast<std::uint64_t>(0) - static_cast<std::uint64_t>(1);
6497
6498 Buffer const pcBf = generateBlindingFactor();
6499 Buffer const pedersenCommitment = mptAlice.getPedersenCommitment(kUnderflowedAmt, pcBf);
6500
6501 auto const currentVersion = mptAlice.getMPTokenVersion(bob);
6502 UInt256 const contextHash =
6503 getConvertBackContextHash(bob, mptAlice.issuanceID(), env.seq(bob), currentVersion);
6504
6505 auto const proof = mptAlice.getConvertBackProof(
6506 bob,
6507 1,
6508 contextHash,
6509 {
6510 .pedersenCommitment = pedersenCommitment,
6511 .amt = kUnderflowedAmt,
6512 .encryptedAmt = underflowedCt,
6513 .blindingFactor = pcBf,
6514 });
6515 if (!BEAST_EXPECT(proof.has_value()))
6516 return;
6517
6518 mptAlice.convertBack({
6519 .account = bob,
6520 .amt = 1,
6521 .proof = proof,
6522 .holderEncryptedAmt = underflowedCt,
6523 .pedersenCommitment = pedersenCommitment,
6524 .err = tecBAD_PROOF,
6525 });
6526
6527 // Supply invariant: both public and confidential balances must be unchanged
6528 // after the rejected attack.
6529 BEAST_EXPECT(mptAlice.getBalance(bob) == bobPublicBefore);
6530 auto const bobSpendingAfter =
6531 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending);
6532 BEAST_EXPECT(bobSpendingBefore == bobSpendingAfter);
6533 }
6534
6535 // Confidential sends carry encrypted amounts and a zero-knowledge proof.
6536 // Both are built from elliptic-curve math, so every coordinate in the
6537 // transaction must be a real point on the secp256k1 curve. These three
6538 // variants confirm the validator rejects garbage coordinates at the right
6539 // stage before any expensive cryptographic verification runs.
6540 void
6542 {
6543 testcase("Send: off-curve EC points");
6544 using namespace test::jtx;
6545
6546 // Variant A: garbage coordinate in ciphertext / commitment fields
6547 // getBadCiphertext() looks structurally valid (correct length, right
6548 // prefix byte 0x02) but its x-coordinate is 0xFF...FF, which does not
6549 // lie on secp256k1. Preflight must reject before any ledger access.
6550 {
6551 Account const alice("alice"), bob("bob"), carol("carol");
6552 Env env{*this, features};
6553 ConfidentialEnv confEnv{
6554 env,
6555 alice,
6556 {
6557 {.account = bob, .payAmount = 100, .convertAmount = 60},
6558 {.account = carol, .payAmount = 50, .convertAmount = 30},
6559 }};
6560 auto& mptAlice = confEnv.mpt;
6561
6562 // sender's encrypted amount has an invalid coordinate
6563 mptAlice.send({
6564 .account = bob,
6565 .dest = carol,
6566 .amt = 10,
6567 .proof = getTrivialSendProofHex(),
6568 .senderEncryptedAmt = getBadCiphertext(),
6569 .amountCommitment = getTrivialCommitment(),
6570 .balanceCommitment = getTrivialCommitment(),
6571 .err = temBAD_CIPHERTEXT,
6572 });
6573
6574 // recipient's encrypted amount has an invalid coordinate
6575 mptAlice.send({
6576 .account = bob,
6577 .dest = carol,
6578 .amt = 10,
6579 .proof = getTrivialSendProofHex(),
6580 .destEncryptedAmt = getBadCiphertext(),
6581 .amountCommitment = getTrivialCommitment(),
6582 .balanceCommitment = getTrivialCommitment(),
6583 .err = temBAD_CIPHERTEXT,
6584 });
6585
6586 // issuer's encrypted amount has an invalid coordinate
6587 mptAlice.send({
6588 .account = bob,
6589 .dest = carol,
6590 .amt = 10,
6591 .proof = getTrivialSendProofHex(),
6592 .issuerEncryptedAmt = getBadCiphertext(),
6593 .amountCommitment = getTrivialCommitment(),
6594 .balanceCommitment = getTrivialCommitment(),
6595 .err = temBAD_CIPHERTEXT,
6596 });
6597
6598 // The amount and balance commitments are single curve coordinates
6599 // used to tie the proof to the transfer amount and sender balance.
6600 // A commitment with a valid-looking prefix but an impossible
6601 // x-coordinate must also be rejected.
6602 Buffer badCommitment(kEcPedersenCommitmentLength);
6603 std::memset(badCommitment.data(), 0xFF, kEcPedersenCommitmentLength);
6604 badCommitment.data()[0] = kEcCompressedPrefixEvenY;
6605
6606 mptAlice.send({
6607 .account = bob,
6608 .dest = carol,
6609 .amt = 10,
6610 .proof = getTrivialSendProofHex(),
6611 .amountCommitment = badCommitment,
6612 .balanceCommitment = getTrivialCommitment(),
6613 .err = temMALFORMED,
6614 });
6615
6616 mptAlice.send({
6617 .account = bob,
6618 .dest = carol,
6619 .amt = 10,
6620 .proof = getTrivialSendProofHex(),
6621 .amountCommitment = getTrivialCommitment(),
6622 .balanceCommitment = badCommitment,
6623 .err = temMALFORMED,
6624 });
6625 }
6626
6627 // Variant B: garbage coordinates inside the ZKP proof blob
6628 // The proof blob has the right total byte length (so it passes the
6629 // length check at preflight), but every embedded coordinate is
6630 // 0xFF...FF — impossible on secp256k1. The proof verifier must detect
6631 // this and return tecBAD_PROOF without crashing.
6632 {
6633 Account const alice("alice"), bob("bob"), carol("carol");
6634 Env env{*this, features};
6635 ConfidentialEnv confEnv{
6636 env,
6637 alice,
6638 {
6639 {.account = bob, .payAmount = 100, .convertAmount = 60},
6640 {.account = carol, .payAmount = 50, .convertAmount = 30},
6641 }};
6642 auto& mptAlice = confEnv.mpt;
6643
6644 Buffer badProof(kEcSendProofLength);
6645 std::memset(badProof.data(), 0xFF, kEcSendProofLength);
6646 badProof.data()[0] = kEcCompressedPrefixEvenY;
6647
6648 mptAlice.send({
6649 .account = bob,
6650 .dest = carol,
6651 .amt = 10,
6652 .proof = strHex(badProof),
6653 .err = tecBAD_PROOF,
6654 });
6655 }
6656
6657 // Variant C: only one of the two ciphertext coordinates is bad
6658 // Each encrypted amount is two coordinates back-to-back: C1 then C2.
6659 // Both must be valid. These tests corrupt only one at a time to
6660 // confirm both are checked independently.
6661 {
6662 Account const alice("alice"), bob("bob"), carol("carol");
6663 Env env{*this, features};
6664 ConfidentialEnv confEnv{
6665 env,
6666 alice,
6667 {
6668 {.account = bob, .payAmount = 100, .convertAmount = 60},
6669 {.account = carol, .payAmount = 50, .convertAmount = 30},
6670 }};
6671 auto& mptAlice = confEnv.mpt;
6672
6673 // getTrivialCiphertext() has both C1 and C2 as valid (but trivial)
6674 // curve coordinates. We replace one half at a time with 0xFF...FF.
6675 auto const& tc = getTrivialCiphertext();
6676
6677 // C1 = bad (0xFF...FF), C2 = valid trivial point
6679 std::memset(badC1goodC2.data(), 0xFF, kEcGamalEncryptedTotalLength);
6680 badC1goodC2.data()[0] = kEcCompressedPrefixEvenY;
6682 badC1goodC2.data() + kEcCiphertextComponentLength,
6683 tc.data() + kEcCiphertextComponentLength,
6685
6686 // C1 = valid trivial point, C2 = bad (0xFF...FF)
6688 std::memset(goodC1badC2.data(), 0xFF, kEcGamalEncryptedTotalLength);
6689 std::memcpy(goodC1badC2.data(), tc.data(), kEcCiphertextComponentLength);
6691
6692 // sender's encrypted amount — bad C1
6693 mptAlice.send({
6694 .account = bob,
6695 .dest = carol,
6696 .amt = 10,
6697 .proof = getTrivialSendProofHex(),
6698 .senderEncryptedAmt = badC1goodC2,
6699 .amountCommitment = getTrivialCommitment(),
6700 .balanceCommitment = getTrivialCommitment(),
6701 .err = temBAD_CIPHERTEXT,
6702 });
6703
6704 // sender's encrypted amount — bad C2
6705 mptAlice.send({
6706 .account = bob,
6707 .dest = carol,
6708 .amt = 10,
6709 .proof = getTrivialSendProofHex(),
6710 .senderEncryptedAmt = goodC1badC2,
6711 .amountCommitment = getTrivialCommitment(),
6712 .balanceCommitment = getTrivialCommitment(),
6713 .err = temBAD_CIPHERTEXT,
6714 });
6715
6716 // recipient's encrypted amount — bad C1
6717 mptAlice.send({
6718 .account = bob,
6719 .dest = carol,
6720 .amt = 10,
6721 .proof = getTrivialSendProofHex(),
6722 .destEncryptedAmt = badC1goodC2,
6723 .amountCommitment = getTrivialCommitment(),
6724 .balanceCommitment = getTrivialCommitment(),
6725 .err = temBAD_CIPHERTEXT,
6726 });
6727
6728 // recipient's encrypted amount — bad C2
6729 mptAlice.send({
6730 .account = bob,
6731 .dest = carol,
6732 .amt = 10,
6733 .proof = getTrivialSendProofHex(),
6734 .destEncryptedAmt = goodC1badC2,
6735 .amountCommitment = getTrivialCommitment(),
6736 .balanceCommitment = getTrivialCommitment(),
6737 .err = temBAD_CIPHERTEXT,
6738 });
6739 }
6740 }
6741
6742 // Reject points from the wrong elliptic curve (wrong-group injection).
6743 //
6744 // An attacker might submit coordinates that come from a completely
6745 // different elliptic curve, for example, the one used in TLS
6746 // certificates (NIST P-256). If those coordinates happen to also be
6747 // valid points on secp256k1 (which is possible since both curves use
6748 // 256-bit fields), the format check at preflight will pass. However,
6749 // the zero-knowledge proof is built specifically for secp256k1: the
6750 // math inside the proof only holds for the right curve, so any
6751 // transaction carrying cross-curve data will still be rejected at
6752 // proof verification (tecBAD_PROOF).
6753 void
6755 {
6756 testcase("Send: wrong-group point injection rejected");
6757 using namespace test::jtx;
6758
6759 Env env{*this, features};
6760 Account const alice("alice"), bob("bob"), carol("carol");
6761 ConfidentialEnv confEnv{
6762 env,
6763 alice,
6764 {
6765 {.account = bob, .payAmount = 100, .convertAmount = 60},
6766 {.account = carol, .payAmount = 50, .convertAmount = 30},
6767 }};
6768 auto& mptAlice = confEnv.mpt;
6769
6770 // The x-coordinate of the NIST P-256 generator point — a real,
6771 // well-known value from a different elliptic curve (used in TLS
6772 // and certificates). This x-coordinate is also a valid secp256k1
6773 // point, so it passes preflight. Rejection happens at proof
6774 // verification because the ZKP is secp256k1-specific.
6775 //
6776 // P-256 generator x:
6777 // 6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296
6778 static constexpr std::uint8_t kP256GeneratorX[32] = {
6779 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6,
6780 0xE5, 0x63, 0xA4, 0x40, 0xF2, 0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB,
6781 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96,
6782 };
6783
6784 // A 66-byte encrypted amount using the P-256 x-coordinate for both halves.
6786 wrongGroupCt.data()[0] = kEcCompressedPrefixEvenY;
6787 std::memcpy(wrongGroupCt.data() + 1, kP256GeneratorX, 32);
6789 std::memcpy(wrongGroupCt.data() + kEcCiphertextComponentLength + 1, kP256GeneratorX, 32);
6790
6791 // A 33-byte commitment using the same wrong-curve x-coordinate.
6792 Buffer wrongGroupCommitment(kEcPedersenCommitmentLength);
6793 wrongGroupCommitment.data()[0] = kEcCompressedPrefixEvenY;
6794 std::memcpy(wrongGroupCommitment.data() + 1, kP256GeneratorX, 32);
6795
6796 // sender's encrypted amount uses a coordinate from the wrong curve
6797 mptAlice.send({
6798 .account = bob,
6799 .dest = carol,
6800 .amt = 10,
6801 .proof = getTrivialSendProofHex(),
6802 .senderEncryptedAmt = wrongGroupCt,
6803 .amountCommitment = getTrivialCommitment(),
6804 .balanceCommitment = getTrivialCommitment(),
6805 .err = tecBAD_PROOF,
6806 });
6807
6808 // recipient's encrypted amount uses a coordinate from the wrong curve
6809 mptAlice.send({
6810 .account = bob,
6811 .dest = carol,
6812 .amt = 10,
6813 .proof = getTrivialSendProofHex(),
6814 .destEncryptedAmt = wrongGroupCt,
6815 .amountCommitment = getTrivialCommitment(),
6816 .balanceCommitment = getTrivialCommitment(),
6817 .err = tecBAD_PROOF,
6818 });
6819
6820 // issuer's encrypted amount uses a coordinate from the wrong curve
6821 mptAlice.send({
6822 .account = bob,
6823 .dest = carol,
6824 .amt = 10,
6825 .proof = getTrivialSendProofHex(),
6826 .issuerEncryptedAmt = wrongGroupCt,
6827 .amountCommitment = getTrivialCommitment(),
6828 .balanceCommitment = getTrivialCommitment(),
6829 .err = tecBAD_PROOF,
6830 });
6831
6832 // amount commitment uses a coordinate from the wrong curve
6833 mptAlice.send({
6834 .account = bob,
6835 .dest = carol,
6836 .amt = 10,
6837 .proof = getTrivialSendProofHex(),
6838 .amountCommitment = wrongGroupCommitment,
6839 .balanceCommitment = getTrivialCommitment(),
6840 .err = tecBAD_PROOF,
6841 });
6842
6843 // balance commitment uses a coordinate from the wrong curve
6844 mptAlice.send({
6845 .account = bob,
6846 .dest = carol,
6847 .amt = 10,
6848 .proof = getTrivialSendProofHex(),
6849 .amountCommitment = getTrivialCommitment(),
6850 .balanceCommitment = wrongGroupCommitment,
6851 .err = tecBAD_PROOF,
6852 });
6853 }
6854
6855 // Reject an all-zero "null" public key.
6856 //
6857 // Every account in a confidential transfer needs a real public key —
6858 // a specific point on the secp256k1 curve derived from a secret number
6859 // only that account knows. An all-zero key (33 bytes of 0x00) is not
6860 // a real key. It has no secret behind it, and encrypting data to it
6861 // would not actually hide anything. The validator must reject it at
6862 // preflight so no account can ever register a broken key.
6863 void
6865 {
6866 testcase("Convert: all-zero public key rejected");
6867 using namespace test::jtx;
6868
6869 // 33 zero bytes — not a real public key; no valid secret maps to this.
6870 Buffer const nullKey = gMakeZeroBuffer(kEcPubKeyLength);
6871
6872 // Recipient (holder) tries to register an all-zero key.
6873 // Must be rejected so no account ends up with an unprotected balance.
6874 {
6875 Env env{*this, features};
6876 Account const alice("alice"), bob("bob"), carol("carol");
6877 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
6878 mptAlice.create({
6879 .ownerCount = 1,
6880 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
6881 });
6882 mptAlice.authorize({.account = bob});
6883 mptAlice.authorize({.account = carol});
6884 mptAlice.pay(alice, bob, 100);
6885 mptAlice.pay(alice, carol, 50);
6886 mptAlice.generateKeyPair(alice);
6887 mptAlice.generateKeyPair(bob);
6888 mptAlice.generateKeyPair(carol);
6889 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
6890
6891 // recipient (carol) tries to register an all-zero key
6892 mptAlice.convert({
6893 .account = carol,
6894 .amt = 10,
6895 .holderPubKey = nullKey,
6896 .err = temMALFORMED,
6897 });
6898
6899 // sender (bob) tries to register an all-zero key
6900 mptAlice.convert({
6901 .account = bob,
6902 .amt = 10,
6903 .holderPubKey = nullKey,
6904 .err = temMALFORMED,
6905 });
6906 }
6907
6908 // Issuer tries to register an all-zero key.
6909 // The issuer's key is used to encrypt the issuer's copy of every
6910 // transfer amount.
6911 {
6912 Env env{*this, features};
6913 Account const alice("alice"), bob("bob");
6914 MPTTester mptAlice(env, alice, {.holders = {bob}});
6915 mptAlice.create({
6916 .ownerCount = 1,
6917 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
6918 });
6919 mptAlice.authorize({.account = bob});
6920 mptAlice.pay(alice, bob, 100);
6921 mptAlice.generateKeyPair(alice);
6922 mptAlice.generateKeyPair(bob);
6923
6924 mptAlice.set({
6925 .account = alice,
6926 .issuerPubKey = nullKey,
6927 .err = temMALFORMED,
6928 });
6929 }
6930 }
6931
6932 /* This test ensures that when sending confidential tokens, the encrypted
6933 * amounts are securely locked to the correct accounts' official public keys.
6934 *
6935 * Attack scenario — Encrypting the issuer's copy with the wrong key:
6936 * A sender correctly encrypts the hidden transfer amount for themselves
6937 * and the receiver. However, they intentionally encrypt the issuer's
6938 * copy of the data using the wrong public key (for example, using the
6939 * receiver's key instead of the official issuer's key). */
6940 void
6942 {
6943 testcase("Send: issuer ciphertext encrypted under wrong public key");
6944 using namespace test::jtx;
6945
6946 Env env{*this, features};
6947 Account const alice("alice"), bob("bob"), carol("carol");
6948 ConfidentialEnv confEnv{
6949 env,
6950 alice,
6951 {
6952 {.account = bob, .payAmount = 100, .convertAmount = 100},
6953 {.account = carol, .payAmount = 50, .convertAmount = 50},
6954 }};
6955 auto& mptAlice = confEnv.mpt;
6956
6957 auto const bobSpendingBefore =
6958 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending);
6959
6960 // issuer ciphertext encrypted under carol's holder key
6961 // (should be under alice's registered issuer key).
6962 {
6963 Buffer const bf = generateBlindingFactor();
6964 Buffer const wrongIssuerCt = mptAlice.encryptAmount(carol, 10, bf);
6965
6966 mptAlice.send({
6967 .account = bob,
6968 .dest = carol,
6969 .amt = 10,
6970 .issuerEncryptedAmt = wrongIssuerCt,
6971 .err = tecBAD_PROOF,
6972 });
6973 }
6974
6975 // issuer ciphertext encrypted under bob's holder key
6976 // (the sender's own key — still not the registered issuer key).
6977 {
6978 Buffer const bf = generateBlindingFactor();
6979 Buffer const wrongIssuerCt = mptAlice.encryptAmount(bob, 10, bf);
6980
6981 mptAlice.send({
6982 .account = bob,
6983 .dest = carol,
6984 .amt = 10,
6985 .issuerEncryptedAmt = wrongIssuerCt,
6986 .err = tecBAD_PROOF,
6987 });
6988 }
6989
6990 // all balances unchanged
6991 BEAST_EXPECT(
6992 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending) ==
6993 bobSpendingBefore);
6994 BEAST_EXPECT(mptAlice.getDecryptedBalance(carol, MPTTester::holderEncryptedInbox) == 0);
6995 }
6996
6997 // This test verifies that the compact AND-composed Send sigma proof
6998 // enforces the shared-randomness invariant across participants.
6999 void
7001 {
7002 testcase("divergent C1 across participants in ConfidentialMPTSend");
7003 using namespace test::jtx;
7004
7005 Env env{*this, features};
7006 Account const alice("alice");
7007 Account const bob("bob");
7008 Account const carol("carol");
7009 Account const auditor("auditor");
7010 ConfidentialEnv confEnv{
7011 env,
7012 alice,
7013 {
7014 {.account = bob, .payAmount = 100, .convertAmount = 50},
7015 {.account = carol, .payAmount = 50, .convertAmount = 50},
7016 },
7017 tfMPTCanLock | tfMPTCanHoldConfidentialBalance | tfMPTCanTransfer,
7018 auditor};
7019 auto& mptAlice = confEnv.mpt;
7020
7021 // Send amount is 10.
7022 uint64_t const amt = 10;
7023
7024 enum class Participant { Sender, Dest, Issuer, Auditor };
7025
7026 // This lambda submits a send transaction where one of the four ciphertexts
7027 // is encrypted with different randomness than the one used to build the proof.
7028 // Note: When divergent is nullopt, all participants
7029 // will use the same randomness and expected to succeed, this is the
7030 // control case that confirms the test setup itself is sound, the bad proof
7031 // is actually from divergent randomness, not other causes.
7032 auto const submitWithDivergentC1 = [&](std::optional<Participant> divergent) {
7033 ConfidentialSendSetup setup(mptAlice, bob, carol, alice, amt, std::cref(auditor));
7034
7035 auto const proofOpt =
7036 requireOptional(setup.generateProof(mptAlice, env, bob, carol), "Missing proof");
7037
7038 // Re-encrypt one participant's ciphertext with divergent randomness.
7039 Buffer senderCt = setup.senderAmt;
7040 Buffer destCt = setup.destAmt;
7041 Buffer issuerCt = setup.issuerAmt;
7042 Buffer auditorCt =
7043 requireOptionalRef(setup.auditorAmt, "Missing auditor encrypted amount");
7044 if (divergent)
7045 {
7046 Buffer const bfDivergent = generateBlindingFactor();
7047 switch (*divergent)
7048 {
7049 case Participant::Sender:
7050 senderCt = mptAlice.encryptAmount(bob, amt, bfDivergent);
7051 break;
7052 case Participant::Dest:
7053 destCt = mptAlice.encryptAmount(carol, amt, bfDivergent);
7054 break;
7055 case Participant::Issuer:
7056 issuerCt = mptAlice.encryptAmount(alice, amt, bfDivergent);
7057 break;
7058 case Participant::Auditor:
7059 auditorCt = mptAlice.encryptAmount(auditor, amt, bfDivergent);
7060 break;
7061 }
7062 }
7063
7064 TER const expectedErr = divergent ? TER{tecBAD_PROOF} : TER{tesSUCCESS};
7065
7066 mptAlice.send({
7067 .account = bob,
7068 .dest = carol,
7069 .amt = amt,
7070 .proof = strHex(proofOpt),
7071 .senderEncryptedAmt = senderCt,
7072 .destEncryptedAmt = destCt,
7073 .issuerEncryptedAmt = issuerCt,
7074 .auditorEncryptedAmt = auditorCt,
7075 .blindingFactor = setup.blindingFactor,
7076 .amountCommitment = setup.amountCommitment,
7077 .balanceCommitment = setup.balanceCommitment,
7078 .err = expectedErr,
7079 });
7080
7081 // Verify balances.
7082 auto const spendingAfter =
7083 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending);
7084 if (divergent)
7085 {
7086 BEAST_EXPECT(spendingAfter == setup.prevSpending);
7087 }
7088 else
7089 {
7090 BEAST_EXPECT(spendingAfter == setup.prevSpending - amt);
7091 }
7092 };
7093
7094 // This confirms the test setup is sound, if any of the divergent cases below
7095 // fail, it is due to the C1 mismatch and not a setup bug.
7096 submitWithDivergentC1(std::nullopt);
7097
7098 // Divergent C1 for different participants should all fail with tecBAD_PROOF:
7099 submitWithDivergentC1(Participant::Sender);
7100 submitWithDivergentC1(Participant::Dest);
7101 submitWithDivergentC1(Participant::Issuer);
7102 submitWithDivergentC1(Participant::Auditor);
7103 }
7104
7105 void
7107 {
7108 testcase("test confidential transactions fee");
7109 using namespace test::jtx;
7110
7111 auto const setup =
7112 [&](MPTTester& mpt, Account const& alice, Account const& bob, Account const& carol) {
7113 mpt.create({
7114 .ownerCount = 1,
7115 .flags = tfMPTCanLock | tfMPTCanHoldConfidentialBalance | tfMPTCanTransfer |
7116 tfMPTCanClawback,
7117 });
7118 mpt.authorize({.account = bob});
7119 mpt.authorize({.account = carol});
7120 mpt.pay(alice, bob, 100);
7121 mpt.pay(alice, carol, 50);
7122 mpt.generateKeyPair(alice);
7123 mpt.generateKeyPair(bob);
7124 mpt.generateKeyPair(carol);
7125 mpt.set({.account = alice, .issuerPubKey = mpt.getPubKey(alice)});
7126 };
7127
7128 // test expected base fee for confidential transactions
7129 {
7130 Env env{*this, features};
7131 Account const alice("alice"), bob("bob"), carol("carol");
7132 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
7133 setup(mptAlice, alice, bob, carol);
7134
7135 auto const baseFee = env.current()->fees().base;
7136 auto const expectedFee = baseFee * (kConfidentialFeeMultiplier + 1);
7137
7138 // lambda function to submit confidential transaction and check fee charged to the
7139 // account
7140 auto const checkFee = [&](Account const& acct, auto&& submitFn) {
7141 auto const before = env.balance(acct);
7142 submitFn();
7143 auto const after = env.balance(acct);
7144 BEAST_EXPECT(before - after == expectedFee);
7145 };
7146
7147 checkFee(bob, [&] {
7148 mptAlice.convert({
7149 .account = bob,
7150 .amt = 50,
7151 .holderPubKey = mptAlice.getPubKey(bob),
7152 .fee = expectedFee,
7153 });
7154 });
7155 checkFee(carol, [&] {
7156 mptAlice.convert({
7157 .account = carol,
7158 .amt = 10,
7159 .holderPubKey = mptAlice.getPubKey(carol),
7160 .fee = expectedFee,
7161 });
7162 });
7163 checkFee(bob, [&] { mptAlice.mergeInbox({.account = bob, .fee = expectedFee}); });
7164 checkFee(carol, [&] { mptAlice.mergeInbox({.account = carol, .fee = expectedFee}); });
7165 checkFee(bob, [&] {
7166 mptAlice.send({.account = bob, .dest = carol, .amt = 5, .fee = expectedFee});
7167 });
7168 checkFee(
7169 bob, [&] { mptAlice.convertBack({.account = bob, .amt = 5, .fee = expectedFee}); });
7170 checkFee(alice, [&] {
7171 mptAlice.confidentialClaw(
7172 {.account = alice, .holder = carol, .amt = 15, .fee = expectedFee});
7173 });
7174
7175 // Check fee for the mirror update transaction.
7176 Account const newIssuerKey("newIssuerKey");
7177 mptAlice.generateKeyPair(newIssuerKey);
7178 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(newIssuerKey)});
7179 checkFee(alice, [&] {
7180 mptAlice.mirrorUpdate({
7181 .account = alice,
7182 .holder = bob,
7183 .issuerEncryptedAmount = getTrivialCiphertext(),
7184 .fee = expectedFee,
7185 });
7186 });
7187 }
7188
7189 // test insufficient fee for confidential transactions
7190 {
7191 Env env{*this, features};
7192 Account const alice("alice"), bob("bob"), carol("carol");
7193 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
7194 setup(mptAlice, alice, bob, carol);
7195 auto const baseFee = env.current()->fees().base;
7196 auto const expectedFee = baseFee * (kConfidentialFeeMultiplier + 1);
7197
7198 mptAlice.convert({
7199 .account = bob,
7200 .amt = 1,
7201 .holderPubKey = mptAlice.getPubKey(bob),
7202 .fee = expectedFee - 1,
7203 .err = telINSUF_FEE_P,
7204 });
7205 mptAlice.mergeInbox({.account = bob, .fee = baseFee, .err = telINSUF_FEE_P});
7206 mptAlice.send({
7207 .account = bob,
7208 .dest = carol,
7209 .amt = 1,
7210 .fee = baseFee * kConfidentialFeeMultiplier,
7211 .err = telINSUF_FEE_P,
7212 });
7213 mptAlice.convertBack({.account = bob, .amt = 1, .fee = baseFee, .err = telINSUF_FEE_P});
7214 mptAlice.confidentialClaw({
7215 .account = alice,
7216 .holder = carol,
7217 .amt = 1,
7218 .fee = baseFee,
7219 .err = telINSUF_FEE_P,
7220 });
7221 mptAlice.mirrorUpdate({
7222 .account = alice,
7223 .holder = bob,
7224 .issuerEncryptedAmount = getTrivialCiphertext(),
7225 .fee = baseFee,
7226 .err = telINSUF_FEE_P,
7227 });
7228 }
7229
7230 // test excessive fee for confidential transactions
7231 {
7232 Env env{*this, features};
7233 Account const alice("alice"), bob("bob"), carol("carol");
7234 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
7235 setup(mptAlice, alice, bob, carol);
7236
7237 auto const baseFee = env.current()->fees().base;
7238 auto const highFee = baseFee * (kConfidentialFeeMultiplier + 1) * 2;
7239 auto const bobBefore = env.balance(bob);
7240 mptAlice.convert({
7241 .account = bob,
7242 .amt = 1,
7243 .holderPubKey = mptAlice.getPubKey(bob),
7244 .fee = highFee,
7245 });
7246 BEAST_EXPECT(env.balance(bob) == bobBefore - highFee);
7247 }
7248 }
7249
7250 void
7252 {
7253 testcase("Send: forged equality proof");
7254
7255 // Test that modifying a ciphertext after proof generation causes
7256 // verification to fail. The Fiat-Shamir challenge binds ciphertexts
7257 // to the proof, so any modification invalidates the proof.
7258
7259 using namespace test::jtx;
7260 Env env{*this, features};
7261 Account const alice("alice"), bob("bob"), carol("carol");
7262 ConfidentialEnv confEnv{
7263 env,
7264 alice,
7265 {{.account = bob}, {.account = carol, .payAmount = 1000, .convertAmount = 50}}};
7266 auto& mptAlice = confEnv.mpt;
7267
7268 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, 10);
7269
7270 // Forge destination ciphertext (Enc(20) instead of Enc(10))
7271 {
7272 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7273 if (!BEAST_EXPECT(proof.has_value()))
7274 return;
7275
7276 Buffer const forgedBlindingFactor = generateBlindingFactor();
7277 auto const forgedDestAmt = mptAlice.encryptAmount(carol, 20, forgedBlindingFactor);
7278
7279 auto args = setup.sendArgs(
7280 bob, carol, requireOptionalRef(proof, "Missing proof"), tecBAD_PROOF);
7281 args.destEncryptedAmt = forgedDestAmt;
7282 mptAlice.send(args);
7283 }
7284
7285 // Forge sender's ciphertext (Enc(5) instead of Enc(10))
7286 {
7287 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7288 if (!BEAST_EXPECT(proof.has_value()))
7289 return;
7290
7291 Buffer const forgedBlindingFactor = generateBlindingFactor();
7292 auto const forgedSenderAmt = mptAlice.encryptAmount(bob, 5, forgedBlindingFactor);
7293
7294 auto args = setup.sendArgs(
7295 bob, carol, requireOptionalRef(proof, "Missing proof"), tecBAD_PROOF);
7296 args.senderEncryptedAmt = forgedSenderAmt;
7297 mptAlice.send(args);
7298 }
7299
7300 // Forge issuer's ciphertext (Enc(100) instead of Enc(10))
7301 {
7302 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7303 if (!BEAST_EXPECT(proof.has_value()))
7304 return;
7305
7306 Buffer const forgedBlindingFactor = generateBlindingFactor();
7307 auto const forgedIssuerAmt = mptAlice.encryptAmount(alice, 100, forgedBlindingFactor);
7308
7309 auto args = setup.sendArgs(
7310 bob, carol, requireOptionalRef(proof, "Missing proof"), tecBAD_PROOF);
7311 args.issuerEncryptedAmt = forgedIssuerAmt;
7312 mptAlice.send(args);
7313 }
7314 }
7315
7316 void
7318 {
7319 testcase("Send: forged range proof");
7320
7321 // Attack: send uint64_max tokens using Enc(uint64_max) ciphertexts
7322 // and a corrupted bulletproof. Verifier rejects due to inner-product
7323 // mismatch and Fiat-Shamir transcript divergence. Supply invariant
7324 // is preserved.
7325
7326 using namespace test::jtx;
7327 Env env{*this, features};
7328 Account const alice("alice"), bob("bob"), carol("carol");
7329 ConfidentialEnv confEnv{
7330 env,
7331 alice,
7332 {{.account = bob}, {.account = carol, .payAmount = 1000, .convertAmount = 50}}};
7333 auto& mptAlice = confEnv.mpt;
7334
7335 uint64_t const badAmount = std::numeric_limits<uint64_t>::max();
7336 Buffer const blindingFactor = generateBlindingFactor();
7337
7338 // Construct Enc(uint64_max) ciphertexts and commitment.
7339 auto const senderAmt = mptAlice.encryptAmount(bob, badAmount, blindingFactor);
7340 auto const destAmt = mptAlice.encryptAmount(carol, badAmount, blindingFactor);
7341 auto const issuerAmt = mptAlice.encryptAmount(alice, badAmount, blindingFactor);
7342 auto const amountCommitment = mptAlice.getPedersenCommitment(badAmount, blindingFactor);
7343
7344 // Balance commitment for Bob's actual balance.
7345 auto const prevSpending = requireOptional(
7346 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending),
7347 "Missing previous spending balance");
7348 auto const balanceBlindingFactor = generateBlindingFactor();
7349 auto const balanceCommitment =
7350 mptAlice.getPedersenCommitment(prevSpending, balanceBlindingFactor);
7351
7352 // Generate a valid proof for a legitimate amount, then corrupt
7353 // the bulletproof segment to simulate a forged range proof.
7354 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, 10);
7355 auto const validProof = setup.generateProof(mptAlice, env, bob, carol);
7356 if (!BEAST_EXPECT(validProof.has_value()))
7357 return;
7358
7359 // Corrupt bulletproof bytes.
7360 Buffer forgedProof = requireOptional(validProof, "Missing valid proof");
7361 for (size_t i = kBulletproofOffset; i < forgedProof.size(); i += 7)
7362 forgedProof.data()[i] ^= 0xFF;
7363
7364 // Submit — rejected due to commitment mismatch.
7365 mptAlice.send({
7366 .account = bob,
7367 .dest = carol,
7368 .amt = badAmount,
7369 .proof = strHex(forgedProof),
7370 .senderEncryptedAmt = senderAmt,
7371 .destEncryptedAmt = destAmt,
7372 .issuerEncryptedAmt = issuerAmt,
7373 .amountCommitment = amountCommitment,
7374 .balanceCommitment = balanceCommitment,
7375 .err = tecBAD_PROOF,
7376 });
7377
7378 // Supply invariant: Bob's balance unchanged.
7379 auto const postSpending = requireOptional(
7380 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending),
7381 "Missing post spending balance");
7382 BEAST_EXPECT(postSpending == prevSpending);
7383 }
7384
7385 void
7387 {
7388 testcase("Send: negative value malleability");
7389
7390 // Attack: forge a bulletproof claiming remaining = (uint64_t)(-10).
7391 // Bob has 10 tokens, sends 10. Honest remaining is 0, but the
7392 // forged proof claims 0xFFFFFFFFFFFFFFF6. Rejected because
7393 // PC(0) != PC(0xFFFFFFFFFFFFFFF6).
7394
7395 using namespace test::jtx;
7396 // Bob converts exactly 10 tokens, leaving honest remaining = 0.
7397 Env env{*this, features};
7398 Account const alice("alice"), bob("bob"), carol("carol");
7399 ConfidentialEnv confEnv{
7400 env,
7401 alice,
7402 {
7403 {.account = bob, .payAmount = 1000, .convertAmount = 10},
7404 {.account = carol, .payAmount = 1000, .convertAmount = 50},
7405 }};
7406 auto& mptAlice = confEnv.mpt;
7407
7408 uint64_t const sendAmount = 10;
7409 auto const negativeRemaining = static_cast<uint64_t>(-10); // 0xFFFFFFFFFFFFFFF6
7410
7411 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, sendAmount);
7412
7413 auto const ctxHash = getSendContextHash(
7414 bob.id(), mptAlice.issuanceID(), env.seq(bob), carol.id(), setup.version);
7415
7416 auto const validProof = setup.generateProof(mptAlice, env, bob, carol);
7417 if (!BEAST_EXPECT(validProof.has_value()))
7418 return;
7419
7420 // Forge bulletproof for {10, 0xFFFFFFFFFFFFFFF6} and splice it in.
7421 auto const forgedBulletproof = getForgedBulletproof(
7422 {sendAmount, negativeRemaining},
7424 ctxHash);
7425
7426 Buffer forgedProof(requireOptionalRef(validProof, "Missing valid proof").size());
7428 forgedProof.data(),
7429 requireOptionalRef(validProof, "Missing valid proof").data(),
7432 forgedProof.data() + kBulletproofOffset,
7433 forgedBulletproof.data(),
7435
7436 mptAlice.send(setup.sendArgs(bob, carol, forgedProof, tecBAD_PROOF));
7437
7438 // Supply invariant: Bob's balance unchanged.
7439 auto const postSpending = requireOptional(
7440 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending),
7441 "Missing post spending balance");
7442 BEAST_EXPECT(postSpending == setup.prevSpending);
7443 }
7444
7445 void
7447 {
7448 testcase("Send proof context binding");
7449 using namespace test::jtx;
7450
7451 auto const runBadProof = [&](auto makeContextHash) {
7452 Env env{*this, features};
7453 Account const alice("alice");
7454 Account const bob("bob");
7455 Account const carol("carol");
7456 ConfidentialEnv confEnv{
7457 env,
7458 alice,
7459 {{.account = bob, .payAmount = 100, .convertAmount = 40}, {.account = carol}}};
7460 auto& mptAlice = confEnv.mpt;
7461
7462 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, 10);
7463
7464 auto const proof = mptAlice.getConfidentialSendProof(
7465 bob,
7466 setup.sendAmount,
7467 setup.recipients,
7468 setup.blindingFactor,
7469 makeContextHash(env, mptAlice, alice, bob, carol, setup.version),
7470 {
7471 .pedersenCommitment = setup.amountCommitment,
7472 .amt = setup.sendAmount,
7473 .encryptedAmt = setup.senderAmt,
7474 .blindingFactor = setup.amountBlindingFactor,
7475 },
7476 {
7477 .pedersenCommitment = setup.balanceCommitment,
7478 .amt = setup.prevSpending,
7479 .encryptedAmt = setup.prevEncryptedSpending,
7480 .blindingFactor = setup.balanceBlindingFactor,
7481 });
7482 if (!BEAST_EXPECT(proof.has_value()))
7483 return;
7484
7485 mptAlice.send(setup.sendArgs(
7486 bob, carol, requireOptionalRef(proof, "Missing proof"), tecBAD_PROOF));
7487 };
7488
7489 // Wrong sender account in the proof context.
7490 runBadProof([&](Env& env,
7491 MPTTester const& mpt,
7492 Account const&,
7493 Account const& bob,
7494 Account const& carol,
7495 std::uint32_t version) {
7496 return getSendContextHash(
7497 carol.id(), mpt.issuanceID(), env.seq(bob), carol.id(), version);
7498 });
7499
7500 // Wrong issuance ID in the proof context.
7501 runBadProof([&](Env& env,
7502 MPTTester const&,
7503 Account const& alice,
7504 Account const& bob,
7505 Account const& carol,
7506 std::uint32_t version) {
7507 return getSendContextHash(
7508 bob.id(),
7509 makeMptID(env.seq(alice) + 100, alice),
7510 env.seq(bob),
7511 carol.id(),
7512 version);
7513 });
7514
7515 // Wrong transaction sequence in the proof context.
7516 runBadProof([&](Env& env,
7517 MPTTester const& mpt,
7518 Account const&,
7519 Account const& bob,
7520 Account const& carol,
7521 std::uint32_t version) {
7522 return getSendContextHash(
7523 bob.id(), mpt.issuanceID(), env.seq(bob) + 1, carol.id(), version);
7524 });
7525
7526 // Wrong destination in the proof context.
7527 runBadProof([&](Env& env,
7528 MPTTester const& mpt,
7529 Account const&,
7530 Account const& bob,
7531 Account const&,
7532 std::uint32_t version) {
7533 return getSendContextHash(bob.id(), mpt.issuanceID(), env.seq(bob), bob.id(), version);
7534 });
7535
7536 // Wrong balance version in the proof context.
7537 runBadProof([&](Env& env,
7538 MPTTester const& mpt,
7539 Account const&,
7540 Account const& bob,
7541 Account const& carol,
7542 std::uint32_t version) {
7543 return getSendContextHash(
7544 bob.id(), mpt.issuanceID(), env.seq(bob), carol.id(), version + 1);
7545 });
7546 }
7547
7548 void
7550 {
7551 testcase("Send: Fiat-Shamir Binding");
7552
7553 using namespace test::jtx;
7554 Env env{*this, features};
7555 Account const alice("alice"), bob("bob"), carol("carol");
7556 ConfidentialEnv confEnv{
7557 env,
7558 alice,
7559 {{.account = bob}, {.account = carol, .payAmount = 1000, .convertAmount = 50}}};
7560 auto& mptAlice = confEnv.mpt;
7561
7562 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, 10);
7563
7564 // Variant A: forged amount commitment.
7565 {
7566 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7567 if (!BEAST_EXPECT(proof.has_value()))
7568 return;
7569
7570 auto const forgedBlindingFactor = generateBlindingFactor();
7571 auto const forgedCommitment =
7572 mptAlice.getPedersenCommitment(setup.sendAmount + 5, forgedBlindingFactor);
7573
7574 auto args = setup.sendArgs(
7575 bob, carol, requireOptionalRef(proof, "Missing proof"), tecBAD_PROOF);
7576 args.amountCommitment = forgedCommitment;
7577 mptAlice.send(args);
7578 }
7579
7580 // Variant B: proof replay at a different sequence.
7581 {
7582 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7583 if (!BEAST_EXPECT(proof.has_value()))
7584 return;
7585
7586 mptAlice.pay(bob, carol, 1);
7587 env.close();
7588
7589 mptAlice.send(setup.sendArgs(
7590 bob, carol, requireOptionalRef(proof, "Missing proof"), tecBAD_PROOF));
7591 }
7592
7593 // Variant C: tampered response scalars.
7594 {
7595 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7596 if (!BEAST_EXPECT(proof.has_value()))
7597 return;
7598
7599 auto const& proofRef = requireOptionalRef(proof, "Missing proof");
7600 Buffer tamperedProof(proofRef.size());
7601 std::memcpy(tamperedProof.data(), proofRef.data(), proofRef.size());
7602 size_t const tamperOffset = tamperedProof.size() / 2;
7603 tamperedProof.data()[tamperOffset] ^= 0xFF;
7604
7605 mptAlice.send(setup.sendArgs(bob, carol, tamperedProof, tecBAD_PROOF));
7606 }
7607 }
7608
7609 void
7611 {
7612 testcase("Send: Proof Component Reuse");
7613
7614 using namespace test::jtx;
7615 Env env{*this, features};
7616 Account const alice("alice"), bob("bob"), carol("carol"), dan("dan");
7617 ConfidentialEnv confEnv{
7618 env,
7619 alice,
7620 {
7621 {.account = bob},
7622 {.account = carol, .payAmount = 1000, .convertAmount = 50},
7623 {.account = dan, .payAmount = 1000, .convertAmount = 50},
7624 }};
7625 auto& mptAlice = confEnv.mpt;
7626
7627 uint64_t const sendAmount = 10;
7628
7629 // Variant A: replay proof to same destination after sequence changes.
7630 {
7631 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, sendAmount);
7632
7633 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7634 if (!BEAST_EXPECT(proof.has_value()))
7635 return;
7636
7637 mptAlice.send(setup.sendArgs(bob, carol, requireOptionalRef(proof, "Missing proof")));
7638 mptAlice.mergeInbox({.account = carol});
7639
7640 mptAlice.send(setup.sendArgs(
7641 bob, carol, requireOptionalRef(proof, "Missing proof"), tecBAD_PROOF));
7642 }
7643
7644 // Variant B: replay proof to a different destination.
7645 {
7646 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, sendAmount);
7647
7648 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7649 if (!BEAST_EXPECT(proof.has_value()))
7650 return;
7651
7652 mptAlice.send(setup.sendArgs(bob, carol, requireOptionalRef(proof, "Missing proof")));
7653 mptAlice.mergeInbox({.account = carol});
7654
7655 auto const destAmtDan = mptAlice.encryptAmount(dan, sendAmount, setup.blindingFactor);
7656 auto const issuerAmtDan =
7657 mptAlice.encryptAmount(alice, sendAmount, setup.blindingFactor);
7658
7659 auto args =
7660 setup.sendArgs(bob, dan, requireOptionalRef(proof, "Missing proof"), tecBAD_PROOF);
7661 args.destEncryptedAmt = destAmtDan;
7662 args.issuerEncryptedAmt = issuerAmtDan;
7663 mptAlice.send(args);
7664 }
7665 }
7666
7667 void
7669 {
7670 testcase("Send: special witness values");
7671
7672 using namespace test::jtx;
7673 Env env{*this, features};
7674 Account const alice("alice"), bob("bob"), carol("carol");
7675 ConfidentialEnv confEnv{
7676 env,
7677 alice,
7678 {{.account = bob}, {.account = carol, .payAmount = 1000, .convertAmount = 50}}};
7679 auto& mptAlice = confEnv.mpt;
7680
7681 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, 10);
7682
7683 // Variant A: zero-valued response scalars.
7684 {
7685 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7686 if (!BEAST_EXPECT(proof.has_value()))
7687 return;
7688
7689 Buffer forgedProof = requireOptionalRef(proof, "Missing proof");
7690
7691 static constexpr size_t kSigmaScalarSize = 32;
7692 static constexpr size_t kChallengeOffset = 0;
7693 static constexpr size_t kResponseOffset = kChallengeOffset + kSigmaScalarSize;
7694 static constexpr size_t kResponseSize = 5 * kSigmaScalarSize; // z_m..z_sk
7695 std::memset(forgedProof.data() + kResponseOffset, 0, kResponseSize);
7696
7697 mptAlice.send(setup.sendArgs(bob, carol, forgedProof, tecBAD_PROOF));
7698 }
7699
7700 // Variant B: identity element in ciphertext.
7701 {
7702 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7703 if (!BEAST_EXPECT(proof.has_value()))
7704 return;
7705
7706 Buffer invalidCiphertext(kEcGamalEncryptedTotalLength);
7707 std::memset(invalidCiphertext.data(), 0, kEcGamalEncryptedTotalLength);
7708
7709 auto args = setup.sendArgs(
7710 bob, carol, requireOptionalRef(proof, "Missing proof"), temBAD_CIPHERTEXT);
7711 args.senderEncryptedAmt = invalidCiphertext;
7712 mptAlice.send(args);
7713 }
7714
7715 // Variant B2: identity element in commitment.
7716 {
7717 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7718 if (!BEAST_EXPECT(proof.has_value()))
7719 return;
7720
7721 Buffer invalidCommitment(kEcPedersenCommitmentLength);
7722 std::memset(invalidCommitment.data(), 0, kEcPedersenCommitmentLength);
7723
7724 auto args = setup.sendArgs(
7725 bob, carol, requireOptionalRef(proof, "Missing proof"), temMALFORMED);
7726 args.amountCommitment = invalidCommitment;
7727 mptAlice.send(args);
7728 }
7729
7730 // Variant C: boundary scalar (curve order).
7731 {
7732 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7733 if (!BEAST_EXPECT(proof.has_value()))
7734 return;
7735
7736 Buffer forgedProof = requireOptionalRef(proof, "Missing proof");
7737
7738 static constexpr unsigned char kCurveOrder[32] = {
7739 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //
7740 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, //
7741 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, //
7742 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41, //
7743 };
7744
7745 std::memcpy(forgedProof.data() + 32, kCurveOrder, 32);
7746
7747 mptAlice.send(setup.sendArgs(bob, carol, forgedProof, tecBAD_PROOF));
7748 }
7749
7750 // Variant C2: overflow scalar (curve order + 1).
7751 {
7752 auto const proof = setup.generateProof(mptAlice, env, bob, carol);
7753 if (!BEAST_EXPECT(proof.has_value()))
7754 return;
7755
7756 Buffer forgedProof = requireOptionalRef(proof, "Missing proof");
7757
7758 static constexpr unsigned char kOverflowScalar[32] = {
7759 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //
7760 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, //
7761 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, //
7762 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x42, //
7763 };
7764
7765 std::memcpy(forgedProof.data() + 32, kOverflowScalar, 32);
7766
7767 mptAlice.send(setup.sendArgs(bob, carol, forgedProof, tecBAD_PROOF));
7768 }
7769 }
7770
7771 void
7773 {
7774 testcase("Send: cross-statement proof substitution");
7775
7776 // This test verifies that proofs generated for one protocol component
7777 // cannot be used in place of another, and that proofs bound to
7778 // different public parameters are rejected.
7779
7780 using namespace test::jtx;
7781 Env env{*this, features};
7782 Account const alice("alice"), bob("bob"), carol("carol");
7783 ConfidentialEnv confEnv{
7784 env,
7785 alice,
7786 {{.account = bob}, {.account = carol, .payAmount = 1000, .convertAmount = 50}},
7787 tfMPTCanLock | tfMPTCanHoldConfidentialBalance | tfMPTCanTransfer | tfMPTCanClawback};
7788 auto& mptAlice = confEnv.mpt;
7789
7790 uint64_t const sendAmount = 10;
7791
7792 // Variant A: Swap proof type (cross-statement substitution)
7793 // -----------------------------------------------------------------
7794 // Attack: Generate a valid convertBack proof (compact sigma +
7795 // single bulletproof) and attempt to use it as the ZK proof in a
7796 // ConfidentialMPTSend transaction.
7797 //
7798 // Expected: The send proof has a different structure
7799 // (equality + 2×pedersen + double bulletproof). Even if sized to
7800 // match, the domain-separated Fiat-Shamir transcript differs,
7801 // so verification equations fail.
7802 {
7803 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, sendAmount);
7804
7805 // Generate a valid convertBack proof for bob
7806 auto const spendingBalance = requireOptional(
7807 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending),
7808 "Missing spending balance");
7809 auto const encryptedSpending = requireOptional(
7810 mptAlice.getEncryptedBalance(bob, MPTTester::holderEncryptedSpending),
7811 "Missing encrypted spending balance");
7812
7813 Buffer const pcBlindingFactor = generateBlindingFactor();
7814 Buffer const pedersenCommitment =
7815 mptAlice.getPedersenCommitment(spendingBalance, pcBlindingFactor);
7816
7817 auto const version = mptAlice.getMPTokenVersion(bob);
7818 UInt256 const convertBackCtxHash =
7819 getConvertBackContextHash(bob.id(), mptAlice.issuanceID(), env.seq(bob), version);
7820
7821 auto const convertBackProof = mptAlice.getConvertBackProof(
7822 bob,
7823 sendAmount,
7824 convertBackCtxHash,
7825 {
7826 .pedersenCommitment = pedersenCommitment,
7827 .amt = spendingBalance,
7828 .encryptedAmt = encryptedSpending,
7829 .blindingFactor = pcBlindingFactor,
7830 });
7831 if (!BEAST_EXPECT(convertBackProof.has_value()))
7832 return;
7833
7834 // Resize the convertBack proof to match the expected send proof
7835 // size so it passes preflight's size check and reaches the actual
7836 // ZK verification in doApply.
7837 auto const expectedSendSize = kEcSendProofLength;
7838 Buffer resizedProof(expectedSendSize);
7839 Buffer const& convertBackProofRef =
7840 requireOptionalRef(convertBackProof, "Missing proof");
7841 auto const copyLen = std::min(convertBackProofRef.size(), expectedSendSize);
7842 std::memcpy(resizedProof.data(), convertBackProofRef.data(), copyLen);
7843 // Zero-pad the rest (if convertBack proof is shorter)
7844 if (copyLen < expectedSendSize)
7845 std::memset(resizedProof.data() + copyLen, 0, expectedSendSize - copyLen);
7846
7847 mptAlice.send(setup.sendArgs(bob, carol, resizedProof, tecBAD_PROOF));
7848 }
7849
7850 // Variant B: Valid proof bound to wrong public parameters
7851 // -----------------------------------------------------------------
7852 // Attack: Generate a valid send proof using a wrong context hash
7853 // (computed with a different issuanceID). The proof is
7854 // mathematically valid for the wrong statement, but when the
7855 // verifier recomputes the Fiat-Shamir challenge using the correct
7856 // issuanceID, the challenge differs and verification fails.
7857 {
7858 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, sendAmount);
7859
7860 // Compute context hash with a fabricated (wrong) issuanceID
7861 UInt192 const fakeIssuanceID{1};
7862 auto const wrongCtxHash = getSendContextHash(
7863 bob.id(), fakeIssuanceID, env.seq(bob), carol.id(), setup.version);
7864
7865 // Generate a proof that is valid for the wrong issuanceID
7866 auto const wrongProof = mptAlice.getConfidentialSendProof(
7867 bob,
7868 sendAmount,
7869 setup.recipients,
7870 setup.blindingFactor,
7871 wrongCtxHash,
7872 {
7873 .pedersenCommitment = setup.amountCommitment,
7874 .amt = sendAmount,
7875 .encryptedAmt = setup.senderAmt,
7876 .blindingFactor = setup.amountBlindingFactor,
7877 },
7878 {
7879 .pedersenCommitment = setup.balanceCommitment,
7880 .amt = setup.prevSpending,
7881 .encryptedAmt = setup.prevEncryptedSpending,
7882 .blindingFactor = setup.balanceBlindingFactor,
7883 });
7884
7885 if (!BEAST_EXPECT(wrongProof.has_value()))
7886 return;
7887
7888 // Submit with the correct issuanceID — verifier recomputes
7889 // the challenge using the real issuanceID, which differs from
7890 // the one baked into the proof.
7891 mptAlice.send(setup.sendArgs(
7892 bob, carol, requireOptionalRef(wrongProof, "Missing wrong proof"), tecBAD_PROOF));
7893 }
7894 }
7895
7896 void
7898 {
7899 testcase("Send: ciphertext malleability");
7900
7901 // Attack: replace ElGamal ciphertext Enc(m) with Enc(2m) to inflate
7902 // the amount credited to the recipient. ElGamal is homomorphic, so
7903 // scalar multiplication (C1, C2) → (k*C1, k*C2) decrypts to k*m.
7904
7905 using namespace test::jtx;
7906 Env env{*this, features};
7907 Account const alice("alice"), bob("bob"), carol("carol");
7908 ConfidentialEnv confEnv{
7909 env,
7910 alice,
7911 {{.account = bob}, {.account = carol, .payAmount = 1000, .convertAmount = 50}},
7912 tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance};
7913 auto& mptAlice = confEnv.mpt;
7914
7915 uint64_t const sendAmount = 10;
7916
7917 // Variant A: Post-signature tampering.
7918 // Build a valid signed transaction, then replace the destination
7919 // ciphertext with Enc(2m) in the serialized blob. The original
7920 // signature no longer covers the modified data.
7921 {
7922 auto const seq = env.seq(bob);
7923 auto const jv =
7924 mptAlice.sendJV({.account = bob, .dest = carol, .amt = sendAmount}, seq);
7925 auto const jtx = env.jt(jv);
7926 BEAST_EXPECT(jtx.stx);
7927
7928 // Serialize signed tx, deserialize into mutable STObject
7929 Serializer s;
7930 jtx.stx->add(s);
7931 SerialIter sit(s.slice());
7932 STObject obj(sit, sfTransaction);
7933
7934 // Replace dest ciphertext with Enc(2m) — a valid EC point
7935 // encrypting an inflated amount under carol's key
7936 Buffer const bf = generateBlindingFactor();
7937 auto const inflatedCiphertext = mptAlice.encryptAmount(carol, sendAmount * 2, bf);
7938 obj.setFieldVL(sfDestinationEncryptedAmount, inflatedCiphertext);
7939
7940 // Re-serialize with the original (now-stale) signature
7941 Serializer tampered;
7942 obj.add(tampered);
7943
7944 // Signature verification fails — rejected before ZKP check
7945 auto const jr = env.rpc("submit", strHex(tampered.slice()));
7946 BEAST_EXPECT(jr[jss::result][jss::error] == "invalidTransaction");
7947 BEAST_EXPECT(!jr[jss::result].isMember(jss::error_code));
7948 BEAST_EXPECT(jr[jss::result][jss::error_message].isNull());
7949 }
7950
7951 // Variant B: Re-signed with inflated ciphertext.
7952 // Generate a valid proof for amount m, then replace the destination
7953 // ciphertext with Enc(2m) and re-sign. Signature passes, but the
7954 // compact sigma proof fails: the proof binds Enc(m) to the Pedersen
7955 // commitment PC(m, r), so substituting Enc(2m) breaks the linkage.
7956 {
7957 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, sendAmount);
7958
7959 auto const ctxHash = getSendContextHash(
7960 bob.id(), mptAlice.issuanceID(), env.seq(bob), carol.id(), setup.version);
7961
7962 auto const validProof = mptAlice.getConfidentialSendProof(
7963 bob,
7964 sendAmount,
7965 setup.recipients,
7966 setup.blindingFactor,
7967 ctxHash,
7968 {
7969 .pedersenCommitment = setup.amountCommitment,
7970 .amt = sendAmount,
7971 .encryptedAmt = setup.senderAmt,
7972 .blindingFactor = setup.amountBlindingFactor,
7973 },
7974 {
7975 .pedersenCommitment = setup.balanceCommitment,
7976 .amt = setup.prevSpending,
7977 .encryptedAmt = setup.prevEncryptedSpending,
7978 .blindingFactor = setup.balanceBlindingFactor,
7979 });
7980
7981 if (!BEAST_EXPECT(validProof.has_value()))
7982 return;
7983
7984 // Replace dest ciphertext with Enc(2m) using the same blinding
7985 // factor — even with matching randomness the proof rejects
7986 // because the committed plaintext differs
7987 auto const inflatedDestAmt =
7988 mptAlice.encryptAmount(carol, sendAmount * 2, setup.blindingFactor);
7989
7990 auto args = setup.sendArgs(
7991 bob, carol, requireOptionalRef(validProof, "Missing valid proof"), tecBAD_PROOF);
7992 args.destEncryptedAmt = inflatedDestAmt;
7993 mptAlice.send(args);
7994 }
7995 }
7996
7997 void
7999 {
8000 testcase("Send: ciphertext negation");
8001
8002 // Attack: negate ciphertext -Enc(m) = (-C1, -C2) to reverse the
8003 // transaction direction. Negation decrypts to the group-level
8004 // additive inverse of m*G, effectively turning a credit into a debit.
8005
8006 using namespace test::jtx;
8007 Env env{*this, features};
8008 Account const alice("alice"), bob("bob"), carol("carol");
8009 ConfidentialEnv confEnv{
8010 env,
8011 alice,
8012 {{.account = bob}, {.account = carol, .payAmount = 1000, .convertAmount = 50}},
8013 tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance};
8014 auto& mptAlice = confEnv.mpt;
8015
8016 uint64_t const sendAmount = 10;
8017
8018 // Negate an ElGamal ciphertext by flipping the y-coordinate parity
8019 // of both compressed EC points. For secp256k1 compressed form,
8020 // prefix 0x02 means even-y and 0x03 means odd-y; negation
8021 // swaps them: -P has the same x but opposite y.
8022 auto const negateCiphertext = [](Buffer const& ct) -> Buffer {
8023 Buffer neg = ct;
8024 neg.data()[0] ^= 0x01; // negate C1
8025 neg.data()[kEcCiphertextComponentLength] ^= 0x01; // negate C2
8026 return neg;
8027 };
8028
8029 // Variant A: Post-signature negation.
8030 // Negate the destination ciphertext in the signed blob.
8031 // Signature no longer covers the modified field.
8032 {
8033 auto const seq = env.seq(bob);
8034 auto const jv =
8035 mptAlice.sendJV({.account = bob, .dest = carol, .amt = sendAmount}, seq);
8036 auto const jtx = env.jt(jv);
8037 BEAST_EXPECT(jtx.stx);
8038
8039 Serializer s;
8040 jtx.stx->add(s);
8041
8042 SerialIter sit(s.slice());
8043 STObject obj(sit, sfTransaction);
8044
8045 auto const origDestAmt = obj.getFieldVL(sfDestinationEncryptedAmount);
8046 Buffer const origBuf(origDestAmt.data(), origDestAmt.size());
8047 auto const negDestAmt = negateCiphertext(origBuf);
8048 obj.setFieldVL(
8049 sfDestinationEncryptedAmount, Slice(negDestAmt.data(), negDestAmt.size()));
8050
8051 Serializer tampered;
8052 obj.add(tampered);
8053
8054 auto const jr = env.rpc("submit", strHex(tampered.slice()));
8055 BEAST_EXPECT(jr[jss::result][jss::error] == "invalidTransaction");
8056 BEAST_EXPECT(!jr[jss::result].isMember(jss::error_code));
8057 BEAST_EXPECT(jr[jss::result][jss::error_message].isNull());
8058 }
8059
8060 // Variant B: Re-signed with all negated ciphertexts.
8061 // Signature passes, but the compact sigma proof fails — the proof
8062 // was generated for Enc(m), not Enc(-m).
8063 {
8064 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, sendAmount);
8065
8066 auto const validProof = setup.generateProof(mptAlice, env, bob, carol);
8067 if (!BEAST_EXPECT(validProof.has_value()))
8068 return;
8069
8070 // Negate all three ciphertexts: Enc(m) -> Enc(-m)
8071 auto const negSenderAmt = negateCiphertext(setup.senderAmt);
8072 auto const negDestAmt = negateCiphertext(setup.destAmt);
8073 auto const negIssuerAmt = negateCiphertext(setup.issuerAmt);
8074
8075 auto args = setup.sendArgs(
8076 bob, carol, requireOptionalRef(validProof, "Missing valid proof"), tecBAD_PROOF);
8077 args.senderEncryptedAmt = negSenderAmt;
8078 args.destEncryptedAmt = negDestAmt;
8079 args.issuerEncryptedAmt = negIssuerAmt;
8080 mptAlice.send(args);
8081 }
8082
8083 // Variant C: Negate only the sender ciphertext.
8084 // The verifier uses the sender ciphertext to derive the remainder
8085 // commitment: Enc(b) - Enc(m) becomes Enc(b) - (-Enc(m)) = Enc(b+m).
8086 // The bulletproof was generated for (b - m), not (b + m), so the
8087 // aggregated range proof fails.
8088 {
8089 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, sendAmount);
8090
8091 auto const validProof = setup.generateProof(mptAlice, env, bob, carol);
8092 if (!BEAST_EXPECT(validProof.has_value()))
8093 return;
8094
8095 auto const negSenderAmt = negateCiphertext(setup.senderAmt);
8096
8097 auto args = setup.sendArgs(
8098 bob, carol, requireOptionalRef(validProof, "Missing valid proof"), tecBAD_PROOF);
8099 args.senderEncryptedAmt = negSenderAmt;
8100 mptAlice.send(args);
8101 }
8102 }
8103
8104 void
8106 {
8107 testcase("Send: ciphertext combination");
8108
8109 // Attack: exploit ElGamal homomorphism to combine ciphertexts
8110 // Enc(m1) + Enc(m2) = Enc(m1+m2), inflating the credited amount
8111 // without knowing the private keys.
8112
8113 using namespace test::jtx;
8114 Env env{*this, features};
8115 Account const alice("alice"), bob("bob"), carol("carol");
8116 ConfidentialEnv confEnv{
8117 env,
8118 alice,
8119 {
8120 {.account = bob, .payAmount = 1000, .convertAmount = 200},
8121 {.account = carol, .payAmount = 1000, .convertAmount = 100},
8122 },
8123 tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance};
8124 auto& mptAlice = confEnv.mpt;
8125
8126 uint64_t const m1 = 10;
8127 uint64_t const m2 = 5;
8128
8129 // Variant A: Post-signature combination.
8130 // Add Enc(m2) to the signed destination ciphertext Enc(m1).
8131 // The original signature doesn't cover the combined ciphertext.
8132 {
8133 auto const seq = env.seq(bob);
8134 auto const jv = mptAlice.sendJV({.account = bob, .dest = carol, .amt = m1}, seq);
8135 auto const jtx = env.jt(jv);
8136 BEAST_EXPECT(jtx.stx);
8137
8138 Serializer s;
8139 jtx.stx->add(s);
8140
8141 SerialIter sit(s.slice());
8142 STObject obj(sit, sfTransaction);
8143
8144 auto const origDestCt = obj.getFieldVL(sfDestinationEncryptedAmount);
8145
8146 // Homomorphically add Enc(m2) to the original Enc(m1)
8147 Buffer const bf2 = generateBlindingFactor();
8148 auto const encM2 = mptAlice.encryptAmount(carol, m2, bf2);
8149 auto const combined = requireOptional(
8151 Slice(origDestCt.data(), origDestCt.size()), Slice(encM2.data(), encM2.size())),
8152 "Missing combined ciphertext");
8153
8154 obj.setFieldVL(sfDestinationEncryptedAmount, combined);
8155
8156 Serializer tampered;
8157 obj.add(tampered);
8158
8159 auto const jr = env.rpc("submit", strHex(tampered.slice()));
8160 BEAST_EXPECT(jr[jss::result][jss::error] == "invalidTransaction");
8161 BEAST_EXPECT(!jr[jss::result].isMember(jss::error_code));
8162 BEAST_EXPECT(jr[jss::result][jss::error_message].isNull());
8163 }
8164
8165 // Variant B: Re-signed with combined ciphertext.
8166 // Generate a valid proof for m1, then replace dest ciphertext with
8167 // Enc(m1) + Enc(m2). Sigma proof fails because the proof was
8168 // generated for Enc(m1) only — the combined ciphertext has
8169 // different randomness.
8170 {
8171 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, m1);
8172
8173 auto const validProof = setup.generateProof(mptAlice, env, bob, carol);
8174 if (!BEAST_EXPECT(validProof.has_value()))
8175 return;
8176
8177 // Homomorphically add Enc(m2) to the valid dest ciphertext
8178 Buffer const bf2 = generateBlindingFactor();
8179 auto const encM2 = mptAlice.encryptAmount(carol, m2, bf2);
8180 auto const combinedDest = homomorphicAdd(setup.destAmt, encM2);
8181 BEAST_EXPECT(combinedDest.has_value());
8182
8183 auto args = setup.sendArgs(
8184 bob, carol, requireOptionalRef(validProof, "Missing valid proof"), tecBAD_PROOF);
8185 args.destEncryptedAmt = combinedDest;
8186 mptAlice.send(args);
8187 }
8188
8189 // Variant C: Cross-transaction ciphertext reuse.
8190 // Execute a valid send of m1, then build a new send for m2 using
8191 // a combined ciphertext oldEnc(m1) + newEnc(m2) = Enc(m1+m2),
8192 // where oldEnc(m1) is the actual ciphertext from the previous tx.
8193 // The proof was generated for the new transaction's context, but
8194 // the ciphertext includes stale randomness from the old Enc(m1).
8195 {
8196 // Execute a valid send of m1, capturing the actual ciphertext used
8197 ConfidentialSendSetup const setup1(mptAlice, bob, carol, alice, m1);
8198 auto const proof1 = setup1.generateProof(mptAlice, env, bob, carol);
8199 if (!BEAST_EXPECT(proof1.has_value()))
8200 return;
8201 mptAlice.send(setup1.sendArgs(bob, carol, requireOptionalRef(proof1, "Missing proof")));
8202
8203 ConfidentialSendSetup const setup2(mptAlice, bob, carol, alice, m2);
8204
8205 auto const proof2 = setup2.generateProof(mptAlice, env, bob, carol);
8206 if (!BEAST_EXPECT(proof2.has_value()))
8207 return;
8208
8209 // Combine the actual prior-tx Enc(m1) with the new Enc(m2)
8210 auto const crossCombined = homomorphicAdd(setup1.destAmt, setup2.destAmt);
8211 BEAST_EXPECT(crossCombined.has_value());
8212
8213 auto args = setup2.sendArgs(
8214 bob, carol, requireOptionalRef(proof2, "Missing proof"), tecBAD_PROOF);
8215 args.destEncryptedAmt = crossCombined;
8216 mptAlice.send(args);
8217 }
8218 }
8219
8220 void
8222 {
8223 testcase("Send: ciphertext rerandomization");
8224
8225 // Attack: substitute the randomness component C1 of an ElGamal
8226 // ciphertext (C1, C2) while keeping the message component C2
8227 // unchanged. This "rerandomizes" the ciphertext to break
8228 // linkability or forge fresh-looking ciphertexts.
8229 //
8230 // The compact sigma proof binds C1 to the shared randomness used
8231 // across all recipients, so any C1 substitution breaks the proof.
8232
8233 using namespace test::jtx;
8234 Env env{*this, features};
8235 Account const alice("alice"), bob("bob"), carol("carol");
8236 ConfidentialEnv confEnv{
8237 env,
8238 alice,
8239 {{.account = bob}, {.account = carol, .payAmount = 1000, .convertAmount = 50}},
8240 tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance};
8241 auto& mptAlice = confEnv.mpt;
8242
8243 uint64_t const sendAmount = 10;
8244
8245 // Helper: replace C1 in a ciphertext with C1 from another
8246 // ciphertext, keeping C2 unchanged. Returns a rerandomized
8247 // ciphertext (C1', C2).
8248 auto const substituteC1 = [](Buffer const& target, Buffer const& source) -> Buffer {
8249 Buffer result = target;
8250 // Copy C1 (the first ciphertext component) from source.
8251 std::memcpy(result.data(), source.data(), kEcCiphertextComponentLength);
8252 return result;
8253 };
8254
8255 // Variant A: Post-signature C1 substitution.
8256 // Replace C1 in the dest ciphertext after signing.
8257 // Signature no longer covers the modified ciphertext.
8258 {
8259 auto const seq = env.seq(bob);
8260 auto const jv =
8261 mptAlice.sendJV({.account = bob, .dest = carol, .amt = sendAmount}, seq);
8262 auto const jtx = env.jt(jv);
8263 BEAST_EXPECT(jtx.stx);
8264
8265 Serializer s;
8266 jtx.stx->add(s);
8267 SerialIter sit(s.slice());
8268 STObject obj(sit, sfTransaction);
8269
8270 // Generate a random C1' by encrypting a different amount
8271 Buffer const bf2 = generateBlindingFactor();
8272 auto const otherCt = mptAlice.encryptAmount(carol, 99, bf2);
8273
8274 // Replace C1 in the dest ciphertext
8275 auto const origDestAmt = obj.getFieldVL(sfDestinationEncryptedAmount);
8276 Buffer const origBuf(origDestAmt.data(), origDestAmt.size());
8277 auto const rerandomized = substituteC1(origBuf, otherCt);
8278 obj.setFieldVL(
8279 sfDestinationEncryptedAmount, Slice(rerandomized.data(), rerandomized.size()));
8280
8281 Serializer tampered;
8282 obj.add(tampered);
8283
8284 // Signature verification fails
8285 auto const jr = env.rpc("submit", strHex(tampered.slice()));
8286 BEAST_EXPECT(jr[jss::result][jss::error] == "invalidTransaction");
8287 BEAST_EXPECT(!jr[jss::result].isMember(jss::error_code));
8288 BEAST_EXPECT(jr[jss::result][jss::error_message].isNull());
8289 }
8290
8291 // Variant B: Re-signed C1 substitution.
8292 // Replace C1 in the dest ciphertext with a fresh random point
8293 // and re-sign. Sigma proof fails because the shared-randomness
8294 // binding no longer holds — C1' wasn't generated with the same r
8295 // used in the proof.
8296 {
8297 ConfidentialSendSetup const setup(mptAlice, bob, carol, alice, sendAmount);
8298
8299 auto const validProof = setup.generateProof(mptAlice, env, bob, carol);
8300 if (!BEAST_EXPECT(validProof.has_value()))
8301 return;
8302
8303 // Create a ciphertext with different randomness to get C1'
8304 Buffer const bf2 = generateBlindingFactor();
8305 auto const otherCt = mptAlice.encryptAmount(carol, sendAmount, bf2);
8306
8307 // Replace C1 in dest ciphertext, keep C2
8308 auto const rerandomizedDest = substituteC1(setup.destAmt, otherCt);
8309
8310 auto args = setup.sendArgs(
8311 bob, carol, requireOptionalRef(validProof, "Missing valid proof"), tecBAD_PROOF);
8312 args.destEncryptedAmt = rerandomizedDest;
8313 mptAlice.send(args);
8314 }
8315 }
8316
8317 void
8319 {
8320 testcase("Send: zero randomness ciphertext");
8321
8322 // Setting r = 0 in ElGamal yields C1 = O (identity), C2 = mG —
8323 // a deterministic ciphertext that reveals the plaintext.
8324
8325 using namespace test::jtx;
8326 Env env{*this, features};
8327 Account const alice("alice"), bob("bob"), carol("carol");
8328 ConfidentialEnv confEnv{
8329 env,
8330 alice,
8331 {{.account = bob}, {.account = carol, .payAmount = 1000, .convertAmount = 50}},
8332 tfMPTCanTransfer | tfMPTCanHoldConfidentialBalance};
8333 auto& mptAlice = confEnv.mpt;
8334
8335 uint64_t const sendAmount = 10;
8336
8337 // -----------------------------------------------------------------
8338 // Variant A: Post-signature zero-randomness substitution
8339 // -----------------------------------------------------------------
8340 // Construct a valid ConfidentialMPTSend transaction with proper
8341 // ciphertexts and ZKPs, sign it, then replace the sender ciphertext
8342 // with a deterministic form (C1 = 0x00...00, C2 = arbitrary).
8343 // Since the identity element has no valid compressed encoding,
8344 // the modified blob fails deserialization / signature check.
8345 {
8346 auto const seq = env.seq(bob);
8347 auto const jv =
8348 mptAlice.sendJV({.account = bob, .dest = carol, .amt = sendAmount}, seq);
8349 auto const jtx = env.jt(jv);
8350 BEAST_EXPECT(jtx.stx);
8351
8352 // Serialize the signed transaction
8353 Serializer s;
8354 jtx.stx->add(s);
8355 SerialIter sit(s.slice());
8356 STObject obj(sit, sfTransaction);
8357
8358 // Replace sender ciphertext with zero-randomness form:
8359 // C1 = all zeros (identity element — invalid encoding)
8360 // C2 = valid trivial point (simulating mG)
8361 Buffer zeroCiphertext(kEcGamalEncryptedTotalLength);
8362 std::memset(zeroCiphertext.data(), 0, kEcGamalEncryptedTotalLength);
8363 // C2 half: use a valid point so only C1 is the problem
8364 auto const& tc = getTrivialCiphertext();
8366 zeroCiphertext.data() + kEcCiphertextComponentLength,
8367 tc.data() + kEcCiphertextComponentLength,
8369 obj.setFieldVL(sfSenderEncryptedAmount, zeroCiphertext);
8370
8371 // Re-serialize with the original (now-stale) signature
8372 Serializer tampered;
8373 obj.add(tampered);
8374
8375 // Signature verification fails because ciphertext fields are
8376 // signed — transaction rejected before ZKP verification.
8377 auto const jr = env.rpc("submit", strHex(tampered.slice()));
8378 BEAST_EXPECT(jr[jss::result][jss::error] == "invalidTransaction");
8379 BEAST_EXPECT(!jr[jss::result].isMember(jss::error_code));
8380 BEAST_EXPECT(jr[jss::result][jss::error_message].isNull());
8381 }
8382
8383 // -----------------------------------------------------------------
8384 // Variant B: Re-signed zero-randomness ciphertext
8385 // -----------------------------------------------------------------
8386 // Same zero-randomness ciphertext as Variant A (C1 = 0, C2 = mG),
8387 // but submitted normally via send() which re-signs the transaction.
8388 // Signature verification passes, but preflight's isValidCiphertext
8389 // rejects it: the identity element has no valid compressed encoding
8390 // on secp256k1, so secp256k1_ec_pubkey_parse fails on C1 = 0.
8391 {
8392 // Build zero-randomness ciphertext: C1 = all zeros (identity),
8393 // C2 = valid trivial point (simulating mG)
8394 Buffer zeroCiphertext(kEcGamalEncryptedTotalLength);
8395 std::memset(zeroCiphertext.data(), 0, kEcGamalEncryptedTotalLength);
8396 auto const& tc = getTrivialCiphertext();
8398 zeroCiphertext.data() + kEcCiphertextComponentLength,
8399 tc.data() + kEcCiphertextComponentLength,
8401
8402 mptAlice.send({
8403 .account = bob,
8404 .dest = carol,
8405 .amt = sendAmount,
8406 .senderEncryptedAmt = zeroCiphertext,
8407 .err = temBAD_CIPHERTEXT,
8408 });
8409 }
8410
8411 // -----------------------------------------------------------------
8412 // Variant C: Deterministic ciphertext reuse across transactions
8413 // -----------------------------------------------------------------
8414 // Construct two transactions using identical deterministic
8415 // ciphertexts (same fixed blinding factor). Even if a valid
8416 // proof could be generated for one, it cannot be reused because
8417 // the TransactionContextID (which includes account sequence)
8418 // differs between transactions.
8419 {
8420 // First transaction: generate valid proof for sendAmount
8421 ConfidentialSendSetup const setup1(mptAlice, bob, carol, alice, sendAmount);
8422
8423 auto const proof1 = setup1.generateProof(mptAlice, env, bob, carol);
8424 if (!BEAST_EXPECT(proof1.has_value()))
8425 return;
8426
8427 // Submit first transaction successfully
8428 mptAlice.send(setup1.sendArgs(bob, carol, requireOptionalRef(proof1, "Missing proof")));
8429
8430 mptAlice.mergeInbox({.account = carol});
8431
8432 // Second transaction: reuse the same proof from tx1.
8433 // The context hash includes the new account sequence, so the
8434 // proof generated for the old sequence is invalid.
8435 ConfidentialSendSetup const setup2(mptAlice, bob, carol, alice, sendAmount);
8436
8437 mptAlice.send(setup2.sendArgs(
8438 bob, carol, requireOptionalRef(proof1, "Missing proof"), tecBAD_PROOF));
8439 }
8440 }
8441
8442 void
8444 {
8445 testcase("Send: recipient inbox rerandomization prevents merge cancellation");
8446
8447 using namespace test::jtx;
8448
8449 // Derive the deterministic canonical-zero randomness r0 used for
8450 // Bob's first spending balance.
8451 auto const getCanonicalZeroBlindingFactor = [](AccountID const& account,
8452 MPTID const& mptID) {
8455 std::memcpy(hashInput.data(), "EncZero", 7);
8456 std::memcpy(hashInput.data() + 7, account.data(), account.size());
8457 std::memcpy(hashInput.data() + 27, mptID.data(), mptID.size());
8458
8459 for (;;)
8460 {
8461 unsigned int mdLen = kEcBlindingFactorLength;
8462 if (EVP_Digest(
8463 hashInput.data(),
8464 hashInput.size(),
8465 scalar.data(),
8466 &mdLen,
8467 EVP_sha256(),
8468 nullptr) != 1)
8469 {
8470 Throw<std::runtime_error>("Failed to derive canonical zero blinding factor");
8471 }
8472
8473 if (secp256k1_ec_seckey_verify(mpt_secp256k1_context(), scalar.data()))
8474 return scalar;
8475
8476 std::memcpy(hashInput.data(), scalar.data(), scalar.size());
8477 }
8478 };
8479
8480 // Pick randomness that would cancel Bob's MergeInbox C1 to infinity
8481 // without receiver-side re-randomization.
8482 auto const negateScalarSum = [](Buffer const& lhs, Buffer const& rhs) {
8485 secp256k1_mpt_scalar_add(sum.data(), lhs.data(), rhs.data());
8486 secp256k1_mpt_scalar_negate(negated.data(), sum.data());
8487 return negated;
8488 };
8489
8490 // Without an auditor, target Bob's holder inbox. The crafted send
8491 // randomness would make MergeInbox hit the point at infinity unless
8492 // ConfidentialMPTSend re-randomizes the recipient ciphertext.
8493 {
8494 Env env{*this, features};
8495 Account const alice("alice"), bob("bob"), carol("carol");
8496 MPTTester mptAlice(env, alice, {.holders = {bob, carol}});
8497
8498 mptAlice.create({
8499 .ownerCount = 1,
8500 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
8501 });
8502
8503 mptAlice.authorize({.account = bob});
8504 mptAlice.authorize({.account = carol});
8505 mptAlice.pay(alice, bob, 100);
8506 mptAlice.pay(alice, carol, 100);
8507
8508 mptAlice.generateKeyPair(alice);
8509 mptAlice.generateKeyPair(bob);
8510 mptAlice.generateKeyPair(carol);
8511 mptAlice.set({.account = alice, .issuerPubKey = mptAlice.getPubKey(alice)});
8512
8513 mptAlice.convert({
8514 .account = carol,
8515 .amt = 50,
8516 .holderPubKey = mptAlice.getPubKey(carol),
8517 });
8518 mptAlice.mergeInbox({.account = carol});
8519
8520 Buffer const convertBlindingFactor = generateBlindingFactor();
8521 mptAlice.convert({
8522 .account = bob,
8523 .amt = 20,
8524 .holderPubKey = mptAlice.getPubKey(bob),
8525 .blindingFactor = convertBlindingFactor,
8526 });
8527
8528 Buffer const canonicalZeroBlindingFactor =
8529 getCanonicalZeroBlindingFactor(bob.id(), mptAlice.issuanceID());
8530
8531 // Holder inbox cancellation happens later in MergeInbox, when
8532 // Bob's spending Enc(0; r0) is added to inbox Enc(25; -r0).
8533 Buffer const maliciousSendBlindingFactor =
8534 negateScalarSum(canonicalZeroBlindingFactor, convertBlindingFactor);
8535
8536 mptAlice.send({
8537 .account = carol,
8538 .dest = bob,
8539 .amt = 5,
8540 .blindingFactor = maliciousSendBlindingFactor,
8541 });
8542
8543 mptAlice.mergeInbox({.account = bob});
8544
8545 auto const bobSpending =
8546 mptAlice.getDecryptedBalance(bob, MPTTester::holderEncryptedSpending);
8547 BEAST_EXPECT(bobSpending && *bobSpending == 25);
8548 }
8549
8550 // With an auditor, verify the destination auditor balance is also
8551 // re-randomized. Auditor balance is updated during send, and this crafted
8552 // randomness would otherwise make that homomorphic sum hit infinity without
8553 // re-randomization.
8554 {
8555 Env env{*this, features};
8556 Account const alice("alice"), bob("bob"), carol("carol"), auditor("auditor");
8557 MPTTester mptAlice(env, alice, {.holders = {bob, carol}, .auditor = auditor});
8558
8559 mptAlice.create({
8560 .ownerCount = 1,
8561 .flags = tfMPTCanTransfer | tfMPTCanLock | tfMPTCanHoldConfidentialBalance,
8562 });
8563
8564 mptAlice.authorize({.account = bob});
8565 mptAlice.authorize({.account = carol});
8566 mptAlice.pay(alice, bob, 100);
8567 mptAlice.pay(alice, carol, 100);
8568
8569 mptAlice.generateKeyPair(alice);
8570 mptAlice.generateKeyPair(bob);
8571 mptAlice.generateKeyPair(carol);
8572 mptAlice.generateKeyPair(auditor);
8573 mptAlice.set({
8574 .account = alice,
8575 .issuerPubKey = mptAlice.getPubKey(alice),
8576 .auditorPubKey = mptAlice.getPubKey(auditor),
8577 });
8578
8579 mptAlice.convert({
8580 .account = carol,
8581 .amt = 50,
8582 .holderPubKey = mptAlice.getPubKey(carol),
8583 });
8584 mptAlice.mergeInbox({.account = carol});
8585
8586 Buffer const convertBlindingFactor = generateBlindingFactor();
8587 mptAlice.convert({
8588 .account = bob,
8589 .amt = 20,
8590 .holderPubKey = mptAlice.getPubKey(bob),
8591 .blindingFactor = convertBlindingFactor,
8592 });
8593
8594 // This would make the homomorphic sum hit infinity.
8595 Buffer const maliciousSendBlindingFactor =
8596 negateScalarSum(gMakeZeroBuffer(kEcBlindingFactorLength), convertBlindingFactor);
8597
8598 mptAlice.send({
8599 .account = carol,
8600 .dest = bob,
8601 .amt = 5,
8602 .blindingFactor = maliciousSendBlindingFactor,
8603 });
8604
8605 auto const bobAuditor =
8606 mptAlice.getDecryptedBalance(bob, MPTTester::auditorEncryptedBalance);
8607 BEAST_EXPECT(bobAuditor && *bobAuditor == 25);
8608 }
8609 }
8610
8611 void
8613 {
8614 // ConfidentialMPTConvert
8615 testConvert(features);
8616 testConvertPreflight(features);
8618 testConvertPreclaim(features);
8619 testConvertWithAuditor(features);
8620
8621 // ConfidentialMPTMergeInbox
8622 testMergeInbox(features);
8623 testMergeInboxPreflight(features);
8624 testMergeInboxPreclaim(features);
8625
8626 testSet(features);
8627 testSetPreflight(features);
8628 testSetPreclaim(features);
8629
8630 // ConfidentialMPTSend
8631 testSend(features);
8632 testSendPreflight(features);
8633 testSendPreclaim(features);
8634 testSendRangeProof(features);
8635
8636 testSendZeroAmount(features);
8637 testSendWithAuditor(features);
8638
8639 // ConfidentialMPTClawback
8640 testClawback(features);
8641 testClawbackPreflight(features);
8642 testClawbackPreclaim(features);
8643 testClawbackProof(features);
8644 testClawbackWithAuditor(features);
8646
8647 testDelete(features);
8648
8649 // ConfidentialMPTConvertBack
8650 testConvertBack(features);
8651 testConvertBackPreflight(features);
8652 testConvertBackPreclaim(features);
8657
8658 // Homomorphic operation tests
8662
8663 // Invalid curve points
8668
8669 // public and private txns
8671
8672 // Replay tests
8673 testMutatePrivacy(features);
8677
8678 // Crafted-proof Tests
8680
8681 // Transaction Fee Tests
8683
8684 // TransferFee (transfer rate) Tests
8685 testTransferFee(features);
8686
8687 // Zero knowledge proof tests
8690 testSendForgedRangeProof(features);
8693 testSendFiatShamirBinding(features);
8697
8698 // Ciphertext malleability tests
8705 }
8706
8707public:
8708 void
8709 run() override
8710 {
8711 using namespace test::jtx;
8712 FeatureBitset const all{testableAmendments()};
8713
8714 testWithFeats(all);
8715 }
8716};
8717
8718BEAST_DEFINE_TESTSUITE(ConfidentialTransfer, app, xrpl);
8719
8720} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
Represents a JSON value.
Definition json_value.h:121
Like std::vector<char> but better.
Definition Buffer.h:19
std::size_t size() const noexcept
Returns the number of bytes in the buffer.
Definition Buffer.h:123
std::uint8_t const * data() const noexcept
Return a pointer to beginning of the storage.
Definition Buffer.h:148
static Buffer getForgedSingleBulletproof(uint64_t value, Buffer const &blindingFactor, UInt256 const &contextHash)
static Buffer getForgedSendProof(test::jtx::MPTTester &mpt, test::jtx::Env &env, test::jtx::Account const &sender, test::jtx::Account const &dest, ConfidentialSendSetup const &setup)
static T requireOptional(std::optional< T > value, char const *message)
static T const & requireOptionalRef(std::optional< T > const &value, char const *message)
static Buffer getForgedBulletproof(std::array< uint64_t, 2 > const &values, std::array< Buffer, 2 > const &blindingFactors, UInt256 const &contextHash)
static Buffer getForgedConvertBackProof(test::jtx::MPTTester &mpt, test::jtx::Account const &holder, uint64_t claimedBalance, uint64_t realBalance, uint64_t amt, Buffer const &pedersenCommitment, Buffer const &encryptedSpendingBalance, Buffer const &pcBlindingFactor, UInt256 const &contextHash)
void testConvertBackPreflight(FeatureBitset features)
void testConvertBackBulletproof(FeatureBitset features)
void testClawbackInvalidProofContextBinding(FeatureBitset features)
void testConfidentialMPTBaseFee(FeatureBitset features)
void testSendRangeProof(FeatureBitset features)
void testConvertBack(FeatureBitset features)
void testPublicTransfersAfterClearingConfidentialFlag(FeatureBitset features)
void testTransferFee(FeatureBitset features)
void testConvert(FeatureBitset features)
void testConvertBackPedersenProof(FeatureBitset features)
void testConvertBackHomomorphicCiphertextModification(FeatureBitset features)
void testSendRerandomizesRecipientInboxAgainstMergeCancellation(FeatureBitset features)
void testConvertIdentityElementRejection(FeatureBitset features)
void testSetPreclaim(FeatureBitset features)
void testSetPreflight(FeatureBitset features)
void testMutatePrivacy(FeatureBitset features)
void testSendCiphertextCombination(FeatureBitset features)
void testSendFiatShamirBinding(FeatureBitset features)
void testSendCiphertextRerandomization(FeatureBitset features)
void testSendPreclaim(FeatureBitset features)
void testConvertBackPreclaim(FeatureBitset features)
void testSendInvalidCurvePoints(FeatureBitset features)
void testClawbackPreclaim(FeatureBitset features)
void testSendWrongIssuerPublicKey(FeatureBitset features)
void testConvertBackWithAuditor(FeatureBitset features)
void testSendOverdraftBulletproof(FeatureBitset features)
void testSendZeroRandomnessCiphertext(FeatureBitset features)
void testSendCiphertextMalleability(FeatureBitset features)
void testSendPreflight(FeatureBitset features)
void testClawbackPreflight(FeatureBitset features)
void testMergeInboxPreclaim(FeatureBitset features)
void testSendNegativeValueMalleability(FeatureBitset features)
void testMergeInbox(FeatureBitset features)
void testClawbackProof(FeatureBitset features)
void testConvertBackOverdraftBulletproof(FeatureBitset features)
void testSendCiphertextNegation(FeatureBitset features)
void testSendForgedRangeProof(FeatureBitset features)
void testConvertBackOverdraftBulletproofImpl(FeatureBitset features, uint64_t balance, uint64_t amt)
void testSendInvalidProofContextBinding(FeatureBitset features)
void testSendForgedEqualityProof(FeatureBitset features)
void testClawbackWithAuditor(FeatureBitset features)
void testSendCrossStatementProofSubstitution(FeatureBitset features)
void testSendProofComponentReuse(FeatureBitset features)
void testSendWithAuditor(FeatureBitset features)
void testConvertWithAuditor(FeatureBitset features)
void testSendHomomorphicOverflow(FeatureBitset features)
void testConvertBackProofCiphertextBinding(FeatureBitset features)
void testSendSharedRandomnessViolation(FeatureBitset features)
void testConvertPreclaim(FeatureBitset features)
void testConvertBackHomomorphicUnderflow(FeatureBitset features)
void testConvertBackInvalidProofContextBinding(FeatureBitset features)
void testConvertInvalidProofContextBinding(FeatureBitset features)
void testSendOverdraftBulletproofImpl(FeatureBitset features, unsigned balance, unsigned amt)
void testMergeInboxPreflight(FeatureBitset features)
void testConvertBackProofVersionMismatch(FeatureBitset features)
void testSendWrongGroupPointInjection(FeatureBitset features)
void testSendZeroAmount(FeatureBitset features)
void testConvertPreflight(FeatureBitset features)
void testSendSpecialWitnessValues(FeatureBitset features)
Writable ledger view that accumulates state and tx changes.
Definition OpenView.h:59
void rawReplace(SLE::Ref sle) override
Unconditionally replace a state item.
Definition OpenView.cpp:246
SLE::const_pointer read(Keylet const &k) const override
Return the state item associated with a key.
Definition OpenView.cpp:170
Identifies fields.
Definition SField.h:131
Blob getFieldVL(SField const &field) const
Definition STObject.cpp:649
void setFieldVL(SField const &field, Blob const &)
Definition STObject.cpp:791
void add(Serializer &s) const override
Definition STObject.cpp:123
Slice slice() const noexcept
Definition Serializer.h:141
An immutable linear range of bytes.
Definition Slice.h:28
void convertBack(MPTConvertBack const &arg=MPTConvertBack{}, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:2139
std::optional< uint64_t > getDecryptedBalance(Account const &account, EncryptedBalanceType balanceType) const
Definition mpt.cpp:1990
std::uint32_t getMPTokenVersion(Account const account) const
Definition mpt.cpp:2123
void send(MPTConfidentialSend const &arg=MPTConfidentialSend{}, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:1463
void pay(Account const &src, Account const &dest, std::int64_t amount, std::optional< TER > err=std::nullopt, std::optional< std::vector< std::string > > credentials=std::nullopt, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:861
void confidentialClaw(MPTConfidentialClawback const &arg=MPTConfidentialClawback{}, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:1831
void set(MPTSet const &set={}, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:581
void authorize(MPTAuthorize const &arg=MPTAuthorize{}, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:459
std::optional< Buffer > getPrivKey(Account const &account, std::optional< std::uint32_t > epoch=std::nullopt) const
Definition mpt.cpp:1936
T data(T... args)
T make_pair(T... args)
T max(T... args)
T memcpy(T... args)
T memset(T... args)
T min(T... args)
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:547
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
constexpr std::size_t kEcPubKeyLength
Length of EC public key (compressed).
Definition Protocol.h:512
@ telINSUF_FEE_P
Definition TER.h:43
constexpr std::uint8_t kEcCompressedPrefixEvenY
Compressed EC point prefix for even y-coordinate.
Definition Protocol.h:588
static auto sum(TCollection const &col)
STAmount convertAmount(STAmount const &amt, bool all)
constexpr std::size_t kEcBlindingFactorLength
Length of the EC blinding factor in bytes.
Definition Protocol.h:522
UInt256 getConvertContextHash(AccountID const &account, UInt192 const &issuanceID, std::uint32_t sequence)
Generates the context hash for ConfidentialMPTConvert transactions.
constexpr std::size_t kCompressedEcPointLength
Length of EC point (compressed).
Definition Protocol.h:497
std::string strHex(FwdIt begin, FwdIt end)
Definition strHex.h:13
UInt256 getSendContextHash(AccountID const &account, UInt192 const &issuanceID, std::uint32_t sequence, AccountID const &destination, std::uint32_t version)
Generates the context hash for ConfidentialMPTSend transactions.
constexpr std::uint32_t kConfidentialFeeMultiplier
Extra base fee multiplier charged to confidential MPT transactions.
Definition Protocol.h:578
UInt256 getConvertBackContextHash(AccountID const &account, UInt192 const &issuanceID, std::uint32_t sequence, std::uint32_t version)
Generates the context hash for ConfidentialMPTConvertBack transactions.
constexpr std::size_t kEcClawbackProofLength
Length of the ZKProof for ConfidentialMPTClawback.
Definition Protocol.h:568
constexpr std::size_t kEcSchnorrProofLength
Length of Schnorr ZKProof for public key registration (compact form) in bytes.
Definition Protocol.h:527
constexpr std::size_t kEcGamalEncryptedTotalLength
EC ElGamal ciphertext length: two compressed EC points concatenated.
Definition Protocol.h:507
BaseUInt< 192 > UInt192
Definition base_uint.h:582
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
constexpr std::size_t kEcConvertBackProofLength
128 bytes compact sigma proof + 688 bytes single bulletproof.
Definition Protocol.h:562
BaseUInt< 256 > UInt256
Definition base_uint.h:581
constexpr std::size_t kEcSingleBulletproofLength
Length of single bulletproof (range proof for 1 commitment) in bytes.
Definition Protocol.h:537
constexpr std::size_t kEcPedersenCommitmentLength
Length of Pedersen Commitment (compressed).
Definition Protocol.h:532
constexpr std::size_t kEcCiphertextComponentLength
Length of one compressed EC point component in an EC ElGamal ciphertext.
Definition Protocol.h:502
std::optional< Buffer > homomorphicSubtract(Slice const &a, Slice const &b)
Homomorphically subtracts two ElGamal ciphertexts.
constexpr std::size_t kEcDoubleBulletproofLength
Length of double bulletproof (range proof for 2 commitments) in bytes.
Definition Protocol.h:542
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
bool after(NetClock::time_point now, std::uint32_t mark)
Has the specified time passed?
Definition View.cpp:668
UInt256 getClawbackContextHash(AccountID const &account, UInt192 const &issuanceID, std::uint32_t sequence, AccountID const &holder)
Generates the context hash for ConfidentialMPTClawback transactions.
Buffer generateBlindingFactor()
Generates a cryptographically secure blinding factor (size=xrpl::kEcBlindingFactorLength).
MPTID makeMptID(std::uint32_t const sequence, AccountID const &account)
Definition Indexes.cpp:219
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
constexpr FlagValue tifMPTCanHoldConfidentialBalance
Definition TxFlags.h:384
constexpr std::size_t kEcSendProofLength
192 bytes compact sigma proof + 754 bytes double bulletproof.
Definition Protocol.h:552
@ temBAD_CIPHERTEXT
Definition TER.h:134
@ temMALFORMED
Definition TER.h:75
@ temDISABLED
Definition TER.h:102
@ temBAD_AMOUNT
Definition TER.h:77
@ temBAD_TRANSFER_FEE
Definition TER.h:130
TERSubset< CanCvtToTER > TER
Definition TER.h:657
@ tecLOCKED
Definition TER.h:369
@ tecNO_TARGET
Definition TER.h:315
@ tecOBJECT_NOT_FOUND
Definition TER.h:337
@ tecNO_AUTH
Definition TER.h:311
@ tecINSUFFICIENT_FUNDS
Definition TER.h:336
@ tecBAD_PROOF
Definition TER.h:379
@ tecNO_PERMISSION
Definition TER.h:316
@ tecDST_TAG_NEEDED
Definition TER.h:320
@ tecDUPLICATE
Definition TER.h:326
@ tecHAS_OBLIGATIONS
Definition TER.h:328
constexpr FlagValue tifMPTCanLock
Definition TxFlags.h:376
constexpr std::uint64_t kMaxMpTokenAmount
The maximum amount of MPTokenIssuance.
Definition Protocol.h:297
BEAST_DEFINE_TESTSUITE(AccountTxPaging, app, xrpl)
std::optional< Buffer > homomorphicAdd(Slice const &a, Slice const &b)
Homomorphically adds two ElGamal ciphertexts.
@ tesSUCCESS
Definition TER.h:253
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
T const_pointer_cast(T... args)
T cref(T... args)
T size(T... args)
std::optional< Buffer > generateProof(test::jtx::MPTTester &mpt, test::jtx::Env &env, test::jtx::Account const &sender, test::jtx::Account const &dest) const
test::jtx::MPTConfidentialSend sendArgs(test::jtx::Account const &sender, test::jtx::Account const &dest, Buffer const &proof, std::optional< TER > err=std::nullopt) const
std::optional< Buffer > amountCommitment
Definition mpt.h:337
std::optional< Buffer > senderEncryptedAmt
Definition mpt.h:329
std::optional< Buffer > destEncryptedAmt
Definition mpt.h:330
std::optional< Buffer > issuerEncryptedAmt
Definition mpt.h:331
T to_string(T... args)