### MemoryStore Example Implementation Source: https://docs.rs/shamir_share/latest/shamir_share/trait.ShareStore.html An example implementation of the ShareStore trait using an in-memory store. ```APIDOC ## Example Implementation ```rust use shamir_share::{ShareStore, Share}; struct MemoryStore; impl ShareStore for MemoryStore { fn store_share(&mut self, _: &Share) -> shamir_share::Result<()> { Ok(()) } fn load_share(&self, _: u8) -> shamir_share::Result { unimplemented!() } fn list_shares(&self) -> shamir_share::Result> { Ok(Vec::new()) } fn delete_share(&mut self, _: u8) -> shamir_share::Result<()> { Ok(()) } } ``` ``` -------------------------------- ### Create ShamirShare with Custom Configuration Source: https://docs.rs/shamir_share/latest/shamir_share/struct.ShamirShareBuilder.html Use `ShamirShare::builder()` to create a new builder instance, then customize it with `with_config()` and finally call `build()` to get a configured ShamirShare instance. This example demonstrates setting up a configuration with integrity checks disabled and parallel split mode. ```rust use shamir_share::{ShamirShare, Config, SplitMode}; let config = Config::new() .with_integrity_check(false) .with_mode(SplitMode::Parallel); let shamir = ShamirShare::builder(5, 3) .with_config(config) .build() .unwrap(); ``` -------------------------------- ### HSSS Integration Example Source: https://docs.rs/shamir_share/latest/src/shamir_share/hsss.rs.html Provides a full workflow example of HSSS, including setting up access levels, splitting a secret, and verifying the structure of the generated hierarchical shares. ```rust 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); ``` -------------------------------- ### Create New FileShareStore Instance Source: https://docs.rs/shamir_share/latest/src/shamir_share/storage.rs.html Example of initializing a `FileShareStore` pointing to a specific directory. The directory will be created if it doesn't exist. ```rust use shamir_share::FileShareStore; use std::path::Path; let store = FileShareStore::new(Path::new("/tmp/shares")).unwrap(); ``` -------------------------------- ### Implement ShareStore Trait - MemoryStore Example Source: https://docs.rs/shamir_share/latest/src/shamir_share/storage.rs.html Example of implementing the `ShareStore` trait for an in-memory storage solution. Useful for testing or simple applications. ```rust use shamir_share::{ShareStore, Share}; struct MemoryStore; impl ShareStore for MemoryStore { fn store_share(&mut self, _: &Share) -> shamir_share::Result<()> { Ok(()) } fn load_share(&self, _: u8) -> shamir_share::Result { unimplemented!() } fn list_shares(&self) -> shamir_share::Result> { Ok(Vec::new()) } fn delete_share(&mut self, _: u8) -> shamir_share::Result<()> { Ok(()) } } ``` -------------------------------- ### Share Structure Example Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Demonstrates the creation and basic properties of a `Share` object. Ensure the `shamir_share` crate is included in your project. ```rust use shamir_share::{Share, ShamirShare}; let mut shamir = ShamirShare::builder(5, 3).build().unwrap(); let shares = shamir.split(b"secret").unwrap(); let share = &shares[0]; assert_eq!(share.index, 1); assert_eq!(share.threshold, 3); assert_eq!(share.total_shares, 5); ``` -------------------------------- ### Example Usage of ShamirShare Source: https://docs.rs/shamir_share/latest/shamir_share/struct.ShamirShare.html Demonstrates how to create a ShamirShare scheme, split a secret into shares, and then reconstruct the secret from a subset of those shares. This example highlights the basic workflow of the library. ```rust use shamir_share::ShamirShare; // Create a scheme with 5 total shares and threshold of 3 let mut scheme = ShamirShare::builder(5, 3).build().unwrap(); // Split a secret let secret = b"my secret data"; let shares = scheme.split(secret).unwrap(); // Reconstruct with 3 shares let reconstructed = ShamirShare::reconstruct(&shares[0..3]).unwrap(); assert_eq!(reconstructed, secret); ``` -------------------------------- ### Example usage of FileShareStore Source: https://docs.rs/shamir_share/latest/shamir_share/struct.FileShareStore.html Demonstrates creating a FileShareStore, storing a share, and then loading it back to verify its content. Ensure the temporary directory is handled correctly. ```rust use shamir_share::{FileShareStore, ShareStore}; use tempfile::tempdir; let temp_dir = tempdir().unwrap(); let mut store = FileShareStore::new(temp_dir.path()).unwrap(); let share = shamir_share::Share { index: 1, data: vec![1, 2, 3], threshold: 3, total_shares: 5, integrity_check: true, compression: false, }; store.store_share(&share).unwrap(); let loaded = store.load_share(1).unwrap(); assert_eq!(loaded.data, vec![1, 2, 3]); ``` -------------------------------- ### Example Usage of Share Source: https://docs.rs/shamir_share/latest/shamir_share/struct.Share.html Demonstrates creating a ShamirShare instance, splitting a secret into shares, and accessing properties of an individual share. ```rust use shamir_share::{Share, ShamirShare}; let mut shamir = ShamirShare::builder(5, 3).build().unwrap(); let shares = shamir.split(b"secret").unwrap(); let share = &shares[0]; assert_eq!(share.index, 1); assert_eq!(share.threshold, 3); assert_eq!(share.total_shares, 5); ``` -------------------------------- ### MemoryStore Implementation of ShareStore Source: https://docs.rs/shamir_share/latest/shamir_share/trait.ShareStore.html An example implementation of the ShareStore trait using an in-memory store. This serves as a basic example for creating custom storage solutions. ```rust use shamir_share::{ShareStore, Share}; struct MemoryStore; impl ShareStore for MemoryStore { fn store_share(&mut self, _: &Share) -> shamir_share::Result<()> { Ok(()) } fn load_share(&self, _: u8) -> shamir_share::Result { unimplemented!() } fn list_shares(&self) -> shamir_share::Result> { Ok(Vec::new()) } fn delete_share(&mut self, _: u8) -> shamir_share::Result<()> { Ok(()) } } ``` -------------------------------- ### FileShareStore Usage Example Source: https://docs.rs/shamir_share/latest/src/shamir_share/storage.rs.html Demonstrates creating a `FileShareStore`, storing a `Share` object, and then loading it back to verify its contents. Requires the `tempfile` crate for temporary directory management. ```rust use shamir_share::{FileShareStore, ShareStore}; use tempfile::tempdir; let temp_dir = tempdir().unwrap(); let mut store = FileShareStore::new(temp_dir.path()).unwrap(); let share = shamir_share::Share { index: 1, data: vec![1, 2, 3], threshold: 3, total_shares: 5, integrity_check: true, compression: false, }; store.store_share(&share).unwrap(); let loaded = store.load_share(1).unwrap(); assert_eq!(loaded.data, vec![1, 2, 3]); ``` -------------------------------- ### Create New Config with Default Values Source: https://docs.rs/shamir_share/latest/shamir_share/struct.Config.html Initializes a new Config instance with default settings. This is the starting point for customizing configuration. ```rust pub fn new() -> Self> ``` -------------------------------- ### Example Usage of HierarchicalShare Source: https://docs.rs/shamir_share/latest/shamir_share/hsss/struct.HierarchicalShare.html Demonstrates how to create an instance of HierarchicalShare. This typically would be created by the HSSS system. ```rust 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 }; ``` -------------------------------- ### Lazy Share Generation and Reconstruction Example Source: https://docs.rs/shamir_share/latest/shamir_share/struct.Dealer.html Demonstrates how to use the Dealer to lazily generate a specified number of shares from a secret and then reconstruct the original secret from these shares. This example requires the ShamirShare struct and its builder. ```rust use shamir_share::ShamirShare; let mut shamir = ShamirShare::builder(5, 3).build().unwrap(); let secret = b"secret data"; // Generate shares lazily let shares: Vec<_> = shamir.dealer(secret).take(3).collect(); assert_eq!(shares.len(), 3); // Reconstruct let reconstructed = ShamirShare::reconstruct(&shares).unwrap(); assert_eq!(reconstructed, secret); ``` -------------------------------- ### HSSS Builder and Reconstruction Example Source: https://docs.rs/shamir_share/latest/src/shamir_share/hsss.rs.html Demonstrates building an HSSS scheme with multiple access levels, splitting a secret, and reconstructing it using different share combinations. Use this to understand the core HSSS workflow. ```rust /// 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); /// ``` -------------------------------- ### Split Stream Example - ShamirShare Rust Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Demonstrates splitting data from a stream into multiple share streams using chunk-based processing. It shows how to set up the ShamirShare instance, prepare source and destination buffers, and call the `split_stream` method. ```rust use shamir_share::{ShamirShare, Config}; use std::io::Cursor; let mut shamir = ShamirShare::builder(3, 2).build().unwrap(); let data = b"This is a test message for streaming"; let mut source = Cursor::new(data); let mut destinations = vec![Vec::new(); 3]; let mut dest_cursors: Vec>> = destinations .iter_mut() .map(|d| Cursor::new(std::mem::take(d))) .collect(); shamir.split_stream(&mut source, &mut dest_cursors).unwrap(); ``` -------------------------------- ### Build HSSS Instance and Check Result Source: https://docs.rs/shamir_share/latest/shamir_share/hsss/struct.HsssBuilder.html Builds the HSSS instance after configuring access levels and validates the configuration. This example shows how to check if the build operation was successful. ```rust use shamir_share::hsss::Hsss; let result = Hsss::builder(5) .add_level("President", 5) .add_level("VP", 3) .build(); assert!(result.is_ok()); ``` -------------------------------- ### Example: Splitting, Refreshing, and Reconstructing Shares Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Demonstrates the full lifecycle of Shamir shares: splitting a secret, refreshing the shares to obscure the original data, and then reconstructing the secret from both original and refreshed shares. Verifies that both sets of shares reconstruct to the same secret but have different underlying data. ```rust use shamir_share::ShamirShare; let mut scheme = ShamirShare::builder(5, 3).build().unwrap(); let secret = b"sensitive data"; // Create initial shares let original_shares = scheme.split(secret).unwrap(); // Refresh the shares to invalidate old ones let refreshed_shares = scheme.refresh_shares(&original_shares[0..3]).unwrap(); // Both sets reconstruct to the same secret let original_secret = ShamirShare::reconstruct(&original_shares[0..3]).unwrap(); let refreshed_secret = ShamirShare::reconstruct(&refreshed_shares).unwrap(); assert_eq!(original_secret, refreshed_secret); // But the share data is completely different assert_ne!(original_shares[0].data, refreshed_shares[0].data); ``` -------------------------------- ### Default Implementation for Config Source: https://docs.rs/shamir_share/latest/shamir_share/struct.Config.html Provides a default configuration when no specific settings are provided. This ensures a sensible starting point for the Config struct. ```rust fn default() -> Self> ``` -------------------------------- ### Initialize HsssBuilder Source: https://docs.rs/shamir_share/latest/shamir_share/hsss/struct.HsssBuilder.html Creates a new HSSS builder with the specified master threshold. This is the starting point for configuring a hierarchical secret sharing scheme. ```rust use shamir_share::hsss::Hsss; let builder = Hsss::builder(5); ``` -------------------------------- ### Full Workflow Test with FileShareStore Source: https://docs.rs/shamir_share/latest/src/shamir_share/lib.rs.html A comprehensive test function demonstrating the complete lifecycle of Shamir's Secret Sharing, including setup, splitting, storing, loading, and reconstructing secrets using a file-based store. Requires a temporary directory for file operations. ```rust use super::*; use tempfile::tempdir; #[test] fn test_full_workflow() -> Result<()> { // Create a temporary directory for storing shares let temp_dir = tempdir()?; let mut store = FileShareStore::new(temp_dir.path())?; // Create secret data let secret = b"This is a secret message that needs to be protected!"; // Configure Shamir's Secret Sharing let mut shamir = ShamirShare::builder(5, 3).build()?; // Split the secret into shares let shares = shamir.split(secret)?; // Store all shares for share in &shares { store.store_share(share)?; } // List available shares let available_shares = store.list_shares()?; assert_eq!(available_shares.len(), 5); // Load a subset of shares for reconstruction let mut reconstruction_shares = Vec::new(); for &index in &available_shares[0..3] { reconstruction_shares.push(store.load_share(index)?); } // Reconstruct the secret let reconstructed = ShamirShare::reconstruct(&reconstruction_shares)?; assert_eq!(&reconstructed, secret); Ok(()) } ``` -------------------------------- ### Reconstructing Secret with President Level Shares in Rust Source: https://docs.rs/shamir_share/latest/src/shamir_share/hsss.rs.html Shows how to reconstruct a secret using shares from the 'President' level. This example verifies that a sufficient number of shares from a specific level can recover the original secret. ```rust 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(); ``` -------------------------------- ### Get Nth Element from Iterator Source: https://docs.rs/shamir_share/latest/shamir_share/struct.Dealer.html Returns the `n`th element of the iterator. This consumes elements up to `n`. ```rust fn nth(&mut self, n: usize) -> Option ``` -------------------------------- ### Create a new FileShareStore Source: https://docs.rs/shamir_share/latest/shamir_share/struct.FileShareStore.html Initializes a new file-based share store in the specified directory. The path should point to a location where the application has write permissions. ```rust use shamir_share::FileShareStore; use std::path::Path; let store = FileShareStore::new(Path::new("/tmp/shares")).unwrap(); ``` -------------------------------- ### Builder Validation Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Tests the validation logic within the builder for invalid parameters and configurations, ensuring that erroneous setups are caught. ```rust // Test invalid parameters through builder assert!(ShamirShare::builder(0, 1).build().is_err()); assert!(ShamirShare::builder(1, 0).build().is_err()); assert!(ShamirShare::builder(3, 5).build().is_err()); // Test invalid config let invalid_config = Config::new().with_chunk_size(0).unwrap_err(); assert!(matches!(invalid_config, ShamirError::InvalidConfig(_))); ``` -------------------------------- ### Get Size Hint for Remaining Shares Source: https://docs.rs/shamir_share/latest/shamir_share/struct.Dealer.html Provides a size hint for the number of remaining shares that can be generated by the iterator. This can be used for optimization purposes. ```rust fn size_hint(&self) -> (usize, Option) ``` -------------------------------- ### Build ShamirShare Scheme with Default Configuration Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Instantiate a `ShamirShare` scheme with default settings. Use this when no specific configuration is needed. ```rust use shamir_share::{ShamirShare, Config}; // With default configuration let shamir = ShamirShare::builder(5, 3).build().unwrap(); ``` -------------------------------- ### Create ShamirShare Builder with Custom Config Source: https://docs.rs/shamir_share/latest/shamir_share/struct.ShamirShareBuilder.html This snippet shows how to create a ShamirShare builder and then apply a custom configuration to it using the `with_config` method. The configuration is created separately and then passed to the builder. ```rust use shamir_share::{ShamirShare, Config}; let config = Config::new().with_integrity_check(false); let shamir = ShamirShare::builder(5, 3) .with_config(config) .build() .unwrap(); ``` -------------------------------- ### Creating a ShamirShare Instance with Builder Source: https://docs.rs/shamir_share/latest/shamir_share/struct.ShamirShare.html Shows how to create a ShamirShare instance using the builder pattern. This allows for default configuration or custom configuration, such as disabling integrity checks. ```rust use shamir_share::{ShamirShare, Config}; // With default configuration let shamir = ShamirShare::builder(5, 3).build().unwrap(); // With custom configuration let config = Config::new().with_integrity_check(false); let shamir = ShamirShare::builder(5, 3) .with_config(config) .build() .unwrap(); ``` -------------------------------- ### Get Exact Number of Remaining Shares Source: https://docs.rs/shamir_share/latest/shamir_share/struct.Dealer.html Returns the exact number of shares that can still be generated by the Dealer iterator. This is useful for pre-allocating memory or tracking progress. ```rust fn len(&self) -> usize ``` -------------------------------- ### Basic Shamir Share Usage in Rust Source: https://docs.rs/shamir_share Demonstrates the fundamental workflow of splitting a secret into shares and reconstructing it using the `shamir_share` crate. Requires setting up a `FileShareStore` for persistence. ```rust use shamir_share::{ShamirShare, FileShareStore, ShareStore}; // Create a scheme with 5 shares and threshold 3 let mut scheme = ShamirShare::builder(5, 3).build().unwrap(); // Split a secret let secret = b"my secret data"; let shares = scheme.split(secret).unwrap(); // Store shares let temp_dir = tempfile::tempdir().unwrap(); let mut store = FileShareStore::new(temp_dir.path()).unwrap(); for share in &shares { store.store_share(share).unwrap(); } // Reconstruct from 3 shares let loaded_shares = vec![ store.load_share(1).unwrap(), store.load_share(2).unwrap(), store.load_share(3).unwrap(), ]; let reconstructed = ShamirShare::reconstruct(&loaded_shares).unwrap(); assert_eq!(reconstructed, secret); ``` -------------------------------- ### Get Remaining Shares Size Hint Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Provides a size hint for the `Dealer` iterator, indicating the number of shares that can still be generated. Useful for pre-allocation and progress tracking. ```rust fn size_hint(&self) -> (usize, Option) { let remaining = if self.current_x == 0 { 0 } else { 256 - self.current_x as usize }; (remaining, Some(remaining)) } ``` -------------------------------- ### Create HSSS Instance with Levels Source: https://docs.rs/shamir_share/latest/shamir_share/hsss/struct.HsssBuilder.html Demonstrates building an HSSS instance with multiple access levels. The master threshold is set first, followed by adding named levels, each with a specified number of shares. ```rust 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(); ``` -------------------------------- ### Config Builder Methods Source: https://docs.rs/shamir_share/latest/src/shamir_share/config.rs.html Provides methods to create and configure `Config` instances. Includes setting chunk size, processing mode, compression (feature-gated), and integrity checks. The `with_chunk_size` method returns a `Result` to handle invalid zero values. ```rust impl Config { /// Creates a new configuration with default values pub fn new() -> Self { Self::default() } /// Sets the chunk size pub fn with_chunk_size(mut self, size: usize) -> Result { if size == 0 { return Err(ShamirError::InvalidConfig( "Chunk size cannot be zero".into(), )); } self.chunk_size = size; Ok(self) } /// Sets the processing mode pub fn with_mode(mut self, mode: SplitMode) -> Self { self.mode = mode; self } /// Enables or disables compression #[cfg(feature = "compress")] pub fn with_compression(mut self, enabled: bool) -> Self { self.compression = enabled; self } /// Enables or disables integrity checking pub fn with_integrity_check(mut self, enabled: bool) -> Self { self.integrity_check = enabled; self } /// Validates the configuration pub fn validate(&self) -> Result<()> { if self.chunk_size == 0 { return Err(ShamirError::InvalidConfig( "Chunk size cannot be zero".into(), )); } Ok(()) } } ``` -------------------------------- ### Split and Reconstruct Large Data Stream Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Splits a large data stream into shares and then reconstructs it using a subset of shares. This example highlights handling larger datasets and custom chunk sizes. ```rust let config = Config::new().with_chunk_size(1024).unwrap(); let mut shamir = ShamirShare::builder(5, 3) .with_config(config) .build() .unwrap(); let data: Vec = (0..10000).map(|i| (i % 256) as u8).collect(); let mut source = Cursor::new(&data); let mut destinations = vec![Vec::new(); 5]; let mut dest_cursors: Vec>> = destinations .iter_mut() .map(|d| Cursor::new(std::mem::take(d))) .collect(); shamir.split_stream(&mut source, &mut dest_cursors).unwrap(); let share_data: Vec> = dest_cursors .into_iter() .map(|cursor| cursor.into_inner()) .collect(); let mut sources: Vec>> = vec![ Cursor::new(share_data[0].clone()), Cursor::new(share_data[2].clone()), Cursor::new(share_data[4].clone()), ]; let mut destination = Vec::new(); let mut dest_cursor = Cursor::new(&mut destination); ShamirShare::reconstruct_stream(&mut sources, &mut dest_cursor).unwrap(); assert_eq!(&destination, &data); ``` -------------------------------- ### Get Master Threshold Source: https://docs.rs/shamir_share/latest/shamir_share/hsss/struct.Hsss.html Obtain the master threshold for the HSSS scheme. This value represents the minimum number of shares required for secret reconstruction, irrespective of their distribution across different access levels. ```rust use shamir_share::hsss::Hsss; let hsss = Hsss::builder(5) .add_level("President", 5) .build() .unwrap(); assert_eq!(hsss.master_threshold(), 5); ``` -------------------------------- ### Test Config Builder Methods Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Demonstrates the usage of the Config builder methods to set chunk size, split mode, compression, and integrity check options, and verifies these settings are applied. ```rust use crate::config::SplitMode; let config = Config::new() .with_chunk_size(2048) .unwrap() .with_mode(SplitMode::Parallel) .with_compression(true) .with_integrity_check(false); let shamir = ShamirShare::builder(5, 3) .with_config(config.clone()) .build() .unwrap(); assert_eq!(shamir.config.chunk_size, 2048); assert_eq!(shamir.config.mode, SplitMode::Parallel); assert!(shamir.config.compression); assert!(!shamir.config.integrity_check); ``` -------------------------------- ### Get Access Levels Source: https://docs.rs/shamir_share/latest/shamir_share/hsss/struct.Hsss.html Retrieve a read-only view of the configured access levels for the HSSS scheme. This allows inspection of the hierarchy's structure, including level names and the number of shares associated with each. ```rust 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); ``` -------------------------------- ### Initialize Hsss Builder Source: https://docs.rs/shamir_share/latest/shamir_share/hsss/struct.Hsss.html Use the builder pattern to configure an HSSS instance. Specify the master threshold and then add hierarchical access levels with their respective share counts. This is the recommended way to create HSSS instances. ```rust use shamir_share::hsss::Hsss; let hsss = Hsss::builder(5) .add_level("President", 5) .add_level("VP", 3) .add_level("Executive", 2) .build() .unwrap(); ``` -------------------------------- ### Get Total Shares Source: https://docs.rs/shamir_share/latest/shamir_share/hsss/struct.Hsss.html Calculate the total number of shares generated by the HSSS scheme. This is the sum of shares across all defined access levels, representing the total shares in the underlying master Shamir scheme. ```rust 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 ``` -------------------------------- ### ShamirShareBuilder::new Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Creates a new builder with the specified parameters and default configuration. ```APIDOC ## ShamirShareBuilder::new ### Description Creates a new builder with the specified parameters and default configuration. ### Arguments * `total_shares` - Total number of shares to create (1-255) * `threshold` - Minimum shares required for reconstruction (1-total_shares) ``` -------------------------------- ### Split and Reconstruct Data Stream with ShamirShare Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Demonstrates splitting a data stream into shares and then reconstructing the original data from a subset of those shares using ShamirShare. Requires `ShamirShare::builder` to set the threshold and number of shares, and then uses `split_stream` and `reconstruct_stream`. ```rust let mut shamir = ShamirShare::builder(3, 2).build().unwrap(); let data = b"test data"; let mut source = Cursor::new(data); let mut destinations = vec![Vec::new(); 3]; let mut dest_cursors: Vec>> = destinations .iter_mut() .map(|d| Cursor::new(std::mem::take(d))) .collect(); shamir.split_stream(&mut source, &mut dest_cursors).unwrap(); let share_data: Vec> = dest_cursors .into_iter() .map(|cursor| cursor.into_inner()) .collect(); // Now reconstruct from the first 2 shares let mut sources = vec![ Cursor::new(share_data[0].clone()), Cursor::new(share_data[1].clone()), ]; let mut destination = Vec::new(); let mut dest_cursor = Cursor::new(&mut destination); ShamirShare::reconstruct_stream(&mut sources, &mut dest_cursor).unwrap(); assert_eq!(&destination, data); ``` -------------------------------- ### Split and Reconstruct Stream with ShamirShare Source: https://docs.rs/shamir_share/latest/shamir_share/struct.ShamirShare.html Demonstrates how to split data into shares using `split_stream` and then reconstruct the original data using `reconstruct_stream`. This is useful for handling data in a streaming fashion. ```rust use shamir_share::ShamirShare; use std::io::Cursor; // First, create some share data using split_stream let mut shamir = ShamirShare::builder(3, 2).build().unwrap(); let data = b"test data"; let mut source = Cursor::new(data); let mut destinations = vec![Vec::new(); 3]; let mut dest_cursors: Vec>> = destinations .iter_mut() .map(|d| Cursor::new(std::mem::take(d))) .collect(); shamir.split_stream(&mut source, &mut dest_cursors).unwrap(); let share_data: Vec> = dest_cursors .into_iter() .map(|cursor| cursor.into_inner()) .collect(); // Now reconstruct from the first 2 shares let mut sources = vec![ Cursor::new(share_data[0].clone()), Cursor::new(share_data[1].clone()), ]; let mut destination = Vec::new(); let mut dest_cursor = Cursor::new(&mut destination); ShamirShare::reconstruct_stream(&mut sources, &mut dest_cursor).unwrap(); assert_eq!(&destination, data); ``` -------------------------------- ### Basic HSSS Builder Test Source: https://docs.rs/shamir_share/latest/src/shamir_share/hsss.rs.html Tests the basic functionality of the HSSS builder, including setting the master threshold, adding multiple access levels, and verifying the total number of shares and level configurations. This is useful for initial setup validation. ```rust #[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); } ``` -------------------------------- ### Define Access Levels Source: https://docs.rs/shamir_share/latest/shamir_share/hsss/struct.AccessLevel.html Illustrates how to create instances of AccessLevel to define different roles and the number of shares associated with them. ```rust 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, }; ``` -------------------------------- ### Create HSSS Scheme with Access Levels Source: https://docs.rs/shamir_share/latest/shamir_share/hsss/index.html Use the Hsss::builder to define the master threshold and add hierarchical access levels with their respective share counts. This setup is useful for scenarios where different roles require varying levels of access to reconstruct a secret. ```rust 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(); ``` -------------------------------- ### Build Hsss with Levels and Split Secret Source: https://docs.rs/shamir_share/latest/shamir_share/hsss/struct.Hsss.html Demonstrates building an Hsss instance with multiple hierarchical levels and then splitting a secret into shares for each level. The number of shares for each level must meet the specified threshold for that level. ```rust 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); ``` -------------------------------- ### Config Methods Source: https://docs.rs/shamir_share/latest/shamir_share/struct.Config.html Methods available for creating and modifying Config instances. ```APIDOC ## impl Config ### `new()` Creates a new configuration with default values. ```rust pub fn new() -> Self ``` ### `with_chunk_size(size: usize)` Sets the chunk size. ```rust pub fn with_chunk_size(self, size: usize) -> Result ``` ### `with_mode(mode: SplitMode)` Sets the processing mode. ```rust pub fn with_mode(self, mode: SplitMode) -> Self ``` ### `with_compression(enabled: bool)` Enables or disables compression. ```rust pub fn with_compression(self, enabled: bool) -> Self ``` ### `with_integrity_check(enabled: bool)` Enables or disables integrity checking. ```rust pub fn with_integrity_check(self, enabled: bool) -> Self ``` ### `validate()` Validates the configuration. ```rust pub fn validate(&self) -> Result<()> ``` ``` -------------------------------- ### Share Zeroization on Drop and Manual Zeroization Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Demonstrates that `Share` data is automatically zeroized when it goes out of scope due to the `ZeroizeOnDrop` derive. Also shows how to manually zeroize a `Share`'s data. ```rust use zeroize::Zeroize; let secret = b"test secret for drop"; let mut shamir = ShamirShare::builder(3, 2).build().unwrap(); // Create a share in a limited scope let share_data = { let shares = shamir.split(secret).unwrap(); shares[0].data.clone() }; // Share is dropped here, should be zeroized automatically // Verify we can still use the cloned data assert!(!share_data.is_empty()); // Test manual zeroization let mut shares = shamir.split(secret).unwrap(); let original_data = shares[0].data.clone(); shares[0].zeroize(); // After zeroization, the share data should be zeroed assert!(shares[0].data.iter().all(|&b| b == 0)); assert_ne!(original_data, shares[0].data); ``` -------------------------------- ### FileShareStore::new Source: https://docs.rs/shamir_share/latest/shamir_share/struct.FileShareStore.html Creates a new file-based store at the specified directory path. This constructor initializes the storage mechanism for shares on the file system. ```APIDOC ## FileShareStore::new ### Description Creates a new file-based store at specified path ### Parameters #### Path Parameters - **base_dir** (P: AsRef) - Required - The directory path where the shares will be stored. ### Request Example ```rust use shamir_share::FileShareStore; use std::path::Path; let store = FileShareStore::new(Path::new("/tmp/shares")).unwrap(); ``` ### Response #### Success Response (Result) - Returns a `FileShareStore` instance if the directory is accessible and initialization is successful. ``` -------------------------------- ### Build ShamirShare Scheme with Custom Configuration Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Instantiate a `ShamirShare` scheme with custom configuration options. This allows disabling integrity checks or enabling compression. ```rust use shamir_share::{ShamirShare, Config}; // With custom configuration let config = Config::new().with_integrity_check(false); let shamir = ShamirShare::builder(5, 3) .with_config(config) .build() .unwrap(); ``` -------------------------------- ### Configuration Test with Custom Settings Source: https://docs.rs/shamir_share/latest/src/shamir_share/lib.rs.html Illustrates creating a custom configuration for Shamir's Secret Sharing, including chunk size, split mode, compression, and integrity checks. This snippet is part of a test function. ```rust use super::*; use tempfile::tempdir; #[test] fn test_with_config() -> Result<()> { let temp_dir = tempdir()?; let mut store = FileShareStore::new(temp_dir.path())?; // Create a custom configuration let _config = Config::new() .with_chunk_size(1024)? .with_mode(SplitMode::Sequential) .with_compression(true) .with_integrity_check(true); // Create and split secret let secret = b"Secret data with custom configuration"; ``` -------------------------------- ### HSSS Builder Method Chaining in Rust Source: https://docs.rs/shamir_share/latest/src/shamir_share/hsss.rs.html Demonstrates fluent API for configuring HSSS with multiple access levels. Use this to define a hierarchy of access rights and their corresponding share counts. ```rust 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); ``` -------------------------------- ### Split and Reconstruct Data with ShamirShare Source: https://docs.rs/shamir_share/latest/shamir_share/struct.ShamirShare.html Demonstrates splitting data into shares and reconstructing the original secret. Ensure the number of shares provided for reconstruction meets or exceeds the threshold. ```rust use shamir_share::ShamirShare; let mut scheme = ShamirShare::builder(5, 3).build().unwrap(); let shares = scheme.split(b"data").unwrap(); // Reconstruct with first 3 shares let secret = ShamirShare::reconstruct(&shares[0..3]).unwrap(); assert_eq!(secret, b"data"); ``` -------------------------------- ### HSSS Reconstruction Scenarios in Rust Source: https://docs.rs/shamir_share/latest/src/shamir_share/hsss.rs.html Demonstrates different scenarios for reconstructing a secret using HSSS. Includes successful reconstructions with adequate shares and failed attempts with insufficient shares, highlighting the threshold mechanism. ```rust 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); ``` -------------------------------- ### Lazy Evaluation of Shares with Dealer Source: https://docs.rs/shamir_share/latest/src/shamir_share/shamir.rs.html Demonstrates how to create a dealer and lazily evaluate shares. Shares can be taken in batches, and the dealer maintains its state. ```rust fn test_dealer_lazy_evaluation() { let secret = b"Lazy evaluation test"; let mut shamir = ShamirShare::builder(10, 5).build().unwrap(); // Create dealer but don't consume all shares let mut dealer = shamir.dealer(secret); // Take only first 3 shares let first_three: Vec = dealer.by_ref().take(3).collect(); assert_eq!(first_three.len(), 3); assert_eq!(first_three[0].index, 1); assert_eq!(first_three[1].index, 2); assert_eq!(first_three[2].index, 3); // Take next 2 shares from the same dealer let next_two: Vec = dealer.by_ref().take(2).collect(); assert_eq!(next_two.len(), 2); assert_eq!(next_two[0].index, 4); assert_eq!(next_two[1].index, 5); // Combine shares and reconstruct let mut combined_shares = first_three; combined_shares.extend(next_two); let reconstructed = ShamirShare::reconstruct(&combined_shares).unwrap(); assert_eq!(&reconstructed, secret); } ``` -------------------------------- ### List Shares in Directory Source: https://docs.rs/shamir_share/latest/src/shamir_share/storage.rs.html Scans the base directory for files prefixed with 'share_' and returns a sorted list of their indices. Ensure the directory exists and has read permissions. ```rust fn list_shares(&self) -> Result> { let mut indices = Vec::new(); for entry in fs::read_dir(&self.base_dir)? { let entry = entry?; let file_name = entry.file_name(); let file_name = file_name.to_string_lossy(); if let Some(stripped) = file_name.strip_prefix("share_") { if let Ok(index) = stripped.parse::() { indices.push(index); } } } indices.sort_unstable(); Ok(indices) } ``` -------------------------------- ### Build and Validate HSSS Configuration Source: https://docs.rs/shamir_share/latest/src/shamir_share/hsss.rs.html Finalize the HSSS configuration by building the instance. This step includes validation checks for the master threshold, defined levels, and share counts. ```rust use shamir_share::hsss::Hsss; let result = Hsss::builder(5) .add_level("President", 5) .add_level("VP", 3) .build(); assert!(result.is_ok()); ``` -------------------------------- ### Initialize HSSS Builder Source: https://docs.rs/shamir_share/latest/src/shamir_share/hsss.rs.html Create a new HSSS builder with a specified master threshold. The master threshold is the minimum number of shares required to reconstruct the secret. ```rust use shamir_share::hsss::Hsss; let builder = Hsss::builder(5); ``` -------------------------------- ### Pointable Source: https://docs.rs/shamir_share/latest/shamir_share/struct.FiniteField.html Provides methods for interacting with raw pointers, including initialization, dereferencing, and dropping. ```APIDOC ## const ALIGN: usize ### Description The alignment requirement for pointers of this type. ### Type `usize` ``` ```APIDOC ## type Init = T ### Description The type used for initializers when creating a new instance via `init`. ### Type Alias ``` ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a new instance of the type with the given initializer and returns a pointer to it. ### Safety This function is unsafe as it deals with raw memory management. ### Method `init` ### Parameters #### Path Parameters - **init** (::Init) - Required - The initializer value for the new instance. ### Response #### Success Response (usize) - Returns a `usize` representing the memory address (pointer) of the newly initialized instance. ``` ```APIDOC ## unsafe fn deref<'a>(ptr: usize) -> &'a T ### Description Dereferences a raw pointer to provide an immutable reference to the object. ### Safety This function is unsafe. The caller must ensure that `ptr` is a valid pointer to a `T` that has not been dropped or mutated elsewhere. ### Method `deref` ### Parameters #### Path Parameters - **ptr** (usize) - Required - The raw pointer to dereference. ### Response #### Success Response (&'a T) - Returns an immutable reference `&'a T` to the object at the given pointer. ``` ```APIDOC ## unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T ### Description Mutably dereferences a raw pointer to provide a mutable reference to the object. ### Safety This function is unsafe. The caller must ensure that `ptr` is a valid pointer to a `T` that has not been dropped or mutated elsewhere, and that no other references to the object exist. ### Method `deref_mut` ### Parameters #### Path Parameters - **ptr** (usize) - Required - The raw pointer to mutably dereference. ### Response #### Success Response (&'a mut T) - Returns a mutable reference `&'a mut T` to the object at the given pointer. ``` ```APIDOC ## unsafe fn drop(ptr: usize) ### Description Drops the object pointed to by the given pointer, freeing its resources. ### Safety This function is unsafe. The caller must ensure that `ptr` is a valid pointer to a `T` that has not already been dropped. ### Method `drop` ### Parameters #### Path Parameters - **ptr** (usize) - Required - The pointer to the object to be dropped. ```