newton-core 0.4.16

newton protocol core sdk
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
//! TOML-friendly configuration types for threshold decryption.
//!
//! These types use hex-encoded strings for cryptographic values (EdwardsPoint,
//! Scalar) so they can be written in human-readable TOML config files. They
//! convert to the internal `dkg::types` at load time.

use curve25519_dalek::{
    constants::ED25519_BASEPOINT_POINT,
    edwards::{CompressedEdwardsY, EdwardsPoint},
    scalar::Scalar,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use super::types::{KeyShare, ThresholdConfig, ThresholdDecryptionContext, ThresholdPublicKey};
#[cfg(feature = "frost-dkg")]
use super::types::{SerializableKeyShare, SerializableThresholdContext};
use crate::crypto::error::CryptoError;
#[cfg(feature = "frost-dkg")]
use std::path::Path;

/// Gateway-side threshold config (TOML-friendly).
///
/// Contains the threshold public key and operator public shares needed to
/// verify partial decryptions and combine them via Lagrange interpolation.
///
/// ```toml
/// [threshold]
/// enabled = true
/// threshold = 2
/// total = 3
/// # Master public key (compressed Edwards Y, 32 bytes hex)
/// master_public_key = "abcd1234..."
/// # Operator public shares: index -> compressed Edwards Y hex
/// [threshold.public_shares]
/// 1 = "1111..."
/// 2 = "2222..."
/// 3 = "3333..."
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ThresholdGatewayConfig {
    /// Enable threshold decryption mode
    #[serde(default)]
    pub enabled: bool,
    /// Minimum shares required to reconstruct (t)
    pub threshold: u32,
    /// Total shares distributed (n)
    pub total: u32,
    /// Master public key as hex-encoded compressed Edwards Y (64 hex chars = 32 bytes)
    pub master_public_key: String,
    /// Operator public shares keyed by 1-based index, hex-encoded compressed Edwards Y
    #[serde(default)]
    pub public_shares: HashMap<String, String>,
    /// Path to encrypted keystore file for threshold context persistence.
    /// When set (with THRESHOLD_KEYSTORE_PASSWORD env var), the gateway loads
    /// threshold context from keystore at startup and persists DKG ceremony
    /// output to this path on completion.
    #[serde(default)]
    pub keystore_path: Option<String>,
}

impl ThresholdGatewayConfig {
    /// Load threshold context with priority: keystore file > TOML hex config.
    ///
    /// If both `keystore_path` and `keystore_password` are `Some` and the file
    /// exists, it is decrypted and deserialized. Otherwise falls back to
    /// [`Self::to_threshold_context`].
    #[cfg(feature = "frost-dkg")]
    pub fn load_threshold_context_with_keystore(
        &self,
        keystore_path: Option<&Path>,
        keystore_password: Option<&[u8]>,
    ) -> Result<ThresholdDecryptionContext, CryptoError> {
        if let (Some(path), Some(password)) = (keystore_path, keystore_password) {
            if path.exists() {
                let plaintext = crate::dkg::keystore::read_keystore(path, password)?;
                let ctx: SerializableThresholdContext = serde_json::from_slice(&plaintext)
                    .map_err(|e| CryptoError::KeystoreDecrypt(format!("deserialize threshold context: {e}")))?;
                return ctx.to_threshold_context();
            }
        }

        // Priority 2: TOML hex config
        self.to_threshold_context()
    }

    /// Convert to internal `ThresholdDecryptionContext`.
    ///
    /// Parses hex strings into Edwards points and validates the configuration.
    pub fn to_threshold_context(&self) -> Result<ThresholdDecryptionContext, CryptoError> {
        if !self.enabled {
            return Err(CryptoError::ThresholdDecrypt("threshold not enabled".into()));
        }
        if self.threshold > self.total {
            return Err(CryptoError::ThresholdDecrypt(format!(
                "threshold ({}) exceeds total ({})",
                self.threshold, self.total
            )));
        }
        if self.public_shares.len() as u32 != self.total {
            return Err(CryptoError::ThresholdDecrypt(format!(
                "expected {} public shares, got {}",
                self.total,
                self.public_shares.len()
            )));
        }

        let mpk_edwards = parse_edwards_hex(&self.master_public_key)?;
        let mpk_montgomery = mpk_edwards.to_montgomery().to_bytes();

        let mut public_shares = HashMap::with_capacity(self.public_shares.len());
        for (idx_str, hex) in &self.public_shares {
            let idx: u32 = idx_str
                .parse()
                .map_err(|e| CryptoError::ThresholdDecrypt(format!("invalid operator index '{}': {}", idx_str, e)))?;
            let point = parse_edwards_hex(hex)?;
            public_shares.insert(idx, point);
        }

        Ok(ThresholdDecryptionContext {
            public_key: ThresholdPublicKey {
                edwards: mpk_edwards,
                hpke_public_key: mpk_montgomery,
            },
            public_shares,
            config: ThresholdConfig {
                threshold: self.threshold,
                total: self.total,
            },
        })
    }
}

/// Operator-side threshold key share config (TOML-friendly).
///
/// Contains this operator's secret share for computing partial decryptions.
///
/// ```toml
/// [threshold]
/// enabled = true
/// index = 1
/// # Secret share as hex-encoded Scalar (64 hex chars = 32 bytes, little-endian)
/// secret_share = "abcd1234..."
/// ```
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ThresholdOperatorConfig {
    /// Enable threshold decryption for this operator
    #[serde(default)]
    pub enabled: bool,
    /// Operator index (1-based, matches DKG share assignment)
    pub index: u32,
    /// Secret share as hex-encoded bytes (64 hex chars = 32 bytes, little-endian Scalar)
    pub secret_share: String,
    /// Path to encrypted keystore file for key share persistence.
    /// When set (with THRESHOLD_KEYSTORE_PASSWORD env var), the operator persists
    /// key shares from FROST DKG ceremonies and loads them at startup.
    #[serde(default)]
    pub keystore_path: Option<String>,
}

impl std::fmt::Debug for ThresholdOperatorConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ThresholdOperatorConfig")
            .field("enabled", &self.enabled)
            .field("index", &self.index)
            .field("secret_share", &"[REDACTED]")
            .field("keystore_path", &self.keystore_path)
            .finish()
    }
}

