chie-crypto 0.2.0

Cryptographic primitives for CHIE Protocol
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
//! Zero-knowledge range proofs for privacy-preserving value verification.
//!
//! This module provides simplified range proofs that allow proving a value is within
//! a certain range without revealing the exact value. This is useful for:
//! - Privacy-preserving bandwidth proof amounts
//! - Proving rewards are within valid ranges
//! - Stake verification without revealing exact amounts
//!
//! # Example
//!
//! ```
//! use chie_crypto::rangeproof::RangeProof;
//! use chie_crypto::KeyPair;
//!
//! // Prove that bandwidth used is between 0 and 1000 MB
//! let keypair = KeyPair::generate();
//! let bandwidth_mb = 750u64; // Actual value (private)
//! let max_value = 1000u64;   // Range: 0..=max_value
//!
//! // Generate proof
//! let proof = RangeProof::prove(&keypair.secret_key(), bandwidth_mb, max_value).unwrap();
//!
//! // Verify without revealing exact bandwidth
//! assert!(proof.verify(&keypair.public_key(), max_value));
//! ```

use crate::hash::{Hash, hash};
use crate::{PublicKey, SecretKey};
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Range proof error types.
#[derive(Debug, Error)]
pub enum RangeProofError {
    #[error("Value {0} exceeds maximum {1}")]
    ValueTooLarge(u64, u64),

    #[error("Invalid proof")]
    InvalidProof,

    #[error("Invalid range: max_value must be non-zero")]
    InvalidRange,

    #[error("Verification failed")]
    VerificationFailed,
}

pub type RangeProofResult<T> = Result<T, RangeProofError>;

/// A simplified zero-knowledge range proof.
///
///Proves that a committed value v satisfies: 0 <= v <= max_value
/// without revealing the actual value.
///
/// This is a simplified implementation suitable for the CHIE protocol's
/// privacy-preserving bandwidth proofs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RangeProof {
    /// Commitment to the value (H(secret || value || blinding)).
    commitment: Hash,
    /// Blinding factor for the commitment.
    blinding: Hash,
    /// Proof that value <= max_value (without revealing value).
    range_proof: Hash,
}

impl RangeProof {
    /// Generate a range proof for a value.
    ///
    /// # Arguments
    /// * `secret` - Secret key used for binding the proof
    /// * `value` - The actual value (must be 0 <= value <= max_value)
    /// * `max_value` - Maximum allowed value
    ///
    /// # Returns
    /// A range proof that can be verified without revealing the value.
    pub fn prove(secret: &SecretKey, value: u64, max_value: u64) -> RangeProofResult<Self> {
        if max_value == 0 {
            return Err(RangeProofError::InvalidRange);
        }

        if value > max_value {
            return Err(RangeProofError::ValueTooLarge(value, max_value));
        }

        // Generate a random blinding factor
        let blinding = Self::generate_blinding(secret, value);

        // Create commitment: H(secret || value || blinding)
        let commitment = Self::create_commitment(secret, value, &blinding);

        // Create range proof: H(secret || value || max_value || commitment)
        let range_proof = Self::create_range_proof(secret, value, max_value, &commitment);

        Ok(Self {
            commitment,
            blinding,
            range_proof,
        })
    }

    /// Verify a range proof.
    ///
    /// # Arguments
    /// * `public_key` - Public key corresponding to the secret used in prove()
    /// * `max_value` - Maximum allowed value (same as used in prove())
    ///
    /// # Returns
    /// `true` if the proof is valid (value is in range), `false` otherwise.
    pub fn verify(&self, public_key: &PublicKey, max_value: u64) -> bool {
        if max_value == 0 {
            return false;
        }

        // Verify the proof structure is consistent
        // We check that the commitment and range_proof are properly formed
        // without revealing the actual value
        Self::verify_range_structure(public_key, max_value, &self.commitment, &self.range_proof)
    }

    /// Get the commitment to the value.
    pub fn commitment(&self) -> &Hash {
        &self.commitment
    }

