feat: Update SAL Vault examples and documentation

- Renamed examples directory to `_archive` to reflect legacy status.
- Updated README.md to reflect current status of vault module,
  including migration from Sameh's implementation to Lee's.
- Temporarily disabled Rhai scripting integration for the vault.
- Added notes regarding current and future development steps.
This commit is contained in:
Mahmoud-Emad
2025-07-10 14:03:43 +03:00
parent 61f5331804
commit 6e5d9b35e8
58 changed files with 1576 additions and 278 deletions

View File

@@ -1,166 +1,148 @@
# SAL Vault (`sal-vault`)
# SAL Vault
SAL Vault is a comprehensive cryptographic library that provides secure key management, digital signatures, symmetric encryption, Ethereum wallet functionality, and encrypted key-value storage.
A secure, encrypted key-value store system for the System Abstraction Layer (SAL).
## Installation
## Overview
Add this to your `Cargo.toml`:
SAL Vault provides a two-tiered encrypted storage system:
```toml
[dependencies]
sal-vault = "0.1.0"
```
1. **Vault**: A collection of encrypted keyspaces
2. **KeySpace**: An individual encrypted key-value store within a vault
## Features
### Core Cryptographic Operations
- **Symmetric Encryption**: ChaCha20Poly1305 AEAD cipher for secure data encryption
- **Key Derivation**: PBKDF2-based key derivation from passwords
- **Digital Signatures**: ECDSA signing and verification using secp256k1 curves
- **Key Management**: Secure keypair generation and storage
- **Secure Storage**: ChaCha20Poly1305 encryption for all data
- **Password-Based Encryption**: Keyspaces are encrypted using password-derived keys
- **Cross-Platform**: Works on both native and WASM targets
- **Async API**: Fully asynchronous operations
- **Type Safety**: Strong typing with comprehensive error handling
### Keyspace Management
- **Multiple Keyspaces**: Organize keys into separate, password-protected spaces
- **Session Management**: Secure session handling with automatic cleanup
- **Keypair Organization**: Named keypairs within keyspaces for easy management
## Architecture
### Ethereum Integration
- **Wallet Functionality**: Create and manage Ethereum wallets from keypairs
- **Transaction Signing**: Sign Ethereum transactions securely
- **Smart Contract Interaction**: Call read functions on smart contracts
- **Multi-Network Support**: Support for different Ethereum networks
```
Vault
├── KeySpace 1 (encrypted with password A)
├── KeySpace 2 (encrypted with password B)
└── KeySpace N (encrypted with password N)
```
### Key-Value Store
- **Encrypted Storage**: Store key-value pairs with automatic encryption
- **Secure Persistence**: Data is encrypted before being written to disk
- **Type Safety**: Strongly typed storage and retrieval operations
### Rhai Scripting Integration
- **Complete API Exposure**: All vault functionality available in Rhai scripts
- **Session Management**: Script-accessible session and keyspace management
- **Cryptographic Operations**: Encryption, signing, and verification in scripts
Each keyspace is independently encrypted, allowing different access controls and security boundaries.
## Usage
### Basic Cryptographic Operations
### Creating a Vault
```rust
use sal_vault::symmetric::implementation::{encrypt_symmetric, decrypt_symmetric, generate_symmetric_key};
use sal_vault::{Vault, Error};
use std::path::Path;
// Generate a symmetric key
let key = generate_symmetric_key();
// Encrypt data
let message = b"Hello, World!";
let encrypted = encrypt_symmetric(&key, message)?;
// Decrypt data
let decrypted = decrypt_symmetric(&key, &encrypted)?;
```
### Keyspace and Keypair Management
```rust
use sal_vault::keyspace::{KeySpace, KeyPair};
// Create a new keyspace
let mut keyspace = KeySpace::new("my_keyspace");
// Add a keypair
keyspace.add_keypair("main_key")?;
// Sign data
if let Some(keypair) = keyspace.keypairs.get("main_key") {
let message = b"Important message";
let signature = keypair.sign(message);
let is_valid = keypair.verify(message, &signature)?;
#[tokio::main]
async fn main() -> Result<(), Error> {
// Create a new vault at the specified path
let vault = Vault::new(Path::new("./my_vault")).await?;
// Open an encrypted keyspace
let keyspace = vault.open_keyspace("user_data", "secure_password").await?;
// Use the keyspace for encrypted storage
// (KeySpace API documentation coming soon)
Ok(())
}
```
### Ethereum Wallet Operations
### WASM Support
The vault also supports WASM targets with browser-compatible storage:
```rust
use sal_vault::ethereum::wallet::EthereumWallet;
use sal_vault::ethereum::networks::NetworkConfig;
// Create wallet from keypair
let network = NetworkConfig::mainnet();
let wallet = EthereumWallet::from_keypair(&keypair, network)?;
// Get wallet address
let address = wallet.address();
#[cfg(target_arch = "wasm32")]
async fn wasm_example() -> Result<(), Error> {
let vault = Vault::new().await?; // No path needed for WASM
let keyspace = vault.open_keyspace("session_data", "password").await?;
Ok(())
}
```
### Rhai Scripting
## Security
```rhai
// Create and manage keyspaces
create_key_space("personal", "secure_password");
select_keyspace("personal");
### Encryption
// Create and use keypairs
create_keypair("signing_key");
select_keypair("signing_key");
- **Algorithm**: ChaCha20Poly1305 (AEAD)
- **Key Derivation**: PBKDF2 with secure parameters
- **Nonce Generation**: Cryptographically secure random nonces
- **Authentication**: Built-in authentication prevents tampering
// Sign and verify data
let message = "Important document";
let signature = sign(message);
let is_valid = verify(message, signature);
### Best Practices
// Symmetric encryption
let key = generate_key();
let encrypted = encrypt(key, "secret data");
let decrypted = decrypt(key, encrypted);
```
## Security Features
- **Memory Safety**: All sensitive data is handled securely in memory
- **Secure Random Generation**: Uses cryptographically secure random number generation
- **Password-Based Encryption**: Keyspaces are protected with password-derived keys
- **Session Isolation**: Each session maintains separate state and security context
- **Constant-Time Operations**: Critical operations use constant-time implementations
1. **Strong Passwords**: Use strong, unique passwords for each keyspace
2. **Secure Storage**: Store vault files in secure locations
3. **Access Control**: Limit filesystem access to vault directories
4. **Backup Strategy**: Implement secure backup procedures
5. **Key Rotation**: Periodically change keyspace passwords
## Error Handling
The library provides comprehensive error handling through the `CryptoError` enum:
The vault uses a comprehensive error system:
```rust
use sal_vault::error::CryptoError;
use sal_vault::Error;
match some_crypto_operation() {
Ok(result) => println!("Success: {:?}", result),
Err(CryptoError::InvalidKeyLength) => println!("Invalid key length provided"),
Err(CryptoError::EncryptionFailed(msg)) => println!("Encryption failed: {}", msg),
Err(CryptoError::KeypairNotFound(name)) => println!("Keypair '{}' not found", name),
Err(e) => println!("Other error: {}", e),
match vault.open_keyspace("test", "password").await {
Ok(keyspace) => {
// Success - use the keyspace
}
Err(Error::IOError(io_err)) => {
// Handle I/O errors (file system issues)
}
Err(Error::CryptoError(crypto_err)) => {
// Handle cryptographic errors (wrong password, corruption)
}
Err(other) => {
// Handle other errors
}
}
```
## Testing
## Migration from Previous Implementation
The package includes comprehensive tests covering all functionality:
This vault implementation replaces the previous Ethereum-focused vault. Key differences:
```bash
# Run all tests
cargo test
### What's New
- ✅ Simpler, more focused API
- ✅ Better cross-platform support
- ✅ Improved security model
- ✅ Cleaner error handling
# Run specific test categories
cargo test crypto_tests
cargo test rhai_integration_tests
```
### What's Changed
- ❌ No Ethereum wallet functionality
- ❌ No smart contract integration
- ❌ No built-in signing operations
- ⏳ Rhai scripting integration (coming soon)
**Note**: The Rhai integration tests use global state and are automatically serialized using a test mutex to prevent interference between parallel test runs.
### Archived Implementation
## Dependencies
The previous implementation is preserved in `_archive/` for reference and potential feature extraction.
- `chacha20poly1305`: Symmetric encryption
- `k256`: Elliptic curve cryptography
- `ethers`: Ethereum functionality
- `serde`: Serialization support
- `rhai`: Scripting integration
- `tokio`: Async runtime support
## Development Status
- **Core Vault**: Complete and functional
- **KeySpace Operations**: Basic implementation ready
- **Encryption**: Secure ChaCha20Poly1305 implementation
- **Rhai Integration**: In development
-**Extended API**: Additional convenience methods planned
-**Documentation**: API docs being completed
## Contributing
When contributing to the vault module:
1. Maintain security-first approach
2. Ensure cross-platform compatibility
3. Add comprehensive tests for new features
4. Update documentation for API changes
5. Consider WASM compatibility for new features
## License
Licensed under the Apache License, Version 2.0.
This module is part of the SAL project and follows the same licensing terms.