impl ThresholdOperatorConfig {
    /// Load key share with priority: keystore file > TOML hex config.
    ///
    /// If both `keystore_path` and `keystore_password` are `Some` and the file
    /// exists, it is decrypted and deserialized. Otherwise falls back to
    /// [`Self::to_key_share`].
    #[cfg(feature = "frost-dkg")]
    pub fn load_key_share_with_keystore(
        &self,
        keystore_path: Option<&Path>,
        keystore_password: Option<&[u8]>,
    ) -> Result<KeyShare, CryptoError> {
        if let (Some(path), Some(password)) = (keystore_path, keystore_password) {
            if path.exists() {
                let plaintext = crate::dkg::keystore::read_keystore(path, password)?;
                let serializable: SerializableKeyShare = serde_json::from_slice(&plaintext)
                    .map_err(|e| CryptoError::KeystoreDecrypt(format!("deserialize key share: {e}")))?;
                return serializable.to_key_share();
            }
        }

        // Priority 2: TOML hex config
        self.to_key_share()
    }

    /// Convert to internal `KeyShare`.
    ///
    /// Parses the hex-encoded secret share and derives the public share.
    pub fn to_key_share(&self) -> Result<KeyShare, CryptoError> {
        if !self.enabled {
            return Err(CryptoError::ThresholdDecrypt("threshold not enabled".into()));
        }
        if self.index == 0 {
            return Err(CryptoError::ThresholdDecrypt(
                "operator index must be >= 1 (1-based indexing)".into(),
            ));
        }

        let secret_share = parse_scalar_hex(&self.secret_share)?;
        let public_share = secret_share * ED25519_BASEPOINT_POINT;

        Ok(KeyShare {
            index: self.index,
            secret_share,
            public_share,
        })
    }
}

