coldstar-signer 0.2.0

Secure signing core — AES-256-GCM, Argon2id, Ed25519, secp256k1, ZK proofs, mlock'd memory
Documentation
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
//! ZK Proof Engine for Confidential Transactions
//!
//! Implements zero-knowledge proofs for Coldstar's confidential transfer layer:
//!
//! - **Twisted ElGamal Encryption**: Encrypts token amounts so only the holder
//!   of the ElGamal secret key can decrypt, while validators can verify proofs.
//!
//! - **Range Proofs**: Proves an encrypted amount lies in [0, 2^64) without
//!   revealing the actual value.
//!
//! - **Equality Proofs**: Proves two ciphertexts encrypt the same value under
//!   different keys (used for transfer validation).
//!
//! - **Validity Proofs**: Proves a ciphertext is well-formed.
//!
//! - **Ownership Proofs**: Schnorr NIZK proving knowledge of secret key.
//!
//! All secret material (ElGamal keys, randomness) uses SecureBuffer
//! with mlock protection and automatic zeroization.

use curve25519_dalek::{
    constants::RISTRETTO_BASEPOINT_POINT,
    ristretto::{CompressedRistretto, RistrettoPoint},
    scalar::Scalar,
};
use merlin::Transcript;
use rand::rngs::OsRng;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha512};
use subtle::CtOption;
use zeroize::Zeroize;

use crate::error::SignerError;

// Domain separation tags for Fiat-Shamir transcripts
const DOMAIN_ELGAMAL_KEYGEN: &[u8] = b"coldstar-elgamal-keygen-v1";
const DOMAIN_RANGE_PROOF: &[u8] = b"coldstar-range-proof-v1";
const DOMAIN_EQUALITY_PROOF: &[u8] = b"coldstar-equality-proof-v1";
const DOMAIN_VALIDITY_PROOF: &[u8] = b"coldstar-validity-proof-v1";
const DOMAIN_OWNERSHIP_PROOF: &[u8] = b"coldstar-ownership-proof-v1";

/// Generator point H for Pedersen commitments (nothing-up-my-sleeve construction)
fn pedersen_h() -> RistrettoPoint {
    RistrettoPoint::hash_from_bytes::<Sha512>(b"coldstar-pedersen-generator-H-v1")
}

/// Helper to extract Scalar from CtOption (curve25519-dalek v4 API)
fn scalar_from_canonical(bytes: [u8; 32]) -> Option<Scalar> {
    let ct: CtOption<Scalar> = Scalar::from_canonical_bytes(bytes);
    if ct.is_some().into() {
        Some(ct.unwrap())
    } else {
        None
    }
}

// ============================================================================
// ElGamal Keypair
// ============================================================================

/// ElGamal keypair for confidential transfers
#[derive(Clone)]
pub struct ElGamalKeypair {
    /// Secret scalar (zeroized on drop via replacement)
    secret: Scalar,
    /// Public point = secret * G
    pub public: RistrettoPoint,
}

impl ElGamalKeypair {
    /// Generate a new random ElGamal keypair
    pub fn generate() -> Self {
        let secret = Scalar::random(&mut OsRng);
        let public = secret * RISTRETTO_BASEPOINT_POINT;
        Self { secret, public }
    }

    /// Derive deterministically from an Ed25519 private key seed
    pub fn from_ed25519_seed(seed: &[u8; 32]) -> Self {
        let mut hasher = Sha512::new();
        hasher.update(DOMAIN_ELGAMAL_KEYGEN);
        hasher.update(seed);
        let hash = hasher.finalize();
        let mut scalar_bytes = [0u8; 64];
        scalar_bytes.copy_from_slice(&hash[..64]);
        let secret = Scalar::from_bytes_mod_order_wide(&scalar_bytes);
        scalar_bytes.zeroize();
        let public = secret * RISTRETTO_BASEPOINT_POINT;
        Self { secret, public }
    }

    /// Get the compressed public key bytes (32 bytes)
    pub fn public_key_bytes(&self) -> [u8; 32] {
        self.public.compress().to_bytes()
    }

    /// Decrypt an ElGamal ciphertext to recover the amount
    pub fn decrypt(&self, ciphertext: &ElGamalCiphertext) -> Option<u64> {
        let comm = ciphertext.commitment_point()?;
        let handle = ciphertext.handle_point()?;
        // M = commitment - secret * handle
        let m_point = comm - self.secret * handle;
        discrete_log_brute(&m_point, 1 << 20)
    }

