-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathlib.rs
More file actions
2523 lines (2312 loc) · 93 KB
/
lib.rs
File metadata and controls
2523 lines (2312 loc) · 93 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
/// Core Client library
///
/// This library implements most functionalities to interact with deployed KMS cores.
/// This library also includes an associated CLI.
mod backup;
mod crsgen;
mod decrypt;
mod keygen;
pub mod mpc_context;
mod mpc_epoch;
mod s3_operations;
// reexport fetch_public_elements for integration test
pub use crate::s3_operations::fetch_public_elements;
use crate::backup::{
do_custodian_backup_recovery, do_custodian_recovery_init, do_get_operator_pub_keys,
do_new_custodian_context, do_restore_from_backup,
};
use crate::crsgen::{do_crsgen, fetch_and_check_crsgen, get_crsgen_responses};
use crate::decrypt::{do_public_decrypt, do_user_decrypt, get_public_decrypt_responses};
use crate::keygen::{
do_keygen, do_partial_preproc, do_preproc, fetch_and_check_keygen, get_keygen_responses,
get_preproc_keygen_responses,
};
use crate::mpc_context::{do_destroy_mpc_context, do_new_mpc_context};
use crate::mpc_epoch::{do_destroy_mpc_epoch, do_new_epoch};
use aes_prng::AesRng;
use clap::{Args, Parser, Subcommand};
use core::str;
use kms_grpc::identifiers::EpochId;
use kms_grpc::kms::v1::{CiphertextFormat, FheParameter, TypedCiphertext, TypedPlaintext};
use kms_grpc::kms_service::v1::core_service_endpoint_client::CoreServiceEndpointClient;
use kms_grpc::rpc_types::PubDataType;
use kms_grpc::{ContextId, KeyId, RequestId};
use kms_lib::backup::custodian::{InternalCustodianRecoveryOutput, InternalCustodianSetupMessage};
use kms_lib::client::client_wasm::Client;
use kms_lib::consts::{DEFAULT_PARAM, SIGNING_KEY_ID, TEST_PARAM};
use kms_lib::util::file_handling::{
read_element, safe_read_element_versioned, safe_write_element_versioned, write_element,
};
use kms_lib::util::key_setup::{
ensure_client_keys_exist,
test_tools::{EncryptionConfig, TestingPlaintext, compute_cipher_from_stored_key},
};
use kms_lib::vault::Vault;
use kms_lib::vault::storage::{StorageType, file::FileStorage};
use kms_lib::vault::storage::{make_storage, read_text_at_request_id};
use kms_lib::{DecryptionMode, conf};
use observability::conf::Settings;
use rand::SeedableRng;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use strum_macros::{Display, EnumString};
use tfhe::FheTypes as TfheFheType;
use tokio::sync::RwLock;
use tracing_appender::rolling::{RollingFileAppender, Rotation};
use tracing_subscriber::fmt::writer::MakeWriterExt;
use validator::{Validate, ValidationError};
// time to sleep between retries of requests in milliseconds
const SLEEP_TIME_BETWEEN_REQUESTS_MS: u64 = 500;
/// Retries a function a given number of times with a given interval between retries.
macro_rules! retry {
($f:expr, $count:expr, $interval:expr) => {{
let mut retries = 0;
let result = loop {
let result = $f;
if result.is_ok() {
break result;
} else if retries > $count {
break result;
}
retries += 1;
tokio::time::sleep(tokio::time::Duration::from_millis($interval)).await;
};
result
}};
($f:expr) => {
retry!($f, 5, 100)
};
}
#[derive(Serialize, Clone, Validate, Debug)]
#[validate(schema(function = validate_core_client_conf))]
pub struct CoreClientConfig {
// The mode of the KMS ("centralized" or "threshold"). Threshold by default.
pub kms_type: KmsType,
// List of configurations for the cores
#[validate(length(min = 1))]
pub cores: Vec<CoreConf>,
pub decryption_mode: Option<DecryptionMode>,
#[validate(range(min = 1))]
pub num_majority: usize,
#[validate(range(min = 1))]
pub num_reconstruct: usize,
pub fhe_params: Option<FheParameter>,
}
#[derive(Deserialize, Serialize, Clone, Validate, Default, Debug, Hash, PartialEq, Eq)]
pub struct CoreConf {
/// The ID of the given KMS server (monotonically increasing positive integer starting at 1)
#[validate(range(min = 1))]
pub party_id: usize,
/// The address of the given KMS server, including the port
#[validate(length(min = 1))]
pub address: String,
/// The S3 endpoint where the public material of the given server can be reached
#[validate(length(min = 1))]
pub s3_endpoint: String,
/// The folder at the S3 endpoint where the data is stored.
pub object_folder: String,
#[cfg(feature = "testing")]
/// The folder at the S3 endpoint where the private data is stored.
/// This is only used for testing context switching.
pub private_object_folder: Option<String>,
#[cfg(feature = "testing")]
/// The path for the KMS configuration file,
/// this is only needed for testing context switching.
pub config_path: Option<PathBuf>,
}
fn validate_core_client_conf(conf: &CoreClientConfig) -> Result<(), ValidationError> {
// The number of parties in the configuration, this may not be the actual number of KMS parties IRL. But is just the ones we currently communicate with.
let num_parties = conf.cores.len();
for cur_core in &conf.cores {
if cur_core.party_id == 0 || cur_core.party_id > num_parties {
return Err(ValidationError::new("Incorrect Party ID").with_message(
format!(
"Party ID must be between 1 and the number of parties ({}), but was {}.",
num_parties, cur_core.party_id
)
.into(),
));
}
if conf
.cores
.iter()
.filter(|x| x.party_id == cur_core.party_id)
.count()
> 1
{
return Err(ValidationError::new("Duplicate Party ID").with_message(
format!(
"Party ID {} is duplicated in the configuration.",
cur_core.party_id
)
.into(),
));
}
if conf
.cores
.iter()
.filter(|x| x.address == cur_core.address)
.count()
> 1
{
return Err(ValidationError::new("Duplicate Address").with_message(
format!(
"Address {} is duplicated in the configuration.",
cur_core.address
)
.into(),
));
}
}
if conf.num_majority > num_parties {
return Err(ValidationError::new("Majority Vote Count Error").with_message(format!("Number for majority votes ({}) must be smaller than or equal to the number of parties the CLI communicates with ({}).", conf.num_majority, num_parties).into()));
}
if conf.num_reconstruct > num_parties {
return Err(ValidationError::new("Reconstruction Count Error").with_message(format!("Number for reconstruction shares ({}) must be smaller than or equal to the number of parties the CLI communicates with ({}).", conf.num_reconstruct, num_parties).into()));
}
if conf.num_reconstruct < conf.num_majority {
return Err(ValidationError::new("Reconstruction Count Error").with_message(format!("Number for reconstruction shares ({}) must be greater than or equal to the number of majority votes ({}).", conf.num_reconstruct, conf.num_majority).into()));
}
if num_parties > 1 {
// Should be a threshold config
if conf.kms_type != KmsType::Threshold {
return Err(ValidationError::new("KMS Type Error").with_message(format!("KMS mode must be 'threshold' when there are multiple cores ({} cores configured).", num_parties).into()));
}
} else {
// We may be in the centralized or threshold mode (communicating with a single server)
if conf.kms_type == KmsType::Centralized {
if conf.num_majority != 1 {
return Err(
ValidationError::new("Centralized Majority Vote Count Error").with_message(
format!(
"Number for majority votes ({}) must be equal to 1 for a centralized config.",
conf.num_majority,
)
.into(),
),
);
}
if conf.num_reconstruct != 1 {
return Err(
ValidationError::new("Centralized Reconstruction Count Error").with_message(
format!(
"Number for reconstruction ({}) must be equal to 1 for a centralized config.",
conf.num_reconstruct,
)
.into(),
),
);
}
if conf.cores.first().expect("no party IDs found").party_id != 1 {
return Err(
ValidationError::new("Centralized Party ID Error").with_message(
format!(
"Party ID of the single core in a centralized config must be 1, but was {}.",
conf.cores.first().unwrap().party_id
)
.into(),
),
);
}
}
}
Ok(())
}
fn validate_cipher_args(cf: &CipherArguments) -> anyhow::Result<()> {
if cf.get_num_requests() == 0 {
return Err(anyhow::anyhow!("Number of requests cannot be zero."));
}
if cf.get_batch_size() == 0 {
return Err(anyhow::anyhow!("Batch size cannot be zero."));
}
if cf.get_parallel_requests() > cf.get_num_requests() {
return Err(anyhow::anyhow!(
"Number of parallel requests ({}) cannot be > total number of requests ({}).",
cf.get_parallel_requests(),
cf.get_num_requests()
));
}
Ok(())
}
impl<'de> Deserialize<'de> for CoreClientConfig {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize, Clone, Debug)]
pub struct CoreClientConfigBuffer {
// The mode of the KMS ("centralized" or "threshold"). Threshold by default.
pub kms_type: KmsType,
// List of configurations for the cores
pub cores: Vec<CoreConf>,
pub decryption_mode: Option<DecryptionMode>,
pub num_majority: usize,
pub num_reconstruct: usize,
pub fhe_params: Option<FheParameter>,
}
let temp = CoreClientConfigBuffer::deserialize(deserializer)?;
let conf = CoreClientConfig {
kms_type: temp.kms_type,
cores: temp.cores,
decryption_mode: temp.decryption_mode,
num_majority: temp.num_majority,
num_reconstruct: temp.num_reconstruct,
fhe_params: temp.fhe_params,
};
conf.validate().map_err(serde::de::Error::custom)?;
Ok(conf)
}
}
#[derive(Copy, Clone, Default, EnumString, PartialEq, Display, Debug, Serialize, Deserialize)]
pub enum FheType {
#[default]
#[strum(serialize = "ebool")]
Ebool,
#[strum(serialize = "euint4")]
Euint4,
#[strum(serialize = "euint8")]
Euint8,
#[strum(serialize = "euint16")]
Euint16,
#[strum(serialize = "euint32")]
Euint32,
#[strum(serialize = "euint64")]
Euint64,
#[strum(serialize = "euint128")]
Euint128,
#[strum(serialize = "euint160")]
Euint160,
#[strum(serialize = "euint256")]
Euint256,
#[strum(serialize = "euint512")]
Euint512,
#[strum(serialize = "euint1024")]
Euint1024,
#[strum(serialize = "euint2048")]
Euint2048,
#[strum(serialize = "unknown")]
Unknown,
}
impl FheType {
// We don't use it for now, but useful to have
#[allow(dead_code)]
fn as_str_name(self) -> &'static str {
match self {
FheType::Ebool => "Ebool",
FheType::Euint4 => "Euint4",
FheType::Euint8 => "Euint8",
FheType::Euint16 => "Euint16",
FheType::Euint32 => "Euint32",
FheType::Euint64 => "Euint64",
FheType::Euint128 => "Euint128",
FheType::Euint160 => "Euint160",
FheType::Euint256 => "Euint256",
FheType::Euint512 => "Euint512",
FheType::Euint1024 => "Euint1024",
FheType::Euint2048 => "Euint2048",
FheType::Unknown => "Unknown",
}
}
pub fn bits(&self) -> usize {
match self {
FheType::Ebool => 1,
FheType::Euint4 => 4,
FheType::Euint8 => 8,
FheType::Euint16 => 16,
FheType::Euint32 => 32,
FheType::Euint64 => 64,
FheType::Euint128 => 128,
FheType::Euint160 => 160,
FheType::Euint256 => 256,
FheType::Euint512 => 512,
FheType::Euint1024 => 1024,
FheType::Euint2048 => 2048,
FheType::Unknown => 0,
}
}
pub fn from_str_name(value: &str) -> FheType {
match value {
"Ebool" => Self::Ebool,
"Euint4" => Self::Euint4,
"Euint8" => Self::Euint8,
"Euint16" => Self::Euint16,
"Euint32" => Self::Euint32,
"Euint64" => Self::Euint64,
"Euint128" => Self::Euint128,
"Euint160" => Self::Euint160,
"Euint256" => Self::Euint256,
"Euint512" => Self::Euint512,
"Euint1024" => Self::Euint1024,
"Euint2048" => Self::Euint2048,
_ => Self::Unknown,
}
}
}
impl From<u8> for FheType {
fn from(value: u8) -> Self {
match value {
0 => FheType::Ebool,
1 => FheType::Euint4,
2 => FheType::Euint8,
3 => FheType::Euint16,
4 => FheType::Euint32,
5 => FheType::Euint64,
6 => FheType::Euint128,
7 => FheType::Euint160,
8 => FheType::Euint256,
9 => FheType::Euint512,
10 => FheType::Euint1024,
11 => FheType::Euint2048,
_ => FheType::Unknown,
}
}
}
impl From<TfheFheType> for FheType {
fn from(value: TfheFheType) -> Self {
match value {
TfheFheType::Bool => FheType::Ebool,
TfheFheType::Uint4 => FheType::Euint4,
TfheFheType::Uint8 => FheType::Euint8,
TfheFheType::Uint16 => FheType::Euint16,
TfheFheType::Uint32 => FheType::Euint32,
TfheFheType::Uint64 => FheType::Euint64,
TfheFheType::Uint128 => FheType::Euint128,
TfheFheType::Uint160 => FheType::Euint160,
TfheFheType::Uint256 => FheType::Euint256,
TfheFheType::Uint512 => FheType::Euint512,
TfheFheType::Uint1024 => FheType::Euint1024,
TfheFheType::Uint2048 => FheType::Euint2048,
_ => FheType::Unknown,
}
}
}
impl TryInto<TfheFheType> for FheType {
type Error = anyhow::Error;
fn try_into(self) -> Result<TfheFheType, Self::Error> {
match self {
FheType::Ebool => Ok(TfheFheType::Bool),
FheType::Euint4 => Ok(TfheFheType::Uint4),
FheType::Euint8 => Ok(TfheFheType::Uint8),
FheType::Euint16 => Ok(TfheFheType::Uint16),
FheType::Euint32 => Ok(TfheFheType::Uint32),
FheType::Euint64 => Ok(TfheFheType::Uint64),
FheType::Euint128 => Ok(TfheFheType::Uint128),
FheType::Euint160 => Ok(TfheFheType::Uint160),
FheType::Euint256 => Ok(TfheFheType::Uint256),
FheType::Euint512 => Ok(TfheFheType::Uint512),
FheType::Euint1024 => Ok(TfheFheType::Uint1024),
FheType::Euint2048 => Ok(TfheFheType::Uint2048),
_ => Err(anyhow::anyhow!("Not supported")),
}
}
}
// CLI arguments
#[derive(Debug, Parser, Clone)]
pub struct NoParameters {}
/// Parse a string as hex string. The string can optionally start with "0x". Odd-length strings will be padded with a single leading zero.
pub fn parse_hex(arg: &str) -> anyhow::Result<Vec<u8>> {
// Remove "0x" or "0X" prefix if present
let arg = arg.strip_prefix("0x").unwrap_or(arg);
let hex_str = arg.strip_prefix("0X").unwrap_or(arg);
// Handle odd-length hex strings by padding with a single leading zero
let hex_str = if hex_str.len() % 2 == 1 {
format!("0{hex_str}")
} else {
hex_str.to_string()
};
Ok(hex::decode(hex_str)?)
}
#[derive(Debug, Subcommand, Clone)]
pub enum CipherArguments {
FromFile(CipherFile),
FromArgs(CipherParameters),
}
impl CipherArguments {
pub fn get_batch_size(&self) -> usize {
match self {
CipherArguments::FromFile(cipher_file) => cipher_file.batch_size,
CipherArguments::FromArgs(cipher_parameters) => cipher_parameters.batch_size,
}
}
pub fn get_num_requests(&self) -> usize {
match self {
CipherArguments::FromFile(cipher_file) => cipher_file.num_requests,
CipherArguments::FromArgs(cipher_parameters) => cipher_parameters.num_requests,
}
}
pub fn get_parallel_requests(&self) -> usize {
match self {
CipherArguments::FromFile(cipher_file) => cipher_file.parallel_requests,
CipherArguments::FromArgs(cipher_parameters) => cipher_parameters.parallel_requests,
}
}
pub fn get_inter_request_delay_ms(&self) -> Duration {
match self {
CipherArguments::FromFile(cipher_file) => {
tokio::time::Duration::from_millis(cipher_file.inter_request_delay_ms)
}
CipherArguments::FromArgs(cipher_parameters) => {
tokio::time::Duration::from_millis(cipher_parameters.inter_request_delay_ms)
}
}
}
pub fn get_extra_data(&self) -> Vec<u8> {
let hex_str = match self {
CipherArguments::FromFile(cipher_file) => &cipher_file.extra_data,
CipherArguments::FromArgs(cipher_parameters) => &cipher_parameters.extra_data,
};
parse_extra_data(hex_str)
}
}
// Helper function to parse the extra data from the CLI arguments, with the same logic for both CipherParameters and CipherFile.
// Defaults to an empty byte vector if the extra data is not provided or if the hex parsing fails.
fn parse_extra_data(hex_str: &Option<String>) -> Vec<u8> {
parse_hex(hex_str.as_deref().unwrap_or("")).unwrap_or_default()
}
#[derive(Debug, Args, Clone, Serialize, Deserialize)]
pub struct CipherParameters {
/// Hex value to encrypt and request a public/user decryption.
/// The value will be converted from a little endian hex string to a `Vec<u8>`.
/// Can optionally have a "0x" prefix.
#[clap(long, short = 'e')]
pub to_encrypt: String,
/// Data type of `to_encrypt`.
/// Expected one of ebool, euint8, ..., euint256
#[clap(long, short = 'd')]
pub data_type: FheType,
/// Disable ciphertext compression. Default: False, i.e. compression is used.
#[clap(long, alias = "nc")]
pub no_compression: bool,
/// Disable SnS preprocessing on the ciphertext on the core-client.
/// SnS preprocessing performs a PBS to convert 64-bit ciphertexts to 128-bit ones.
/// Default: False, i.e. the SnS is precomputed on the core client.
#[clap(long, alias = "ns")]
pub no_precompute_sns: bool,
/// Key identifier to use for public/user decryption.
#[clap(long, short = 'k')]
pub key_id: KeyId,
/// Optionally specify the context ID to use for the decryption.
/// If not specified, the default context will be used.
#[clap(long)]
pub context_id: Option<ContextId>,
/// Optionally specify the epoch ID to use for the decryption.
/// If not specified, the default epoch will be used.
#[clap(long)]
pub epoch_id: Option<EpochId>,
/// Number of copies of the ciphertext to process in a single request.
/// This is ignored for the encryption command.
#[serde(skip_serializing, skip_deserializing)]
#[clap(long, short = 'b', default_value_t = 1)]
pub batch_size: usize,
/// Numbers of requests to process at once.
/// Each request uses a copy of the same batch.
#[serde(skip_serializing, skip_deserializing)]
#[clap(long, short = 'n', default_value_t = 1)]
pub num_requests: usize,
/// Optionally dump the ciphertext to a file.
#[serde(skip_serializing, skip_deserializing)]
#[clap(long)]
pub ciphertext_output_path: Option<PathBuf>,
/// Delay (in ms) between consecutive requests for decrypt operations
#[serde(skip_serializing, skip_deserializing)]
#[clap(long, short = 'i', default_value_t = 0)]
pub inter_request_delay_ms: u64,
/// Number of requests to be sent in parallel (at most num_requests) before waiting for inter_request_delay_ms.
#[serde(skip_serializing, skip_deserializing)]
#[clap(long, short = 'p', default_value_t = 0)]
pub parallel_requests: usize,
/// Use legacy uncompressed public key material (`PublicKey` + `ServerKey`).
/// By default the client uses `CompressedXofKeySet`.
#[serde(skip_serializing, skip_deserializing)]
#[clap(long, short = 'u', default_value_t = false)]
pub uncompressed_keys: bool,
/// Optional extra data (hex-encoded) to include in the request.
/// Can optionally have a "0x" prefix.
#[serde(skip_serializing, skip_deserializing)]
#[clap(long)]
pub extra_data: Option<String>,
}
#[derive(Debug, Args, Clone)]
pub struct CipherFile {
/// Input file of the ciphertext.
#[clap(long)]
pub input_path: PathBuf,
/// Number of copies of the ciphertext to process in a single request.
#[clap(long, short = 'b', default_value_t = 1)]
pub batch_size: usize,
/// Numbers of requests to process at once.
/// Each request uses a copy of the same batch.
#[clap(long, short = 'n', default_value_t = 1)]
pub num_requests: usize,
/// Delay (in ms) between consecutive requests for decrypt operations
#[clap(long, default_value_t = 0)]
pub inter_request_delay_ms: u64,
/// Number of requests to be sent in parallel (at most num_requests) before waiting for inter_request_delay_ms.
#[clap(long, short = 'p', default_value_t = 0)]
pub parallel_requests: usize,
/// Optional extra data (hex-encoded) to include in the request.
/// Can optionally have a "0x" prefix.
#[clap(long)]
pub extra_data: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CipherWithParams {
params: CipherParameters,
ct_format: String,
cipher: Vec<u8>,
}
#[derive(Args, Debug, Clone, Default)]
pub struct SharedKeyGenParameters {
/// Generate legacy uncompressed public key material instead of the default compressed keyset.
#[clap(long, short = 'u', default_value_t = false)]
pub uncompressed: bool,
/// Existing keyset ID to reuse all secret shares from.
/// When set, generates new public keys from existing private key shares
/// instead of running full distributed keygen.
#[clap(long)]
pub existing_keyset_id: Option<RequestId>,
/// Epoch ID for the existing keyset (optional, defaults to the request's epoch).
#[clap(long)]
pub existing_epoch_id: Option<EpochId>,
/// Reuse the tag from the existing keyset instead of using the new key ID as tag.
/// This is only used when generating a key from existing shares.
#[clap(long, default_value_t = false)]
pub use_existing_key_tag: bool,
pub context_id: Option<ContextId>,
pub epoch_id: Option<EpochId>,
/// Optional extra data (hex-encoded) to include in the request.
/// Can optionally have a "0x" prefix.
#[clap(long)]
pub extra_data: Option<String>,
}
#[derive(Debug, Parser, Clone)]
pub struct KeyGenParameters {
#[clap(long, short = 'i')]
pub preproc_id: RequestId,
#[command(flatten)]
pub shared_args: SharedKeyGenParameters,
}
/// Parameters for insecure key generation (testing/development only).
#[derive(Debug, Parser, Clone)]
pub struct InsecureKeyGenParameters {
#[command(flatten)]
pub shared_args: SharedKeyGenParameters,
}
#[derive(Debug, Parser, Clone)]
pub struct CrsParameters {
#[clap(long, short = 'm')]
pub max_num_bits: u32,
#[clap(long)]
pub epoch_id: Option<EpochId>,
#[clap(long)]
pub context_id: Option<ContextId>,
/// Optional extra data (hex-encoded) to include in the request.
/// Can optionally have a "0x" prefix.
#[clap(long)]
pub extra_data: Option<String>,
}
impl Default for CrsParameters {
fn default() -> Self {
Self {
max_num_bits: 2048,
epoch_id: None,
context_id: None,
extra_data: None,
}
}
}
#[derive(Debug, Parser, Clone)]
pub struct NewCustodianContextParameters {
#[clap(long, short = 't')]
pub threshold: u32,
#[clap(long, short = 'm')]
pub setup_msg_paths: Vec<PathBuf>,
}
#[derive(Debug, Args, Clone)]
pub struct ContextPath {
/// Input file of the ciphertext.
#[clap(long)]
pub input_path: PathBuf,
}
#[derive(Debug, Subcommand, Clone)]
pub enum NewMpcContextParameters {
/// Safe Serialized version of the struct ContextInfo
/// stored in a file.
SerializedContextPath(ContextPath),
ContextToml(ContextPath),
}
#[derive(Debug, Parser, Clone)]
pub struct DestroyMpcContextParameters {
/// The context ID to use for the MPC context to destroy.
#[clap(long)]
pub context_id: ContextId,
}
#[derive(Debug, Parser, Clone)]
pub struct DestroyMpcEpochParameters {
/// The epoch ID to use for the MPC epoch to destroy.
#[clap(long)]
pub epoch_id: EpochId,
}
#[derive(Debug, Parser, Clone)]
pub struct NewTestingMpcContextFileParameters {
/// The context ID to use for the new MPC context.
#[clap(long)]
pub context_id: ContextId,
/// The path to store the context.
#[clap(long)]
pub context_path: PathBuf,
}
#[derive(Debug, Parser, Clone)]
pub struct ResultParameters {
#[clap(long, short = 'i')]
pub request_id: RequestId,
}
#[derive(Debug, Parser, Clone)]
pub struct KeyGenResultParameters {
#[clap(long, short = 'i')]
pub request_id: RequestId,
/// Fetch legacy uncompressed public key material instead of the default compressed keyset.
#[clap(long, short = 'u', default_value_t = false)]
pub uncompressed: bool,
}
#[derive(Debug, Parser, Clone)]
pub struct RecoveryInitParameters {
/// Indicator as to whether the KMS should overwrite a possible existing ephemeral key
/// If false, the call will be indempotent, if true, this will not be the case
#[clap(long, short = 'o', default_value_t = false)]
pub overwrite_ephemeral_key: bool,
/// Paths to write the operator responses, the responses stored in these paths are not ordered.
#[clap(long, short = 'r')]
pub operator_recovery_resp_paths: Vec<PathBuf>,
}
#[derive(Debug, Parser, Clone)]
pub struct RecoveryParameters {
#[clap(long, short = 'i')]
pub custodian_context_id: RequestId,
#[clap(long, short = 'r')]
pub custodian_recovery_outputs: Vec<PathBuf>,
}
#[derive(Debug, Clone)]
pub enum DigestKeySet {
CompressedKeySet(String),
/// The first string is the server key digest, the second string is the public key digest.
NonCompressedKeySet(String, String),
}
#[derive(Debug, Clone)]
pub struct PreviousKeyInfo {
/// Key id of the key to reshare
pub key_id: KeyId,
/// Preprocessing request id for the key to reshare, this should correspond to the preprocessing used to generate the key specified by `key_id`.
pub preproc_id: RequestId,
/// The hex-encoded digest(s) of the public part(s) of the key being reshared.
/// For compressed keysets, this is a single digest of the compressed keyset.
/// For non-compressed keysets, this includes the digest of the server key and the digest of the public key.
pub key_digest: DigestKeySet,
}
#[derive(Debug, Clone)]
pub struct PreviousCrsInfo {
/// Id of the CRS to re-sign
pub crs_id: RequestId,
/// The hex-encoded digest of the CRS to re-sign
pub digest: String,
}
#[derive(Debug, Parser, Clone)]
pub struct PreviousEpochParameters {
#[clap(long)]
pub context_id: ContextId,
#[clap(long)]
pub epoch_id: EpochId,
/// Information about the keys to reshare in the new epoch.
#[clap(long)]
pub previous_keys: Vec<PreviousKeyInfo>,
/// Information about the CRSes to re-sign in the new epoch.
#[clap(long)]
pub previous_crs: Vec<PreviousCrsInfo>,
}
#[derive(Debug, Parser, Clone)]
pub struct NewEpochParameters {
/// ID of the epoch to be created
#[clap(long)]
pub new_epoch_id: EpochId,
/// Context ID for which the new epoch is created
#[clap(long)]
pub new_context_id: ContextId,
/// Optional parameters for resharing keys from a previous epoch in the new epoch.
/// Format is:
///
/// For compressed keyset
/// `--previous-epoch-params context_id:<context_id>;epoch_id:<epoch_id>;previous_keys:[key_id=<key_id>,preproc_id=<preproc_id>,xof_key_digest=<key_digest>;...];previous_crs:[crs_id=<crs_id>,digest=<crs_digest>;...]`
///
/// For non-compressed keyset
/// `--previous-epoch-params context_id:<context_id>;epoch_id:<epoch_id>;previous_keys:[key_id=<key_id>,preproc_id=<preproc_id>,server_key_digest=<server_key_digest>,public_key_digest=<public_key_digest>;...];previous_crs:[crs_id=<crs_id>,digest=<crs_digest>;...]`
#[clap(long)]
pub previous_epoch_params: Option<PreviousEpochParameters>,
}
#[derive(Debug, Parser, Clone)]
pub struct KeyGenPreprocParameters {
/// Optionally specify the context ID to use for the preprocessing.
/// Defaults to the default context if not specified.
#[clap(long)]
pub context_id: Option<ContextId>,
/// Optionally specify the epoch ID to use for the preprocessing.
/// Defaults to the default epoch if not specified.
#[clap(long)]
pub epoch_id: Option<EpochId>,
/// Generate legacy uncompressed public key material instead of the default compressed keyset.
#[clap(long, short = 'u', default_value_t = false)]
pub uncompressed: bool,
/// Do preprocessing that's needed to generate a key from existing shares.
#[clap(long, default_value_t = false)]
pub from_existing_shares: bool,
}
#[derive(Debug, Parser, Clone)]
pub struct PartialKeyGenPreprocParameters {
#[clap(long)]
pub context_id: Option<ContextId>,
#[clap(long)]
pub epoch_id: Option<EpochId>,
/// Percentage of offline phase to run (0-100)
#[clap(long, short = 'p')]
pub percentage_offline: u32,
/// Whether to store dummy preprocessing, needed to run online DKG if percentage is not 100
#[clap(long, short = 's')]
pub store_dummy_preprocessing: bool,
}
#[derive(Debug, Subcommand, Clone)]
pub enum CCCommand {
PreprocKeyGen(KeyGenPreprocParameters),
PartialPreprocKeyGen(PartialKeyGenPreprocParameters),
PreprocKeyGenResult(ResultParameters),
KeyGen(KeyGenParameters),
KeyGenResult(KeyGenResultParameters),
InsecureKeyGen(InsecureKeyGenParameters),
InsecureKeyGenResult(KeyGenResultParameters),
Encrypt(CipherParameters),
#[clap(subcommand)]
PublicDecrypt(CipherArguments),
PublicDecryptResult(ResultParameters),
#[clap(subcommand)]
UserDecrypt(CipherArguments),
CrsGen(CrsParameters),
CrsGenResult(ResultParameters),
InsecureCrsGen(CrsParameters),
InsecureCrsGenResult(ResultParameters),
NewCustodianContext(NewCustodianContextParameters),
GetOperatorPublicKey(NoParameters),
CustodianRecoveryInit(RecoveryInitParameters),
CustodianBackupRecovery(RecoveryParameters),
BackupRestore(NoParameters),
NewEpoch(NewEpochParameters),
#[clap(subcommand)]
NewMpcContext(NewMpcContextParameters),
DestroyMpcContext(DestroyMpcContextParameters),
DestroyMpcEpoch(DestroyMpcEpochParameters),
#[cfg(feature = "testing")]
NewTestingMpcContextFile(NewTestingMpcContextFileParameters),
DoNothing(NoParameters),
}
#[derive(Debug, Parser, Validate)]
pub struct CmdConfig {
/// Path to the configuration file
#[clap(long, short = 'f')]
#[validate(length(min = 1))]
pub file_conf: Option<Vec<String>>,
/// The command to execute
#[clap(subcommand)]
pub command: CCCommand,
/// Whether to print logs or not
#[clap(long, short = 'l')]
pub logs: bool,
/// Max number of iterations to query the KMS for a response
#[clap(long, default_value = "30")]
#[validate(range(min = 1))]
pub max_iter: usize,
/// Set this if you expect a response from every KMS core
#[clap(long, short = 'a', default_value_t = false)]
pub expect_all_responses: bool,
/// Set this if you want to download the generated keys/CRSes from all KMS cores
#[clap(long, short = 'd', default_value_t = false)]
pub download_all: bool,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, EnumString, Display)]
pub enum KmsType {
#[strum(serialize = "centralized")]
#[serde(rename = "centralized")]
Centralized,
#[strum(serialize = "threshold")]
#[serde(rename = "threshold")]
Threshold,
}
/// a dummy Eip-712 domain for testing
fn dummy_domain() -> alloy_sol_types::Eip712Domain {
alloy_sol_types::eip712_domain!(
name: "Authorization token",
version: "1",
chain_id: 8006,
verifying_contract: alloy_primitives::address!("66f9664f97F2b50F62D13eA064982f936dE76657"),
)
}
// dummy ciphertext handle for testing
fn dummy_handle() -> Vec<u8> {
vec![23_u8; 32]
}
pub struct EncryptionResult {
pub cipher: Vec<u8>,
pub ct_format: CiphertextFormat,
pub plaintext: TypedPlaintext,
pub key_id: KeyId,
pub context_id: Option<ContextId>,
pub epoch_id: Option<EpochId>,
}
impl EncryptionResult {
pub fn new(
cipher: Vec<u8>,
ct_format: CiphertextFormat,
plaintext: TypedPlaintext,
key_id: KeyId,
context_id: Option<ContextId>,
epoch_id: Option<EpochId>,
) -> Self {
Self {
cipher,
ct_format,
plaintext,
key_id,
context_id,
epoch_id,
}
}
}
impl FromStr for PreviousEpochParameters {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut context_id = None;
let mut epoch_id = None;
let mut previous_keys = Vec::new();
let mut previous_crs = Vec::new();
let mut string_iterator = s.split(";");
while let Some(pair) = string_iterator.next() {
let (key, value) = pair
.split_once(':')
.ok_or_else(|| format!("Invalid key:value pair: {}", pair))?;
match key {
"context_id" => {
context_id = Some(
value
.parse()
.map_err(|e| format!("Invalid context_id: {e}"))?,
)
}
"epoch_id" => {
epoch_id = Some(
value
.parse()
.map_err(|e| format!("Invalid epoch_id: {e}. {value}"))?,
)
}
"previous_keys" => {
let mut values = Vec::new();