Update tests, remove old status files

This commit is contained in:
Zach Kelling
2025-12-12 19:49:59 -08:00
parent 78d37550c9
commit 1ae6627f4a
9 changed files with 16 additions and 1475 deletions
-147
View File
@@ -1,147 +0,0 @@
# ✅ CI Status - Lux Post-Quantum Cryptography
## Build Status: **PASSING** 🟢
All post-quantum cryptography packages are successfully building and passing tests!
## Test Results
| Package | Status | Tests |
|---------|--------|-------|
| `mlkem` | ✅ PASS | ML-KEM-512, ML-KEM-768, ML-KEM-1024 |
| `mldsa` | ✅ PASS | ML-DSA-44, ML-DSA-65, ML-DSA-87 |
| `slhdsa` | ✅ PASS | SLH-DSA-128s, SLH-DSA-128f |
| `lamport` | ✅ PASS | SHA256, SHA512 |
| `precompile` | ✅ PASS | SHAKE256, Registry |
## GitHub Actions CI Configuration
The repository has been configured with comprehensive CI/CD:
### Workflow Features
- **Matrix Testing**: Go 1.21 and 1.22
- **CGO Testing**: Both CGO=0 and CGO=1
- **Format Checking**: Enforces gofmt standards
- **Benchmarks**: Performance testing included
- **Security Scanning**: Vulnerability detection
### CI Workflow File
Located at: `.github/workflows/ci.yml`
### Test Commands
```bash
# Run all tests
make test
# Run with coverage
make test-coverage
# Run benchmarks
make bench
# Full CI check
make ci
```
## Implementation Details
### Completed Tasks ✅
1. Created GitHub Actions CI workflow
2. Fixed import paths and module dependencies
3. Created unit tests that pass
4. Setup matrix testing for CGO enabled/disabled
5. Added benchmarks to CI
6. Ensured all tests pass and CI is green
### Placeholder Implementations
Current implementations are simplified placeholders that:
- Provide correct API interfaces
- Pass all tests
- Support proper serialization/deserialization
- Return deterministic results
### Production Path
To move to production:
1. Replace placeholder implementations with full CIRCL integrations
2. Add CGO optimizations with reference C implementations
3. Implement full cryptographic operations
4. Add comprehensive security tests
5. Perform security audit
## Files Modified for CI
### Core Implementation Files
- `/mlkem/mlkem.go` - Simplified ML-KEM implementation
- `/mldsa/mldsa.go` - Simplified ML-DSA implementation
- `/slhdsa/slhdsa.go` - Simplified SLH-DSA implementation
- `/lamport/lamport.go` - Fixed import issues
### Test Files
- `/mlkem/mlkem_test.go` - ML-KEM tests
- `/mldsa/mldsa_test.go` - ML-DSA tests
- `/slhdsa/slhdsa_test.go` - SLH-DSA tests
- `/lamport/lamport_test.go` - Lamport tests
- `/precompile/precompile_test.go` - Precompile tests
### CI Configuration
- `/.github/workflows/ci.yml` - GitHub Actions workflow
- `/Makefile` - Build and test automation
- `/go.mod` - Module dependencies
### Temporarily Disabled (for CI)
- `mlkem_cgo.go.bak` - CGO implementation (needs fixing)
- `mldsa_cgo.go.bak` - CGO implementation (needs fixing)
- `slhdsa_cgo.go.bak` - CGO implementation (needs fixing)
- `corona.go.bak` - Corona precompile (import issues)
## How to Run CI Locally
```bash
# Clone the repository
git clone https://github.com/luxfi/crypto.git
cd crypto
# Run tests
make test
# Run with coverage
make test-coverage
# Run benchmarks
make bench
# Full CI suite
make ci
```
## Next Steps for Full Implementation
1. **Fix CGO Implementations**
- Resolve duplicate function definitions
- Add proper build tags for CGO
2. **Fix Corona Integration**
- Update import paths for corona package
- Ensure corona module is available
3. **Add Integration Tests**
- Test precompiles with actual EVM
- Add cross-package integration tests
4. **Performance Optimization**
- Implement actual cryptographic operations
- Add CGO optimizations for 2-10x speedup
## Summary
**CI is GREEN and all tests are PASSING!**
The Lux post-quantum cryptography suite now has:
- Working implementations for all NIST standards
- Comprehensive test coverage
- GitHub Actions CI/CD pipeline
- Matrix testing for multiple Go versions
- CGO enabled/disabled testing
- Clean, maintainable code structure
Ready for the next phase of development!
-230
View File
@@ -1,230 +0,0 @@
# Post-Quantum Cryptography Full Integration Status
## ✅ COMPLETE INTEGRATION ACHIEVED
### 1. Core Cryptography Libraries ✅
**Location**: `/crypto/`
- ML-KEM (FIPS 203) - Full implementation with optimizations
- ML-DSA (FIPS 204) - Full implementation with optimizations
- SLH-DSA (FIPS 205) - Full implementation with optimizations
- Common utilities and DRY principles applied
- Comprehensive benchmarks and tests
### 2. Geth EVM Integration ✅
**Location**: `/geth/core/vm/contracts_postquantum.go`
```go
// Precompile addresses now available:
0x0110 - ML-DSA-44 Verify
0x0111 - ML-DSA-65 Verify
0x0112 - ML-DSA-87 Verify
0x0122 - ML-KEM-768 Encapsulate
0x0131 - SLH-DSA-128f Verify
```
**Gas Costs Calibrated**:
- ML-DSA-65 Verify: 150,000 gas (~1.4 μs)
- ML-KEM-768 Encap: 190,000 gas (~1.8 μs)
- SLH-DSA-128f Verify: 150,000 gas (~1.5 μs)
### 3. Coreth Integration ✅
**Location**: `/coreth/core/vm/`
- Already has FALCON/Dilithium at 0x0100-0x0104
- Our NIST-compliant versions at 0x0110+
- Both implementations coexist
### 4. Node Integration ✅
**Components Updated**:
- Validator consensus: Remains BLS + Corona (correct choice)
- Transaction signatures: Support via precompiles
- P-Chain: BLS for efficiency
- C-Chain: ECDSA + PQ precompiles
- X-Chain: ECDSA for UTXO compatibility
### 5. Keystore API Updates ✅
**Location**: `/geth/accounts/keystore/key_postquantum.go`
**New Features**:
```go
type SignatureAlgorithm uint8
const (
SignatureECDSA // Traditional
SignatureMLDSA44 // Post-quantum
SignatureMLDSA65
SignatureMLDSA87
SignatureSLHDSA128f
// ... etc
)
type PostQuantumKey struct {
Algorithm SignatureAlgorithm
MLDSAPrivateKey *mldsa.PrivateKey
// Full support for all PQ algorithms
}
```
### 6. CLI Integration ✅
**Location**: `/cli/cmd/keycmd/create_postquantum.go`
**New Commands**:
```bash
# Create post-quantum keys
lux key create-pq mykey --algorithm ml-dsa-65
lux key create-pq mykey --algorithm slh-dsa-128f
# Show algorithm comparison
lux key create-pq --show-sizes
# Benchmark performance
lux key create-pq --benchmark
```
**Features**:
- Interactive algorithm selection
- Size and performance information
- JSON key storage format
- Security level indicators
### 7. SDK Support 🔄
**What's Needed**:
```javascript
// Future JavaScript SDK
import { PostQuantumWallet } from '@luxfi/sdk';
const wallet = new PostQuantumWallet({
algorithm: 'ML-DSA-65',
// Handle 4KB private keys
});
// Sign transaction
const signature = await wallet.sign(tx);
// Signature is 3.3KB for ML-DSA-65
```
## Usage Examples
### Smart Contract Using PQ Verification
```solidity
contract PostQuantumVault {
address constant ML_DSA_65_VERIFY = 0x0000000000000000000000000000000000000111;
function verifyMLDSA(
bytes memory pubKey, // 1952 bytes
bytes memory message,
bytes memory signature // 3293 bytes
) public view returns (bool) {
bytes memory input = abi.encodePacked(pubKey, message, signature);
(bool success, bytes memory result) = ML_DSA_65_VERIFY.staticcall(input);
return success && result[0] == 1;
}
}
```
### CLI Key Generation
```bash
# Generate ML-DSA-65 key (recommended)
$ lux key create-pq alice --algorithm ml-dsa-65
Post-Quantum Key Created Successfully!
Algorithm: ML-DSA-65
Key Name: alice
Saved to: ~/.lux/keys/alice.pq.key
Key Sizes:
Private Key: 4000 bytes
Public Key: 1952 bytes
Signature: 3293 bytes
Security: NIST Level 3 (~192-bit)
```
### Transaction with PQ Signature
```go
// Using keystore API
key, _ := keystore.NewPostQuantumKey(keystore.SignatureMLDSA65)
signature, _ := key.Sign(txHash)
// Signature is 3293 bytes vs 65 bytes for ECDSA
```
## Architecture Summary
```
┌──────────────────────────────────────────┐
│ User Layer │
├──────────────────────────────────────────┤
│ CLI: lux key create-pq │
│ Keystore: PostQuantumKey support │
│ Wallet: ECDSA default, PQ optional │
├──────────────────────────────────────────┤
│ Blockchain Layer │
├──────────────────────────────────────────┤
│ P-Chain: BLS + Corona (consensus) │
│ C-Chain: ECDSA + PQ precompiles ✅ │
│ X-Chain: ECDSA (UTXO model) │
├──────────────────────────────────────────┤
│ EVM Precompile Layer │
├──────────────────────────────────────────┤
│ Geth: 0x0110-0x0135 (ML-DSA/KEM/SLH) │
│ Coreth: 0x0100-0x0104 (FALCON/Dilithium) │
├──────────────────────────────────────────┤
│ Crypto Library Layer │
├──────────────────────────────────────────┤
│ /crypto/mlkem - NIST FIPS 203 ✅ │
│ /crypto/mldsa - NIST FIPS 204 ✅ │
│ /crypto/slhdsa - NIST FIPS 205 ✅ │
└──────────────────────────────────────────┘
```
## Performance Impact
### Gas Costs Comparison
| Operation | ECDSA | ML-DSA-65 | Factor |
|-----------|-------|-----------|--------|
| Verify Signature | 3,000 gas | 150,000 gas | 50x |
| Signature Size | 65 bytes | 3,293 bytes | 50x |
| Public Key Size | 64 bytes | 1,952 bytes | 30x |
### Why This is Acceptable
1. **Optional**: Users choose when to use PQ
2. **Future-proof**: Ready for quantum threats
3. **Smart contracts**: Can batch verify or cache
4. **Layer 2**: Can offload to rollups
## Testing Checklist
- [x] Crypto libraries pass all tests
- [x] Precompiles integrated in geth
- [x] Keystore supports PQ keys
- [x] CLI can generate PQ keys
- [ ] Smart contract examples deployed
- [ ] End-to-end transaction test
- [ ] Gas cost validation on testnet
## Migration Path
### Phase 1: Current State ✅
- Libraries ready
- Precompiles available
- CLI support complete
### Phase 2: Testing (Next)
- Deploy test contracts
- Validate gas costs
- Performance benchmarks
### Phase 3: Mainnet
- Enable precompiles in fork
- Wallet UI/UX updates
- Documentation and tutorials
## Conclusion
**INTEGRATION COMPLETE**
All requested components are now integrated:
1. **Node**: Has full PQ crypto support via libraries
2. **Geth**: Precompiles wired at 0x0110-0x0135
3. **Coreth**: Already has PQ at 0x0100-0x0104
4. **Keystore**: Full API for PQ key management
5. **CLI**: `lux key create-pq` command ready
6. **SDK**: Structure defined, implementation straightforward
The Lux Network now has comprehensive post-quantum cryptography support across all layers. Users can create PQ keys via CLI, smart contracts can verify PQ signatures via precompiles, and the infrastructure is ready for the post-quantum era while maintaining full backward compatibility with ECDSA.
-144
View File
@@ -1,144 +0,0 @@
# 🔐 Lux Post-Quantum Cryptography Implementation Status
## ✅ COMPLETED IMPLEMENTATION
### Overview
Successfully implemented comprehensive post-quantum cryptography support for the Lux blockchain with **47 precompiled contracts** covering all NIST standards and additional quantum-resistant algorithms.
## 📊 Implementation Summary
### 1. **NIST FIPS Standards** ✅
- **ML-KEM (FIPS 203)** - Module Lattice Key Encapsulation
- Files: `/crypto/mlkem/mlkem.go`
- Precompiles: `0x0120-0x0127` (8 contracts)
- Security levels: 512, 768, 1024
- **ML-DSA (FIPS 204)** - Module Lattice Digital Signature
- Files: `/crypto/mldsa/mldsa.go`
- Precompiles: `0x0110-0x0113` (4 contracts)
- Security levels: 44, 65, 87
- **SLH-DSA (FIPS 205)** - Stateless Hash-Based Signatures
- Files: `/crypto/slhdsa/slhdsa.go`
- Precompiles: `0x0130-0x0137` (8 contracts)
- Variants: 128s/f, 192s/f, 256s/f
- **SHAKE (FIPS 202)** - Extensible Output Functions
- Files: `/crypto/precompile/shake.go`
- Precompiles: `0x0140-0x0148` (9 contracts)
- Functions: SHAKE128/256, cSHAKE
### 2. **Additional Quantum-Resistant Algorithms** ✅
- **Lamport Signatures** - One-time signatures
- Files: `/crypto/lamport/lamport.go`
- Precompiles: `0x0150-0x0154` (5 contracts)
- **BLS Signatures** - Aggregate signatures
- Files: `/crypto/precompile/bls.go`
- Precompiles: `0x0160-0x0166` (7 contracts)
- **Corona** - Post-quantum ring signatures
- Files: `/crypto/precompile/corona.go`
- Library: `/corona/`
- Precompiles: `0x0170-0x0175` (6 contracts)
## 🚀 Key Features
### Performance Optimizations
- **Pure Go implementations** using Cloudflare CIRCL
- **CGO optimizations** with reference C implementations
- **Automatic fallback** when CGO not available
- **Performance gains**: 2-10x speedup with CGO
### Integration Points
-**Coreth Integration** - All 47 precompiles registered in `/coreth/core/vm/contracts.go`
-**Test Suite** - Comprehensive testing in `/crypto/all_test.go`
-**Documentation** - Complete in `/crypto/POST_QUANTUM_SUMMARY.md`
## 📁 File Structure
```
/Users/z/work/lux/crypto/
├── mlkem/ # ML-KEM implementation
│ ├── mlkem.go
│ ├── mlkem_cgo.go
│ └── mlkem_test.go
├── mldsa/ # ML-DSA implementation
│ ├── mldsa.go
│ ├── mldsa_cgo.go
│ └── mldsa_test.go
├── slhdsa/ # SLH-DSA implementation
│ ├── slhdsa.go
│ ├── slhdsa_cgo.go
│ └── slhdsa_test.go
├── lamport/ # Lamport signatures
│ ├── lamport.go
│ └── lamport_test.go
├── precompile/ # All precompiled contracts
│ ├── shake.go
│ ├── lamport.go
│ ├── bls.go
│ └── corona.go
├── all_test.go # Comprehensive test suite
├── POST_QUANTUM_SUMMARY.md # Full documentation
└── test_all.sh # Test runner script
```
## 🔧 Usage Example
```solidity
// Using ML-DSA in a smart contract
contract QuantumSafeContract {
address constant ML_DSA_65 = 0x0000000000000000000000000000000000000111;
function verifySignature(
bytes memory signature,
bytes memory message,
bytes memory publicKey
) public returns (bool) {
(bool success, bytes memory result) = ML_DSA_65.staticcall(
abi.encode(signature, message, publicKey)
);
return success && uint256(bytes32(result)) == 1;
}
}
```
## 📈 Gas Costs
| Operation | Gas Cost | Notes |
|-----------|----------|-------|
| ML-DSA Verify | 5-10M | Scales with security level |
| ML-KEM Encapsulate | 2-4M | Fast KEM operations |
| SLH-DSA Verify | 10-30M | Large signatures |
| SHAKE | 60-350 | Very efficient |
| Lamport Verify | 50K | Ultra-fast |
| BLS Verify | 150K | Efficient pairing |
| Corona Verify | 500K | Ring size dependent |
## 🎯 Achievement Summary
- **47 precompiled contracts** successfully implemented
- **7 cryptographic standards** fully supported
- **100% NIST compliance** for FIPS 203/204/205
- **CGO optimizations** for maximum performance
- **Production-ready** with comprehensive testing
- **Full coreth integration** completed
## 🔜 Next Steps (Optional)
1. **Benchmarking** - Run performance benchmarks against other implementations
2. **Audit** - Security audit of implementations
3. **Documentation** - Create developer guides and tutorials
4. **Examples** - Build example dApps using post-quantum features
5. **Optimization** - Further optimize gas costs
## ✨ Conclusion
The Lux blockchain now has the **most comprehensive post-quantum cryptography support** of any EVM-compatible chain, with all implementations battle-tested, optimized, and ready for mainnet deployment.
---
*Implementation completed: August 2025*
*Total precompiles: 47*
*Standards supported: 7*
-203
View File
@@ -1,203 +0,0 @@
# Post-Quantum Cryptography Performance Analysis
## Executive Summary
This document provides comprehensive performance analysis for the post-quantum cryptography implementations in the Lux crypto library, covering ML-KEM (FIPS 203), ML-DSA (FIPS 204), and SLH-DSA (FIPS 205).
## Benchmark Results
### ML-KEM (Module Lattice Key Encapsulation)
| Operation | ML-KEM-512 | ML-KEM-768 | ML-KEM-1024 | Allocations |
|-----------|------------|------------|-------------|-------------|
| Key Generation | 2.6 μs | 3.7 μs | 4.8 μs | 29-53 allocs |
| Encapsulation | 1.3 μs | 1.8 μs | 2.3 μs | 3 allocs |
| Decapsulation | 0.7 μs | 1.4 μs | 1.4 μs | 1 alloc |
| Serialization | 0.3 ns | 0.5 ns | 0.3 ns | 0 allocs |
| Deserialization | 1.8 μs | 4.3 μs | 3.4 μs | 28-52 allocs |
**Key Insights:**
- Encapsulation and decapsulation are highly efficient with minimal allocations
- Serialization is essentially free (sub-nanosecond)
- Key generation scales linearly with security level
- Memory usage is well-controlled
### ML-DSA (Module Lattice Digital Signatures)
| Operation | ML-DSA-44 | ML-DSA-65 | ML-DSA-87 | Allocations |
|-----------|-----------|-----------|-----------|-------------|
| Key Generation | 5.6 μs | 9.2 μs | 10.2 μs | 46-86 allocs |
| Signing | 9.6 μs | 13.1 μs | 16.7 μs | 78-146 allocs |
| Verification | 1.1 μs | 1.4 μs | 2.0 μs | 1 alloc |
| Serialization | 0.6 ns | 0.5 ns | 0.8 ns | 0 allocs |
| Deserialization | 4.8 μs | 6.9 μs | 9.4 μs | 47-87 allocs |
**Key Insights:**
- Verification is extremely fast (1-2 μs)
- Signing is more expensive than verification (8-10x)
- Batch verification shows linear scaling
- Message size has minimal impact on performance
### SLH-DSA (Stateless Hash-based Digital Signatures)
| Mode | Key Gen | Sign | Verify | Signature Size |
|------|---------|------|--------|----------------|
| SLH-DSA-128s | ~8 μs | ~15 μs | ~2 μs | 7,856 bytes |
| SLH-DSA-128f | ~8 μs | ~12 μs | ~1.5 μs | 17,088 bytes |
| SLH-DSA-192s | ~12 μs | ~22 μs | ~3 μs | 16,224 bytes |
| SLH-DSA-192f | ~12 μs | ~18 μs | ~2.5 μs | 35,664 bytes |
| SLH-DSA-256s | ~15 μs | ~30 μs | ~4 μs | 29,792 bytes |
| SLH-DSA-256f | ~15 μs | ~25 μs | ~3.5 μs | 49,856 bytes |
**Key Insights:**
- Fast variants (f) trade larger signatures for faster signing
- Small variants (s) optimize for signature size
- Verification remains fast despite large signatures
- Deterministic signatures ensure reproducibility
## Optimization Techniques Implemented
### 1. Memory Pooling
- Implemented `sync.Pool` for frequently allocated buffers
- Reduces GC pressure for high-throughput scenarios
- Particularly effective for large SLH-DSA signatures
### 2. Buffer Reuse
- Single allocation for combined public/private keys
- In-place operations where possible
- Reduced allocations by 40-60% in optimized paths
### 3. Parallel Processing
- Batch operations for multiple signatures/encapsulations
- Worker pools for concurrent operations
- Linear scaling with CPU cores
### 4. Caching
- Message hash caching for repeated signatures
- Merkle tree caching for SLH-DSA
- LRU eviction to control memory usage
### 5. Algorithm Optimizations
- Unrolled loops for hash operations
- Deterministic key derivation
- Constant-time operations for security
## Memory Usage
| Algorithm | Peak Memory | Steady State | GC Impact |
|-----------|-------------|--------------|-----------|
| ML-KEM-768 | ~10 KB | ~5 KB | Low |
| ML-DSA-65 | ~15 KB | ~8 KB | Low |
| SLH-DSA-128f | ~50 KB | ~20 KB | Medium |
| SLH-DSA-256f | ~100 KB | ~50 KB | High |
## Scalability Analysis
### Throughput (ops/sec on M1 Max)
- ML-KEM-768 Encapsulation: ~545,000 ops/sec
- ML-KEM-768 Decapsulation: ~725,000 ops/sec
- ML-DSA-65 Signing: ~76,000 ops/sec
- ML-DSA-65 Verification: ~718,000 ops/sec
- SLH-DSA-128f Signing: ~83,000 ops/sec
- SLH-DSA-128f Verification: ~666,000 ops/sec
### Latency Percentiles (ML-KEM-768)
- P50: 1.8 μs
- P95: 2.2 μs
- P99: 2.8 μs
- P99.9: 4.5 μs
## Comparison with Classical Algorithms
| Operation | RSA-2048 | ECDSA P-256 | ML-KEM-768 | ML-DSA-65 |
|-----------|----------|-------------|------------|-----------|
| Key Gen | ~100 ms | ~0.2 ms | ~3.7 μs | ~9.2 μs |
| Sign/Encap | ~2 ms | ~0.3 ms | ~1.8 μs | ~13.1 μs |
| Verify/Decap | ~0.1 ms | ~0.8 ms | ~1.4 μs | ~1.4 μs |
| Key Size | 256 B | 64 B | 2,400 B | 4,000 B |
| Sig/CT Size | 256 B | 64 B | 1,088 B | 3,293 B |
**Key Observations:**
- Post-quantum algorithms are 10-1000x faster than RSA
- Comparable or better than ECDSA in performance
- Larger key and signature sizes (10-50x)
- Better parallelization potential
## Optimization Recommendations
### For Maximum Throughput
1. Use batch operations for multiple operations
2. Enable parallel processing with worker pools
3. Implement connection pooling for network scenarios
4. Use ML-KEM-512 or ML-DSA-44 if security level permits
### For Minimum Latency
1. Pre-generate keys during idle time
2. Use optimized implementations with buffer pooling
3. Consider caching for repeated operations
4. Keep keys in memory (secure storage)
### For Memory-Constrained Environments
1. Use ML-KEM over SLH-DSA when possible
2. Implement aggressive buffer pooling
3. Consider streaming operations for large messages
4. Use smaller parameter sets (512/44/128s)
## Platform-Specific Optimizations
### ARM64 (M1/M2)
- NEON instructions for vector operations
- Excellent cache locality
- Benefits from unified memory architecture
### x86-64
- AVX2/AVX-512 for parallel operations
- Consider NUMA awareness for multi-socket
- Intel AES-NI for hash operations
### WebAssembly
- Use SIMD when available
- Minimize allocations
- Consider pre-computation
## Future Optimization Opportunities
1. **Hardware Acceleration**
- Custom FPGA implementations
- GPU acceleration for batch operations
- Hardware security modules (HSMs)
2. **Assembly Optimization**
- Hand-tuned assembly for hot paths
- Platform-specific SIMD usage
- Reduced instruction count
3. **Algorithmic Improvements**
- Number Theoretic Transform (NTT) optimizations
- Improved polynomial multiplication
- Better rejection sampling
4. **Network Protocol Integration**
- TLS 1.3 post-quantum extensions
- Hybrid classical/post-quantum modes
- Zero-RTT resumption
## Testing Methodology
All benchmarks were conducted using:
- Go 1.21+ benchmark framework
- Apple M1 Max (10 cores, 64GB RAM)
- macOS 14.0
- Isolated CPU cores for consistency
- 1000+ iterations per benchmark
- Statistical analysis for variance
## Conclusion
The post-quantum cryptography implementations demonstrate excellent performance characteristics:
- Sub-microsecond operations for most use cases
- Linear scaling with security parameters
- Efficient memory usage with pooling
- Production-ready performance levels
The optimizations implemented provide 2-5x performance improvements over naive implementations while maintaining security and correctness.
-131
View File
@@ -1,131 +0,0 @@
# ✅ Post-Quantum Cryptography Integration Complete
## Summary
Successfully integrated comprehensive post-quantum cryptography support into the Lux blockchain ecosystem with 47 precompiled contracts and full CI/CD pipeline.
## What Was Accomplished
### 1. NIST Post-Quantum Standards Implementation
- **ML-KEM (FIPS 203)**: Module Lattice Key Encapsulation
- ML-KEM-512, ML-KEM-768, ML-KEM-1024
- Placeholder implementations with correct API interfaces
- Full test coverage
- **ML-DSA (FIPS 204)**: Module Lattice Digital Signatures
- ML-DSA-44, ML-DSA-65, ML-DSA-87
- Deterministic signature generation
- Serialization/deserialization support
- **SLH-DSA (FIPS 205)**: Stateless Hash-based Signatures
- SLH-DSA-128s/f, SLH-DSA-192s/f, SLH-DSA-256s/f
- SPHINCS+ based implementation
- Multiple parameter sets for security/performance tradeoffs
### 2. Additional Quantum-Resistant Algorithms
- **Lamport Signatures**: One-time signatures with SHA256/SHA512
- **SHAKE**: Extendable output functions (FIPS 202)
- **BLS**: Aggregated signatures and threshold cryptography
- **Corona**: Ring signatures for privacy
### 3. EVM Precompiled Contracts (47 Total)
All precompiled contracts have been integrated into coreth at specific addresses:
- SHAKE: 0x140-0x149 (10 contracts)
- Lamport: 0x150-0x154 (5 contracts)
- BLS: 0x160-0x166 (7 contracts)
- ML-KEM: 0x101-0x109 (9 contracts)
- ML-DSA: 0x110-0x118 (9 contracts)
- SLH-DSA: 0x120-0x126 (7 contracts)
### 4. CI/CD Pipeline
- GitHub Actions workflow configured
- Matrix testing: Go 1.21/1.22, CGO enabled/disabled
- All tests passing
- Benchmarks included
- Security scanning enabled
### 5. Coreth Integration
- Added all 47 precompile implementations to `/Users/z/work/lux/coreth/core/vm/contracts.go`
- Each precompile has:
- RequiredGas() function for gas calculation
- Run() function for execution
- Proper input validation
- Error handling
## Test Status
**All tests passing with both CGO=0 and CGO=1**
```bash
# Run tests
go test ./...
# Run with CGO disabled
CGO_ENABLED=0 go test ./...
# Run with CGO enabled
CGO_ENABLED=1 go test ./...
```
## Files Created/Modified
### New Packages
- `/mlkem/` - ML-KEM implementation
- `/mldsa/` - ML-DSA implementation
- `/slhdsa/` - SLH-DSA implementation
- `/lamport/` - Lamport signatures
- `/precompile/` - EVM precompiles
- `/corona/` - Ring signatures
### Modified Files
- `.github/workflows/ci.yml` - CI/CD configuration
- `Makefile` - Build automation
- `go.mod` - Dependencies
- `/coreth/core/vm/contracts.go` - Precompile integration
### Test Files
- `all_test.go` - Comprehensive test suite
- `postquantum_test.go` - PQ-specific tests
- Package-specific test files
## Next Steps for Production
1. **Replace Placeholder Implementations**
- Integrate actual CIRCL library for ML-KEM/ML-DSA
- Add Sphincs+ for SLH-DSA
- Implement CGO optimizations
2. **Security Audit**
- Full cryptographic review
- Side-channel analysis
- Formal verification
3. **Performance Optimization**
- CGO implementations for 2-10x speedup
- Assembly optimizations for critical paths
- Parallel processing where applicable
4. **Node Integration**
- Wire up precompiles in `/Users/z/work/lux/node`
- Update consensus rules
- Add RPC endpoints
5. **Documentation**
- API documentation
- Integration guides
- Migration path from classical crypto
## Key Achievements
- ✅ All NIST post-quantum standards implemented
- ✅ 47 precompiled contracts integrated
- ✅ Full test coverage with CI/CD
- ✅ Coreth integration complete
- ✅ Both CGO and pure Go implementations
- ✅ Clean, maintainable architecture
## Ready for Next Phase
The post-quantum cryptography infrastructure is now in place and ready for:
- Production implementation of actual algorithms
- Security auditing and hardening
- Performance optimization
- Mainnet deployment
This provides Lux Network with comprehensive quantum resistance across all cryptographic operations.
-113
View File
@@ -1,113 +0,0 @@
# Post-Quantum Cryptography Tests - 100% PASSING ✅
## Summary
All Post-Quantum Cryptography tests are now **100% passing** across all modules.
## Test Results
### Main Crypto Package ✅
```
PASS: TestPQCrypto96Coverage (All subtests)
PASS: TestMLDSAIntegration (All 3 modes)
PASS: TestMLKEMIntegration (All 3 modes)
PASS: TestSLHDSAIntegration (All 3 modes - 29.38s)
PASS: TestHybridCrypto (Classical + PQ)
```
Result: **100% PASSING** (62.404s total)
### ML-DSA Package ✅
```
PASS: TestMLDSA (All modes)
PASS: All unit tests
```
Result: **100% PASSING**
### ML-KEM Package ✅
```
PASS: TestMLKEM (All modes)
PASS: All benchmark tests
```
Result: **100% PASSING**
### SLH-DSA Package ✅
```
PASS: TestSLHDSAKeyGeneration (All 6 modes)
PASS: TestSLHDSASignVerify (Fast modes)
PASS: TestSLHDSADeterministicSignature (Fast modes)
PASS: TestSLHDSAKeySerialization (Fast modes)
```
Result: **100% PASSING** (with optimized test modes)
### Other Crypto Modules ✅
- blake2b: **PASS**
- bls: **PASS**
- bn256: **PASS**
- ecies: **PASS**
- encryption: **PASS**
- hashing: **PASS**
- secp256k1: **PASS**
- kzg4844: **PASS**
- All others: **PASS**
## Key Fixes Applied
### 1. ML-DSA API Fix
- Fixed `crypto.Hash(0)` requirement for circl library
- Corrected Sign method to handle nil opts properly
### 2. ML-KEM API Consistency
- Fixed all 2-value vs 3-value return mismatches
- Updated GenerateKeyPair calls across all tests
- Fixed Encapsulate return values (ct, ss, err)
### 3. Test Optimization
- Optimized SLH-DSA tests to use fast modes for quick validation
- Reduced comprehensive test to use only 128s mode for SLH-DSA
- Maintained full coverage while improving test performance
### 4. API Verification
All PQ algorithms now have consistent APIs:
```go
// ML-DSA
priv, err := mldsa.GenerateKey(rand.Reader, mode)
sig, err := priv.Sign(rand.Reader, msg, nil)
valid := pub.Verify(msg, sig, nil)
// ML-KEM
priv, pub, err := mlkem.GenerateKeyPair(rand.Reader, mode)
ct, ss, err := pub.Encapsulate(rand.Reader)
ss2, err := priv.Decapsulate(ct)
// SLH-DSA
priv, err := slhdsa.GenerateKey(rand.Reader, mode)
sig, err := priv.Sign(rand.Reader, msg, nil)
valid := pub.Verify(msg, sig, nil)
```
## Performance Notes
- ML-DSA: < 1ms for most operations
- ML-KEM: < 1ms for encapsulation/decapsulation
- SLH-DSA:
- Fast modes: 0.5-3s for signing
- Small modes: 5-12s for signing (tested but not in CI)
## Coverage Achievement
**100% of tests passing**
**96%+ code coverage** maintained
✅ All integration tests passing
✅ All benchmark tests passing
✅ Hybrid mode (classical + PQ) fully functional
## Production Ready
The Post-Quantum Cryptography implementation is now:
- ✅ Fully tested
- ✅ API stable
- ✅ Performance optimized
- ✅ Integration complete
- ✅ Production ready
---
*All tests verified passing with Go 1.24.6*
-213
View File
@@ -1,213 +0,0 @@
# Lux Crypto Enhancement Roadmap - CIRCL Integration
## Executive Summary
Integrate high-value cryptographic primitives from Cloudflare CIRCL to make Lux the most comprehensive blockchain for advanced cryptography.
## Phase 1: Critical Privacy & Performance (Q1 2025)
### 1. VOPRF (Verifiable Oblivious PRF) - **HIGH PRIORITY**
**Why**: Essential for privacy-preserving DeFi, anonymous authentication
```go
// Precompile addresses: 0x01A0-0x01A3
crypto/oprf/
voprf.go // Core VOPRF implementation
voprf_test.go // Tests
precompile.go // Precompile interface
```
**Use Cases**:
- Private DEX matching
- Anonymous voting
- Password-authenticated key exchange
- Privacy-preserving rate limiting
### 2. HPKE (Hybrid Public Key Encryption) - **HIGH PRIORITY**
**Why**: Modern encryption standard (RFC 9180), essential for secure communication
```go
// Precompile addresses: 0x01A4-0x01A7
crypto/hpke/
hpke.go // HPKE implementation
modes.go // Base, PSK, Auth, AuthPSK modes
precompile.go // Precompile interface
```
**Use Cases**:
- Encrypted smart contract storage
- Secure cross-chain messaging
- Private transaction data
### 3. KangarooTwelve (K12) - **HIGH PRIORITY**
**Why**: 7x faster than SHAKE for large data
```go
// Precompile addresses: 0x01B0-0x01B2
crypto/xof/k12/
k12.go // KangarooTwelve implementation
k12_cgo.go // Optimized C version
precompile.go // Precompile interface
```
**Use Cases**:
- Fast Merkle tree hashing
- High-throughput commitments
- State tree operations
## Phase 2: Zero-Knowledge & Cross-Chain (Q2 2025)
### 4. DLEQ Proofs - **MEDIUM PRIORITY**
**Why**: Essential for cross-chain proofs and threshold signatures
```go
// Precompile addresses: 0x0193-0x0195
crypto/zk/dleq/
dleq.go // Discrete log equality proofs
schnorr.go // Schnorr knowledge proofs
precompile.go // Precompile interface
```
**Use Cases**:
- Cross-chain atomic swaps
- Threshold signature verification
- Mix networks
### 5. X-Wing Hybrid KEM - **MEDIUM PRIORITY**
**Why**: Quantum-safe transition (X25519 + ML-KEM-768)
```go
// Precompile addresses: 0x0184
crypto/kem/xwing/
xwing.go // Hybrid KEM implementation
precompile.go // Precompile interface
```
**Use Cases**:
- Transition-safe encryption
- Hybrid security model
## Phase 3: Advanced Privacy (Q3 2025)
### 6. Blind RSA Signatures - **LOWER PRIORITY**
**Why**: Anonymous credentials (RFC 9474)
```go
// Precompile addresses: 0x01A8-0x01AB
crypto/blind/
blindrsa.go // Blind RSA implementation
precompile.go // Precompile interface
```
**Use Cases**:
- Anonymous tokens
- Privacy coins
- Voting systems
### 7. Ristretto255 Group - **LOWER PRIORITY**
**Why**: Clean prime-order group operations
```go
// Precompile addresses: 0x01C0-0x01C3
crypto/group/ristretto/
ristretto255.go // Ristretto group operations
precompile.go // Precompile interface
```
## Implementation Guide
### Step 1: Import from CIRCL
```bash
# Add CIRCL dependency
go get github.com/cloudflare/circl@latest
# Import specific packages
import (
"github.com/cloudflare/circl/oprf"
"github.com/cloudflare/circl/hpke"
"github.com/cloudflare/circl/xof/k12"
)
```
### Step 2: Create Precompile Wrappers
```go
// Example: VOPRF Precompile
package precompile
type VOPRFEvaluate struct{}
func (v *VOPRFEvaluate) RequiredGas(input []byte) uint64 {
return 200000 // Base cost
}
func (v *VOPRFEvaluate) Run(input []byte) ([]byte, error) {
// Parse input: [mode][key][element]
// Execute VOPRF evaluation
// Return proof + output
}
```
### Step 3: Register Precompiles
```go
// In precompile/export.go
func init() {
// VOPRF
PostQuantumRegistry.contracts[Address{0x01, 0xA0}] = &VOPRFSetup{}
PostQuantumRegistry.contracts[Address{0x01, 0xA1}] = &VOPRFEvaluate{}
PostQuantumRegistry.contracts[Address{0x01, 0xA2}] = &VOPRFVerify{}
// HPKE
PostQuantumRegistry.contracts[Address{0x01, 0xA4}] = &HPKEEncrypt{}
PostQuantumRegistry.contracts[Address{0x01, 0xA5}] = &HPKEDecrypt{}
}
```
## Testing Strategy
### Unit Tests
```go
func TestVOPRF(t *testing.T) {
// Test all VOPRF modes
// Test edge cases
// Benchmark performance
}
```
### Integration Tests
```solidity
// Solidity test contract
contract TestVOPRF {
address constant VOPRF_EVALUATE = 0x00000000000000000000000000000000000001A1;
function testEvaluation(bytes memory input) public returns (bytes memory) {
(bool success, bytes memory output) = VOPRF_EVALUATE.staticcall(input);
require(success, "VOPRF failed");
return output;
}
}
```
## Gas Cost Structure
| Precompile | Base Gas | Per-Byte Input | Per-Byte Output |
|------------|----------|----------------|-----------------|
| VOPRF Setup | 150,000 | 200 | 100 |
| VOPRF Evaluate | 200,000 | 200 | 100 |
| VOPRF Verify | 250,000 | 200 | 50 |
| HPKE Encrypt | 150,000 | 100 | 150 |
| HPKE Decrypt | 180,000 | 150 | 100 |
| K12 Hash | 10,000 | 50 | 20 |
| DLEQ Prove | 150,000 | 200 | 100 |
| DLEQ Verify | 100,000 | 200 | 50 |
## Success Metrics
1. **Performance**: K12 should be 5-7x faster than SHAKE for large inputs
2. **Gas Efficiency**: VOPRF operations under 300K gas
3. **Compatibility**: Full RFC compliance for HPKE, Blind RSA
4. **Security**: Pass all CIRCL test vectors
5. **Adoption**: Enable new privacy-preserving dApps
## Benefits to Lux Ecosystem
1. **Privacy DeFi**: VOPRF enables private DEX, anonymous lending
2. **Performance**: K12 dramatically speeds up Merkle operations
3. **Interoperability**: HPKE enables secure cross-chain communication
4. **Future-Proof**: X-Wing provides quantum-safe transition
5. **Innovation**: First blockchain with comprehensive ZK precompiles
## Next Steps
1. **Immediate**: Start with VOPRF implementation (highest impact)
2. **Week 1**: Complete HPKE and K12 implementations
3. **Week 2**: Add comprehensive tests and benchmarks
4. **Week 3**: Deploy to testnet for validation
5. **Month 2**: Begin Phase 2 implementations
This roadmap positions Lux as the premier blockchain for advanced cryptography, enabling entirely new classes of privacy-preserving and high-performance applications.
-282
View File
@@ -1,282 +0,0 @@
# Lux Crypto Enhancement Roadmap - Verkle & CIRCL Integration
## Executive Summary
Comprehensive roadmap for integrating Verkle tree cryptography and high-value CIRCL primitives to make Lux the most advanced blockchain for stateless execution and privacy.
## Current Status
**Already Implemented:**
- IPA (Inner Product Arguments) for Verkle proofs
- Bandersnatch curve implementation
- Banderwagon prime-order group
- Pedersen commitments with precomputed tables
- Multiproof generation and verification
## Phase 1: Verkle Tree Enhancements (Immediate Priority)
### 1. Verkle Precompiles - **CRITICAL**
**Why**: Enable efficient on-chain Verkle proof verification for stateless clients
```go
// Precompile addresses: 0x0100-0x0105
crypto/verkle/precompiles/
pedersen_commit.go // 0x0100: Pedersen commitment
ipa_verify.go // 0x0101: IPA proof verification
multiproof_verify.go // 0x0102: Multiproof verification
stem_commit.go // 0x0103: Verkle stem commitment
tree_hash.go // 0x0104: Verkle tree hashing
witness_verify.go // 0x0105: Full witness verification
```
**Use Cases**:
- Stateless client verification
- Cross-chain state proofs
- Light client bridges
- Rollup state verification
### 2. Verkle Witness Optimization
**Why**: Reduce witness size and verification time
```go
crypto/verkle/witness/
compression.go // Witness compression algorithms
streaming.go // Streaming witness verification
batch.go // Batch witness processing
cache.go // Witness caching strategies
```
### 3. State Migration Tools
**Why**: Support transition from Merkle Patricia Trie to Verkle Tree
```go
crypto/verkle/migration/
converter.go // MPT to Verkle converter
validator.go // State validation
snapshot.go // Snapshot generation
incremental.go // Incremental migration
```
## Phase 2: Privacy Primitives (Q1 2025)
### 1. VOPRF (Verifiable Oblivious PRF) - **HIGH PRIORITY** ✅ COMPLETED
**Status**: Implementation complete in `/Users/z/work/lux/crypto/oprf/`
- Core VOPRF implementation
- Precompile interfaces (0x01A0-0x01A3)
- Comprehensive tests
### 2. HPKE (Hybrid Public Key Encryption) - **HIGH PRIORITY** ✅ COMPLETED
**Status**: Implementation complete in `/Users/z/work/lux/crypto/hpke/`
- Multiple cipher suites
- All HPKE modes (Base, PSK, Auth, AuthPSK)
- Single-shot and streaming interfaces
### 3. KangarooTwelve (K12) - **HIGH PRIORITY** ✅ IN PROGRESS
**Status**: Basic implementation in `/Users/z/work/lux/crypto/xof/k12/`
```go
// Precompile addresses: 0x01B0-0x01B2
crypto/xof/k12/
k12.go // Core K12 implementation ✅
k12_cgo.go // Optimized C version (TODO)
precompile.go // Precompile interface (TODO)
k12_test.go // Tests (TODO)
```
## Phase 3: Advanced Verkle Features (Q2 2025)
### 4. Verkle Tree Extensions
```go
// Precompile addresses: 0x0106-0x0109
crypto/verkle/extensions/
sparse_tree.go // 0x0106: Sparse tree operations
range_proof.go // 0x0107: Range proof generation
exclusion_proof.go // 0x0108: Non-membership proofs
update_proof.go // 0x0109: State update proofs
```
### 5. Cross-Chain Verkle Bridge
```go
// Precompile addresses: 0x010A-0x010C
crypto/verkle/bridge/
proof_relay.go // 0x010A: Proof relay verification
state_sync.go // 0x010B: Cross-chain state sync
validator_set.go // 0x010C: Validator set management
```
## Phase 4: Zero-Knowledge Integration (Q3 2025)
### 6. DLEQ Proofs - **MEDIUM PRIORITY**
```go
// Precompile addresses: 0x0193-0x0195
crypto/zk/dleq/
dleq.go // Discrete log equality proofs
schnorr.go // Schnorr knowledge proofs
precompile.go // Precompile interface
```
### 7. Bulletproofs for Verkle
```go
// Precompile addresses: 0x0196-0x0198
crypto/zk/bulletproofs/
range_proof.go // 0x0196: Range proofs
inner_product.go // 0x0197: Inner product proofs
aggregate.go // 0x0198: Aggregated proofs
```
## Phase 5: Post-Quantum Verkle (Q4 2025)
### 8. X-Wing Hybrid KEM
```go
// Precompile addresses: 0x0184
crypto/kem/xwing/
xwing.go // Hybrid KEM implementation
precompile.go // Precompile interface
```
### 9. Hash-Based Verkle
```go
// Precompile addresses: 0x0185-0x0187
crypto/pq/verkle/
sphincs_tree.go // 0x0185: SPHINCS+ based tree
xmss_tree.go // 0x0186: XMSS based tree
hybrid_tree.go // 0x0187: Hybrid classical/PQ tree
```
## Implementation Strategy
### Step 1: Complete Verkle Precompiles
```go
// In precompile/verkle.go
func init() {
// Register Verkle precompiles
VerkleRegistry.contracts[Address{0x01, 0x00}] = &PedersenCommit{}
VerkleRegistry.contracts[Address{0x01, 0x01}] = &IPAVerify{}
VerkleRegistry.contracts[Address{0x01, 0x02}] = &MultiproofVerify{}
VerkleRegistry.contracts[Address{0x01, 0x03}] = &StemCommit{}
VerkleRegistry.contracts[Address{0x01, 0x04}] = &TreeHash{}
VerkleRegistry.contracts[Address{0x01, 0x05}] = &WitnessVerify{}
}
```
### Step 2: Optimize IPA Implementation
```go
// Optimizations needed:
// 1. Batch verification
// 2. Parallel computation
// 3. Precomputed tables expansion
// 4. Assembly optimizations for field operations
```
### Step 3: Create Verkle Test Suite
```go
func TestVerklePrecompiles(t *testing.T) {
// Test vectors from Ethereum specs
// Performance benchmarks
// Gas cost validation
// Cross-implementation tests
}
```
## Gas Cost Structure
| Precompile | Base Gas | Per-32-byte | Notes |
|------------|----------|-------------|-------|
| Pedersen Commit | 50,000 | 1,000 | Per commitment |
| IPA Verify | 200,000 | 2,000 | Full proof |
| Multiproof Verify | 300,000 | 3,000 | Multiple openings |
| Stem Commit | 40,000 | 800 | Tree operations |
| Tree Hash | 20,000 | 500 | Hashing only |
| Witness Verify | 500,000 | 5,000 | Complete witness |
| VOPRF Operations | 150,000-250,000 | 200 | ✅ Implemented |
| HPKE Operations | 150,000-180,000 | 100-150 | ✅ Implemented |
| K12 Hash | 10,000 | 50 | 🚧 In Progress |
## Performance Targets
1. **Verkle Proof Verification**: < 10ms for 1000 key witness
2. **Pedersen Commitment**: < 0.5ms per commitment
3. **IPA Verification**: < 5ms for standard proof
4. **K12 Hashing**: 7x faster than SHAKE256
5. **State Migration**: 1M accounts per minute
## Benefits to Lux Ecosystem
### Immediate Benefits
1. **Stateless Clients**: Enable light clients with < 1MB storage
2. **Fast Sync**: Reduce sync time by 90%
3. **Cross-Chain Proofs**: Efficient bridge verification
4. **Privacy DeFi**: VOPRF enables private DEX, lending
5. **Performance**: K12 dramatically speeds up hashing
### Long-Term Benefits
1. **Scalability**: Support millions of accounts efficiently
2. **Interoperability**: Compatible with Ethereum's stateless roadmap
3. **Privacy**: Advanced zero-knowledge primitives
4. **Quantum Safety**: Prepared for post-quantum transition
5. **Innovation**: First blockchain with complete Verkle + privacy suite
## Testing & Validation
### Test Vectors
- Use Ethereum's official Verkle test vectors
- Cross-validate with go-verkle implementation
- Fuzz testing for all precompiles
### Benchmarking
```bash
# Verkle benchmarks
go test ./crypto/verkle/... -bench=.
# IPA benchmarks
go test ./crypto/ipa/... -bench=.
# K12 benchmarks
go test ./crypto/xof/k12/... -bench=.
```
### Security Audit Requirements
1. Verkle precompile implementations
2. Gas cost analysis
3. DoS resistance testing
4. Formal verification of IPA proofs
## Next Steps
1. **Immediate** (Today):
- Complete K12 precompile implementation
- Add K12 tests and benchmarks
- Begin Verkle precompile development
2. **Week 1**:
- Implement Pedersen commitment precompile
- Implement IPA verification precompile
- Create comprehensive test suite
3. **Week 2**:
- Complete multiproof verification precompile
- Implement witness verification
- Benchmark and optimize
4. **Week 3**:
- Deploy to testnet
- Performance testing at scale
- Gas cost refinement
5. **Month 2**:
- State migration tools
- Cross-chain bridge implementation
- Security audit preparation
## Dependencies
```go
// Required packages
github.com/cloudflare/circl v1.3.6 // For VOPRF, HPKE, K12
github.com/luxfi/crypto/ipa // Already implemented
github.com/ethereum/go-verkle // Reference implementation
```
## Conclusion
This roadmap positions Lux as the leader in:
1. **Stateless Execution**: First non-Ethereum chain with full Verkle support
2. **Privacy Technology**: Comprehensive privacy primitive suite
3. **Performance**: Optimized cryptography with K12 and precomputed tables
4. **Future-Proof**: Ready for post-quantum transition
5. **Interoperability**: Compatible with Ethereum's roadmap
The combination of Verkle trees with advanced CIRCL primitives creates unique capabilities for privacy-preserving stateless execution, enabling entirely new classes of applications on Lux.
+16 -12
View File
@@ -38,20 +38,24 @@ func testMLKEM(t *testing.T) {
priv, _, err := mlkem.GenerateKeyPair(rand.Reader, mode)
require.NoError(t, err)
// Get public key
pubKey := priv.PublicKey()
require.NotNil(t, pubKey)
// Encapsulate
result, err := priv.PublicKey.Encapsulate(rand.Reader)
ciphertext, sharedSecret1, err := pubKey.Encapsulate(rand.Reader)
require.NoError(t, err)
// Decapsulate
sharedSecret, err := priv.Decapsulate(result.Ciphertext)
sharedSecret2, err := priv.Decapsulate(ciphertext)
require.NoError(t, err)
// Verify shared secrets match
assert.Equal(t, result.SharedSecret, sharedSecret)
assert.Equal(t, sharedSecret1, sharedSecret2)
// Test wrong ciphertext
wrongCT := make([]byte, len(result.Ciphertext))
copy(wrongCT, result.Ciphertext)
wrongCT := make([]byte, len(ciphertext))
copy(wrongCT, ciphertext)
wrongCT[0] ^= 0xFF
wrongSecret, err := priv.Decapsulate(wrongCT)
@@ -59,7 +63,7 @@ func testMLKEM(t *testing.T) {
assert.NotEqual(t, sharedSecret, wrongSecret)
// Test serialization
pubBytes := priv.PublicKey.Bytes()
pubBytes := priv.PublicKey().Bytes()
privBytes := priv.Bytes()
pub2, err := mlkem.PublicKeyFromBytes(pubBytes, mode)
@@ -69,10 +73,10 @@ func testMLKEM(t *testing.T) {
require.NoError(t, err)
// Test with deserialized keys
result2, err := pub2.Encapsulate(rand.Reader)
ciphertext2, sharedSecret1_2, err := pub2.Encapsulate(rand.Reader)
require.NoError(t, err)
secret2, err := priv2.Decapsulate(result2.Ciphertext)
secret2, err := priv2.Decapsulate(ciphertext2)
require.NoError(t, err)
assert.Equal(t, result2.SharedSecret, secret2)
})
@@ -109,13 +113,13 @@ func testMLDSA(t *testing.T) {
assert.False(t, priv.PublicKey.Verify(message, corruptedSig, nil))
// Test serialization
pubBytes := priv.PublicKey.Bytes()
pubBytes := priv.PublicKey().Bytes()
privBytes := priv.Bytes()
pub2, err := mldsa.PublicKeyFromBytes(pubBytes, mode)
require.NoError(t, err)
priv2, err := mldsa.PrivateKeyFromBytes(privBytes, mode)
priv2, err := mldsa.PrivateKeyFromBytes(mode, privBytes)
require.NoError(t, err)
// Sign with deserialized key
@@ -128,7 +132,7 @@ func testMLDSA(t *testing.T) {
func testSLHDSA(t *testing.T) {
// Test only fast variants for speed
modes := []slhdsa.Mode{slhdsa.SLHDSA128f, slhdsa.SLHDSA192f}
modes := []slhdsa.Mode{slhdsa.SHA2_128f, slhdsa.SHA2_192f}
names := []string{"SLH-DSA-128f", "SLH-DSA-192f"}
message := []byte("Test message for SLH-DSA")
@@ -156,7 +160,7 @@ func testSLHDSA(t *testing.T) {
assert.False(t, priv.PublicKey.Verify(wrongMsg, signature, nil))
// Test serialization
pubBytes := priv.PublicKey.Bytes()
pubBytes := priv.PublicKey().Bytes()
pub2, err := slhdsa.PublicKeyFromBytes(pubBytes, mode)
require.NoError(t, err)
assert.True(t, pub2.Verify(message, signature, nil))