shamir_share 0.2.1

A secure and efficient Rust library for Shamir's Secret Sharing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
//! Hierarchical Secret Sharing Scheme (HSSS) implementation
//!
//! This module provides a hierarchical approach to Shamir's Secret Sharing where different
//! participants can be assigned different numbers of shares based on their access level or role.
//! The core concept uses a single "master" scheme with a threshold and distributes varying
//! numbers of shares to participants based on their hierarchical level.
//!
//! # Concept
//!
//! The HSSS implementation uses a single, powerful "master" scheme (k_master, n_master) and
//! distributes different numbers of shares to participants based on their role. For example,
//! with a master scheme of (k=5, n=50):
//! - A President might get 5 shares (and can reconstruct alone)
//! - A VP might get 3 shares
//! - An Executive might get 2 shares
//!
//! A combination like a VP (3 shares) and an Executive (2 shares) would meet the threshold of 5.
//!
//! # Example
//! ```
//! use shamir_share::hsss::{Hsss, AccessLevel, HierarchicalShare};
//!
//! // Create an HSSS scheme with master threshold of 5
//! let hsss = Hsss::builder(5)
//!     .add_level("President", 5)
//!     .add_level("VP", 3)
//!     .add_level("Executive", 2)
//!     .build()
//!     .unwrap();
//! ```

use crate::error::{Result, ShamirError};
use crate::shamir::{ShamirShare, Share};

#[cfg(feature = "zeroize")]
use zeroize::{Zeroize, ZeroizeOnDrop};

/// Represents an access level in the hierarchical secret sharing scheme
///
/// An access level defines a role or position in the hierarchy and specifies
/// how many shares participants at that level should receive. This allows
/// for flexible access control where higher-level participants receive more
/// shares and can potentially reconstruct the secret with fewer collaborators.
///
/// # Example
/// ```
/// use shamir_share::hsss::AccessLevel;
///
/// let president_level = AccessLevel {
///     name: "President".to_string(),
///     shares_count: 5,
/// };
///
/// let vp_level = AccessLevel {
///     name: "VP".to_string(),
///     shares_count: 3,
/// };
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "zeroize", derive(Zeroize, ZeroizeOnDrop))]
pub struct AccessLevel {
    /// Human-readable name for this access level (e.g., "President", "VP", "Executive")
    pub name: String,
    /// Number of shares that participants at this level should receive
    pub shares_count: u8,
}

/// Represents the actual shares assigned to a participant in the hierarchical scheme
///
/// This struct contains the access level name and the actual cryptographic shares
/// that were generated for a participant at that level. The number of shares
/// should match the `shares_count` specified in the corresponding `AccessLevel`.
///
/// # Example
/// ```
/// use shamir_share::hsss::HierarchicalShare;
/// use shamir_share::Share;
///
/// // This would typically be created by the HSSS system
/// let hierarchical_share = HierarchicalShare {
///     level_name: "President".to_string(),
///     shares: vec![], // Would contain actual Share objects
/// };
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "zeroize", derive(Zeroize, ZeroizeOnDrop))]
pub struct HierarchicalShare {
    /// Name of the access level this share set belongs to
    pub level_name: String,
    /// The actual cryptographic shares for this participant
    pub shares: Vec<Share>,
}

/// Main Hierarchical Secret Sharing Scheme implementation
///
/// The `Hsss` struct represents a configured hierarchical secret sharing scheme
/// that can split secrets according to the defined access levels. It maintains
/// the underlying Shamir scheme and the hierarchy definition.
///
/// # Security
///
/// The HSSS inherits all security properties from the underlying Shamir's Secret
/// Sharing implementation, including:
/// - Constant-time operations to prevent side-channel attacks
/// - Cryptographically secure random number generation
/// - Integrity verification capabilities
///
/// # Example
/// ```
/// use shamir_share::hsss::Hsss;
///
/// let hsss = Hsss::builder(5)
///     .add_level("President", 5)
///     .add_level("VP", 3)
///     .add_level("Executive", 2)
///     .build()
///     .unwrap();
/// ```
#[derive(Debug)]
pub struct Hsss {
    /// The underlying Shamir's Secret Sharing scheme
    master_scheme: ShamirShare,
    /// Defined access levels in the hierarchy
    levels: Vec<AccessLevel>,
}