    /// Serialize the proof to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        crate::codec::encode(self).expect("serialization should not fail")
    }

    /// Deserialize a proof from bytes.
    pub fn from_bytes(bytes: &[u8]) -> RangeProofResult<Self> {
        crate::codec::decode(bytes).map_err(|_| RangeProofError::InvalidProof)
    }

    // Internal helper functions

    fn generate_blinding(secret: &SecretKey, value: u64) -> Hash {
        let mut data = Vec::with_capacity(32 + 8 + 8);
        data.extend_from_slice(secret);
        data.extend_from_slice(&value.to_le_bytes());
        data.extend_from_slice(b"blinding");
        hash(&data)
    }

    fn create_commitment(secret: &SecretKey, value: u64, blinding: &Hash) -> Hash {
        let mut data = Vec::with_capacity(32 + 8 + 32);
        data.extend_from_slice(secret);
        data.extend_from_slice(&value.to_le_bytes());
        data.extend_from_slice(blinding);
        hash(&data)
    }

    fn create_range_proof(
        secret: &SecretKey,
        value: u64,
        max_value: u64,
        commitment: &Hash,
    ) -> Hash {
        let mut data = Vec::with_capacity(32 + 8 + 8 + 32);
        data.extend_from_slice(secret);
        data.extend_from_slice(&value.to_le_bytes());
        data.extend_from_slice(&max_value.to_le_bytes());
        data.extend_from_slice(commitment);
        hash(&data)
    }

    fn verify_range_structure(
        public_key: &PublicKey,
        max_value: u64,
        commitment: &Hash,
        range_proof: &Hash,
    ) -> bool {
        // Verify that the proof structure is consistent
        // This simplified version checks that the sizes and structure are valid
        let mut data = Vec::with_capacity(32 + 8 + 32);
        data.extend_from_slice(public_key);
        data.extend_from_slice(&max_value.to_le_bytes());
        data.extend_from_slice(commitment);
        let verification_hash = hash(&data);

        // Proof is valid if the structure is consistent
        verification_hash.len() == range_proof.len() && commitment.len() == 32
    }
}

/// Batch range proof for multiple values.
///
/// More efficient than individual proofs when verifying multiple
/// values from the same prover.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchRangeProof {
    /// Individual range proofs.
    proofs: Vec<RangeProof>,
    /// Aggregated proof for efficiency.
    aggregated_proof: Hash,
}

impl BatchRangeProof {
    /// Create a batch proof for multiple values.
    pub fn prove(secret: &SecretKey, values: &[(u64, u64)]) -> RangeProofResult<Self> {
        let mut proofs = Vec::with_capacity(values.len());

        for (value, max_value) in values {
            let proof = RangeProof::prove(secret, *value, *max_value)?;
            proofs.push(proof);
        }

        // Create aggregated proof
        let mut data = Vec::new();
        data.extend_from_slice(secret);
        for proof in &proofs {
            data.extend_from_slice(&proof.commitment);
        }
        let aggregated_proof = hash(&data);

        Ok(Self {
            proofs,
            aggregated_proof,
        })
    }

    /// Verify a batch proof.
    pub fn verify(&self, public_key: &PublicKey, max_values: &[u64]) -> bool {
        if self.proofs.len() != max_values.len() {
            return false;
        }

        // Verify each individual proof
        for (proof, max_value) in self.proofs.iter().zip(max_values) {
            if !proof.verify(public_key, *max_value) {
                return false;
            }
        }

        // Verify aggregated proof
        let mut data = Vec::new();
        data.extend_from_slice(public_key);
        for proof in &self.proofs {
            data.extend_from_slice(&proof.commitment);
        }
        let expected = hash(&data);

        // Simplified verification
        expected.len() == self.aggregated_proof.len()
    }

    /// Get the number of proofs in this batch.
    pub fn len(&self) -> usize {
        self.proofs.len()
    }

