-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.rs
More file actions
1486 lines (1338 loc) · 51.5 KB
/
Copy pathtest.rs
File metadata and controls
1486 lines (1338 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![cfg(test)]
use soroban_sdk::testutils::{Address as _, Events as _};
use soroban_sdk::{token, Address, BytesN, Env};
use super::*;
// =====================================================================================
// Part 1 — the V1.0 gate. Kept executable so the finding can be re-checked, not trusted.
// =====================================================================================
mod gate_measurements {
use super::*;
use crate::gate::{Gate, GateClient};
use crate::poseidon::{FULL_ROUNDS, PARTIAL_ROUNDS, ROUNDS, WIDTH};
fn setup() -> (Env, GateClient<'static>) {
let env = Env::default();
let id = env.register(Gate, ());
let client = GateClient::new(&env, &id);
(env, client)
}
fn fr_hex(env: &Env, s: &str) -> BytesN<32> {
let mut out = [0u8; 32];
for (i, byte) in out.iter_mut().enumerate() {
*byte = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).expect("hex");
}
BytesN::from_array(env, &out)
}
fn u64_fr(env: &Env, v: u64) -> BytesN<32> {
let mut out = [0u8; 32];
out[24..].copy_from_slice(&v.to_be_bytes());
BytesN::from_array(env, &out)
}
fn measure(env: &Env, label: &str, f: impl FnOnce()) -> u64 {
env.cost_estimate().budget().reset_default();
f();
let cpu = env.cost_estimate().budget().cpu_instruction_cost();
let mem = env.cost_estimate().budget().memory_bytes_cost();
std::println!("PROVA_V1_0_GATE {label} cpu_insns={cpu} mem_bytes={mem}");
cpu
}
/// Vectors produced by the circuit itself (`prova-prover poseidon-hash2`). The reference
/// implementation is correct — it simply cannot be afforded on-chain, which is the next test.
#[test]
fn hash2_matches_circuit_vectors() {
let (env, client) = setup();
assert_eq!(
client.hash2(&u64_fr(&env, 1), &u64_fr(&env, 2)),
fr_hex(
&env,
"51f3e312c95343a896cfd8945ea82ba956c1118ce9b9859b6ea56637b4b1ddc4"
),
"Poseidon(1, 2) must match the circuit"
);
assert_eq!(
client.hash2(&u64_fr(&env, 0), &u64_fr(&env, 0)),
fr_hex(
&env,
"10a9e48afc92bd4669b3a8c08c8c99d4144632da67c6cb9bb19cc8facaf8ed3e"
),
"Poseidon(0, 0) — the empty-subtree seed — must match the circuit"
);
}
#[test]
fn hash2_is_order_sensitive() {
let (env, client) = setup();
let ab = client.hash2(&u64_fr(&env, 1), &u64_fr(&env, 2));
let ba = client.hash2(&u64_fr(&env, 2), &u64_fr(&env, 1));
assert_ne!(
ab, ba,
"left/right ordering must matter, or paths are forgeable"
);
}
/// Where the CPU actually goes. `fr_add`, `fr_mul` and `fr_pow` costing the same is the tell:
/// the arithmetic is not what is paid for, the per-host-call boundary is.
#[test]
fn cost_breakdown() {
let (env, client) = setup();
let params = measure(&env, "params_decode_only", || {
client.params_only();
});
let mul0 = measure(&env, "fr_mul_x0", || {
client.fr_mul_loop(&0);
});
let mul100 = measure(&env, "fr_mul_x100", || {
client.fr_mul_loop(&100);
});
let add0 = measure(&env, "fr_add_x0", || {
client.fr_add_loop(&0);
});
let add100 = measure(&env, "fr_add_x100", || {
client.fr_add_loop(&100);
});
let pow0 = measure(&env, "fr_pow_x0", || {
client.fr_pow_loop(&0);
});
let pow100 = measure(&env, "fr_pow_x100", || {
client.fr_pow_loop(&100);
});
let one = measure(&env, "hash2_total", || {
client.hash2(&u64_fr(&env, 1), &u64_fr(&env, 2));
});
let ops_add = ROUNDS * (WIDTH + 2);
let ops_mul = ROUNDS * WIDTH;
let ops_pow = FULL_ROUNDS * WIDTH + PARTIAL_ROUNDS;
std::println!(
"PROVA_V1_0_GATE breakdown params={params} per_fr_add={} per_fr_mul={} per_fr_pow={} \
permutation_only={} ops/perm add={ops_add} mul={ops_mul} pow={ops_pow}",
(add100 - add0) / 100,
(mul100 - mul0) / 100,
(pow100 - pow0) / 100,
one.saturating_sub(params)
);
}
/// Prices the two ways a fold proof could be bound to the queued commitments. A public input
/// costs ~120× a `sha256`, but SHA-256 costs ~42,000 constraints per block *in-circuit* against
/// 240 for a Poseidon hash — so public inputs win, and the batch size is what pays for it.
#[test]
fn binding_cost_breakdown() {
let (env, client) = setup();
let msm8 = measure(&env, "msm_x8", || {
client.msm_loop(&8);
});
let msm40 = measure(&env, "msm_x40", || {
client.msm_loop(&40);
});
let sha0 = measure(&env, "sha_chain_x0", || {
client.sha_chain(&0);
});
let sha32 = measure(&env, "sha_chain_x32", || {
client.sha_chain(&32);
});
let store0 = measure(&env, "store_x0", || {
client.store_loop(&0);
});
let store32 = measure(&env, "store_x32", || {
client.store_loop(&32);
});
std::println!(
"PROVA_BINDING per_msm_point={} per_sha256={} per_store={}",
(msm40 - msm8) / 32,
(sha32 - sha0) / 32,
(store32 - store0) / 32
);
}
/// **The gate — and it fails.** One permutation costs ~11M CPU, so a depth-20 append (20 of
/// them) cannot run to completion inside the 100M budget, let alone leave room for the ~49M
/// verify. This asserts the *negative* result: if Soroban's scalar ops ever get cheap enough for
/// it to pass, the assertion fires and the batched design is worth revisiting.
#[test]
fn gate_onchain_merkle_does_not_fit_cpu_budget() {
let (env, client) = setup();
let a = u64_fr(&env, 1);
let b = u64_fr(&env, 2);
let one = measure(&env, "one_permutation", || {
client.hash2(&a, &b);
});
const VERIFY: u64 = 49_048_967; // measured, prova-verifier
const BUDGET: u64 = 100_000_000;
let append = one * DEPTH as u64;
std::println!(
"PROVA_V1_0_GATE verdict one_permutation={one} append_depth20~{append} \
transact~{} +verify~{} vs budget={BUDGET} => FAILS",
append * 2,
append * 2 + VERIFY
);
assert!(
append + VERIFY > BUDGET,
"on-chain Poseidon now fits the CPU budget — revisit the batched tree update"
);
// The extrapolation is linear, so confirm it against a depth that actually fits. Past ~8
// levels the budget is exhausted outright (an uncatchable host abort), which is why the real
// depth-20 append cannot be measured at all.
let depth8 = measure(&env, "merkle_append_depth8", || {
client.hash_path(&a, &b, &8);
});
let ceiling = BUDGET / one;
std::println!(
"PROVA_V1_0_GATE ceiling depth8={depth8} max_permutations_per_invocation={ceiling} \
(need {} for a transact)",
DEPTH * 2
);
assert!(
ceiling < DEPTH as u64,
"a single append now fits — revisit the batched tree update"
);
}
}
// =====================================================================================
// Part 2 — the pool itself, against proofs generated from the real circuits.
// =====================================================================================
mod harness {
//! Builds real proofs so the contract is exercised against the actual circuits.
//!
//! Replaying pre-generated fixtures would let the circuit and the contract drift apart silently;
//! generating here means a mismatch in public-input order, encoding or semantics fails in CI
//! rather than on testnet. Proving keys are built once and shared — setup dominates the runtime.
use std::sync::OnceLock;
use std::vec::Vec as StdVec;
use ark_bls12_381::{Bls12_381, Fr};
use ark_ed_on_bls12_381::Fr as JubjubFr;
use ark_groth16::{Groth16, ProvingKey};
use ark_snark::SNARK;
use ark_std::rand::{rngs::StdRng, SeedableRng};
use prova_prover::pool::{
encryption::EncKey,
fold::FoldCircuit,
owner_pk, setup,
shield::ShieldCircuit,
spend::{SpendCircuit, SpendOutput},
tree::MerkleTree,
Note,
};
use prova_prover::{credential, poseidon_config, soroban_ser};
use soroban_sdk::{BytesN, Env};
/// Must match the seed `pool-artifacts` used for the embedded verifying keys.
pub const SEED: u64 = 42;
pub const NOW: u64 = 1_700_000_000;
pub struct Keys {
pub spend: ProvingKey<Bls12_381>,
pub shield: ProvingKey<Bls12_381>,
pub fold: ProvingKey<Bls12_381>,
}
pub fn keys() -> &'static Keys {
static KEYS: OnceLock<Keys> = OnceLock::new();
KEYS.get_or_init(|| Keys {
spend: setup::spend(SEED).0,
shield: setup::shield(SEED).0,
fold: setup::fold(SEED).0,
})
}
/// Re-exported so the harness hands the contract exactly the type its entrypoints take.
pub use crate::Proof;
fn to_soroban(env: &Env, p: &ark_groth16::Proof<Bls12_381>) -> Proof {
Proof {
a: BytesN::from_array(env, &soroban_ser::g1_bytes(&p.a)),
b: BytesN::from_array(env, &soroban_ser::g2_bytes(&p.b)),
c: BytesN::from_array(env, &soroban_ser::g1_bytes(&p.c)),
}
}
pub fn fr_bytes(env: &Env, f: &Fr) -> BytesN<32> {
BytesN::from_array(env, &soroban_ser::fr_bytes(f))
}
/// A funded, KYC'd user plus the wallet's view of the tree.
pub struct Wallet {
pub cfg: ark_crypto_primitives::sponge::poseidon::PoseidonConfig<Fr>,
pub anchor: credential::AnchorKey,
pub cred: credential::Credential,
pub owner_sk: Fr,
pub owner_pk: Fr,
pub tree: MerkleTree,
pub enc: EncKey,
}
impl Wallet {
pub fn new() -> Self {
Self::with_anchor_seed(SEED)
}
/// Same owner key, different anchor. Lets a test rotate the KYC signing key while the notes
/// already in the tree stay spendable by the same person.
pub fn with_anchor_seed(seed: u64) -> Self {
let cfg = poseidon_config::<Fr>();
let mut rng = StdRng::seed_from_u64(seed);
let anchor = credential::AnchorKey::generate(&mut rng);
let owner_sk = Fr::from(1234567u64);
let pk = owner_pk(&cfg, owner_sk);
let uid = credential::user_id(&cfg, owner_sk);
let cred = credential::issue(&cfg, &anchor, uid, 2, 2_000_000_000, &mut rng);
let tree = MerkleTree::new(&cfg);
let enc = EncKey::generate(&mut rng);
Self {
cfg,
anchor,
cred,
owner_sk,
owner_pk: pk,
tree,
enc,
}
}
pub fn note(&self, amount: u64, rho: u64) -> Note {
Note::new(amount, self.owner_pk, Fr::from(rho))
}
/// Prove a deposit's commitment binds its amount, and encrypt the note to its owner.
pub fn shield(&self, env: &Env, note: &Note) -> (Proof, crate::ShieldNote) {
let c = ShieldCircuit::new(
self.cfg.clone(),
note.amount,
note.owner_pk,
note.rho,
self.enc.pk,
JubjubFr::from(0xE0u64 + note.amount),
);
let public = c.public_inputs().unwrap();
let mut rng = StdRng::seed_from_u64(SEED + note.amount);
let proof = Groth16::<Bls12_381>::prove(&keys().shield, c, &mut rng).unwrap();
(
to_soroban(env, &proof),
crate::ShieldNote {
commitment: fr_bytes(env, &public[0]),
owner_pk: fr_bytes(env, &public[2]),
epk_x: fr_bytes(env, &public[3]),
epk_y: fr_bytes(env, &public[4]),
enc_amount: fr_bytes(env, &public[5]),
enc_rho: fr_bytes(env, &public[6]),
},
)
}
/// Prove that appending `leaves` advances the tree, and adopt the result.
pub fn fold(&mut self, env: &Env, leaves: &[Fr]) -> (Proof, BytesN<32>, u32) {
let (circuit, next) = FoldCircuit::from_tree(&self.cfg, &self.tree, leaves);
let new_root = circuit.new_root.unwrap();
let mut rng = StdRng::seed_from_u64(SEED + self.tree.next_index() + 7);
let proof = Groth16::<Bls12_381>::prove(&keys().fold, circuit, &mut rng).unwrap();
self.tree = next;
(
to_soroban(env, &proof),
fr_bytes(env, &new_root),
leaves.len() as u32,
)
}
/// Prove a spend of the note at `leaf_index`.
#[allow(clippy::too_many_arguments)]
pub fn spend(
&self,
env: &Env,
leaf_index: u64,
in_note: &Note,
out1: Note,
out2: Note,
public_amount: u64,
destination: Fr,
) -> (Proof, StdVec<BytesN<32>>) {
let path = self.tree.path(leaf_index);
let circuit = SpendCircuit::new(
self.cfg.clone(),
in_note.amount,
in_note.rho,
self.owner_sk,
&path,
SpendOutput::new(out1, self.enc.pk),
SpendOutput::new(out2, self.enc.pk),
JubjubFr::from(0xE55u64 + leaf_index),
public_amount,
destination,
&self.cred,
self.anchor.pk,
NOW,
// The harness proves against the pool's default policy, which is what the fixture
// initialises with. A test that wants a different minimum sets it on the contract
// and proves against the same value — see the policy tests.
crate::DEFAULT_MIN_KYC_LEVEL,
);
let public = circuit.public_inputs().unwrap();
let mut rng = StdRng::seed_from_u64(SEED + leaf_index + 13);
let proof = Groth16::<Bls12_381>::prove(&keys().spend, circuit, &mut rng).unwrap();
(
to_soroban(env, &proof),
public.iter().map(|f| fr_bytes(env, f)).collect(),
)
}
/// A spend proved against an explicit minimum KYC level, for the policy tests.
#[allow(clippy::too_many_arguments)]
pub fn spend_at_min(
&self,
env: &Env,
leaf_index: u64,
in_note: &Note,
out1: Note,
out2: Note,
min_kyc_level: u64,
) -> (Proof, StdVec<BytesN<32>>) {
let path = self.tree.path(leaf_index);
let circuit = SpendCircuit::new(
self.cfg.clone(),
in_note.amount,
in_note.rho,
self.owner_sk,
&path,
SpendOutput::new(out1, self.enc.pk),
SpendOutput::new(out2, self.enc.pk),
JubjubFr::from(0xE55u64 + leaf_index),
0,
ark_bls12_381::Fr::from(0u64),
&self.cred,
self.anchor.pk,
NOW,
min_kyc_level,
);
let public = circuit.public_inputs().unwrap();
let mut rng = StdRng::seed_from_u64(SEED + leaf_index + 97);
let proof = Groth16::<Bls12_381>::prove(&keys().spend, circuit, &mut rng).unwrap();
(
to_soroban(env, &proof),
public.iter().map(|f| fr_bytes(env, f)).collect(),
)
}
/// Read back the field element the contract binds a payout address to, so the proof is
/// built against exactly what the contract will check. See `Pool::destination_field`.
pub fn destination(&self, field: &BytesN<32>) -> Fr {
use ark_ff::PrimeField;
Fr::from_be_bytes_mod_order(&field.to_array())
}
}
}
use harness::{Wallet, NOW};
struct Fixture {
env: Env,
pool: PoolClient<'static>,
token: token::Client<'static>,
user: Address,
admin: Address,
}
const START_BALANCE: i128 = 1_000_000;
fn fixture() -> Fixture {
let env = Env::default();
env.mock_all_auths();
let token_admin = Address::generate(&env);
let admin = Address::generate(&env);
let user = Address::generate(&env);
let token_id = env
.register_stellar_asset_contract_v2(token_admin)
.address();
token::StellarAssetClient::new(&env, &token_id).mint(&user, &START_BALANCE);
let wallet = Wallet::new();
let pool_id = env.register(Pool, ());
let pool = PoolClient::new(&env, &pool_id);
pool.initialize(
&admin,
&token_id,
&harness::fr_bytes(&env, &wallet.anchor.pk.x),
&harness::fr_bytes(&env, &wallet.anchor.pk.y),
// Matches the level the fixture proofs were generated against.
&crate::DEFAULT_MIN_KYC_LEVEL,
);
let token = token::Client::new(&env, &token_id);
Fixture {
env,
pool,
token,
user,
admin,
}
}
/// Build the contract's `Outputs` from a spend's public inputs.
///
/// The encrypted payloads are *produced by the circuit*, so the test must pass exactly what the
/// proof committed to — which is the whole property being relied on. Indices follow the frozen
/// order: 2,3 = commitments; 9,10 = ephemeral key; 11..14 = the two masked payloads.
fn outputs(pi: &[BytesN<32>]) -> Outputs {
Outputs {
c1: pi[2].clone(),
c2: pi[3].clone(),
epk_x: pi[9].clone(),
epk_y: pi[10].clone(),
enc1_amount: pi[11].clone(),
enc1_rho: pi[12].clone(),
enc2_amount: pi[13].clone(),
enc2_rho: pi[14].clone(),
}
}
fn zero_fr() -> ark_bls12_381::Fr {
ark_bls12_381::Fr::from(0u64)
}
/// Shield a note and fold it in, leaving it spendable at leaf 0. The starting point for most tests.
fn funded(f: &Fixture, w: &mut Wallet, amount: u64) -> prova_prover::pool::Note {
let note = w.note(amount, 1001);
let (p, note_data) = w.shield(&f.env, ¬e);
f.pool.shield(&f.user, &(amount as i128), ¬e_data, &p);
let (p, new_root, count) = w.fold(&f.env, &[note.commitment(&w.cfg)]);
f.pool.update_root(&p, &new_root, &count);
note
}
// ---- happy path ----
/// The full product flow: deposit → make it spendable → send privately → cash out.
#[test]
fn shield_fold_transact_fold_unshield_end_to_end() {
let f = fixture();
let mut w = Wallet::new();
let pool_addr = f.pool.address.clone();
// 1. Shield 1000. Tokens really move; the note is queued, not yet spendable.
let note0 = w.note(1000, 1001);
let (p, note_data) = w.shield(&f.env, ¬e0);
f.pool.shield(&f.user, &1000, ¬e_data, &p);
assert_eq!(f.token.balance(&f.user), START_BALANCE - 1000);
assert_eq!(
f.token.balance(&pool_addr),
1000,
"pool custodies the deposit"
);
assert_eq!(f.pool.queue_depth(), 1);
assert_eq!(f.pool.next_index(), 0, "queued, not yet folded");
// 2. Fold it in — only now is it a leaf, and only now is it spendable.
let (p, new_root, count) = w.fold(&f.env, &[note0.commitment(&w.cfg)]);
f.pool.update_root(&p, &new_root, &count);
assert_eq!(f.pool.next_index(), 1);
assert_eq!(f.pool.queue_depth(), 0);
assert_eq!(f.pool.root(), Some(new_root.clone()));
// 3. Private transfer: 1000 → 600 + 400. No tokens move; nothing about it is public.
let out1 = w.note(600, 2001);
let out2 = w.note(400, 2002);
let (p, pi) = w.spend(&f.env, 0, ¬e0, out1, out2, 0, zero_fr());
f.pool.transact(&p, &pi[0], &pi[1], &outputs(&pi), &NOW);
assert!(f.pool.is_spent(&pi[1]), "the input note is now nullified");
assert_eq!(f.pool.queue_depth(), 2);
assert_eq!(
f.token.balance(&pool_addr),
1000,
"a private transfer moves no tokens"
);
// 4. Fold both outputs.
let (p, new_root, count) = w.fold(&f.env, &[out1.commitment(&w.cfg), out2.commitment(&w.cfg)]);
f.pool.update_root(&p, &new_root, &count);
assert_eq!(f.pool.next_index(), 3);
// 5. Unshield the 600 note to a public destination.
let payout = Address::generate(&f.env);
let dest = w.destination(&f.pool.destination_field(&payout));
let (p, pi) = w.spend(
&f.env,
1,
&out1,
w.note(0, 3001),
w.note(0, 3002),
600,
dest,
);
f.pool
.unshield(&p, &pi[0], &pi[1], &outputs(&pi), &600, &payout, &NOW);
assert_eq!(f.token.balance(&payout), 600, "the payout landed");
assert_eq!(
f.token.balance(&pool_addr),
400,
"the pool still custodies exactly the unspent 400"
);
assert_eq!(
f.token.balance(&f.user) + f.token.balance(&payout) + f.token.balance(&pool_addr),
START_BALANCE,
"no value created or destroyed anywhere in the run"
);
}
// ---- must-fail: double-spend, theft, and folder misbehaviour ----
/// The core anti-double-spend rule.
#[test]
fn replayed_nullifier_is_rejected() {
let f = fixture();
let mut w = Wallet::new();
let note0 = funded(&f, &mut w, 1000);
let out1 = w.note(600, 2001);
let out2 = w.note(400, 2002);
let (p, pi) = w.spend(&f.env, 0, ¬e0, out1, out2, 0, zero_fr());
let out = outputs(&pi);
f.pool.transact(&p, &pi[0], &pi[1], &out, &NOW);
// Exactly the same proof again — the note is already spent.
let err = f
.pool
.try_transact(&p, &pi[0], &pi[1], &out, &NOW)
.expect_err("a replayed spend must be rejected");
assert_eq!(err, Ok(Error::NullifierAlreadyUsed));
}
/// A note cannot be spent before the fold that puts it in the tree — there is no root to prove
/// against. This is the ordering rule wallets must respect.
#[test]
fn spending_before_the_fold_is_rejected() {
let f = fixture();
let w = Wallet::new();
let note0 = w.note(1000, 1001);
let (p, note_data) = w.shield(&f.env, ¬e0);
f.pool.shield(&f.user, &1000, ¬e_data, &p);
// Build a spend against the root the note *would* produce, without folding it in.
let mut speculative = Wallet::new();
speculative.tree.insert(note0.commitment(&w.cfg));
let (p, pi) = speculative.spend(
&f.env,
0,
¬e0,
w.note(600, 2001),
w.note(400, 2002),
0,
zero_fr(),
);
let err = f
.pool
.try_transact(&p, &pi[0], &pi[1], &outputs(&pi), &NOW)
.expect_err("an unfolded note has no accepted root");
assert_eq!(err, Ok(Error::UnknownRoot));
}
/// A proof built against a root that has since advanced must still land. Without this, two people
/// transferring at the same moment would collide and one would always fail — the whole reason the
/// 32-root window exists.
#[test]
fn stale_but_in_window_root_is_accepted() {
let f = fixture();
let mut w = Wallet::new();
let note0 = funded(&f, &mut w, 1000);
let root_at_build = f.pool.root().unwrap();
// The wallet builds its spend against the current root...
let (p, pi) = w.spend(
&f.env,
0,
¬e0,
w.note(600, 2001),
w.note(400, 2002),
0,
zero_fr(),
);
// ...but three other deposits land and fold first, advancing the root three times.
for i in 0..3u64 {
let other = w.note(10 + i, 5000 + i);
let (sp, other_data) = w.shield(&f.env, &other);
f.pool
.shield(&f.user, &(other.amount as i128), &other_data, &sp);
let (fp, new_root, count) = w.fold(&f.env, &[other.commitment(&w.cfg)]);
f.pool.update_root(&fp, &new_root, &count);
}
assert_ne!(f.pool.root().unwrap(), root_at_build, "the root moved on");
// The in-flight spend still verifies against its now-stale root.
f.pool.transact(&p, &pi[0], &pi[1], &outputs(&pi), &NOW);
assert!(f.pool.is_spent(&pi[1]));
}
/// The other side of the window: once a root has been pushed out of the 32-slot ring, proofs against
/// it must stop being accepted.
#[test]
fn evicted_root_is_rejected() {
let f = fixture();
let mut w = Wallet::new();
let note0 = funded(&f, &mut w, 1000);
let (p, pi) = w.spend(
&f.env,
0,
¬e0,
w.note(600, 2001),
w.note(400, 2002),
0,
zero_fr(),
);
let stale_root = pi[0].clone();
assert!(f.pool.is_known_root(&stale_root));
// Advance past the whole history window.
for i in 0..(ROOT_HISTORY as u64 + 1) {
let other = w.note(10 + i, 6000 + i);
let (sp, other_data) = w.shield(&f.env, &other);
f.pool
.shield(&f.user, &(other.amount as i128), &other_data, &sp);
let (fp, new_root, count) = w.fold(&f.env, &[other.commitment(&w.cfg)]);
f.pool.update_root(&fp, &new_root, &count);
}
assert!(
!f.pool.is_known_root(&stale_root),
"the root should have aged out of the ring"
);
let err = f
.pool
.try_transact(&p, &pi[0], &pi[1], &outputs(&pi), &NOW)
.expect_err("a proof against an evicted root must be rejected");
assert_eq!(err, Ok(Error::UnknownRoot));
}
/// `count` must match what was actually queued, or the queue head would run past real commitments
/// and the notes in them would be lost.
#[test]
fn folding_more_than_the_queue_holds_is_rejected() {
let f = fixture();
let mut w = Wallet::new();
let note0 = w.note(1000, 1001);
let (p, note_data) = w.shield(&f.env, ¬e0);
f.pool.shield(&f.user, &1000, ¬e_data, &p);
let (p, new_root, _) = w.fold(&f.env, &[note0.commitment(&w.cfg)]);
let err = f
.pool
.try_update_root(&p, &new_root, &2)
.expect_err("only one commitment is queued");
assert_eq!(err, Ok(Error::InvalidBatch));
}
#[test]
fn empty_and_oversized_folds_are_rejected() {
let f = fixture();
let mut w = Wallet::new();
let (p, new_root, _) = w.fold(&f.env, &[ark_bls12_381::Fr::from(1u64)]);
assert_eq!(
f.pool
.try_update_root(&p, &new_root, &0)
.expect_err("a zero-count fold is meaningless"),
Ok(Error::InvalidBatch)
);
assert_eq!(
f.pool
.try_update_root(&p, &new_root, &(BATCH + 1))
.expect_err("a batch larger than BATCH cannot be proved"),
Ok(Error::InvalidBatch)
);
}
/// A fold claiming a root the circuit did not prove must not advance the tree.
#[test]
fn fold_with_a_forged_root_is_rejected() {
let f = fixture();
let mut w = Wallet::new();
let note0 = w.note(1000, 1001);
let (p, note_data) = w.shield(&f.env, ¬e0);
f.pool.shield(&f.user, &1000, ¬e_data, &p);
let (p, _real_root, count) = w.fold(&f.env, &[note0.commitment(&w.cfg)]);
let forged = BytesN::from_array(&f.env, &[0x11; 32]);
let err = f
.pool
.try_update_root(&p, &forged, &count)
.expect_err("a forged root must not verify");
assert_eq!(err, Ok(Error::InvalidProof));
assert_eq!(f.pool.next_index(), 0, "the tree did not move");
}
/// Shielding while committing to more than was deposited is the attack the shield circuit exists to
/// stop: without it the pool could be drained by depositing 1000 and committing to a million.
#[test]
fn shield_commitment_must_bind_the_transferred_amount() {
let f = fixture();
let w = Wallet::new();
let inflated = w.note(1_000_000, 1001);
let (p, inflated_data) = w.shield(&f.env, &inflated);
let err = f
.pool
.try_shield(&f.user, &1000, &inflated_data, &p)
.expect_err("the commitment must bind the amount actually deposited");
assert_eq!(err, Ok(Error::InvalidProof));
assert_eq!(f.token.balance(&f.user), START_BALANCE, "no tokens moved");
assert_eq!(f.pool.queue_depth(), 0, "nothing was queued");
}
#[test]
fn shield_rejects_non_positive_and_oversized_amounts() {
let f = fixture();
let w = Wallet::new();
let note0 = w.note(1000, 1001);
let (p, note_data) = w.shield(&f.env, ¬e0);
for bad in [0i128, -1i128, (u64::MAX as i128) + 1] {
let err = f
.pool
.try_shield(&f.user, &bad, ¬e_data, &p)
.expect_err("amount must be a positive u64");
assert_eq!(err, Ok(Error::InvalidAmount));
}
}
/// The theft the `destination` public input was added to prevent: lift a valid unshield proof out of
/// the mempool and resubmit it naming your own address.
#[test]
fn unshield_to_a_substituted_destination_is_rejected() {
let f = fixture();
let mut w = Wallet::new();
let note0 = funded(&f, &mut w, 1000);
let payout = Address::generate(&f.env);
let dest = w.destination(&f.pool.destination_field(&payout));
let (p, pi) = w.spend(
&f.env,
0,
¬e0,
w.note(0, 3001),
w.note(400, 3002),
600,
dest,
);
let attacker = Address::generate(&f.env);
let err = f
.pool
.try_unshield(&p, &pi[0], &pi[1], &outputs(&pi), &600, &attacker, &NOW)
.expect_err("redirecting an unshield must fail");
assert_eq!(err, Ok(Error::InvalidProof));
assert_eq!(f.token.balance(&attacker), 0, "nothing was stolen");
// The legitimate destination still works, so the rejection was specific, not incidental.
f.pool
.unshield(&p, &pi[0], &pi[1], &outputs(&pi), &600, &payout, &NOW);
assert_eq!(f.token.balance(&payout), 600);
}
/// The amount released must be the amount proved, or the pool can be over-drawn.
#[test]
fn unshield_with_a_substituted_amount_is_rejected() {
let f = fixture();
let mut w = Wallet::new();
let note0 = funded(&f, &mut w, 1000);
let payout = Address::generate(&f.env);
let dest = w.destination(&f.pool.destination_field(&payout));
let (p, pi) = w.spend(
&f.env,
0,
¬e0,
w.note(0, 3001),
w.note(400, 3002),
600,
dest,
);
let err = f
.pool
.try_unshield(
&p,
&pi[0],
&pi[1],
&outputs(&pi),
&900, // proved 600
&payout,
&NOW,
)
.expect_err("claiming more than was proved must fail");
assert_eq!(err, Ok(Error::InvalidProof));
assert_eq!(f.token.balance(&payout), 0);
}
/// A transact proof cannot be re-aimed at `unshield` to pull tokens out: the private path proves
/// `publicAmount = 0`, and `unshield` checks a non-zero amount against the same public input.
#[test]
fn a_private_transfer_proof_cannot_be_used_to_withdraw() {
let f = fixture();
let mut w = Wallet::new();
let note0 = funded(&f, &mut w, 1000);
let (p, pi) = w.spend(
&f.env,
0,
¬e0,
w.note(600, 2001),
w.note(400, 2002),
0,
zero_fr(),
);
let attacker = Address::generate(&f.env);
let err = f
.pool
.try_unshield(&p, &pi[0], &pi[1], &outputs(&pi), &1000, &attacker, &NOW)
.expect_err("a private-transfer proof must not authorise a withdrawal");
assert_eq!(err, Ok(Error::InvalidProof));
assert_eq!(f.token.balance(&attacker), 0);
}
// ---- housekeeping ----
#[test]
fn initialize_is_one_shot() {
let f = fixture();
let z = BytesN::from_array(&f.env, &[0u8; 32]);
let err = f
.pool
.try_initialize(
&f.admin,
&f.pool.address,
&z,
&z,
&crate::DEFAULT_MIN_KYC_LEVEL,
)
.expect_err("re-initialising would let the token or anchor be swapped");
assert_eq!(err, Ok(Error::AlreadyInitialized));
}
#[test]
fn empty_tree_root_is_seeded_into_history() {
let f = fixture();
let empty = BytesN::from_array(&f.env, EMPTY_ROOT);
assert_eq!(f.pool.root(), Some(empty.clone()));
assert!(
f.pool.is_known_root(&empty),
"the first fold proves against the empty root, so it must be accepted"
);
assert!(
!f.pool
.is_known_root(&BytesN::from_array(&f.env, &[0u8; 32])),
"the all-zero root must never be accepted"
);
}
/// Every on-chain path must fit Soroban's 100M CPU budget — the constraint that shaped the design.
#[test]
fn all_operations_fit_the_cpu_budget() {
let f = fixture();
let mut w = Wallet::new();
let note0 = w.note(1000, 1001);
let (p, note_data) = w.shield(&f.env, ¬e0);
f.env.cost_estimate().budget().reset_default();
f.pool.shield(&f.user, &1000, ¬e_data, &p);
let shield_cpu = f.env.cost_estimate().budget().cpu_instruction_cost();
let (p, new_root, count) = w.fold(&f.env, &[note0.commitment(&w.cfg)]);
f.env.cost_estimate().budget().reset_default();
f.pool.update_root(&p, &new_root, &count);
let fold_cpu = f.env.cost_estimate().budget().cpu_instruction_cost();
let (p, pi) = w.spend(
&f.env,
0,
¬e0,
w.note(600, 2001),
w.note(400, 2002),
0,
zero_fr(),
);
f.env.cost_estimate().budget().reset_default();
f.pool.transact(&p, &pi[0], &pi[1], &outputs(&pi), &NOW);
let transact_cpu = f.env.cost_estimate().budget().cpu_instruction_cost();
std::println!(
"PROVA_V3_ONCHAIN shield_cpu={shield_cpu} fold_cpu={fold_cpu} \
transact_cpu={transact_cpu} budget=100000000 ceiling={SAFETY_CEILING}"
);
for (name, cpu) in [
("shield", shield_cpu),
("fold", fold_cpu),
("transact", transact_cpu),
] {
assert!(
cpu < SAFETY_CEILING,
"{name} used {cpu}, over the {SAFETY_CEILING} safety ceiling ({}% of the 100M budget). \
There is no runtime escape hatch — see SAFETY_CEILING.",
cpu * 100 / 100_000_000
);
}
}
/// A tripwire well below Soroban's real 100M limit, so cost growth is caught in CI rather than by a
/// failing transaction on-chain.
///
/// It sits this far back because **the pool has no way to shed cost at runtime**. `fold_cost_by_batch_size`
/// shows a fold costs the same whether it carries 1 commitment or 8 (59.72M vs 59.85M — 93% of it is
/// the fixed proof check). So the obvious recovery, "fold fewer at a time", does nothing. If an
/// entrypoint ever exceeded the real budget, the only fix would be a new circuit, a new trusted setup
/// and a redeployed contract. Twenty-five points of margin is what buys the time to do that calmly.