/// Builder for creating HSSS instances with hierarchical access levels
///
/// The `HsssBuilder` provides a fluent interface for defining the hierarchical
/// structure of the secret sharing scheme. It automatically calculates the
/// total number of shares needed based on the defined access levels.
///
/// # Example
/// ```
/// use shamir_share::hsss::Hsss;
///
/// let hsss = Hsss::builder(5)  // Master threshold of 5
///     .add_level("President", 5)    // President gets 5 shares
///     .add_level("VP", 3)           // VP gets 3 shares  
///     .add_level("Executive", 2)    // Executive gets 2 shares
///     .build()
///     .unwrap();
/// ```
#[derive(Debug)]
pub struct HsssBuilder {
    /// The master threshold for reconstruction
    master_threshold: u8,
    /// Access levels being defined
    levels: Vec<AccessLevel>,
}

impl HsssBuilder {
    /// Creates a new HSSS builder with the specified master threshold
    ///
    /// The master threshold determines how many shares are needed to reconstruct
    /// the secret. Participants can combine their shares to meet this threshold.
    ///
    /// # Arguments
    /// * `master_threshold` - Minimum number of shares required for reconstruction (1-255)
    ///
    /// # Example
    /// ```
    /// use shamir_share::hsss::Hsss;
    ///
    /// let builder = Hsss::builder(5);
    /// ```
    pub fn new(master_threshold: u8) -> Self {
        Self {
            master_threshold,
            levels: Vec::new(),
        }
    }

    /// Adds a new access level to the hierarchical scheme
    ///
    /// This method defines a new role or level in the hierarchy and specifies
    /// how many shares participants at that level should receive. Access levels
    /// can be added in any order.
    ///
    /// # Arguments
    /// * `name` - Human-readable name for the access level
    /// * `shares_count` - Number of shares for participants at this level (1-255)
    ///
    /// # Returns
    /// The builder instance for method chaining
    ///
    /// # Example
    /// ```
    /// use shamir_share::hsss::Hsss;
    ///
    /// let hsss = Hsss::builder(5)
    ///     .add_level("President", 5)
    ///     .add_level("VP", 3)
    ///     .add_level("Manager", 2)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn add_level(mut self, name: &str, shares_count: u8) -> Self {
        self.levels.push(AccessLevel {
            name: name.to_string(),
            shares_count,
        });
        self
    }

    /// Builds the HSSS instance with validation
    ///
    /// This method validates the configuration and creates the underlying
    /// Shamir's Secret Sharing scheme. It calculates the total number of
    /// shares needed (n_master) by summing the shares_count of all levels.
    ///
    /// # Returns
    /// A configured `Hsss` instance ready for use
    ///
    /// # Errors
    /// Returns `ShamirError` if:
    /// - `master_threshold` is 0
    /// - No access levels have been defined
    /// - Total shares count is 0 or exceeds 255
    /// - `master_threshold` exceeds the total shares count
    /// - Any individual `shares_count` is 0
    ///
    /// # Example
    /// ```
    /// use shamir_share::hsss::Hsss;
    ///
    /// let result = Hsss::builder(5)
    ///     .add_level("President", 5)
    ///     .add_level("VP", 3)
    ///     .build();
    ///
    /// assert!(result.is_ok());
    /// ```
    pub fn build(self) -> Result<Hsss> {
        // Validate master threshold
        if self.master_threshold == 0 {
            return Err(ShamirError::InvalidThreshold(self.master_threshold));
        }

        // Validate that at least one level is defined
        if self.levels.is_empty() {
            return Err(ShamirError::InvalidConfig(
                "At least one access level must be defined".to_string(),
            ));
        }

        // Validate that all levels have non-zero share counts
        for level in &self.levels {
            if level.shares_count == 0 {
                return Err(ShamirError::InvalidShareCount(level.shares_count));
            }
        }

        // Calculate total number of shares needed (n_master)
        let total_shares: u32 = self.levels.iter().map(|level| level.shares_count as u32).sum();

        // Validate total shares count
        if total_shares == 0 {
            return Err(ShamirError::InvalidShareCount(0));
        }
        if total_shares > 255 {
            return Err(ShamirError::InvalidConfig(format!(
                "Total shares count {} exceeds maximum of 255",
                total_shares
            )));
        }

        let n_master = total_shares as u8;

        // Validate that master threshold doesn't exceed total shares
        if self.master_threshold > n_master {
            return Err(ShamirError::ThresholdTooLarge {
                threshold: self.master_threshold,
                total_shares: n_master,
            });
        }

        // Create the underlying Shamir scheme
        let master_scheme = ShamirShare::builder(n_master, self.master_threshold).build()?;

        Ok(Hsss {
            master_scheme,
            levels: self.levels,
        })
    }
}