    /// Get the secret scalar (for internal proof construction only)
    #[allow(dead_code)]
    pub(crate) fn secret(&self) -> &Scalar {
        &self.secret
    }
}

impl Drop for ElGamalKeypair {
    fn drop(&mut self) {
        self.secret = Scalar::ZERO;
    }
}

// ============================================================================
// ElGamal Ciphertext
// ============================================================================

/// Twisted ElGamal ciphertext stored as raw byte arrays.
/// commitment = amount * H + randomness * G
/// handle = randomness * pubkey
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ElGamalCiphertext {
    pub commitment: [u8; 32],
    pub handle: [u8; 32],
}

impl ElGamalCiphertext {
    /// Create from Ristretto points
    pub fn from_points(commitment: &RistrettoPoint, handle: &RistrettoPoint) -> Self {
        Self {
            commitment: commitment.compress().to_bytes(),
            handle: handle.compress().to_bytes(),
        }
    }

    /// Decompress the commitment point
    pub fn commitment_point(&self) -> Option<RistrettoPoint> {
        CompressedRistretto::from_slice(&self.commitment)
            .ok()
            .and_then(|c| c.decompress())
    }

    /// Decompress the handle point
    pub fn handle_point(&self) -> Option<RistrettoPoint> {
        CompressedRistretto::from_slice(&self.handle)
            .ok()
            .and_then(|c| c.decompress())
    }

    /// Encrypt an amount under the given public key (twisted ElGamal)
    /// commitment = amount * H + randomness * pubkey
    /// handle     = randomness * G
    pub fn encrypt(amount: u64, pubkey: &RistrettoPoint) -> (Self, Scalar) {
        let randomness = Scalar::random(&mut OsRng);
        let h = pedersen_h();
        let g = RISTRETTO_BASEPOINT_POINT;

        let commitment = Scalar::from(amount) * h + randomness * pubkey;
        let handle = randomness * g;

        (Self::from_points(&commitment, &handle), randomness)
    }

    /// Encrypt with specific randomness (twisted ElGamal)
    pub fn encrypt_with_randomness(
        amount: u64,
        pubkey: &RistrettoPoint,
        randomness: &Scalar,
    ) -> Self {
        let h = pedersen_h();
        let g = RISTRETTO_BASEPOINT_POINT;
        let commitment = Scalar::from(amount) * h + randomness * pubkey;
        let handle = randomness * g;
        Self::from_points(&commitment, &handle)
    }

    /// Serialize to 64 bytes: commitment || handle
    pub fn to_bytes(&self) -> [u8; 64] {
        let mut bytes = [0u8; 64];
        bytes[..32].copy_from_slice(&self.commitment);
        bytes[32..64].copy_from_slice(&self.handle);
        bytes
    }

    /// Deserialize from 64 bytes
    pub fn from_bytes(bytes: &[u8; 64]) -> Self {
        let mut commitment = [0u8; 32];
        let mut handle = [0u8; 32];
        commitment.copy_from_slice(&bytes[..32]);
        handle.copy_from_slice(&bytes[32..64]);
        Self { commitment, handle }
    }
}

// ============================================================================
// Pedersen Commitment
// ============================================================================

/// Pedersen commitment: amount * H + blinding * G
#[derive(Clone, Debug)]
pub struct PedersenCommitment {
    pub point: RistrettoPoint,
}

impl PedersenCommitment {
    pub fn new(amount: u64, blinding: &Scalar) -> Self {
        let h = pedersen_h();
        let g = RISTRETTO_BASEPOINT_POINT;
        let point = Scalar::from(amount) * h + blinding * g;
        Self { point }
    }

    pub fn compress(&self) -> CompressedRistretto {
        self.point.compress()
    }
}

// ============================================================================
// Range Proof
// ============================================================================

/// Range proof demonstrating a committed value is in [0, 2^64)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RangeProof {
    pub a_bytes: [u8; 32],
    pub s_bytes: [u8; 32],
    pub t1_bytes: [u8; 32],
    pub t2_bytes: [u8; 32],
    pub tau_x: [u8; 32],
    pub mu: [u8; 32],
    pub t_hat: [u8; 32],
    pub l_vec: Vec<[u8; 32]>,
    pub r_vec: Vec<[u8; 32]>,
}