/// Parse a hex-encoded compressed Edwards Y point (32 bytes = 64 hex chars).
fn parse_edwards_hex(hex: &str) -> Result<EdwardsPoint, CryptoError> {
    let hex = hex.strip_prefix("0x").unwrap_or(hex);
    let bytes =
        hex::decode(hex).map_err(|e| CryptoError::ThresholdDecrypt(format!("invalid hex for Edwards point: {}", e)))?;

    if bytes.len() != 32 {
        return Err(CryptoError::ThresholdDecrypt(format!(
            "Edwards point must be 32 bytes, got {}",
            bytes.len()
        )));
    }

    let mut arr = [0u8; 32];
    arr.copy_from_slice(&bytes);

    CompressedEdwardsY(arr)
        .decompress()
        .ok_or_else(|| CryptoError::ThresholdDecrypt("invalid compressed Edwards Y point".into()))
}

/// Parse a hex-encoded Scalar (32 bytes little-endian = 64 hex chars).
fn parse_scalar_hex(hex: &str) -> Result<Scalar, CryptoError> {
    let hex = hex.strip_prefix("0x").unwrap_or(hex);
    let bytes =
        hex::decode(hex).map_err(|e| CryptoError::ThresholdDecrypt(format!("invalid hex for Scalar: {}", e)))?;

    if bytes.len() != 32 {
        return Err(CryptoError::ThresholdDecrypt(format!(
            "Scalar must be 32 bytes, got {}",
            bytes.len()
        )));
    }

    let mut arr = [0u8; 32];
    arr.copy_from_slice(&bytes);

    Option::from(Scalar::from_canonical_bytes(arr))
        .ok_or_else(|| CryptoError::ThresholdDecrypt("scalar not in canonical form".into()))
}

/// Configuration for automatic epoch rotation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EpochConfig {
    /// Enable automatic epoch rotation.
    #[serde(default)]
    pub enabled: bool,
    /// Epoch duration in seconds (default: 86400 = 24h).
    #[serde(default = "default_epoch_duration")]
    pub duration_seconds: u64,
    /// Number of past epochs to keep shares for (default: 2).
    #[serde(default = "default_grace_period_epochs")]
    pub grace_period_epochs: u32,
    /// Retry interval in seconds after failed refresh (default: 1800 = 30min).
    #[serde(default = "default_retry_interval")]
    pub retry_interval_seconds: u64,
}

fn default_epoch_duration() -> u64 {
    86400
}
fn default_grace_period_epochs() -> u32 {
    2
}
fn default_retry_interval() -> u64 {
    1800
}