impl Hsss {
    /// Creates a builder for configuring an HSSS instance
    ///
    /// This is the recommended way to create HSSS instances as it provides
    /// a fluent interface for defining the hierarchical structure.
    ///
    /// # Arguments
    /// * `master_threshold` - Minimum number of shares required for reconstruction (1-255)
    ///
    /// # Returns
    /// An `HsssBuilder` instance for configuring the hierarchy
    ///
    /// # Example
    /// ```
    /// use shamir_share::hsss::Hsss;
    ///
    /// let hsss = Hsss::builder(5)
    ///     .add_level("President", 5)
    ///     .add_level("VP", 3)
    ///     .add_level("Executive", 2)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn builder(master_threshold: u8) -> HsssBuilder {
        HsssBuilder::new(master_threshold)
    }

    /// Returns a reference to the defined access levels
    ///
    /// This method provides read-only access to the hierarchy definition,
    /// allowing inspection of the configured access levels and their
    /// associated share counts.
    ///
    /// # Returns
    /// A slice containing all defined access levels
    ///
    /// # Example
    /// ```
    /// use shamir_share::hsss::Hsss;
    ///
    /// let hsss = Hsss::builder(5)
    ///     .add_level("President", 5)
    ///     .add_level("VP", 3)
    ///     .build()
    ///     .unwrap();
    ///
    /// let levels = hsss.levels();
    /// assert_eq!(levels.len(), 2);
    /// assert_eq!(levels[0].name, "President");
    /// assert_eq!(levels[0].shares_count, 5);
    /// ```
    pub fn levels(&self) -> &[AccessLevel] {
        &self.levels
    }

    /// Returns the master threshold for this HSSS scheme
    ///
    /// The master threshold is the minimum number of shares required to
    /// reconstruct the secret, regardless of how they are distributed
    /// among participants.
    ///
    /// # Returns
    /// The master threshold value
    ///
    /// # Example
    /// ```
    /// use shamir_share::hsss::Hsss;
    ///
    /// let hsss = Hsss::builder(5)
    ///     .add_level("President", 5)
    ///     .build()
    ///     .unwrap();
    ///
    /// assert_eq!(hsss.master_threshold(), 5);
    /// ```
    pub fn master_threshold(&self) -> u8 {
        self.master_scheme.threshold()
    }

    /// Returns the total number of shares in the master scheme
    ///
    /// This is the sum of all shares_count values across all defined
    /// access levels, representing the total number of shares that
    /// will be generated.
    ///
    /// # Returns
    /// The total number of shares (n_master)
    ///
    /// # Example
    /// ```
    /// use shamir_share::hsss::Hsss;
    ///
    /// let hsss = Hsss::builder(5)
    ///     .add_level("President", 5)
    ///     .add_level("VP", 3)
    ///     .add_level("Executive", 2)
    ///     .build()
    ///     .unwrap();
    ///
    /// assert_eq!(hsss.total_shares(), 10); // 5 + 3 + 2
    /// ```
    pub fn total_shares(&self) -> u8 {
        self.master_scheme.total_shares()
    }

    /// Splits a secret into hierarchical shares according to the defined access levels
    ///
    /// This method uses an optimized approach that generates all master shares efficiently
    /// and then distributes them to the different hierarchical levels according to their
    /// configured share counts. It leverages the underlying Shamir scheme's optimized
    /// implementation for maximum performance.
    ///
    /// # Arguments
    /// * `secret` - The secret data to be split and distributed
    ///
    /// # Returns
    /// A vector of `HierarchicalShare` instances, one for each defined access level.
    /// Each `HierarchicalShare` contains the level name and the shares allocated to that level.
    ///
    /// # Process
    /// 1. **Generate all master shares**: Use the underlying Shamir scheme to generate all shares
    /// 2. **Distribution**: Distribute shares to hierarchical levels according to their counts
    ///
    /// # Performance
    /// This implementation:
    /// - Uses the optimized Shamir implementation which already employs columnar processing
    /// - Generates all shares at once to avoid repeated polynomial evaluations
    /// - Provides significantly better performance than the previous iterative approach
    /// - Maintains identical security properties and output
    ///
    /// # Errors
    /// Returns `ShamirError` if:
    /// - The underlying Shamir scheme encounters an error
    /// - Memory allocation fails for large secrets
    /// - Internal computation errors occur
    ///
    /// # Example
    /// ```
    /// use shamir_share::hsss::Hsss;
    ///
    /// let mut hsss = Hsss::builder(5)
    ///     .add_level("President", 5)
    ///     .add_level("VP", 3)
    ///     .add_level("Executive", 2)
    ///     .build()
    ///     .unwrap();
    ///
    /// let secret = b"top secret data";
    /// let hierarchical_shares = hsss.split_secret(secret).unwrap();
    ///
    /// assert_eq!(hierarchical_shares.len(), 3);
    /// assert_eq!(hierarchical_shares[0].level_name, "President");
    /// assert_eq!(hierarchical_shares[0].shares.len(), 5);
    /// assert_eq!(hierarchical_shares[1].level_name, "VP");
    /// assert_eq!(hierarchical_shares[1].shares.len(), 3);
    /// assert_eq!(hierarchical_shares[2].level_name, "Executive");
    /// assert_eq!(hierarchical_shares[2].shares.len(), 2);
    /// ```
    ///
    /// # Security
    /// - Inherits all security properties from the underlying Shamir scheme
    /// - Uses cryptographically secure random number generation
    /// - Constant-time operations prevent side-channel attacks
    /// - Each share reveals no information about the secret without meeting the threshold
    pub fn split_secret(&mut self, secret: &[u8]) -> Result<Vec<HierarchicalShare>> {
        // Generate all master shares at once using the optimized Shamir implementation
        // This is much more efficient than the previous dealer-based approach
        let all_master_shares = self.master_scheme.split(secret)?;
        
        // Distribute master shares to hierarchical levels
        let mut share_iter = all_master_shares.into_iter();
        let mut hierarchical_shares = Vec::with_capacity(self.levels.len());
        
        for level in &self.levels {
            let mut shares = Vec::with_capacity(level.shares_count as usize);
            
            for _ in 0..level.shares_count {
                // Take the next master share
                let share = share_iter.next().ok_or_else(|| {
                    ShamirError::InvalidConfig(format!(
                        "Insufficient master shares available for level '{}': this should not happen",
                        level.name
                    ))
                })?;
                
                shares.push(share);
            }
            
            // Create the hierarchical share for this level
            let hierarchical_share = HierarchicalShare {
                level_name: level.name.clone(),
                shares,
            };
            
            hierarchical_shares.push(hierarchical_share);
        }
        
        Ok(hierarchical_shares)
    }

    /// Reconstructs the original secret from hierarchical shares
    ///
    /// This method provides a convenient way to reconstruct the secret from one or more
    /// `HierarchicalShare` instances. It flattens all the individual shares from the
    /// hierarchical shares and uses the standard Shamir reconstruction algorithm.
    ///
    /// # Arguments
    /// * `hierarchical_shares` - Slice of hierarchical shares to use for reconstruction
    ///
    /// # Returns
    /// The original secret data if reconstruction succeeds
    ///
    /// # Process
    /// 1. Flattens all `Share` objects from all provided `HierarchicalShare` instances
    /// 2. Calls the standard `ShamirShare::reconstruct()` method on the flattened shares
    /// 3. Returns the reconstructed secret
    ///
    /// # Threshold Requirements
    /// The total number of individual shares across all provided hierarchical shares
    /// must meet or exceed the master threshold. For example, with a master threshold of 5:
    /// - A President with 5 shares can reconstruct alone
    /// - A VP (3 shares) + Executive (2 shares) can reconstruct together
    /// - Any combination totaling 5 or more shares can reconstruct
    ///
    /// # Errors
    /// Returns `ShamirError` if:
    /// - No hierarchical shares provided
    /// - Insufficient total shares to meet the master threshold
    /// - Shares have inconsistent properties (length, integrity settings, etc.)
    /// - Integrity check fails (if enabled)
    /// - Invalid share data or corruption detected
    ///
    /// # Example
    /// ```
    /// use shamir_share::hsss::Hsss;
    ///
    /// let mut hsss = Hsss::builder(5)
    ///     .add_level("President", 5)
    ///     .add_level("VP", 3)
    ///     .add_level("Executive", 2)
    ///     .build()
    ///     .unwrap();
    ///
    /// let secret = b"confidential information";
    /// let hierarchical_shares = hsss.split_secret(secret).unwrap();
    ///
    /// // President can reconstruct alone (5 shares >= threshold of 5)
    /// let reconstructed = hsss.reconstruct(&hierarchical_shares[0..1]).unwrap();
    /// assert_eq!(reconstructed, secret);
    ///
    /// // VP + Executive can reconstruct together (3 + 2 = 5 shares >= threshold of 5)
    /// let reconstructed = hsss.reconstruct(&hierarchical_shares[1..3]).unwrap();
    /// assert_eq!(reconstructed, secret);
    /// ```
    ///
    /// # Security
    /// - Inherits all security properties from the underlying Shamir reconstruction
    /// - Constant-time operations prevent side-channel attacks
    /// - Integrity verification (if enabled during splitting)
    /// - No information leakage about the secret with insufficient shares
    pub fn reconstruct(&self, hierarchical_shares: &[HierarchicalShare]) -> Result<Vec<u8>> {
        // Flatten all shares from all hierarchical shares into a single vector
        let mut all_shares = Vec::new();
        
        for hierarchical_share in hierarchical_shares {
            all_shares.extend_from_slice(&hierarchical_share.shares);
        }
        
        // Use the standard Shamir reconstruction method
        ShamirShare::reconstruct(&all_shares)
    }
}

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

    #[test]
    fn test_access_level_creation() {
        let level = AccessLevel {
            name: "President".to_string(),
            shares_count: 5,
        };

        assert_eq!(level.name, "President");
        assert_eq!(level.shares_count, 5);
    }

    #[test]
    fn test_hierarchical_share_creation() {
        let share = HierarchicalShare {
            level_name: "VP".to_string(),
            shares: vec![],
        };

        assert_eq!(share.level_name, "VP");
        assert_eq!(share.shares.len(), 0);
    }

    #[test]
    fn test_hsss_builder_basic() {
        let hsss = Hsss::builder(5)
            .add_level("President", 5)
            .add_level("VP", 3)
            .add_level("Executive", 2)
            .build()
            .unwrap();

        assert_eq!(hsss.master_threshold(), 5);
        assert_eq!(hsss.total_shares(), 10); // 5 + 3 + 2
        assert_eq!(hsss.levels().len(), 3);

        let levels = hsss.levels();
        assert_eq!(levels[0].name, "President");
        assert_eq!(levels[0].shares_count, 5);
        assert_eq!(levels[1].name, "VP");
        assert_eq!(levels[1].shares_count, 3);
        assert_eq!(levels[2].name, "Executive");
        assert_eq!(levels[2].shares_count, 2);
    }

    #[test]
    fn test_hsss_builder_single_level() {
        let hsss = Hsss::builder(3)
            .add_level("Admin", 5)
            .build()
            .unwrap();

        assert_eq!(hsss.master_threshold(), 3);
        assert_eq!(hsss.total_shares(), 5);
        assert_eq!(hsss.levels().len(), 1);
        assert_eq!(hsss.levels()[0].name, "Admin");
        assert_eq!(hsss.levels()[0].shares_count, 5);
    }

    #[test]
    fn test_hsss_builder_validation_zero_threshold() {
        let result = Hsss::builder(0)
            .add_level("President", 5)
            .build();

        assert!(matches!(result, Err(ShamirError::InvalidThreshold(0))));
    }

    #[test]
    fn test_hsss_builder_validation_no_levels() {
        let result = Hsss::builder(5).build();

        assert!(matches!(result, Err(ShamirError::InvalidConfig(_))));
    }

    #[test]
    fn test_hsss_builder_validation_zero_shares() {
        let result = Hsss::builder(5)
            .add_level("President", 0)
            .build();

        assert!(matches!(result, Err(ShamirError::InvalidShareCount(0))));
    }

    #[test]
    fn test_hsss_builder_validation_threshold_too_large() {
        let result = Hsss::builder(10)
            .add_level("President", 5)
            .add_level("VP", 3)
            .build();

        assert!(matches!(
            result,
            Err(ShamirError::ThresholdTooLarge { threshold: 10, total_shares: 8 })
        ));
    }

    #[test]
    fn test_hsss_builder_validation_too_many_shares() {
        let result = Hsss::builder(5)
            .add_level("Level1", 200)
            .add_level("Level2", 100)
            .build();

        assert!(matches!(result, Err(ShamirError::InvalidConfig(_))));
    }

    #[test]
    fn test_hsss_builder_method_chaining() {
        let hsss = Hsss::builder(7)
            .add_level("CEO", 7)
            .add_level("CTO", 5)
            .add_level("Manager", 3)
            .add_level("Employee", 1)
            .build()
            .unwrap();

        assert_eq!(hsss.master_threshold(), 7);
        assert_eq!(hsss.total_shares(), 16); // 7 + 5 + 3 + 1
        assert_eq!(hsss.levels().len(), 4);
    }

    #[test]
    fn test_hsss_builder_edge_case_threshold_equals_total() {
        let hsss = Hsss::builder(10)
            .add_level("President", 5)
            .add_level("VP", 5)
            .build()
            .unwrap();

        assert_eq!(hsss.master_threshold(), 10);
        assert_eq!(hsss.total_shares(), 10);
    }

    #[test]
    fn test_hsss_builder_max_shares() {
        let hsss = Hsss::builder(255)
            .add_level("Level1", 255)
            .build()
            .unwrap();

        assert_eq!(hsss.master_threshold(), 255);
        assert_eq!(hsss.total_shares(), 255);
    }

    #[test]
    fn test_access_level_clone() {
        let level1 = AccessLevel {
            name: "President".to_string(),
            shares_count: 5,
        };

        let level2 = level1.clone();
        assert_eq!(level1, level2);
        assert_eq!(level1.name, level2.name);
        assert_eq!(level1.shares_count, level2.shares_count);
    }

    #[test]
    fn test_hierarchical_share_clone() {
        let share1 = HierarchicalShare {
            level_name: "VP".to_string(),
            shares: vec![],
        };

        let share2 = share1.clone();
        assert_eq!(share1, share2);
        assert_eq!(share1.level_name, share2.level_name);
        assert_eq!(share1.shares.len(), share2.shares.len());
    }

    #[test]
    #[cfg(feature = "zeroize")]
    fn test_zeroize_derives() {
        use zeroize::Zeroize;

        let mut level = AccessLevel {
            name: "Secret".to_string(),
            shares_count: 5,
        };

        level.zeroize();
        // After zeroization, the name should be empty and shares_count should be 0
        assert_eq!(level.name, "");
        assert_eq!(level.shares_count, 0);

        let mut hierarchical_share = HierarchicalShare {
            level_name: "Secret".to_string(),
            shares: vec![],
        };

        hierarchical_share.zeroize();
        // After zeroization, the level_name should be empty and shares should be empty
        assert_eq!(hierarchical_share.level_name, "");
        assert_eq!(hierarchical_share.shares.len(), 0);
    }

    #[test]
    fn test_split_secret_basic() {
        let mut hsss = Hsss::builder(5)
            .add_level("President", 5)
            .add_level("VP", 3)
            .add_level("Executive", 2)
            .build()
            .unwrap();

        let secret = b"top secret information";
        let hierarchical_shares = hsss.split_secret(secret).unwrap();

        // Verify we got the expected number of hierarchical shares
        assert_eq!(hierarchical_shares.len(), 3);

        // Verify President level
        assert_eq!(hierarchical_shares[0].level_name, "President");
        assert_eq!(hierarchical_shares[0].shares.len(), 5);

        // Verify VP level
        assert_eq!(hierarchical_shares[1].level_name, "VP");
        assert_eq!(hierarchical_shares[1].shares.len(), 3);

        // Verify Executive level
        assert_eq!(hierarchical_shares[2].level_name, "Executive");
        assert_eq!(hierarchical_shares[2].shares.len(), 2);

        // Verify share properties
        for hierarchical_share in &hierarchical_shares {
            for share in &hierarchical_share.shares {
                assert_eq!(share.threshold, 5); // Master threshold
                assert_eq!(share.total_shares, 10); // Total shares (5+3+2)
                assert!(share.integrity_check); // Default is true
            }
        }
    }

    #[test]
    fn test_reconstruct_president_alone() {
        let mut hsss = Hsss::builder(5)
            .add_level("President", 5)
            .add_level("VP", 3)
            .add_level("Executive", 2)
            .build()
            .unwrap();

        let secret = b"classified data";
        let hierarchical_shares = hsss.split_secret(secret).unwrap();

        // President should be able to reconstruct alone (5 shares >= threshold of 5)
        let reconstructed = hsss.reconstruct(&hierarchical_shares[0..1]).unwrap();
        assert_eq!(reconstructed, secret);
    }

    #[test]
    fn test_reconstruct_vp_and_executive() {
        let mut hsss = Hsss::builder(5)
            .add_level("President", 5)
            .add_level("VP", 3)
            .add_level("Executive", 2)
            .build()
            .unwrap();

        let secret = b"sensitive information";
        let hierarchical_shares = hsss.split_secret(secret).unwrap();

        // VP + Executive should be able to reconstruct together (3 + 2 = 5 shares >= threshold of 5)
        let reconstructed = hsss.reconstruct(&hierarchical_shares[1..3]).unwrap();
        assert_eq!(reconstructed, secret);
    }

    #[test]
    fn test_reconstruct_all_levels() {
        let mut hsss = Hsss::builder(5)
            .add_level("President", 5)
            .add_level("VP", 3)
            .add_level("Executive", 2)
            .build()
            .unwrap();

        let secret = b"multi-level secret";
        let hierarchical_shares = hsss.split_secret(secret).unwrap();

        // All levels together should also work (5 + 3 + 2 = 10 shares >= threshold of 5)
        let reconstructed = hsss.reconstruct(&hierarchical_shares).unwrap();
        assert_eq!(reconstructed, secret);
    }

    #[test]
    fn test_reconstruct_insufficient_shares() {
        let mut hsss = Hsss::builder(5)
            .add_level("President", 5)
            .add_level("VP", 3)
            .add_level("Executive", 2)
            .build()
            .unwrap();

        let secret = b"protected data";
        let hierarchical_shares = hsss.split_secret(secret).unwrap();

        // VP alone should not be able to reconstruct (3 shares < threshold of 5)
        let result = hsss.reconstruct(&hierarchical_shares[1..2]);
        assert!(matches!(result, Err(ShamirError::InsufficientShares { needed: 5, got: 3 })));

        // Executive alone should not be able to reconstruct (2 shares < threshold of 5)
        let result = hsss.reconstruct(&hierarchical_shares[2..3]);
        assert!(matches!(result, Err(ShamirError::InsufficientShares { needed: 5, got: 2 })));
    }

    #[test]
    fn test_split_secret_single_level() {
        let mut hsss = Hsss::builder(3)
            .add_level("Admin", 5)
            .build()
            .unwrap();

        let secret = b"admin secret";
        let hierarchical_shares = hsss.split_secret(secret).unwrap();

        assert_eq!(hierarchical_shares.len(), 1);
        assert_eq!(hierarchical_shares[0].level_name, "Admin");
        assert_eq!(hierarchical_shares[0].shares.len(), 5);

        // Should be able to reconstruct with any 3 shares
        let reconstructed = hsss.reconstruct(&hierarchical_shares).unwrap();
        assert_eq!(reconstructed, secret);
    }

    #[test]
    fn test_split_secret_empty_secret() {
        let mut hsss = Hsss::builder(2)
            .add_level("Level1", 3)
            .add_level("Level2", 2)
            .build()
            .unwrap();

        let secret = b"";
        let hierarchical_shares = hsss.split_secret(secret).unwrap();

        assert_eq!(hierarchical_shares.len(), 2);
        
        // Should be able to reconstruct empty secret
        let reconstructed = hsss.reconstruct(&hierarchical_shares).unwrap();
        assert_eq!(reconstructed, secret);
    }

    #[test]
    fn test_split_secret_large_secret() {
        let mut hsss = Hsss::builder(10)
            .add_level("CEO", 10)
            .add_level("CTO", 7)
            .add_level("Manager", 5)
            .add_level("Employee", 3)
            .build()
            .unwrap();

        // Create a larger secret
        let secret: Vec<u8> = (0..1000).map(|i| (i % 256) as u8).collect();
        let hierarchical_shares = hsss.split_secret(&secret).unwrap();

        assert_eq!(hierarchical_shares.len(), 4);
        assert_eq!(hierarchical_shares[0].shares.len(), 10); // CEO
        assert_eq!(hierarchical_shares[1].shares.len(), 7);  // CTO
        assert_eq!(hierarchical_shares[2].shares.len(), 5);  // Manager
        assert_eq!(hierarchical_shares[3].shares.len(), 3);  // Employee

        // CEO should be able to reconstruct alone
        let reconstructed = hsss.reconstruct(&hierarchical_shares[0..1]).unwrap();
        assert_eq!(reconstructed, secret);

        // CTO + Manager should be able to reconstruct (7 + 5 = 12 >= 10)
        let reconstructed = hsss.reconstruct(&hierarchical_shares[1..3]).unwrap();
        assert_eq!(reconstructed, secret);
    }

    #[test]
    fn test_split_secret_different_combinations() {
        let mut hsss = Hsss::builder(7)
            .add_level("Level1", 7)
            .add_level("Level2", 4)
            .add_level("Level3", 3)
            .add_level("Level4", 2)
            .build()
            .unwrap();

        let secret = b"combination test secret";
        let hierarchical_shares = hsss.split_secret(secret).unwrap();

        // Test various combinations that should work
        let valid_combinations = vec![
            vec![0],       // Level1 alone (7 shares >= 7)
            vec![1, 2],    // Level2 + Level3 (4 + 3 = 7 shares >= 7)
            vec![0, 1],    // Level1 + Level2 (7 + 4 = 11 shares >= 7)
            vec![1, 2, 3], // Level2 + Level3 + Level4 (4 + 3 + 2 = 9 shares >= 7)
        ];

        for combo in valid_combinations {
            let mut selected_shares = Vec::new();
            for &level_idx in &combo {
                if level_idx < hierarchical_shares.len() {
                    selected_shares.push(hierarchical_shares[level_idx].clone());
                }
            }
            
            let reconstructed = hsss.reconstruct(&selected_shares).unwrap();
            assert_eq!(reconstructed, secret);
        }
    }

    #[test]
    fn test_reconstruct_no_hierarchical_shares() {
        let hsss = Hsss::builder(5)
            .add_level("President", 5)
            .build()
            .unwrap();

        // Empty slice should fail
        let result = hsss.reconstruct(&[]);
        assert!(matches!(result, Err(ShamirError::InsufficientShares { needed: 1, got: 0 })));
    }

    #[test]
    fn test_share_indices_are_unique() {
        let mut hsss = Hsss::builder(5)
            .add_level("Level1", 3)
            .add_level("Level2", 4)
            .add_level("Level3", 2)
            .build()
            .unwrap();

        let secret = b"unique indices test";
        let hierarchical_shares = hsss.split_secret(secret).unwrap();

        // Collect all share indices
        let mut all_indices = Vec::new();
        for hierarchical_share in &hierarchical_shares {
            for share in &hierarchical_share.shares {
                all_indices.push(share.index);
            }
        }

        // Verify all indices are unique
        all_indices.sort();
        for i in 1..all_indices.len() {
            assert_ne!(all_indices[i-1], all_indices[i], "Found duplicate share index: {}", all_indices[i]);
        }

        // Verify indices are in expected range (1 to total_shares)
        assert_eq!(all_indices[0], 1);
        assert_eq!(all_indices[all_indices.len() - 1], hsss.total_shares());
    }

    #[test]
    fn test_split_secret_with_integrity_disabled() {
        use crate::config::Config;

        // Create HSSS with integrity check disabled
        let config = Config::new().with_integrity_check(false);
        let master_scheme = ShamirShare::builder(10, 5)
            .with_config(config)
            .build()
            .unwrap();

        let mut hsss = Hsss {
            master_scheme,
            levels: vec![
                AccessLevel { name: "Admin".to_string(), shares_count: 6 },
                AccessLevel { name: "User".to_string(), shares_count: 4 },
            ],
        };

        let secret = b"no integrity check";
        let hierarchical_shares = hsss.split_secret(secret).unwrap();

        // Verify shares have integrity_check = false
        for hierarchical_share in &hierarchical_shares {
            for share in &hierarchical_share.shares {
                assert!(!share.integrity_check);
            }
        }

        // Should still reconstruct correctly
        let reconstructed = hsss.reconstruct(&hierarchical_shares[0..1]).unwrap();
        assert_eq!(reconstructed, secret);
    }

    #[test]
    fn test_hsss_integration_example() {
        // This test demonstrates the full HSSS workflow as described in the prompt
        let mut hsss = Hsss::builder(5)
            .add_level("President", 5)    // President gets 5 shares (can reconstruct alone)
            .add_level("VP", 3)           // VP gets 3 shares
            .add_level("Executive", 2)    // Executive gets 2 shares
            .build()
            .unwrap();

        let secret = b"Top secret company information";

        // Split the secret into hierarchical shares
        let hierarchical_shares = hsss.split_secret(secret).unwrap();
        
        // Verify the structure
        assert_eq!(hierarchical_shares.len(), 3);
        assert_eq!(hierarchical_shares[0].level_name, "President");
        assert_eq!(hierarchical_shares[0].shares.len(), 5);
        assert_eq!(hierarchical_shares[1].level_name, "VP");
        assert_eq!(hierarchical_shares[1].shares.len(), 3);
        assert_eq!(hierarchical_shares[2].level_name, "Executive");
        assert_eq!(hierarchical_shares[2].shares.len(), 2);

        // Scenario 1: President reconstructs alone (5 shares >= threshold of 5)
        let reconstructed = hsss.reconstruct(&hierarchical_shares[0..1]).unwrap();
        assert_eq!(reconstructed, secret);

        // Scenario 2: VP and Executive collaborate (3 + 2 = 5 shares >= threshold of 5)
        let reconstructed = hsss.reconstruct(&hierarchical_shares[1..3]).unwrap();
        assert_eq!(reconstructed, secret);

        // Scenario 3: VP alone should fail (3 shares < threshold of 5)
        let result = hsss.reconstruct(&hierarchical_shares[1..2]);
        assert!(matches!(result, Err(ShamirError::InsufficientShares { needed: 5, got: 3 })));

        // Scenario 4: Executive alone should fail (2 shares < threshold of 5)
        let result = hsss.reconstruct(&hierarchical_shares[2..3]);
        assert!(matches!(result, Err(ShamirError::InsufficientShares { needed: 5, got: 2 })));

        // Scenario 5: All levels together should work (5 + 3 + 2 = 10 shares >= threshold of 5)
        let reconstructed = hsss.reconstruct(&hierarchical_shares).unwrap();
        assert_eq!(reconstructed, secret);
    }
}