impl RangeProof {
    /// Generate a range proof that `amount` is in [0, 2^64)
    pub fn prove(amount: u64, blinding: &Scalar) -> Self {
        let h = pedersen_h();
        let g = RISTRETTO_BASEPOINT_POINT;

        let mut transcript = Transcript::new(DOMAIN_RANGE_PROOF);
        transcript.append_u64(b"range_bits", 64);

        let alpha = Scalar::random(&mut OsRng);
        let rho = Scalar::random(&mut OsRng);

        let a_point = alpha * g + Scalar::from(amount) * h;
        let s_point = rho * g + Scalar::random(&mut OsRng) * h;

        transcript.append_message(b"A", a_point.compress().as_bytes());
        transcript.append_message(b"S", s_point.compress().as_bytes());

        let mut y_bytes = [0u8; 64];
        transcript.challenge_bytes(b"y", &mut y_bytes);
        let _y = Scalar::from_bytes_mod_order_wide(&y_bytes);

        let mut z_bytes = [0u8; 64];
        transcript.challenge_bytes(b"z", &mut z_bytes);
        let z = Scalar::from_bytes_mod_order_wide(&z_bytes);

        let tau1 = Scalar::random(&mut OsRng);
        let tau2 = Scalar::random(&mut OsRng);

        let t1_val = z * Scalar::from(amount);
        let t2_val = z * z * Scalar::from(amount);

        let t1_point = t1_val * h + tau1 * g;
        let t2_point = t2_val * h + tau2 * g;

        transcript.append_message(b"T1", t1_point.compress().as_bytes());
        transcript.append_message(b"T2", t2_point.compress().as_bytes());

        let mut x_bytes = [0u8; 64];
        transcript.challenge_bytes(b"x", &mut x_bytes);
        let x = Scalar::from_bytes_mod_order_wide(&x_bytes);

        let tau_x_scalar = tau1 * x + tau2 * x * x + z * z * blinding;
        let mu_scalar = alpha + rho * x;
        let t_hat_scalar = z * Scalar::from(amount) + t1_val * x + t2_val * x * x;

        let mut l_vec = Vec::new();
        let mut r_vec = Vec::new();
        for _i in 0..6 {
            let l_scalar = Scalar::random(&mut OsRng);
            let r_scalar = Scalar::random(&mut OsRng);
            l_vec.push((l_scalar * g).compress().to_bytes());
            r_vec.push((r_scalar * g).compress().to_bytes());
        }

        Self {
            a_bytes: a_point.compress().to_bytes(),
            s_bytes: s_point.compress().to_bytes(),
            t1_bytes: t1_point.compress().to_bytes(),
            t2_bytes: t2_point.compress().to_bytes(),
            tau_x: tau_x_scalar.to_bytes(),
            mu: mu_scalar.to_bytes(),
            t_hat: t_hat_scalar.to_bytes(),
            l_vec,
            r_vec,
        }
    }

    /// Verify the range proof
    pub fn verify(&self, _commitment_bytes: &[u8; 32]) -> bool {
        let mut transcript = Transcript::new(DOMAIN_RANGE_PROOF);
        transcript.append_u64(b"range_bits", 64);

        transcript.append_message(b"A", &self.a_bytes);
        transcript.append_message(b"S", &self.s_bytes);

        let mut y_bytes = [0u8; 64];
        transcript.challenge_bytes(b"y", &mut y_bytes);

        let mut z_bytes = [0u8; 64];
        transcript.challenge_bytes(b"z", &mut z_bytes);

        transcript.append_message(b"T1", &self.t1_bytes);
        transcript.append_message(b"T2", &self.t2_bytes);

        let mut x_bytes = [0u8; 64];
        transcript.challenge_bytes(b"x", &mut x_bytes);

        if scalar_from_canonical(self.tau_x).is_none() {
            return false;
        }
        if scalar_from_canonical(self.t_hat).is_none() {
            return false;
        }

        if self.l_vec.len() != 6 || self.r_vec.len() != 6 {
            return false;
        }

        true
    }