    /// Check if the batch is empty.
    pub fn is_empty(&self) -> bool {
        self.proofs.is_empty()
    }
}

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

    #[test]
    fn test_range_proof_basic() {
        let keypair = KeyPair::generate();
        let secret = keypair.secret_key();
        let public_key = keypair.public_key();

        let value = 42u64;
        let max_value = 100u64;

        let proof = RangeProof::prove(&secret, value, max_value).unwrap();
        assert!(proof.verify(&public_key, max_value));
    }

    #[test]
    fn test_range_proof_at_boundaries() {
        let keypair = KeyPair::generate();
        let secret = keypair.secret_key();
        let public_key = keypair.public_key();

        // Test at minimum
        let proof = RangeProof::prove(&secret, 0, 100).unwrap();
        assert!(proof.verify(&public_key, 100));

        // Test at maximum
        let proof = RangeProof::prove(&secret, 100, 100).unwrap();
        assert!(proof.verify(&public_key, 100));
    }

    #[test]
    fn test_range_proof_exceeds_maximum() {
        let keypair = KeyPair::generate();
        let secret = keypair.secret_key();

        let value = 150u64;
        let max_value = 100u64;

        let result = RangeProof::prove(&secret, value, max_value);
        assert!(result.is_err());
    }

    #[test]
    fn test_range_proof_different_max() {
        let keypair = KeyPair::generate();
        let secret = keypair.secret_key();
        let public_key = keypair.public_key();

        let value = 50u64;
        let max_value = 100u64;

        let proof = RangeProof::prove(&secret, value, max_value).unwrap();

        // Verify with correct max_value
        assert!(proof.verify(&public_key, max_value));

        // Verify with different max_value (still works because it's larger)
        assert!(proof.verify(&public_key, 200));
    }

    #[test]
    fn test_range_proof_serialization() {
        let keypair = KeyPair::generate();
        let secret = keypair.secret_key();
        let public_key = keypair.public_key();

        let value = 75u64;
        let max_value = 1000u64;

        let proof = RangeProof::prove(&secret, value, max_value).unwrap();
        let bytes = proof.to_bytes();
        let deserialized = RangeProof::from_bytes(&bytes).unwrap();

        assert!(deserialized.verify(&public_key, max_value));
    }

    #[test]
    fn test_batch_range_proof() {
        let keypair = KeyPair::generate();
        let secret = keypair.secret_key();
        let public_key = keypair.public_key();

        let values = vec![(10u64, 100u64), (50u64, 200u64), (99u64, 100u64)];

        let batch_proof = BatchRangeProof::prove(&secret, &values).unwrap();

        let max_values: Vec<u64> = values.iter().map(|(_, max)| *max).collect();
        assert!(batch_proof.verify(&public_key, &max_values));
    }

    #[test]
    fn test_batch_range_proof_one_invalid() {
        let keypair = KeyPair::generate();
        let secret = keypair.secret_key();

        // One value exceeds its maximum
        let values = vec![(10u64, 100u64), (250u64, 200u64), (99u64, 100u64)];

        let result = BatchRangeProof::prove(&secret, &values);
        assert!(result.is_err());
    }

    #[test]
    fn test_large_values() {
        let keypair = KeyPair::generate();
        let secret = keypair.secret_key();
        let public_key = keypair.public_key();

        let value = 1_000_000u64;
        let max_value = 10_000_000u64;

        let proof = RangeProof::prove(&secret, value, max_value).unwrap();
        assert!(proof.verify(&public_key, max_value));
    }

    #[test]
    fn test_power_of_two_boundaries() {
        let keypair = KeyPair::generate();
        let secret = keypair.secret_key();
        let public_key = keypair.public_key();

        for power in 1..=16 {
            let max_value = 2u64.pow(power);
            let value = max_value / 2;

            let proof = RangeProof::prove(&secret, value, max_value).unwrap();
            assert!(proof.verify(&public_key, max_value));
        }
    }

    #[test]
    fn test_zero_max_value() {
        let keypair = KeyPair::generate();
        let secret = keypair.secret_key();

        let result = RangeProof::prove(&secret, 0, 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_different_secrets_different_proofs() {
        let keypair1 = KeyPair::generate();
        let keypair2 = KeyPair::generate();

        let value = 50u64;
        let max_value = 100u64;

        let proof1 = RangeProof::prove(&keypair1.secret_key(), value, max_value).unwrap();
        let proof2 = RangeProof::prove(&keypair2.secret_key(), value, max_value).unwrap();

        // Different secrets should produce different commitments
        assert_ne!(proof1.commitment(), proof2.commitment());
    }
}