clock-rand 1.0.0

Next-generation random number generation with blockchain-aware RNGs, fork detection, and cryptographic security
Documentation
# clock-rand ๐Ÿ•๐ŸŽฒ

<div align="center">

[![crates.io](https://img.shields.io/crates/v/clock-rand.svg)](https://crates.io/crates/clock-rand)
[![Documentation](https://docs.rs/clock-rand/badge.svg)](https://docs.rs/clock-rand)
[![License](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue.svg)](https://github.com/Olyntar-Labs/clock-rand/blob/main/LICENSE)
[![CI](https://github.com/Olyntar-Labs/clock-rand/workflows/CI/badge.svg)](https://github.com/Olyntar-Labs/clock-rand/actions)
[![Code Coverage](https://codecov.io/gh/Olyntar-Labs/clock-rand/branch/main/graph/badge.svg)](https://codecov.io/gh/Olyntar-Labs/clock-rand)
[![Security Audit](https://github.com/Olyntar-Labs/clock-rand/workflows/Security%20Scan/badge.svg)](https://github.com/Olyntar-Labs/clock-rand/actions)

**Custom blockchain-aware RNG crate with fast and crypto-secure RNGs**<br>
*by Olyntar Labs, an Olyntar company*

[๐Ÿ“ฆ Install](#installation) โ€ข [๐Ÿ“š Docs](https://docs.rs/clock-rand) โ€ข [๐Ÿงช Examples](#examples) โ€ข [๐Ÿค Contributing](CONTRIBUTING.md)

</div>

---

## โœจ Why clock-rand?

**clock-rand** is a next-generation random number generation library designed specifically for modern applications that need both **speed** and **security**. Unlike generic RNG libraries, clock-rand provides specialized RNGs for blockchain applications, with built-in fork detection and deterministic seeding.

### ๐Ÿš€ Key Highlights

- **๐Ÿ† Production-Ready**: Comprehensive testing, security audits, and CI/CD
- **๐Ÿ”— Blockchain-Native**: Fork detection, block hash seeding, VRF support
- **โšก High Performance**: 2GB/s throughput for fast RNGs
- **๐Ÿ”’ Cryptographically Secure**: FIPS-compliant algorithms with zeroization
- **๐ŸŒ Cross-Platform**: no_std, WASM, embedded systems support
- **๐Ÿงต Thread-Safe**: Optional thread-safe wrappers for concurrent applications

## ๐Ÿ“ฆ Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
clock-rand = "1.0"
```

Or for specific features:

```toml
[dependencies]
clock-rand = { version = "1.0", features = ["crypto_rng", "custom_rng", "thread_safe"] }
```

## ๐ŸŽฏ Quick Start

```rust
use clock_rand::*;

// ๐Ÿš€ Fast RNG for simulations and games
let mut rng = Xoshiro256Plus::new(42);
let dice_roll = rng.gen_range(1..=6);

// ๐Ÿ” Cryptographically secure RNG for keys and signatures
let seed = Seed::from_block_hash(&[0x42u8; 32])?;
let mut crypto_rng = ChaCha20Rng::from_seed(seed)?;
let mut key = [0u8; 32];
crypto_rng.fill_bytes(&mut key);

// โ›“๏ธ Blockchain-aware RNG with fork detection
let mut chain_rng = ChainSeedX::builder()
    .with_block_hash([0x01u8; 32])
    .with_timestamp(12345)
    .with_fork_detection(true)
    .build()?;

// ๐Ÿ”„ Automatic reseeding on blockchain forks
if chain_rng.check_fork(&new_block_hash)? {
    println!("Fork detected - RNG reseeded automatically!");
}
```

## ๐Ÿ—๏ธ Architecture

### RNG Types Overview

| RNG Type | Algorithm | Security | Performance | Use Case |
|----------|-----------|----------|-------------|----------|
| **Xoshiro256+** | Xoshiro256+ | โš ๏ธ Fast only | โญโญโญโญโญ ~2GB/s | Simulations, games |
| **PCG64** | PCG64 | โš ๏ธ Fast only | โญโญโญโญ ~1.5GB/s | General purpose |
| **ChaCha20Rng** | ChaCha20 | ๐Ÿ”’ Crypto-secure | โญโญโญ ~500MB/s | Keys, signatures |
| **Blake3Drbg** | Blake3-DRBG | ๐Ÿ”’ Crypto-secure | โญโญโญ ~500MB/s | Crypto operations |
| **ChainSeed-X** | Hybrid Blake3+PCG | ๐Ÿ”’ Crypto + Fork-aware | โญโญ ~300MB/s | Blockchain apps |
| **EntroCrypt** | Hybrid ChaCha20+Blake3 | ๐Ÿ”’ Maximum security | โญโญ ~280MB/s | High-security needs |

### โšก Feature Flags

```toml
# Core features (always enabled)
clock-rand = "1.0"

# Optional features
clock-rand = { version = "1.0", features = [
    "crypto_rng",    # ChaCha20, Blake3-DRBG, AES-CTR
    "custom_rng",    # ChainSeed-X, EntroCrypt, HashMix256
    "distributions", # Uniform and other distributions
    "thread_safe",   # Arc<Mutex<>> wrappers
    "fork_safe",     # Fork detection capabilities
    "serde",         # Serialization support
    "security",      # Memory zeroization
    "wasm",          # WASM bindings
    "wasm_crypto"    # WASM crypto APIs
] }
```

## ๐Ÿ”’ Security

**Security is our top priority.** clock-rand provides multiple RNG types with clear security boundaries:

### ๐Ÿ›ก๏ธ Security Levels

| Level | RNG Types | Use Cases | Security Features |
|-------|-----------|-----------|-------------------|
| **โš ๏ธ Fast** | Xoshiro256+, PCG64 | Simulations, games, testing | High performance, deterministic |
| **๐Ÿ”’ Crypto** | ChaCha20Rng, Blake3Drbg, AesCtrRng | Keys, signatures, crypto | FIPS-compliant, constant-time |
| **๐Ÿš€ Hybrid** | ChainSeed-X, EntroCrypt | Blockchain, consensus | Crypto + fork detection |

### ๐Ÿ” Key Security Features

- **โœ… Audited**: Regular security audits with `cargo-audit`
- **โœ… Zeroization**: Sensitive data automatically zeroized (when `security` feature enabled)
- **โœ… Seed Validation**: Rejects weak seeds, validates entropy
- **โœ… Constant-Time**: Cryptographic operations are timing-attack resistant
- **โœ… Fork Detection**: Automatic reseeding on blockchain forks

### โš ๏ธ Important Security Notes

```rust
// โŒ NEVER use fast RNGs for security-critical operations
let mut insecure = Xoshiro256Plus::new(42); // NOT for crypto!

// โœ… ALWAYS use crypto RNGs for security-critical operations
let seed = Seed::from_block_hash(&secure_block_hash)?;
let mut secure = ChaCha20Rng::from_seed(seed)?; // SAFE for crypto!

// โœ… Use blockchain-aware RNGs for consensus applications
let mut chain_rng = ChainSeedX::builder()
    .with_block_hash(current_block_hash)
    .with_fork_detection(true)
    .build()?; // Handles forks automatically
```

๐Ÿ“– **Detailed Security Guide**: [SECURITY.md](docs/SECURITY.md)

## โšก Performance

**Industry-leading performance** with security guarantees:

### ๐Ÿ“Š Throughput Benchmarks

| RNG Type | Throughput | Memory | Use Case |
|----------|------------|--------|----------|
| **Xoshiro256+** | ~2.0 GB/s | 32 bytes | Simulations, games |
| **PCG64** | ~1.5 GB/s | 16 bytes | General computing |
| **ChaCha20Rng** | ~500 MB/s | 100 bytes | Cryptographic keys |
| **Blake3Drbg** | ~500 MB/s | 150 bytes | Crypto operations |
| **ChainSeed-X** | ~300 MB/s | 200 bytes | Blockchain apps |
| **EntroCrypt** | ~280 MB/s | 300 bytes | Maximum security |

### ๐ŸŽฏ Performance Tips

```rust
// Use fill_bytes for bulk operations (much faster!)
let mut buffer = [0u8; 1024];
rng.fill_bytes(&mut buffer); // โœ… ~10x faster than individual calls

// Cache RNG instances when possible
let mut rng = Xoshiro256Plus::new(seed); // โœ… Create once, reuse

// Use SIMD features when available (enabled by default)
clock-rand = { version = "1.0", features = ["simd"] } // โœ… SIMD acceleration
```

๐Ÿ“– **Complete Performance Guide**: [PERFORMANCE.md](docs/PERFORMANCE.md)

## ๐Ÿ”„ Migration from `rand`

**Drop-in replacement** for the `rand` crate ecosystem:

```rust
// Before (rand crate)
use rand::{RngCore, Rng};
let mut rng = rand::thread_rng();
let value: u64 = rng.gen();

// After (clock-rand)
use clock_rand::{Rng, RngExt};
let mut rng = Xoshiro256Plus::new(42);
let value: u64 = rng.gen(); // Same API!
```

### Migration Table

| `rand` | `clock-rand` | Notes |
|--------|--------------|-------|
| `rand::thread_rng()` | `Xoshiro256Plus::new(seed)` | Deterministic seeding |
| `rand::random::<T>()` | `rng.gen::<T>()` | Same API |
| `rng.gen_range(0..100)` | `rng.gen_range(0..100)` | Identical usage |
| `rng.fill_bytes(&mut buf)` | `rng.fill_bytes(&mut buf)` | Same performance |

## ๐ŸŽฎ Examples

### Basic Usage
```rust
use clock_rand::{Rng, Xoshiro256Plus};

let mut rng = Xoshiro256Plus::new(42);

// Generate random numbers
let random_u64 = rng.next_u64();
let random_i32 = rng.gen::<i32>();
let dice_roll = rng.gen_range(1..=6);

// Fill buffers efficiently
let mut buffer = [0u8; 1024];
rng.fill_bytes(&mut buffer);
```

### Cryptographic Security
```rust
use clock_rand::{Rng, ChaCha20Rng, Seed};

let seed = Seed::from_block_hash(&secure_hash)?;
let mut rng = ChaCha20Rng::from_seed(seed)?;

// Generate cryptographic keys
let mut key = [0u8; 32];
rng.fill_bytes(&mut key);

// Generate nonces
let nonce = rng.next_u64();
```

### Blockchain Applications
```rust
use clock_rand::{ChainSeedX, Seed};

let mut rng = ChainSeedX::builder()
    .with_block_hash(current_block_hash)
    .with_timestamp(block_timestamp)
    .with_vrf_output(vrf_proof)
    .with_fork_detection(true)
    .build()?;

// Consensus randomness
let validator_selection = rng.gen_range(0..validator_count);

// Automatic fork handling
if rng.check_fork(&new_block_hash)? {
    println!("๐Ÿ”„ Fork detected, RNG reseeded!");
}
```

### Thread-Safe Usage
```rust
use clock_rand::{thread_safe::ThreadSafeRng, Xoshiro256Plus};
use std::sync::Arc;

// Share RNG across threads
let rng = Arc::new(ThreadSafeRng::new(Xoshiro256Plus::new(42)));

// Use in multiple threads
let rng_clone = Arc::clone(&rng);
std::thread::spawn(move || {
    let value = rng_clone.lock().gen::<u64>();
    println!("Thread got: {}", value);
});
```

### WASM Support
```rust
use clock_rand::{Rng, Xoshiro256Plus};

#[cfg(target_arch = "wasm32")]
use clock_rand::wasm::WasmCryptoRng;

#[cfg(target_arch = "wasm32")]
async fn web_crypto_rng() -> Result<WasmCryptoRng, JsValue> {
    WasmCryptoRng::new().await
}
```

๐Ÿ“ **Complete Examples**: [examples/](examples/)
- `basic_usage.rs` - Getting started
- `blockchain_seeding.rs` - Block hash seeding
- `fork_detection.rs` - Fork handling
- `thread_safe.rs` - Multi-threading
- `serialization.rs` - State persistence
- `wasm_example/` - WebAssembly usage

## ๐Ÿ“š Documentation

### ๐Ÿ“– Guides & References
- **[๐Ÿ“š API Documentation]https://docs.rs/clock-rand** - Complete API reference
- **[๐Ÿ—๏ธ Architecture Guide]docs/ARCHITECTURE.md** - System design and internals
- **[๐Ÿ”’ Security Guide]docs/SECURITY.md** - Security considerations and best practices
- **[โšก Performance Guide]docs/PERFORMANCE.md** - Benchmarks and optimization tips
- **[๐ŸŒฟ Branching Strategy]BRANCHING.md** - Development workflow

### ๐Ÿ”ง API Reference

```rust
// Core traits
use clock_rand::{Rng, CryptoRng, RngCore, SeedableRng};

// RNG implementations
use clock_rand::{Xoshiro256Plus, ChaCha20Rng, ChainSeedX};

// Utilities
use clock_rand::{Seed, RngExt, utils::*};
```

## ๐Ÿค Contributing

We โค๏ธ contributions! Help make clock-rand even better.

### ๐Ÿš€ Quick Start
1. ๐Ÿ“– Read our [Contributing Guide]CONTRIBUTING.md
2. ๐Ÿด Fork and clone the repository
3. ๐ŸŒฟ Create a feature branch: `git checkout -b feature/amazing-feature`
4. ๐Ÿงช Write tests for your changes
5. ๐Ÿ’พ Commit with conventional format: `git commit -m "feat: add amazing feature"`
6. ๐Ÿ”„ Push and create a PR

### ๐Ÿท๏ธ Contribution Types
- ๐Ÿ› **Bug fixes** - Fix issues and vulnerabilities
- โœจ **Features** - Add new functionality
- ๐Ÿ“š **Documentation** - Improve docs and examples
- ๐Ÿงช **Testing** - Add tests and fuzzing
- โšก **Performance** - Optimize and benchmark
- ๐Ÿ”’ **Security** - Security enhancements

### ๐Ÿ“Š Development Workflow
```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   feature   โ”‚ -> โ”‚ pull request โ”‚ -> โ”‚   review    โ”‚
โ”‚   branch    โ”‚    โ”‚  (develop)   โ”‚    โ”‚  & merge    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
       โ†‘                   โ†‘                   โ†‘
   implement         CI checks          approval
```

## ๐Ÿ› Issue Reporting

Found a bug? Have a feature request?

- ๐Ÿ› **Bug Reports**: [Open an issue]https://github.com/Olyntar-Labs/clock-rand/issues/new?template=bug_report.md
- ๐Ÿ’ก **Feature Requests**: [Open an issue]https://github.com/Olyntar-Labs/clock-rand/issues/new
- ๐Ÿ’ฌ **Discussions**: [GitHub Discussions]https://github.com/Olyntar-Labs/clock-rand/discussions

### ๐Ÿ”’ Security Issues
**๐Ÿšจ Never report security vulnerabilities publicly!**

Email: [security@olyntar.com](mailto:security@olyntar.com)

We take security seriously and will respond promptly.

## ๐Ÿข About Olyntar Labs

**Olyntar Labs** is a technology company specializing in blockchain infrastructure, cryptography, and secure systems. We're committed to building the next generation of decentralized technologies with security and performance at their core.

- ๐ŸŒ **Website**: [olyntar.com]https://olyntar.com
- ๐Ÿฆ **Twitter**: [@OlyntarLabs]https://twitter.com/OlyntarLabs
- ๐Ÿ’ผ **LinkedIn**: [Olyntar Labs]https://linkedin.com/company/olyntar-labs

## ๐Ÿ“„ License

**Dual-licensed** for maximum compatibility:

Licensed under either of:
- **Apache License 2.0** ([LICENSE-APACHE]LICENSE-APACHE) - *Permissive, patent protection*
- **MIT License** ([LICENSE-MIT]LICENSE-MIT) - *Simple and permissive*

Choose the license that works best for your project!

---

<div align="center">

**Made with โค๏ธ by [Olyntar Labs](https://olyntar.com)**

[๐Ÿ“ฆ Install](#installation) โ€ข [๐Ÿ“š Docs](https://docs.rs/clock-rand) โ€ข [๐Ÿ› Report Bug](https://github.com/Olyntar-Labs/clock-rand/issues) โ€ข [๐Ÿ’ก Request Feature](https://github.com/Olyntar-Labs/clock-rand/issues)

</div>