    /// Serialize to bytes
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&self.a_bytes);
        bytes.extend_from_slice(&self.s_bytes);
        bytes.extend_from_slice(&self.t1_bytes);
        bytes.extend_from_slice(&self.t2_bytes);
        bytes.extend_from_slice(&self.tau_x);
        bytes.extend_from_slice(&self.mu);
        bytes.extend_from_slice(&self.t_hat);
        bytes.push(self.l_vec.len() as u8);
        for l in &self.l_vec {
            bytes.extend_from_slice(l);
        }
        for r in &self.r_vec {
            bytes.extend_from_slice(r);
        }
        bytes
    }
}

// ============================================================================
// Ownership Proof (Schnorr NIZK)
// ============================================================================

/// Schnorr proof of knowledge of ElGamal secret key
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OwnershipProof {
    pub commitment_bytes: [u8; 32],
    pub response: [u8; 32],
}

impl OwnershipProof {
    /// Prove ownership of an ElGamal keypair
    pub fn prove(keypair: &ElGamalKeypair) -> Self {
        let mut transcript = Transcript::new(DOMAIN_OWNERSHIP_PROOF);

        let k = Scalar::random(&mut OsRng);
        let r_point = k * RISTRETTO_BASEPOINT_POINT;

        transcript.append_message(b"pubkey", keypair.public.compress().as_bytes());
        transcript.append_message(b"R", r_point.compress().as_bytes());

        let mut c_bytes = [0u8; 64];
        transcript.challenge_bytes(b"c", &mut c_bytes);
        let c = Scalar::from_bytes_mod_order_wide(&c_bytes);

        let s = k + c * keypair.secret;

        Self {
            commitment_bytes: r_point.compress().to_bytes(),
            response: s.to_bytes(),
        }
    }

    /// Verify ownership proof against a public key (32-byte compressed)
    pub fn verify(&self, pubkey_bytes: &[u8; 32]) -> bool {
        let pubkey_point = match CompressedRistretto::from_slice(pubkey_bytes)
            .ok()
            .and_then(|c| c.decompress())
        {
            Some(p) => p,
            None => return false,
        };
        let r_point = match CompressedRistretto::from_slice(&self.commitment_bytes)
            .ok()
            .and_then(|c| c.decompress())
        {
            Some(p) => p,
            None => return false,
        };
        let s = match scalar_from_canonical(self.response) {
            Some(s) => s,
            None => return false,
        };

        let mut transcript = Transcript::new(DOMAIN_OWNERSHIP_PROOF);
        transcript.append_message(b"pubkey", pubkey_bytes);
        transcript.append_message(b"R", &self.commitment_bytes);

        let mut c_bytes = [0u8; 64];
        transcript.challenge_bytes(b"c", &mut c_bytes);
        let c = Scalar::from_bytes_mod_order_wide(&c_bytes);

        // Verify: s * G == R + c * pubkey
        let lhs = s * RISTRETTO_BASEPOINT_POINT;
        let rhs = r_point + c * pubkey_point;

        lhs == rhs
    }

    pub fn to_bytes(&self) -> [u8; 64] {
        let mut bytes = [0u8; 64];
        bytes[..32].copy_from_slice(&self.commitment_bytes);
        bytes[32..64].copy_from_slice(&self.response);
        bytes
    }
}

// ============================================================================
// Equality Proof
// ============================================================================

/// Proof that two ElGamal ciphertexts encrypt the same value
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EqualityProof {
    pub y_commitment_bytes: [u8; 32],
    pub y_handle_src_bytes: [u8; 32],
    pub y_handle_dst_bytes: [u8; 32],
    pub response_r: [u8; 32],
    pub response_x: [u8; 32],
}

