forked from Dshield-xyz/Dshield
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1425 lines (1201 loc) · 50 KB
/
Copy pathlib.rs
File metadata and controls
1425 lines (1201 loc) · 50 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
#![no_std]
use soroban_sdk::{
contract, contracterror, contractevent, contractimpl, symbol_short, Address, Bytes, BytesN,
Env, InvokeError, IntoVal, Symbol, Val, Vec as SorobanVec,
};
use ultrahonk_soroban_verifier::{UltraHonkVerifier, VkLoadError, PROOF_BYTES};
#[contract]
pub struct ComplianceContract;
#[contracterror]
#[repr(u32)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ComplianceError {
VkInvalidLength = 1,
VkInvalidParameters = 2,
ProofParseError = 3,
VerificationFailed = 4,
VkNotSet = 5,
AlreadyInitialized = 6,
InvalidPublicInputs = 7,
KycNotRegistered = 8,
DisclosureVkNotSet = 9,
/// merkle_root in the public inputs doesn't belong to any configured pool.
UnknownMerkleRoot = 10,
/// disclosed_amount doesn't equal the actual fixed deposit_amount of the
/// pool the merkle_root belongs to.
AmountMismatch = 11,
/// threshold exceeds the actual fixed deposit_amount of the pool the
/// merkle_root belongs to.
ThresholdNotMet = 12,
/// accept_admin called with no admin rotation in progress.
NoPendingAdmin = 13,
}
/// Cross-contract call into a pool's `is_known_root(root) -> bool` view.
/// Returns false on any invocation error (e.g. `pool` isn't a real pool
/// contract), so a misconfigured pool address simply never matches rather
/// than panicking.
fn pool_has_root(env: &Env, pool: &Address, root: &BytesN<32>) -> bool {
let mut args: SorobanVec<Val> = SorobanVec::new(env);
args.push_back(root.into_val(env));
env.try_invoke_contract::<bool, InvokeError>(pool, &Symbol::new(env, "is_known_root"), args)
.ok()
.and_then(|r| r.ok())
.unwrap_or(false)
}
/// Cross-contract call into a pool's `get_deposit_amount() -> Result<i128,_>`.
fn pool_deposit_amount(env: &Env, pool: &Address) -> Option<i128> {
let args: SorobanVec<Val> = SorobanVec::new(env);
env.try_invoke_contract::<i128, InvokeError>(pool, &Symbol::new(env, "get_deposit_amount"), args)
.ok()
.and_then(|r| r.ok())
}
/// Finds the configured pool that `root` belongs to and returns its fixed
/// per-note deposit amount. This is the authoritative source of "amount" for
/// any note — the circuit's `amount` witness is never constrained to the
/// note itself (see main.nr), so it cannot be trusted; the pool the root
/// came from is what actually fixes the amount (DShield pools are
/// fixed-denomination: every note in a given pool has the same amount).
fn amount_for_root(env: &Env, pools: &SorobanVec<Address>, root: &BytesN<32>) -> Option<i128> {
for pool in pools.iter() {
if pool_has_root(env, &pool, root) {
return pool_deposit_amount(env, &pool);
}
}
None
}
/// Encodes a non-negative i128 as the 32-byte big-endian field element the
/// Noir circuit and frontend would produce for that plain integer value
/// (top 16 bytes zero, value right-aligned in the low 16 bytes) — the same
/// convention as the pool contract's own Poseidon2 input encoding.
fn amount_to_field_bytes(amount: i128) -> [u8; 32] {
let mut buf = [0u8; 32];
buf[16..32].copy_from_slice(&(amount as u128).to_be_bytes());
buf
}
/// Decodes a 32-byte public-input field element back to u128, rejecting any
/// value that doesn't fit (top 16 bytes must be zero) rather than silently
/// truncating.
fn field_bytes_to_u128(bytes: &[u8; 32]) -> Option<u128> {
if bytes[0..16] != [0u8; 16] {
return None;
}
let mut b16 = [0u8; 16];
b16.copy_from_slice(&bytes[16..32]);
Some(u128::from_be_bytes(b16))
}
#[contractevent(topics = ["kyc_registered"])]
pub struct KycRegisteredEvent<'a> {
pub kyc_hash: &'a BytesN<32>,
pub registrar: &'a Address,
}
#[contractevent(topics = ["compliance_verified"])]
pub struct ComplianceVerifiedEvent<'a> {
pub kyc_hash: &'a BytesN<32>,
pub auditor_key: &'a BytesN<32>,
}
#[contractevent(topics = ["disclosure_verified"])]
pub struct DisclosureVerifiedEvent<'a> {
pub kyc_hash: &'a BytesN<32>,
pub auditor_key: &'a BytesN<32>,
pub threshold: &'a BytesN<32>,
}
#[contractevent(topics = ["pools_updated"])]
pub struct PoolsUpdatedEvent<'a> {
pub pool_count: u32,
pub updated_by: &'a Address,
}
#[contractevent(topics = ["disclosure_vk_updated"])]
pub struct DisclosureVkUpdatedEvent<'a> {
pub updated_by: &'a Address,
}
#[contractevent(topics = ["admin_updated"])]
pub struct AdminUpdatedEvent<'a> {
pub previous_admin: &'a Address,
pub new_admin: &'a Address,
}
// KYC registry, VKs, admin, and pools all live in bounded instance storage.
// Every state-mutating or verification entrypoint extends the TTL so the
// entry doesn't silently expire and brick the contract between demos.
const BUMP_THRESHOLD: u32 = 17_280; // ~1 day of ledgers
const BUMP_AMOUNT: u32 = 518_400; // ~30 days of ledgers
fn bump_instance(env: &Env) {
env.storage()
.instance()
.extend_ttl(BUMP_THRESHOLD, BUMP_AMOUNT);
}
#[contractimpl]
impl ComplianceContract {
fn key_vk() -> Symbol {
symbol_short!("vk")
}
fn key_admin() -> Symbol {
symbol_short!("admin")
}
fn key_kyc_prefix() -> Symbol {
symbol_short!("kyc")
}
fn key_disclosure_vk() -> Symbol {
symbol_short!("dvk")
}
fn key_pools() -> Symbol {
symbol_short!("pools")
}
fn key_pending_admin() -> Symbol {
symbol_short!("pendadm")
}
pub fn __constructor(
env: Env,
vk_bytes: Bytes,
admin: Address,
pools: soroban_sdk::Vec<Address>,
) -> Result<(), ComplianceError> {
if env.storage().instance().has(&Self::key_vk()) {
return Err(ComplianceError::AlreadyInitialized);
}
let _ = UltraHonkVerifier::new(&env, &vk_bytes).map_err(|e| match e {
VkLoadError::WrongLength => ComplianceError::VkInvalidLength,
VkLoadError::InvalidParameters => ComplianceError::VkInvalidParameters,
})?;
env.storage().instance().set(&Self::key_vk(), &vk_bytes);
env.storage().instance().set(&Self::key_admin(), &admin);
env.storage().instance().set(&Self::key_pools(), &pools);
Ok(())
}
/// Updates the set of pool contracts whose roots/amounts are trusted for
/// compliance and disclosure verification (e.g. when a new tier is added).
pub fn set_pools(env: Env, pools: soroban_sdk::Vec<Address>) -> Result<(), ComplianceError> {
let admin: Address = env
.storage()
.instance()
.get(&Self::key_admin())
.ok_or(ComplianceError::VkNotSet)?;
admin.require_auth();
bump_instance(&env);
let pool_count = pools.len();
env.storage().instance().set(&Self::key_pools(), &pools);
PoolsUpdatedEvent {
pool_count,
updated_by: &admin,
}
.publish(&env);
Ok(())
}
pub fn get_pools(env: Env) -> soroban_sdk::Vec<Address> {
env.storage()
.instance()
.get(&Self::key_pools())
.unwrap_or(SorobanVec::new(&env))
}
/// Step 1 of admin rotation: the current admin nominates `new_admin`.
/// Takes effect only once `new_admin` calls `accept_admin`, so a typoed
/// or unreachable address can never brick admin access.
pub fn propose_admin(env: Env, new_admin: Address) -> Result<(), ComplianceError> {
let admin: Address = env
.storage()
.instance()
.get(&Self::key_admin())
.ok_or(ComplianceError::VkNotSet)?;
admin.require_auth();
bump_instance(&env);
env.storage()
.instance()
.set(&Self::key_pending_admin(), &new_admin);
Ok(())
}
/// Step 2 of admin rotation: the proposed admin claims the role. Must be
/// called by the address passed to `propose_admin`; the previous admin
/// loses access as soon as this succeeds.
pub fn accept_admin(env: Env) -> Result<(), ComplianceError> {
let pending_admin: Address = env
.storage()
.instance()
.get(&Self::key_pending_admin())
.ok_or(ComplianceError::NoPendingAdmin)?;
pending_admin.require_auth();
bump_instance(&env);
let previous_admin: Address = env
.storage()
.instance()
.get(&Self::key_admin())
.ok_or(ComplianceError::VkNotSet)?;
env.storage()
.instance()
.set(&Self::key_admin(), &pending_admin);
env.storage().instance().remove(&Self::key_pending_admin());
AdminUpdatedEvent {
previous_admin: &previous_admin,
new_admin: &pending_admin,
}
.publish(&env);
Ok(())
}
pub fn register_kyc(env: Env, kyc_hash: BytesN<32>) -> Result<(), ComplianceError> {
let admin: Address = env
.storage()
.instance()
.get(&Self::key_admin())
.ok_or(ComplianceError::VkNotSet)?;
admin.require_auth();
bump_instance(&env);
let kyc_key = (Self::key_kyc_prefix(), kyc_hash.clone());
env.storage().instance().set(&kyc_key, &true);
KycRegisteredEvent {
kyc_hash: &kyc_hash,
registrar: &admin,
}
.publish(&env);
Ok(())
}
pub fn is_kyc_registered(env: Env, kyc_hash: BytesN<32>) -> bool {
let kyc_key = (Self::key_kyc_prefix(), kyc_hash);
env.storage().instance().has(&kyc_key)
}
pub fn verify_compliance(
env: Env,
public_inputs: Bytes,
proof_bytes: Bytes,
) -> Result<(), ComplianceError> {
if proof_bytes.len() as usize != PROOF_BYTES {
return Err(ComplianceError::ProofParseError);
}
bump_instance(&env);
// Public inputs: [merkle_root(32), kyc_hash(32), disclosed_amount(32), auditor_key(32)]
if public_inputs.len() != 128 {
return Err(ComplianceError::InvalidPublicInputs);
}
let mut buf = [0u8; 128];
public_inputs.copy_into_slice(&mut buf);
let mut root_arr = [0u8; 32];
root_arr.copy_from_slice(&buf[0..32]);
let merkle_root = BytesN::from_array(&env, &root_arr);
let mut kyc_arr = [0u8; 32];
kyc_arr.copy_from_slice(&buf[32..64]);
let kyc_hash = BytesN::from_array(&env, &kyc_arr);
let kyc_key = (Self::key_kyc_prefix(), kyc_hash.clone());
if !env.storage().instance().has(&kyc_key) {
return Err(ComplianceError::KycNotRegistered);
}
// Authoritative amount binding: `disclosed_amount` is only trustworthy
// if it matches the fixed deposit_amount of whichever configured pool
// the merkle_root actually belongs to (see amount_for_root doc comment).
let pools: SorobanVec<Address> = env
.storage()
.instance()
.get(&Self::key_pools())
.unwrap_or(SorobanVec::new(&env));
let pool_amount =
amount_for_root(&env, &pools, &merkle_root).ok_or(ComplianceError::UnknownMerkleRoot)?;
let mut disclosed_arr = [0u8; 32];
disclosed_arr.copy_from_slice(&buf[64..96]);
if disclosed_arr != amount_to_field_bytes(pool_amount) {
return Err(ComplianceError::AmountMismatch);
}
let mut auditor_arr = [0u8; 32];
auditor_arr.copy_from_slice(&buf[96..128]);
let auditor_key = BytesN::from_array(&env, &auditor_arr);
let vk_bytes: Bytes = env
.storage()
.instance()
.get(&Self::key_vk())
.ok_or(ComplianceError::VkNotSet)?;
let verifier = UltraHonkVerifier::new(&env, &vk_bytes).map_err(|e| match e {
VkLoadError::WrongLength => ComplianceError::VkInvalidLength,
VkLoadError::InvalidParameters => ComplianceError::VkInvalidParameters,
})?;
verifier
.verify(&env, &proof_bytes, &public_inputs)
.map_err(|_| ComplianceError::VerificationFailed)?;
ComplianceVerifiedEvent {
kyc_hash: &kyc_hash,
auditor_key: &auditor_key,
}
.publish(&env);
Ok(())
}
pub fn set_disclosure_vk(env: Env, vk_bytes: Bytes) -> Result<(), ComplianceError> {
let admin: Address = env
.storage()
.instance()
.get(&Self::key_admin())
.ok_or(ComplianceError::VkNotSet)?;
admin.require_auth();
bump_instance(&env);
let _ = UltraHonkVerifier::new(&env, &vk_bytes).map_err(|e| match e {
VkLoadError::WrongLength => ComplianceError::VkInvalidLength,
VkLoadError::InvalidParameters => ComplianceError::VkInvalidParameters,
})?;
env.storage()
.instance()
.set(&Self::key_disclosure_vk(), &vk_bytes);
DisclosureVkUpdatedEvent {
updated_by: &admin,
}
.publish(&env);
Ok(())
}
pub fn verify_disclosure(
env: Env,
public_inputs: Bytes,
proof_bytes: Bytes,
) -> Result<(), ComplianceError> {
if proof_bytes.len() as usize != PROOF_BYTES {
return Err(ComplianceError::ProofParseError);
}
bump_instance(&env);
// Public inputs: [merkle_root(32), kyc_hash(32), threshold(32), auditor_key(32)]
if public_inputs.len() != 128 {
return Err(ComplianceError::InvalidPublicInputs);
}
let mut buf = [0u8; 128];
public_inputs.copy_into_slice(&mut buf);
let mut root_arr = [0u8; 32];
root_arr.copy_from_slice(&buf[0..32]);
let merkle_root = BytesN::from_array(&env, &root_arr);
let mut kyc_arr = [0u8; 32];
kyc_arr.copy_from_slice(&buf[32..64]);
let kyc_hash = BytesN::from_array(&env, &kyc_arr);
let kyc_key = (Self::key_kyc_prefix(), kyc_hash.clone());
if !env.storage().instance().has(&kyc_key) {
return Err(ComplianceError::KycNotRegistered);
}
let vk_bytes: Bytes = env
.storage()
.instance()
.get(&Self::key_disclosure_vk())
.ok_or(ComplianceError::DisclosureVkNotSet)?;
// Authoritative threshold binding: the note's real amount is the
// deposit_amount of whichever configured pool merkle_root belongs to
// (see amount_for_root); the claimed threshold must not exceed it.
let pools: SorobanVec<Address> = env
.storage()
.instance()
.get(&Self::key_pools())
.unwrap_or(SorobanVec::new(&env));
let pool_amount =
amount_for_root(&env, &pools, &merkle_root).ok_or(ComplianceError::UnknownMerkleRoot)?;
let mut threshold_arr = [0u8; 32];
threshold_arr.copy_from_slice(&buf[64..96]);
let threshold_val =
field_bytes_to_u128(&threshold_arr).ok_or(ComplianceError::InvalidPublicInputs)?;
if threshold_val > pool_amount as u128 {
return Err(ComplianceError::ThresholdNotMet);
}
let threshold = BytesN::from_array(&env, &threshold_arr);
let mut auditor_arr = [0u8; 32];
auditor_arr.copy_from_slice(&buf[96..128]);
let auditor_key = BytesN::from_array(&env, &auditor_arr);
let verifier = UltraHonkVerifier::new(&env, &vk_bytes).map_err(|e| match e {
VkLoadError::WrongLength => ComplianceError::VkInvalidLength,
VkLoadError::InvalidParameters => ComplianceError::VkInvalidParameters,
})?;
verifier
.verify(&env, &proof_bytes, &public_inputs)
.map_err(|_| ComplianceError::VerificationFailed)?;
DisclosureVerifiedEvent {
kyc_hash: &kyc_hash,
auditor_key: &auditor_key,
threshold: &threshold,
}
.publish(&env);
Ok(())
}
}
#[cfg(test)]
extern crate std;
#[cfg(test)]
mod tests {
use super::*;
use soroban_sdk::{
testutils::{Address as TestAddress, Events as _, MockAuth, MockAuthInvoke},
Env, Event,
};
fn vk_bytes(env: &Env) -> Bytes {
Bytes::from_slice(
env,
include_bytes!("../../../circuits/compliance/target/vk"),
)
}
fn dummy_hash(env: &Env, seed: u8) -> BytesN<32> {
let mut arr = [0u8; 32];
arr[0] = seed;
BytesN::from_array(env, &arr)
}
fn setup(env: &Env) -> (Address, Address) {
let admin = <Address as TestAddress>::generate(env);
let contract_id: Address = env.register(
ComplianceContract,
(vk_bytes(env), admin.clone(), SorobanVec::<Address>::new(env)),
);
(contract_id, admin)
}
// ──────────────────────────────────────────────
// Constructor
// ──────────────────────────────────────────────
#[test]
fn test_constructor_stores_vk() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
assert!(env.as_contract(&contract_id, || {
env.storage()
.instance()
.has(&ComplianceContract::key_vk())
}));
}
#[test]
fn test_constructor_stores_admin() {
let env = Env::default();
let (contract_id, admin) = setup(&env);
let stored_admin: Address = env.as_contract(&contract_id, || {
env.storage()
.instance()
.get(&ComplianceContract::key_admin())
.unwrap()
});
assert_eq!(stored_admin, admin);
}
#[test]
#[should_panic]
fn test_constructor_invalid_vk_length() {
let env = Env::default();
let admin = <Address as TestAddress>::generate(&env);
let short_vk = Bytes::from_slice(&env, &[0u8; 32]);
let _contract_id: Address = env.register(
ComplianceContract,
(short_vk, admin, SorobanVec::<Address>::new(&env)),
);
}
// ──────────────────────────────────────────────
// KYC Registration
// ──────────────────────────────────────────────
#[test]
fn test_register_kyc_stores_hash() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let kyc_hash = dummy_hash(&env, 1);
client.register_kyc(&kyc_hash);
assert!(client.is_kyc_registered(&kyc_hash));
}
#[test]
fn test_kyc_not_registered_returns_false() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let kyc_hash = dummy_hash(&env, 99);
assert!(!client.is_kyc_registered(&kyc_hash));
}
#[test]
fn test_register_kyc_requires_admin_auth() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let kyc_hash = dummy_hash(&env, 1);
let result = client.try_register_kyc(&kyc_hash);
assert!(result.is_err());
}
#[test]
fn test_multiple_kyc_registrations() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let h1 = dummy_hash(&env, 1);
let h2 = dummy_hash(&env, 2);
let h3 = dummy_hash(&env, 3);
client.register_kyc(&h1);
client.register_kyc(&h2);
assert!(client.is_kyc_registered(&h1));
assert!(client.is_kyc_registered(&h2));
assert!(!client.is_kyc_registered(&h3));
}
#[test]
fn test_register_kyc_idempotent() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let kyc_hash = dummy_hash(&env, 1);
client.register_kyc(&kyc_hash);
client.register_kyc(&kyc_hash);
assert!(client.is_kyc_registered(&kyc_hash));
}
#[test]
fn test_register_kyc_zero_hash() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let zero_hash = BytesN::from_array(&env, &[0u8; 32]);
client.register_kyc(&zero_hash);
assert!(client.is_kyc_registered(&zero_hash));
}
#[test]
fn test_register_kyc_max_hash() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let max_hash = BytesN::from_array(&env, &[0xFF; 32]);
client.register_kyc(&max_hash);
assert!(client.is_kyc_registered(&max_hash));
}
#[test]
fn test_register_kyc_succeeds_with_auth() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let kyc_hash = dummy_hash(&env, 1);
client.register_kyc(&kyc_hash);
assert!(client.is_kyc_registered(&kyc_hash));
}
#[test]
fn test_many_kyc_registrations_isolation() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
for i in 0u8..20 {
let h = dummy_hash(&env, i);
client.register_kyc(&h);
}
for i in 0u8..20 {
let h = dummy_hash(&env, i);
assert!(client.is_kyc_registered(&h));
}
let unregistered = dummy_hash(&env, 200);
assert!(!client.is_kyc_registered(&unregistered));
}
// ──────────────────────────────────────────────
// Compliance Verification: input validation
// ──────────────────────────────────────────────
#[test]
fn test_verify_compliance_bad_public_inputs_length() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let bad_inputs = Bytes::from_slice(&env, &[0u8; 64]);
let proof = Bytes::from_slice(&env, &[0u8; PROOF_BYTES]);
let result = client.try_verify_compliance(&bad_inputs, &proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::InvalidPublicInputs
);
}
#[test]
fn test_verify_compliance_empty_public_inputs() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let empty_inputs = Bytes::from_slice(&env, &[]);
let proof = Bytes::from_slice(&env, &[0u8; PROOF_BYTES]);
let result = client.try_verify_compliance(&empty_inputs, &proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::InvalidPublicInputs
);
}
#[test]
fn test_verify_compliance_oversized_public_inputs() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let big_inputs = Bytes::from_slice(&env, &[0u8; 256]);
let proof = Bytes::from_slice(&env, &[0u8; PROOF_BYTES]);
let result = client.try_verify_compliance(&big_inputs, &proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::InvalidPublicInputs
);
}
#[test]
fn test_verify_compliance_127_bytes_rejected() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let inputs = Bytes::from_slice(&env, &[0u8; 127]);
let proof = Bytes::from_slice(&env, &[0u8; PROOF_BYTES]);
let result = client.try_verify_compliance(&inputs, &proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::InvalidPublicInputs
);
}
#[test]
fn test_verify_compliance_129_bytes_rejected() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let inputs = Bytes::from_slice(&env, &[0u8; 129]);
let proof = Bytes::from_slice(&env, &[0u8; PROOF_BYTES]);
let result = client.try_verify_compliance(&inputs, &proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::InvalidPublicInputs
);
}
// ──────────────────────────────────────────────
// Compliance Verification: KYC gate
// ──────────────────────────────────────────────
#[test]
fn test_verify_compliance_kyc_not_registered() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let mut pi = [0u8; 128];
pi[32] = 0xAB;
let public_inputs = Bytes::from_slice(&env, &pi);
let proof = Bytes::from_slice(&env, &[0u8; PROOF_BYTES]);
let result = client.try_verify_compliance(&public_inputs, &proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::KycNotRegistered
);
}
#[test]
fn test_verify_compliance_wrong_proof_length() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let kyc_hash = dummy_hash(&env, 0xAB);
client.register_kyc(&kyc_hash);
let mut pi = [0u8; 128];
pi[32] = 0xAB;
let public_inputs = Bytes::from_slice(&env, &pi);
let bad_proof = Bytes::from_slice(&env, &[0u8; 100]);
let result = client.try_verify_compliance(&public_inputs, &bad_proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::ProofParseError
);
}
#[test]
fn test_verify_compliance_empty_proof() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let kyc_hash = dummy_hash(&env, 1);
client.register_kyc(&kyc_hash);
let mut pi = [0u8; 128];
pi[32] = 1;
let public_inputs = Bytes::from_slice(&env, &pi);
let empty_proof = Bytes::from_slice(&env, &[]);
let result = client.try_verify_compliance(&public_inputs, &empty_proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::ProofParseError
);
}
#[test]
fn test_verify_compliance_kyc_hash_extraction_exact_position() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let mut kyc_arr = [0u8; 32];
kyc_arr[0] = 0xDE;
kyc_arr[31] = 0xAD;
let kyc_hash = BytesN::from_array(&env, &kyc_arr);
client.register_kyc(&kyc_hash);
let mut pi = [0u8; 128];
pi[32..64].copy_from_slice(&kyc_arr);
let public_inputs = Bytes::from_slice(&env, &pi);
let proof = Bytes::from_slice(&env, &[0u8; PROOF_BYTES]);
// proof is garbage so it will fail at verification, not at KYC check
let result = client.try_verify_compliance(&public_inputs, &proof);
assert_ne!(
result.err().unwrap().unwrap(),
ComplianceError::KycNotRegistered
);
}
#[test]
fn test_verify_compliance_kyc_hash_one_bit_off_rejected() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let kyc_hash = dummy_hash(&env, 0xAA);
client.register_kyc(&kyc_hash);
let mut pi = [0u8; 128];
pi[32] = 0xAB; // one bit different from 0xAA
let public_inputs = Bytes::from_slice(&env, &pi);
let proof = Bytes::from_slice(&env, &[0u8; PROOF_BYTES]);
let result = client.try_verify_compliance(&public_inputs, &proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::KycNotRegistered
);
}
// ──────────────────────────────────────────────
// Compliance Verification: error ordering
// ──────────────────────────────────────────────
#[test]
fn test_proof_length_checked_before_kyc() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let pi = Bytes::from_slice(&env, &[0u8; 128]);
let short_proof = Bytes::from_slice(&env, &[0u8; 100]);
let result = client.try_verify_compliance(&pi, &short_proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::ProofParseError
);
}
#[test]
fn test_public_inputs_length_checked_before_proof_length() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
// Both invalid: short public inputs + short proof
// proof length is checked first in the code
let short_pi = Bytes::from_slice(&env, &[0u8; 64]);
let short_proof = Bytes::from_slice(&env, &[0u8; 100]);
let result = client.try_verify_compliance(&short_pi, &short_proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::ProofParseError
);
}
// ──────────────────────────────────────────────
// Disclosure VK management
// ──────────────────────────────────────────────
fn disclosure_vk_bytes(env: &Env) -> Bytes {
Bytes::from_slice(
env,
include_bytes!("../../../circuits/disclosure/target/vk"),
)
}
#[test]
fn test_set_disclosure_vk_stores_vk() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
client.set_disclosure_vk(&disclosure_vk_bytes(&env));
assert!(env.as_contract(&contract_id, || {
env.storage()
.instance()
.has(&ComplianceContract::key_disclosure_vk())
}));
}
#[test]
fn test_set_disclosure_vk_requires_admin() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let result = client.try_set_disclosure_vk(&disclosure_vk_bytes(&env));
assert!(result.is_err());
}
#[test]
fn test_set_disclosure_vk_invalid_length() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let short_vk = Bytes::from_slice(&env, &[0u8; 32]);
let result = client.try_set_disclosure_vk(&short_vk);
assert!(result.is_err());
}
// ──────────────────────────────────────────────
// Disclosure Verification
// ──────────────────────────────────────────────
#[test]
fn test_verify_disclosure_vk_not_set() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let kyc_hash = dummy_hash(&env, 1);
client.register_kyc(&kyc_hash);
let mut pi = [0u8; 128];
pi[32] = 1;
let public_inputs = Bytes::from_slice(&env, &pi);
let proof = Bytes::from_slice(&env, &[0u8; PROOF_BYTES]);
let result = client.try_verify_disclosure(&public_inputs, &proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::DisclosureVkNotSet
);
}
#[test]
fn test_verify_disclosure_bad_public_inputs_length() {
let env = Env::default();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
let bad_inputs = Bytes::from_slice(&env, &[0u8; 64]);
let proof = Bytes::from_slice(&env, &[0u8; PROOF_BYTES]);
let result = client.try_verify_disclosure(&bad_inputs, &proof);
assert_eq!(
result.err().unwrap().unwrap(),
ComplianceError::InvalidPublicInputs
);
}
#[test]
fn test_verify_disclosure_kyc_not_registered() {
let env = Env::default();
env.mock_all_auths();
let (contract_id, _admin) = setup(&env);
let client = ComplianceContractClient::new(&env, &contract_id);
client.set_disclosure_vk(&disclosure_vk_bytes(&env));