impl Default for EpochConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            duration_seconds: default_epoch_duration(),
            grace_period_epochs: default_grace_period_epochs(),
            retry_interval_seconds: default_retry_interval(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dkg::dealer;
    #[cfg(feature = "frost-dkg")]
    use crate::dkg::{keystore, types::SerializableKeyShare};

    #[test]
    fn gateway_config_roundtrip() {
        let config = ThresholdConfig { threshold: 2, total: 3 };
        let (tpk, _commitment, shares) = dealer::generate_shares(config).unwrap();

        // Build TOML-friendly config from DKG output
        let mpk_hex = hex::encode(tpk.edwards.compress().as_bytes());
        let mut public_shares = HashMap::new();
        for share in &shares {
            public_shares.insert(
                share.index.to_string(),
                hex::encode(share.public_share.compress().as_bytes()),
            );
        }

        let gw_config = ThresholdGatewayConfig {
            enabled: true,
            threshold: 2,
            total: 3,
            master_public_key: mpk_hex,
            public_shares,
            keystore_path: None,
        };

        // Convert to internal type
        let ctx = gw_config.to_threshold_context().unwrap();
        assert_eq!(ctx.config.threshold, 2);
        assert_eq!(ctx.config.total, 3);
        assert_eq!(ctx.public_key.edwards.compress(), tpk.edwards.compress());
        assert_eq!(ctx.public_shares.len(), 3);

        for share in &shares {
            let loaded = ctx.public_shares.get(&share.index).unwrap();
            assert_eq!(loaded.compress(), share.public_share.compress());
        }
    }

    #[test]
    fn operator_config_roundtrip() {
        let config = ThresholdConfig { threshold: 2, total: 3 };
        let (_tpk, _commitment, shares) = dealer::generate_shares(config).unwrap();

        let share = &shares[0];
        let secret_hex = hex::encode(share.secret_share.as_bytes());

        let op_config = ThresholdOperatorConfig {
            enabled: true,
            index: share.index,
            secret_share: secret_hex,
            keystore_path: None,
        };

        let loaded = op_config.to_key_share().unwrap();
        assert_eq!(loaded.index, share.index);
        assert_eq!(loaded.secret_share, share.secret_share);
        assert_eq!(loaded.public_share.compress(), share.public_share.compress());
    }

    #[test]
    fn disabled_config_returns_error() {
        let gw = ThresholdGatewayConfig {
            enabled: false,
            threshold: 2,
            total: 3,
            master_public_key: String::new(),
            public_shares: HashMap::new(),
            keystore_path: None,
        };
        assert!(gw.to_threshold_context().is_err());

        let op = ThresholdOperatorConfig {
            enabled: false,
            index: 1,
            secret_share: String::new(),
            keystore_path: None,
        };
        assert!(op.to_key_share().is_err());
    }

    #[test]
    fn invalid_hex_returns_error() {
        let gw = ThresholdGatewayConfig {
            enabled: true,
            threshold: 2,
            total: 3,
            master_public_key: "not_hex".into(),
            public_shares: HashMap::new(),
            keystore_path: None,
        };
        assert!(gw.to_threshold_context().is_err());
    }

    #[test]
    fn hex_with_0x_prefix_works() {
        let config = ThresholdConfig { threshold: 2, total: 3 };
        let (_tpk, _commitment, shares) = dealer::generate_shares(config).unwrap();

        let share = &shares[0];
        let secret_hex = format!("0x{}", hex::encode(share.secret_share.as_bytes()));

        let op_config = ThresholdOperatorConfig {
            enabled: true,
            index: share.index,
            secret_share: secret_hex,
            keystore_path: None,
        };

        let loaded = op_config.to_key_share().unwrap();
        assert_eq!(loaded.secret_share, share.secret_share);
    }

    #[test]
    fn serde_json_roundtrip() {
        let config = ThresholdConfig { threshold: 2, total: 3 };
        let (tpk, _commitment, shares) = dealer::generate_shares(config).unwrap();

        let mpk_hex = hex::encode(tpk.edwards.compress().as_bytes());
        let mut public_shares = HashMap::new();
        for share in &shares {
            public_shares.insert(
                share.index.to_string(),
                hex::encode(share.public_share.compress().as_bytes()),
            );
        }

        let gw_config = ThresholdGatewayConfig {
            enabled: true,
            threshold: 2,
            total: 3,
            master_public_key: mpk_hex,
            public_shares,
            keystore_path: None,
        };

        // Serialize to JSON and back (validates serde derive works)
        let json_str = serde_json::to_string(&gw_config).unwrap();
        let deserialized: ThresholdGatewayConfig = serde_json::from_str(&json_str).unwrap();
        assert_eq!(gw_config, deserialized);
    }

    #[cfg(feature = "frost-dkg")]
    #[test]
    fn load_key_share_prefers_keystore_over_toml() {
        use tempfile::NamedTempFile;

        // Generate a real key share (index will be 1)
        let config = ThresholdConfig { threshold: 2, total: 3 };
        let (_tpk, _commitment, shares) = dealer::generate_shares(config).unwrap();
        let key_share = &shares[0];
        assert_eq!(key_share.index, 1);

        // Write the key share to an encrypted keystore
        let serializable = SerializableKeyShare::from_key_share(key_share);
        let serialized = serde_json::to_vec(&serializable).unwrap();
        let tmp = NamedTempFile::new().unwrap();
        keystore::write_keystore(tmp.path(), "test-ceremony", &serialized, b"pass").unwrap();

        // TOML config has a different index (99)
        let toml_config = ThresholdOperatorConfig {
            enabled: true,
            index: 99,
            secret_share: hex::encode(curve25519_dalek::Scalar::from(42u64).to_bytes()),
            keystore_path: None,
        };

        // Keystore should win — loaded key share has index=1, not 99
        let loaded = toml_config
            .load_key_share_with_keystore(Some(tmp.path()), Some(b"pass"))
            .unwrap();
        assert_eq!(loaded.index, 1);
        assert_eq!(loaded.secret_share, key_share.secret_share);
        assert_eq!(loaded.public_share.compress(), key_share.public_share.compress());
    }

    #[cfg(feature = "frost-dkg")]
    #[test]
    fn load_key_share_falls_back_to_toml_when_no_keystore() {
        let config = ThresholdConfig { threshold: 2, total: 3 };
        let (_tpk, _commitment, shares) = dealer::generate_shares(config).unwrap();
        let share = &shares[0];

        let toml_config = ThresholdOperatorConfig {
            enabled: true,
            index: share.index,
            secret_share: hex::encode(share.secret_share.as_bytes()),
            keystore_path: None,
        };

        // No keystore path provided — should use TOML values
        let loaded = toml_config.load_key_share_with_keystore(None, None).unwrap();
        assert_eq!(loaded.index, share.index);
        assert_eq!(loaded.secret_share, share.secret_share);
    }

    #[cfg(feature = "frost-dkg")]
    #[test]
    fn load_threshold_context_prefers_keystore_over_toml() {
        use crate::dkg::types::SerializableThresholdContext;
        use tempfile::NamedTempFile;

        let config = ThresholdConfig { threshold: 2, total: 3 };
        let (tpk, _commitment, shares) = dealer::generate_shares(config).unwrap();

        // Build a ThresholdDecryptionContext from generated data
        let public_shares: HashMap<u32, curve25519_dalek::edwards::EdwardsPoint> =
            shares.iter().map(|s| (s.index, s.public_share)).collect();
        let ctx = crate::dkg::types::ThresholdDecryptionContext {
            public_key: tpk.clone(),
            public_shares,
            config,
        };

        // Write to keystore
        let serializable = SerializableThresholdContext::from_threshold_context(&ctx);
        let serialized = serde_json::to_vec(&serializable).unwrap();
        let tmp = NamedTempFile::new().unwrap();
        keystore::write_keystore(tmp.path(), "test-ceremony-gw", &serialized, b"gwpass").unwrap();

        // TOML config with different (wrong) master public key — use shares[0]'s pubkey as MPK
        // We just want a valid-but-different config, so use threshold=1, total=1, shares[0] as MPK
        let wrong_mpk_hex = hex::encode(shares[0].public_share.compress().as_bytes());
        let toml_config = ThresholdGatewayConfig {
            enabled: true,
            threshold: 1,
            total: 1,
            master_public_key: wrong_mpk_hex,
            public_shares: std::collections::HashMap::from([(
                "1".to_string(),
                hex::encode(shares[0].public_share.compress().as_bytes()),
            )]),
            keystore_path: None,
        };

        // Keystore should win — loaded context has the real MPK
        let loaded = toml_config
            .load_threshold_context_with_keystore(Some(tmp.path()), Some(b"gwpass"))
            .unwrap();
        assert_eq!(loaded.public_key.edwards.compress(), tpk.edwards.compress());
        assert_eq!(loaded.config.threshold, 2);
        assert_eq!(loaded.config.total, 3);
    }

    #[cfg(feature = "frost-dkg")]
    #[test]
    fn load_threshold_context_falls_back_to_toml_when_no_keystore() {
        let config = ThresholdConfig { threshold: 2, total: 3 };
        let (tpk, _commitment, shares) = dealer::generate_shares(config).unwrap();

        let mpk_hex = hex::encode(tpk.edwards.compress().as_bytes());
        let mut public_shares = HashMap::new();
        for share in &shares {
            public_shares.insert(
                share.index.to_string(),
                hex::encode(share.public_share.compress().as_bytes()),
            );
        }

        let toml_config = ThresholdGatewayConfig {
            enabled: true,
            threshold: 2,
            total: 3,
            master_public_key: mpk_hex,
            public_shares,
            keystore_path: None,
        };

        // No keystore path — falls back to TOML
        let loaded = toml_config.load_threshold_context_with_keystore(None, None).unwrap();
        assert_eq!(loaded.public_key.edwards.compress(), tpk.edwards.compress());
        assert_eq!(loaded.config.threshold, 2);
    }
}