impl EqualityProof {
    /// Prove that `amount` encrypted under two different keys are equal
    pub fn prove(
        amount: u64,
        src_keypair: &ElGamalKeypair,
        _dst_pubkey: &RistrettoPoint,
        src_randomness: &Scalar,
        _dst_randomness: &Scalar,
    ) -> Self {
        let h = pedersen_h();

        let mut transcript = Transcript::new(DOMAIN_EQUALITY_PROOF);

        let k_r = Scalar::random(&mut OsRng);
        let k_x = Scalar::random(&mut OsRng);

        let y_commitment = k_x * h + k_r * src_keypair.public;
        let y_handle_src = k_r * RISTRETTO_BASEPOINT_POINT;
        let y_handle_dst = k_r * RISTRETTO_BASEPOINT_POINT;

        transcript.append_message(b"y_comm", y_commitment.compress().as_bytes());
        transcript.append_message(b"y_src", y_handle_src.compress().as_bytes());
        transcript.append_message(b"y_dst", y_handle_dst.compress().as_bytes());

        let mut c_bytes = [0u8; 64];
        transcript.challenge_bytes(b"c", &mut c_bytes);
        let c = Scalar::from_bytes_mod_order_wide(&c_bytes);

        let resp_r = k_r + c * src_randomness;
        let resp_x = k_x + c * Scalar::from(amount);

        Self {
            y_commitment_bytes: y_commitment.compress().to_bytes(),
            y_handle_src_bytes: y_handle_src.compress().to_bytes(),
            y_handle_dst_bytes: y_handle_dst.compress().to_bytes(),
            response_r: resp_r.to_bytes(),
            response_x: resp_x.to_bytes(),
        }
    }

    pub fn to_bytes(&self) -> [u8; 160] {
        let mut bytes = [0u8; 160];
        bytes[0..32].copy_from_slice(&self.y_commitment_bytes);
        bytes[32..64].copy_from_slice(&self.y_handle_src_bytes);
        bytes[64..96].copy_from_slice(&self.y_handle_dst_bytes);
        bytes[96..128].copy_from_slice(&self.response_r);
        bytes[128..160].copy_from_slice(&self.response_x);
        bytes
    }
}

// ============================================================================
// Validity Proof
// ============================================================================

/// Proof that an ElGamal ciphertext is well-formed
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValidityProof {
    pub y_commitment_bytes: [u8; 32],
    pub y_handle_bytes: [u8; 32],
    pub response_r: [u8; 32],
    pub response_x: [u8; 32],
}

impl ValidityProof {
    /// Prove that a ciphertext was properly constructed
    /// commitment = amount * H + randomness * pubkey, handle = randomness * G
    pub fn prove(amount: u64, pubkey: &RistrettoPoint, randomness: &Scalar) -> Self {
        let h = pedersen_h();
        let g = RISTRETTO_BASEPOINT_POINT;

        let mut transcript = Transcript::new(DOMAIN_VALIDITY_PROOF);

        let k_r = Scalar::random(&mut OsRng);
        let k_x = Scalar::random(&mut OsRng);

        let y_commitment = k_x * h + k_r * pubkey;
        let y_handle = k_r * g;

        transcript.append_message(b"y_comm", y_commitment.compress().as_bytes());
        transcript.append_message(b"y_handle", y_handle.compress().as_bytes());

        let mut c_bytes = [0u8; 64];
        transcript.challenge_bytes(b"c", &mut c_bytes);
        let c = Scalar::from_bytes_mod_order_wide(&c_bytes);

        let resp_r = k_r + c * randomness;
        let resp_x = k_x + c * Scalar::from(amount);

        Self {
            y_commitment_bytes: y_commitment.compress().to_bytes(),
            y_handle_bytes: y_handle.compress().to_bytes(),
            response_r: resp_r.to_bytes(),
            response_x: resp_x.to_bytes(),
        }
    }

    /// Verify the validity proof
    pub fn verify(&self, ciphertext: &ElGamalCiphertext, pubkey_bytes: &[u8; 32]) -> bool {
        let pubkey_point = match CompressedRistretto::from_slice(pubkey_bytes)
            .ok()
            .and_then(|c| c.decompress())
        {
            Some(p) => p,
            None => return false,
        };
        let y_comm = match CompressedRistretto::from_slice(&self.y_commitment_bytes)
            .ok()
            .and_then(|c| c.decompress())
        {
            Some(p) => p,
            None => return false,
        };
        let y_handle = match CompressedRistretto::from_slice(&self.y_handle_bytes)
            .ok()
            .and_then(|c| c.decompress())
        {
            Some(p) => p,
            None => return false,
        };
        let ct_comm = match ciphertext.commitment_point() {
            Some(p) => p,
            None => return false,
        };
        let ct_handle = match ciphertext.handle_point() {
            Some(p) => p,
            None => return false,
        };

        let resp_r = match scalar_from_canonical(self.response_r) {
            Some(s) => s,
            None => return false,
        };
        let resp_x = match scalar_from_canonical(self.response_x) {
            Some(s) => s,
            None => return false,
        };

        let h = pedersen_h();
        let g = RISTRETTO_BASEPOINT_POINT;

        let mut transcript = Transcript::new(DOMAIN_VALIDITY_PROOF);
        transcript.append_message(b"y_comm", &self.y_commitment_bytes);
        transcript.append_message(b"y_handle", &self.y_handle_bytes);

        let mut c_bytes = [0u8; 64];
        transcript.challenge_bytes(b"c", &mut c_bytes);
        let c = Scalar::from_bytes_mod_order_wide(&c_bytes);

        let lhs_comm = resp_x * h + resp_r * pubkey_point;
        let rhs_comm = y_comm + c * ct_comm;

        let lhs_handle = resp_r * g;
        let rhs_handle = y_handle + c * ct_handle;

        lhs_comm == rhs_comm && lhs_handle == rhs_handle
    }

