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
use bulletproofs::PedersenGens;
use curve25519_dalek::{ristretto::RistrettoPoint, scalar::Scalar};
use log::{debug, info};
use primitive_types::H256;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use crate::{
accumulators::{Accumulator, AccumulatorType, NdmSmt, NdmSmtError},
read_write_utils::{self},
utils::LogOnErr,
AggregationFactor, Entity, EntityId, Height, InclusionProof, MaxLiability, MaxThreadCount,
Salt, Secret,
};
pub const SERIALIZED_TREE_EXTENSION: &str = "dapoltree";
pub const SERIALIZED_TREE_FILE_PREFIX: &str = "proof_of_liabilities_merkle_sum_tree_";
pub const SERIALIZED_ROOT_PUB_FILE_PREFIX: &str = "public_root_data_";
pub const SERIALIZED_ROOT_PVT_FILE_PREFIX: &str = "secret_root_data_";
// -------------------------------------------------------------------------------------------------
// Main struct.
/// Proof of Liabilities Sparse Merkle Sum Tree.
///
/// This is the top-most module in the hierarchy of the [dapol] crate.
///
/// It is recommended that one use [DapolConfig](crate::DapolConfig) to construct the
/// tree, which has extra sanity checks on the inputs and more ways to set
/// the parameters. But there is also a `new` function for direct construction.
#[derive(Debug, Serialize, Deserialize)]
pub struct DapolTree {
accumulator: Accumulator,
master_secret: Secret,
salt_s: Salt,
salt_b: Salt,
max_liability: MaxLiability,
}
// -------------------------------------------------------------------------------------------------
// Periphery structs.
/// The public values of the root node.
///
/// These values should be put on a Public Bulletin Board (such as a blockchain)
/// to legitimize the proof of liabilities. Without doing this there is no
/// guarantee to the user that their inclusion proof is checked against the same
/// data as other users' inclusion proofs.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RootPublicData {
pub hash: H256,
pub commitment: RistrettoPoint,
}
/// The secret values of the root node.
///
/// These are the values that are used to construct the Pedersen commitment.
/// These values should not be shared if the tree owner does not want to
/// disclose their total liability.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RootSecretData {
pub liability: u64,
pub blinding_factor: Scalar,
}
// -------------------------------------------------------------------------------------------------
// Construction & proof generation.
impl DapolTree {
/// Construct a new tree.
///
/// It is recommended to rather use [crate][DapolConfig] to construct the
/// tree, which has extra sanity checks on the inputs and more ways to set
/// the parameters.
///
/// An error is returned if the underlying accumulator type construction
/// fails.
///
/// - `accumulator_type`: This value must be set.
#[doc = include_str!("./shared_docs/accumulator_type.md")]
/// - `master_secret`: This value is known only to the tree generator, and
/// is used to determine all other secret values needed in the tree. This
/// value must be set.
/// - `salt_b`: If not set then it will be randomly generated.
#[doc = include_str!("./shared_docs/salt_b.md")]
/// - `salt_s`: If not set then it will be randomly generated.
#[doc = include_str!("./shared_docs/salt_s.md")]
/// - `max_liability`: If not set then a default value is used.
#[doc = include_str!("./shared_docs/max_liability.md")]
/// - `height`: If not set the [default height] will be used.
#[doc = include_str!("./shared_docs/height.md")]
/// - `max_thread_count`: If not set the max parallelism of the underlying
/// machine will be used.
#[doc = include_str!("./shared_docs/max_thread_count.md")]
/// - `secrets_file_path`: Path to the secrets file. If not present the
/// secrets will be generated randomly.
/// - `entities`:
#[doc = include_str!("./shared_docs/entities_vector.md")]
///
/// Example of how to use the construtor:
/// ```
/// use std::str::FromStr;
/// use dapol::{
/// AccumulatorType, DapolTree, Entity, EntityId, Height, MaxLiability,
/// MaxThreadCount, Salt, Secret,
/// };
///
/// let accumulator_type = AccumulatorType::NdmSmt;
/// let height = Height::expect_from(8);
/// let salt_b = Salt::from_str("salt_b").unwrap();
/// let salt_s = Salt::from_str("salt_s").unwrap();
/// let master_secret = Secret::from_str("master_secret").unwrap();
/// let max_liability = MaxLiability::from(10_000_000);
/// let max_thread_count = MaxThreadCount::from(8);
///
/// let entity = Entity {
/// liability: 1u64,
/// id: EntityId::from_str("id").unwrap(),
/// };
/// let entities = vec![entity];
///
/// let dapol_tree = DapolTree::new(
/// accumulator_type,
/// master_secret,
/// salt_b,
/// salt_s,
/// max_liability,
/// max_thread_count,
/// height,
/// entities,
/// ).unwrap();
/// ```
///
/// [default height]: crate::Height::default
pub fn new(
accumulator_type: AccumulatorType,
master_secret: Secret,
salt_b: Salt,
salt_s: Salt,
max_liability: MaxLiability,
max_thread_count: MaxThreadCount,
height: Height,
entities: Vec<Entity>,
) -> Result<Self, DapolTreeError> {
let accumulator = match accumulator_type {
AccumulatorType::NdmSmt => {
let ndm_smt = NdmSmt::new(
master_secret.clone(),
salt_b.clone(),
salt_s.clone(),
height,
max_thread_count,
entities,
)?;
Accumulator::NdmSmt(ndm_smt)
}
};
let tree = DapolTree {
accumulator,
master_secret,
salt_b: salt_b.clone(),
salt_s: salt_s.clone(),
max_liability,
};
tree.log_successful_tree_creation();
Ok(tree)
}
/// Constructor for testing purposes.
///
/// Note: This is **not** cryptographically secure and should only be used
/// for testing.
///
/// An error is returned if the underlying accumulator type construction
/// fails.
///
/// - `accumulator_type`: This value must be set.
#[doc = include_str!("./shared_docs/accumulator_type.md")]
/// - `master_secret`: This value is known only to the tree generator, and
/// is used to determine all other secret values needed in the tree. This
/// value must be set.
/// - `salt_b`: If not set then it will be randomly generated.
#[doc = include_str!("./shared_docs/salt_b.md")]
/// - `salt_s`: If not set then it will be randomly generated.
#[doc = include_str!("./shared_docs/salt_s.md")]
/// - `max_liability`: If not set then a default value is used.
#[doc = include_str!("./shared_docs/max_liability.md")]
/// - `height`: If not set the [default height] will be used
/// [crate][Height].
#[doc = include_str!("./shared_docs/height.md")]
/// - `max_thread_count`: If not set the max parallelism of the underlying
/// machine will be used.
#[doc = include_str!("./shared_docs/max_thread_count.md")]
/// - `secrets_file_path`: Path to the secrets file. If not present the
/// secrets will be generated randomly.
/// - `entities`:
#[doc = include_str!("./shared_docs/entities_vector.md")]
/// - `seed`: random seed for any PRNG used.
///
/// [default height]: crate::Height::default
#[cfg(any(test, feature = "testing"))]
pub fn new_with_random_seed(
accumulator_type: AccumulatorType,
master_secret: Secret,
salt_b: Salt,
salt_s: Salt,
max_liability: MaxLiability,
max_thread_count: MaxThreadCount,
height: Height,
entities: Vec<Entity>,
seed: u64,
) -> Result<Self, DapolTreeError> {
let accumulator = match accumulator_type {
AccumulatorType::NdmSmt => {
let ndm_smt = NdmSmt::new_with_random_seed(
master_secret.clone(),
salt_b.clone(),
salt_s.clone(),
height,
max_thread_count,
entities,
seed,
)?;
Accumulator::NdmSmt(ndm_smt)
}
};
let tree = DapolTree {
accumulator,
master_secret,
salt_b: salt_b.clone(),
salt_s: salt_s.clone(),
max_liability,
};
tree.log_successful_tree_creation();
Ok(tree)
}
/// Generate an inclusion proof for the given `entity_id`.
///
/// Parameters:
/// - `entity_id`: unique ID for the entity that the proof will be generated
/// for.
/// - `aggregation_factor`:
#[doc = include_str!("./shared_docs/aggregation_factor.md")]
pub fn generate_inclusion_proof_with(
&self,
entity_id: &EntityId,
aggregation_factor: AggregationFactor,
) -> Result<InclusionProof, NdmSmtError> {
match &self.accumulator {
Accumulator::NdmSmt(ndm_smt) => ndm_smt.generate_inclusion_proof(
&self.master_secret,
&self.salt_b,
&self.salt_s,
entity_id,
aggregation_factor,
self.max_liability.as_range_proof_upper_bound_bit_length(),
),
}
}
/// Generate an inclusion proof for the given `entity_id`.
///
/// Parameters:
/// - `entity_id`: unique ID for the entity that the proof will be generated
/// for.
pub fn generate_inclusion_proof(
&self,
entity_id: &EntityId,
) -> Result<InclusionProof, NdmSmtError> {
match &self.accumulator {
Accumulator::NdmSmt(ndm_smt) => ndm_smt.generate_inclusion_proof(
&self.master_secret,
&self.salt_b,
&self.salt_s,
entity_id,
AggregationFactor::default(),
self.max_liability.as_range_proof_upper_bound_bit_length(),
),
}
}
/// Check that the public Pedersen commitment corresponds to the secret
/// values of the root.
///
/// If the secret data does not match the commitment then false is returned,
/// otherwise true.
pub fn verify_root_commitment(
public_commitment: &RistrettoPoint,
secret_root_data: &RootSecretData,
) -> Result<(), DapolTreeError> {
let commitment = PedersenGens::default().commit(
Scalar::from(secret_root_data.liability),
secret_root_data.blinding_factor,
);
if commitment == *public_commitment {
Ok(())
} else {
Err(DapolTreeError::RootVerificationError)
}
}
}
// -------------------------------------------------------------------------------------------------
// Accessor methods.
impl DapolTree {
#[doc = include_str!("./shared_docs/accumulator_type.md")]
pub fn accumulator_type(&self) -> AccumulatorType {
self.accumulator.get_type()
}
#[doc = include_str!("./shared_docs/master_secret.md")]
pub fn master_secret(&self) -> &Secret {
&self.master_secret
}
#[doc = include_str!("./shared_docs/salt_b.md")]
pub fn salt_b(&self) -> &Salt {
&self.salt_b
}
#[doc = include_str!("./shared_docs/salt_s.md")]
pub fn salt_s(&self) -> &Salt {
&self.salt_s
}
#[doc = include_str!("./shared_docs/max_liability.md")]
pub fn max_liability(&self) -> &MaxLiability {
&self.max_liability
}
#[doc = include_str!("./shared_docs/height.md")]
pub fn height(&self) -> &Height {
self.accumulator.height()
}
/// Mapping of [EntityId](crate::EntityId) to x-coord on the bottom layer of the tree.
///
/// If the underlying accumulator is an NDM-SMT then a hashmap is returned
/// otherwise None is returned.
pub fn entity_mapping(&self) -> Option<&std::collections::HashMap<EntityId, u64>> {
match &self.accumulator {
Accumulator::NdmSmt(ndm_smt) => Some(ndm_smt.entity_mapping()),
_ => None,
}
}
/// Hash & Pedersen commitment for the root node of the Merkle Sum Tree.
///
/// These values can be made public and do not disclose secret information
/// about the tree such as the number of leaf nodes or their liabilities.
pub fn public_root_data(&self) -> RootPublicData {
RootPublicData {
hash: self.root_hash().clone(),
commitment: self.root_commitment().clone(),
}
}
/// Liability & blinding factor that make up the Pederesen commitment of
/// the Merkle Sum Tree.
///
/// Neither of these values should be made public if the owner of the tree
/// does not want to disclose the total liability sum of their users.
pub fn secret_root_data(&self) -> RootSecretData {
RootSecretData {
liability: self.root_liability(),
blinding_factor: self.root_blinding_factor().clone(),
}
}
#[doc = include_str!("./shared_docs/root_hash.md")]
pub fn root_hash(&self) -> &H256 {
self.accumulator.root_hash()
}
#[doc = include_str!("./shared_docs/root_commitment.md")]
pub fn root_commitment(&self) -> &RistrettoPoint {
self.accumulator.root_commitment()
}
#[doc = include_str!("./shared_docs/root_liability.md")]
pub fn root_liability(&self) -> u64 {
self.accumulator.root_liability()
}
#[doc = include_str!("./shared_docs/root_blinding_factor.md")]
pub fn root_blinding_factor(&self) -> &Scalar {
self.accumulator.root_blinding_factor()
}
}
// -------------------------------------------------------------------------------------------------
// Serialization & deserialization.
impl DapolTree {
fn log_successful_tree_creation(&self) {
info!(
"\nDAPOL tree has been constructed. Public data:\n \
- accumulator type: {}\n \
- height: {}\n \
- salt_b: 0x{}\n \
- salt_s: 0x{}\n \
- root hash: 0x{}\n \
- root commitment: {:?}",
self.accumulator_type(),
self.height().as_u32(),
self.salt_b
.as_bytes()
.iter()
.map(|b| format!("{:02x}", b))
.collect::<String>(),
self.salt_s
.as_bytes()
.iter()
.map(|b| format!("{:02x}", b))
.collect::<String>(),
self.root_hash()
.as_bytes()
.iter()
.map(|b| format!("{:02x}", b))
.collect::<String>(),
self.root_commitment().compress()
);
}
/// Parse `path` as one that points to a serialized dapol tree file.
///
/// `path` can be either of the following:
/// 1. Existing directory: in this case a default file name is appended to
/// `path`. 2. Non-existing directory: in this case all dirs in the path
/// are created, and a default file name is appended.
/// 3. File in existing dir: in this case the extension is checked to be
/// [SERIALIZED_TREE_EXTENSION], then `path` is returned.
/// 4. File in non-existing dir: dirs in the path are created and the file
/// extension is checked.
///
/// The file prefix is [SERIALIZED_TREE_FILE_PREFIX].
pub fn parse_tree_serialization_path(
path: PathBuf,
) -> Result<PathBuf, read_write_utils::ReadWriteError> {
read_write_utils::parse_serialization_path(
path,
SERIALIZED_TREE_EXTENSION,
SERIALIZED_TREE_FILE_PREFIX,
)
}
/// Parse `path` as one that points to a json file containing the public
/// data of the root node.
///
/// `path` can be either of the following:
/// 1. Existing directory: in this case a default file name is appended to
/// `path`. 2. Non-existing directory: in this case all dirs in the path
/// are created, and a default file name is appended.
/// 3. File in existing dir: in this case the extension is checked to be
/// ".json", then `path` is returned.
/// 4. File in non-existing dir: dirs in the path are created and the file
/// extension is checked.
///
/// The file prefix is [SERIALIZED_ROOT_PUB_FILE_PREFIX].
pub fn parse_public_root_data_serialization_path(
path: PathBuf,
) -> Result<PathBuf, read_write_utils::ReadWriteError> {
read_write_utils::parse_serialization_path(path, "json", SERIALIZED_ROOT_PUB_FILE_PREFIX)
}
/// Parse `path` as one that points to a json file containing the secret
/// data of the root node.
///
/// `path` can be either of the following:
/// 1. Existing directory: in this case a default file name is appended to
/// `path`. 2. Non-existing directory: in this case all dirs in the path
/// are created, and a default file name is appended.
/// 3. File in existing dir: in this case the extension is checked to be
/// ".json", then `path` is returned.
/// 4. File in non-existing dir: dirs in the path are created and the file
/// extension is checked.
///
/// The file prefix is [SERIALIZED_ROOT_PVT_FILE_PREFIX].
pub fn parse_secret_root_data_serialization_path(
path: PathBuf,
) -> Result<PathBuf, read_write_utils::ReadWriteError> {
read_write_utils::parse_serialization_path(path, "json", SERIALIZED_ROOT_PVT_FILE_PREFIX)
}
/// Serialize the whole tree to a file.
///
/// Serialization is done using [bincode].
///
/// An error is returned if
/// 1. [bincode] fails to serialize the file.
/// 2. There is an issue opening or writing the file.
///
/// `path` can be either of the following:
/// 1. Existing directory: in this case a default file name is appended to
/// `path`. 2. Non-existing directory: in this case all dirs in the path
/// are created, and a default file name is appended.
/// 3. File in existing dir: in this case the extension is checked to be
/// [SERIALIZED_TREE_EXTENSION], then `path` is returned.
/// 4. File in non-existing dir: dirs in the path are created and the file
/// extension is checked.
///
/// The file prefix is [SERIALIZED_TREE_FILE_PREFIX].
pub fn serialize(&self, path: PathBuf) -> Result<PathBuf, DapolTreeError> {
let path = DapolTree::parse_tree_serialization_path(path)?;
info!(
"Serializing accumulator to file {:?}",
path.clone().into_os_string()
);
read_write_utils::serialize_to_bin_file(&self, path.clone()).log_on_err()?;
Ok(path)
}
/// Serialize the public root node data to a file.
///
/// The data that will be serialized to a json file:
/// - Pedersen commitment
/// - hash
///
/// An error is returned if
/// 1. [serde_json] fails to serialize the file.
/// 2. There is an issue opening or writing to the file.
///
/// `path` can be either of the following:
/// 1. Existing directory: in this case a default file name is appended to
/// `path`. 2. Non-existing directory: in this case all dirs in the path
/// are created, and a default file name is appended.
/// 3. File in existing dir: in this case the extension is checked to be
/// ".json", then `path` is returned.
/// 4. File in non-existing dir: dirs in the path are created and the file
/// extension is checked.
///
/// The file prefix is [SERIALIZED_ROOT_PUB_FILE_PREFIX].
pub fn serialize_public_root_data(&self, path: PathBuf) -> Result<PathBuf, DapolTreeError> {
let public_root_data: RootPublicData = self.public_root_data();
let path = DapolTree::parse_public_root_data_serialization_path(path.clone())?;
read_write_utils::serialize_to_json_file(&public_root_data, path.clone())?;
Ok(path)
}
/// Serialize the public root node data to a file.
///
/// The data that will be serialized to a json file:
/// - Pedersen commitment
/// - hash
/// - secret data (liability & blinding factor for Pedersen commitment)
///
/// An error is returned if
/// 1. [serde_json] fails to serialize any of the files.
/// 2. There is an issue opening or writing to any of the files.
///
/// `path` can be either of the following:
/// 1. Existing directory: in this case a default file name is appended to
/// `path`. 2. Non-existing directory: in this case all dirs in the path
/// are created, and a default file name is appended.
/// 3. File in existing dir: in this case the extension is checked to be
/// ".json", then `path` is returned.
/// 4. File in non-existing dir: dirs in the path are created and the file
/// extension is checked.
///
/// The file prefix is [SERIALIZED_ROOT_PVT_FILE_PREFIX].
pub fn serialize_secret_root_data(&self, dir: PathBuf) -> Result<PathBuf, DapolTreeError> {
let secret_root_data: RootSecretData = self.secret_root_data();
let path = DapolTree::parse_secret_root_data_serialization_path(dir.clone())?;
read_write_utils::serialize_to_json_file(&secret_root_data, path.clone())?;
Ok(path)
}
/// Deserialize the tree from the given file path.
///
/// The file is assumed to be in [bincode] format.
///
/// An error is logged and returned if
/// 1. The file cannot be opened.
/// 2. The [bincode] deserializer fails.
/// 3. The file extension is not [SERIALIZED_TREE_EXTENSION]
pub fn deserialize(path: PathBuf) -> Result<DapolTree, DapolTreeError> {
debug!(
"Deserializing DapolTree from file {:?}",
path.clone().into_os_string()
);
read_write_utils::check_deserialization_path(&path, SERIALIZED_TREE_EXTENSION)?;
let dapol_tree: DapolTree =
read_write_utils::deserialize_from_bin_file(path.clone()).log_on_err()?;
dapol_tree.log_successful_tree_creation();
Ok(dapol_tree)
}
/// Deserialize the public root data from the given file path.
///
/// The file is assumed to be in json format.
///
/// An error is logged and returned if
/// 1. The file cannot be opened.
/// 2. The [serde_json] deserializer fails.
/// 3. The file extension is not [SERIALIZED_ROOT_PUB_FILE_PREFIX]
pub fn deserialize_public_root_data(path: PathBuf) -> Result<RootPublicData, DapolTreeError> {
read_write_utils::check_deserialization_path(&path, "json")?;
let public_root_data: RootPublicData =
read_write_utils::deserialize_from_json_file(path.clone()).log_on_err()?;
Ok(public_root_data)
}
/// Deserialize the secret root data from the given file path.
///
/// The file is assumed to be in json format.
///
/// An error is logged and returned if
/// 1. The file cannot be opened.
/// 2. The [serde_json] deserializer fails.
/// 3. The file extension is not [SERIALIZED_ROOT_PUB_FILE_PREFIX]
pub fn deserialize_secret_root_data(path: PathBuf) -> Result<RootSecretData, DapolTreeError> {
read_write_utils::check_deserialization_path(&path, "json")?;
let secret_root_data: RootSecretData =
read_write_utils::deserialize_from_json_file(path.clone()).log_on_err()?;
Ok(secret_root_data)
}
}
// -------------------------------------------------------------------------------------------------
// Errors.
/// Errors encountered when handling an [Accumulator].
#[derive(thiserror::Error, Debug)]
pub enum DapolTreeError {
#[error("Error serializing/deserializing file")]
SerdeError(#[from] read_write_utils::ReadWriteError),
#[error("Error constructing a new NDM-SMT")]
NdmSmtConstructionError(#[from] NdmSmtError),
#[error("Verification of root data failed")]
RootVerificationError,
}
// -------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::test_utils::assert_err;
use crate::{
AccumulatorType, DapolTree, Entity, EntityId, Height, MaxLiability, MaxThreadCount, Salt,
Secret,
};
use std::path::{Path, PathBuf};
use std::str::FromStr;
fn new_tree() -> DapolTree {
let accumulator_type = AccumulatorType::NdmSmt;
let height = Height::expect_from(8);
let salt_b = Salt::from_str("salt_b").unwrap();
let salt_s = Salt::from_str("salt_s").unwrap();
let master_secret = Secret::from_str("master_secret").unwrap();
let max_liability = MaxLiability::from(10_000_000);
let max_thread_count = MaxThreadCount::from(8);
let random_seed = 1;
let entity = Entity {
liability: 1u64,
id: EntityId::from_str("id").unwrap(),
};
let entities = vec![entity.clone()];
DapolTree::new_with_random_seed(
accumulator_type.clone(),
master_secret.clone(),
salt_b.clone(),
salt_s.clone(),
max_liability.clone(),
max_thread_count.clone(),
height.clone(),
entities,
random_seed,
)
.unwrap()
}
mod construction {
use super::*;
#[test]
fn constructor_and_getters_work() {
let accumulator_type = AccumulatorType::NdmSmt;
let height = Height::expect_from(8);
let salt_b = Salt::from_str("salt_b").unwrap();
let salt_s = Salt::from_str("salt_s").unwrap();
let master_secret = Secret::from_str("master_secret").unwrap();
let max_liability = MaxLiability::from(10_000_000);
let max_thread_count = MaxThreadCount::from(8);
let random_seed = 1u64;
let entity = Entity {
liability: 1u64,
id: EntityId::from_str("id").unwrap(),
};
let entities = vec![entity.clone()];
let tree = DapolTree::new_with_random_seed(
accumulator_type.clone(),
master_secret.clone(),
salt_b.clone(),
salt_s.clone(),
max_liability.clone(),
max_thread_count.clone(),
height.clone(),
entities,
random_seed,
)
.unwrap();
assert_eq!(tree.master_secret(), &master_secret);
assert_eq!(tree.height(), &height);
assert_eq!(tree.max_liability(), &max_liability);
assert_eq!(tree.salt_b(), &salt_b);
assert_eq!(tree.salt_s(), &salt_s);
assert_eq!(tree.accumulator_type(), accumulator_type);
assert!(tree.entity_mapping().is_some());
assert!(tree.entity_mapping().unwrap().get(&entity.id).is_some());
}
}
mod serde {
use super::*;
mod tree {
use super::*;
#[test]
fn serde_does_not_change_tree() {
let tree = new_tree();
let src_dir = env!("CARGO_MANIFEST_DIR");
let examples_dir = Path::new(&src_dir).join("examples");
let path = examples_dir.join("my_serialized_tree_for_testing.dapoltree");
let path_2 = tree.serialize(path.clone()).unwrap();
assert_eq!(path, path_2);
let tree_2 = DapolTree::deserialize(path).unwrap();
assert_eq!(tree.master_secret(), tree_2.master_secret());
assert_eq!(tree.height(), tree_2.height());
assert_eq!(tree.max_liability(), tree_2.max_liability());
assert_eq!(tree.salt_b(), tree_2.salt_b());
assert_eq!(tree.salt_s(), tree_2.salt_s());
assert_eq!(tree.accumulator_type(), tree_2.accumulator_type());
assert_eq!(tree.entity_mapping(), tree_2.entity_mapping());
}
#[test]
fn serialization_path_parser_fails_for_unsupported_extensions() {
let path = PathBuf::from_str("./mytree.myext").unwrap();
let res = DapolTree::parse_tree_serialization_path(path);
assert_err!(
res,
Err(read_write_utils::ReadWriteError::UnsupportedFileExtension {
expected: _,
actual: _
})
);
}
#[test]
fn serialization_path_parser_gives_correct_file_prefix() {
let path = PathBuf::from_str("./").unwrap();
let path = DapolTree::parse_tree_serialization_path(path).unwrap();
assert!(path
.to_str()
.unwrap()
.contains("proof_of_liabilities_merkle_sum_tree_"));
}
}
mod public_root_data {
use super::*;
#[test]
fn serde_does_not_change_public_root_data() {
let tree = new_tree();
let public_root_data = tree.public_root_data();
let src_dir = env!("CARGO_MANIFEST_DIR");
let examples_dir = Path::new(&src_dir).join("examples");
let path = examples_dir.join("public_root_data.json");
let path_2 = tree.serialize_public_root_data(path.clone()).unwrap();
assert_eq!(path, path_2);
let public_root_data_2 = DapolTree::deserialize_public_root_data(path).unwrap();
assert_eq!(public_root_data, public_root_data_2);
}
#[test]
fn public_root_data_serialization_path_parser_fails_for_unsupported_extensions() {
let path = PathBuf::from_str("./public_root_data.myext").unwrap();
let res = DapolTree::parse_public_root_data_serialization_path(path);
assert_err!(
res,
Err(read_write_utils::ReadWriteError::UnsupportedFileExtension {
expected: _,
actual: _
})
);
}
#[test]
fn public_root_data_serialization_path_parser_gives_correct_file_prefix() {
let path = PathBuf::from_str("./").unwrap();
let path = DapolTree::parse_public_root_data_serialization_path(path).unwrap();
assert!(path.to_str().unwrap().contains("public_root_data_"));
}
}
mod secret_root_data {
use super::*;
#[test]
fn serde_does_not_change_secret_root_data() {
let tree = new_tree();
let secret_root_data = tree.secret_root_data();
let src_dir = env!("CARGO_MANIFEST_DIR");
let examples_dir = Path::new(&src_dir).join("examples");
let path = examples_dir.join("secret_root_data.json");
let path_2 = tree.serialize_secret_root_data(path.clone()).unwrap();
assert_eq!(path, path_2);
let secret_root_data_2 = DapolTree::deserialize_secret_root_data(path).unwrap();
assert_eq!(secret_root_data, secret_root_data_2);
}
#[test]
fn secret_root_data_serialization_path_parser_fails_for_unsupported_extensions() {
let path = PathBuf::from_str("./secret_root_data.myext").unwrap();
let res = DapolTree::parse_secret_root_data_serialization_path(path);
assert_err!(
res,
Err(read_write_utils::ReadWriteError::UnsupportedFileExtension {
expected: _,
actual: _
})
);
}
#[test]
fn secret_root_data_serialization_path_parser_gives_correct_file_prefix() {
let path = PathBuf::from_str("./").unwrap();
let path = DapolTree::parse_secret_root_data_serialization_path(path).unwrap();
assert!(path.to_str().unwrap().contains("secret_root_data_"));
}
}
}
mod inclusion_proofs {
use super::*;
#[test]
fn generate_inclusion_proof_works() {
let tree = new_tree();
assert!(tree
.generate_inclusion_proof(&EntityId::from_str("id").unwrap())
.is_ok());
}
#[test]
fn generate_inclusion_proof_with_aggregation_factor_works() {
let tree = new_tree();
let agg = AggregationFactor::Divisor(2u8);
assert!(tree
.generate_inclusion_proof_with(&EntityId::from_str("id").unwrap(), agg)
.is_ok());
}
}
}