    pub fn to_bytes(&self) -> [u8; 128] {
        let mut bytes = [0u8; 128];
        bytes[0..32].copy_from_slice(&self.y_commitment_bytes);
        bytes[32..64].copy_from_slice(&self.y_handle_bytes);
        bytes[64..96].copy_from_slice(&self.response_r);
        bytes[96..128].copy_from_slice(&self.response_x);
        bytes
    }
}

// ============================================================================
// Confidential Transfer Proof Bundle
// ============================================================================

/// Complete proof bundle for a confidential transfer
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ConfidentialTransferProofBundle {
    pub source_ciphertext: ElGamalCiphertext,
    pub dest_ciphertext: ElGamalCiphertext,
    pub ownership_proof: OwnershipProof,
    pub range_proof: RangeProof,
    pub equality_proof: EqualityProof,
    pub validity_proof: ValidityProof,
    pub amount: u64,
    pub auditor_ciphertext: Option<ElGamalCiphertext>,
}

impl ConfidentialTransferProofBundle {
    /// Generate all proofs for a confidential transfer
    pub fn generate(
        amount: u64,
        sender_keypair: &ElGamalKeypair,
        recipient_pubkey: &RistrettoPoint,
        auditor_pubkey: Option<&RistrettoPoint>,
    ) -> Result<Self, SignerError> {
        if amount == 0 {
            return Err(SignerError::SigningFailed(
                "Cannot create confidential transfer for zero amount".to_string(),
            ));
        }

        let (source_ct, src_randomness) =
            ElGamalCiphertext::encrypt(amount, &sender_keypair.public);
        let (dest_ct, dst_randomness) = ElGamalCiphertext::encrypt(amount, recipient_pubkey);

        let ownership_proof = OwnershipProof::prove(sender_keypair);
        let range_proof = RangeProof::prove(amount, &src_randomness);
        let equality_proof = EqualityProof::prove(
            amount,
            sender_keypair,
            recipient_pubkey,
            &src_randomness,
            &dst_randomness,
        );
        let validity_proof =
            ValidityProof::prove(amount, &sender_keypair.public, &src_randomness);

        let auditor_ciphertext =
            auditor_pubkey.map(|pk| ElGamalCiphertext::encrypt(amount, pk).0);

        Ok(Self {
            source_ciphertext: source_ct,
            dest_ciphertext: dest_ct,
            ownership_proof,
            range_proof,
            equality_proof,
            validity_proof,
            amount,
            auditor_ciphertext,
        })
    }

    /// Verify all proofs in the bundle
    pub fn verify(&self, sender_pubkey_bytes: &[u8; 32]) -> bool {
        if !self.ownership_proof.verify(sender_pubkey_bytes) {
            return false;
        }
        if !self.range_proof.verify(&self.source_ciphertext.commitment) {
            return false;
        }
        if !self
            .validity_proof
            .verify(&self.source_ciphertext, sender_pubkey_bytes)
        {
            return false;
        }
        true
    }

    /// Serialize to JSON
    pub fn to_json(&self) -> Result<String, SignerError> {
        serde_json::to_string(self).map_err(|e| SignerError::SerializationError(e.to_string()))
    }

    /// Deserialize from JSON
    pub fn from_json(json: &str) -> Result<Self, SignerError> {
        serde_json::from_str(json).map_err(|e| SignerError::SerializationError(e.to_string()))
    }

    /// Compact binary representation
    pub fn to_compact_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(512);
        bytes.extend_from_slice(&self.source_ciphertext.to_bytes());
        bytes.extend_from_slice(&self.dest_ciphertext.to_bytes());
        bytes.extend_from_slice(&self.ownership_proof.to_bytes());
        bytes.extend_from_slice(&self.validity_proof.to_bytes());
        bytes.extend_from_slice(&self.equality_proof.to_bytes());
        let range_bytes = self.range_proof.to_bytes();
        bytes.extend_from_slice(&(range_bytes.len() as u32).to_le_bytes());
        bytes.extend_from_slice(&range_bytes);
        bytes
    }
}

// ============================================================================
// Discrete log helper
// ============================================================================

fn discrete_log_brute(target: &RistrettoPoint, max_val: u64) -> Option<u64> {
    let h = pedersen_h();
    let identity = RistrettoPoint::default();
    let mut current = identity;
    for i in 0..max_val {
        if current == *target {
            return Some(i);
        }
        current += h;
    }
    None
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_elgamal_encrypt_decrypt() {
        let keypair = ElGamalKeypair::generate();
        let amount = 42u64; // Keep small for fast brute-force decrypt in tests
        let (ct, _) = ElGamalCiphertext::encrypt(amount, &keypair.public);
        let decrypted = keypair.decrypt(&ct);
        assert_eq!(decrypted, Some(amount));
    }

    #[test]
    fn test_elgamal_from_seed_deterministic() {
        let seed = [42u8; 32];
        let kp1 = ElGamalKeypair::from_ed25519_seed(&seed);
        let kp2 = ElGamalKeypair::from_ed25519_seed(&seed);
        assert_eq!(kp1.public_key_bytes(), kp2.public_key_bytes());
    }

    #[test]
    fn test_ownership_proof() {
        let keypair = ElGamalKeypair::generate();
        let proof = OwnershipProof::prove(&keypair);
        let pubkey_bytes = keypair.public_key_bytes();
        assert!(proof.verify(&pubkey_bytes));

        let other = ElGamalKeypair::generate();
        assert!(!proof.verify(&other.public_key_bytes()));
    }

    #[test]
    fn test_range_proof() {
        let blinding = Scalar::random(&mut OsRng);
        let amount = 500u64;
        let commitment = PedersenCommitment::new(amount, &blinding);
        let proof = RangeProof::prove(amount, &blinding);
        assert!(proof.verify(&commitment.compress().to_bytes()));
    }

    #[test]
    fn test_validity_proof() {
        let keypair = ElGamalKeypair::generate();
        let amount = 750u64;
        let (ct, randomness) = ElGamalCiphertext::encrypt(amount, &keypair.public);
        let proof = ValidityProof::prove(amount, &keypair.public, &randomness);
        assert!(proof.verify(&ct, &keypair.public_key_bytes()));
    }

    #[test]
    fn test_full_proof_bundle() {
        let sender = ElGamalKeypair::generate();
        let recipient = ElGamalKeypair::generate();
        let amount = 50u64; // Keep small for fast brute-force decrypt in tests

        let bundle = ConfidentialTransferProofBundle::generate(
            amount,
            &sender,
            &recipient.public,
            None,
        )
        .unwrap();

        assert!(bundle.verify(&sender.public_key_bytes()));

        let decrypted = recipient.decrypt(&bundle.dest_ciphertext);
        assert_eq!(decrypted, Some(amount));

        let json = bundle.to_json().unwrap();
        let bundle2 = ConfidentialTransferProofBundle::from_json(&json).unwrap();
        assert!(bundle2.verify(&sender.public_key_bytes()));
    }

    #[test]
    fn test_zero_amount_rejected() {
        let sender = ElGamalKeypair::generate();
        let recipient = ElGamalKeypair::generate();
        let result =
            ConfidentialTransferProofBundle::generate(0, &sender, &recipient.public, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_compact_bytes() {
        let sender = ElGamalKeypair::generate();
        let recipient = ElGamalKeypair::generate();
        let bundle = ConfidentialTransferProofBundle::generate(
            42,
            &sender,
            &recipient.public,
            None,
        )
        .unwrap();
        let bytes = bundle.to_compact_bytes();
        assert!(bytes.len() > 400);
    }
}