Skip to main content

API_REFERENCE.md

TimeChain Protocol Stack - Complete API Reference

Version: 1.0.0
Date: December 6, 2025
Status: Production Ready

Table of Contents

  1. Cryptography Module
  2. WEAVE P2P Module
  3. ForkNode CRDT Module
  4. TNP Navigation Module
  5. VEST Audit Module
  6. ForkNode-VEST Hybrid Module
  7. System Integration Module
  8. AEGIS Access Control Module
  9. Deployment Module
  10. Benchmarks Module

Cryptography Module

Location: .tcproto/crypto/src/

Ed25519 Digital Signatures

pub fn generate_keypair() -> (PublicKey, SecretKey)
Generates an Ed25519 keypair for signing operations. Parameters: None
Returns: Tuple of (PublicKey, SecretKey)
Example:
let (public, secret) = generate_keypair();

pub fn sign(message: &[u8], secret_key: &SecretKey) -> Signature
Signs a message using Ed25519. Parameters:
  • message: Byte slice to sign
  • secret_key: Secret key for signing
Returns: Cryptographic signature
Example:
let sig = sign(b"message", &secret_key);

pub fn verify(message: &[u8], signature: &Signature, public_key: &PublicKey) -> bool
Verifies an Ed25519 signature. Parameters:
  • message: Original message
  • signature: Signature to verify
  • public_key: Public key for verification
Returns: true if signature is valid, false otherwise
Error: None (returns bool directly)
Example:
if verify(b"message", &sig, &public_key) {
    println!("Signature valid!");
}

BLAKE3 Hashing

pub fn hash(data: &[u8]) -> Hash
Computes BLAKE3 hash of data for content addressing. Parameters:
  • data: Data to hash
Returns: 32-byte hash
Example:
let h = hash(b"data");

Order-Preserving Encryption

pub fn ope_encrypt(plaintext: u64, key: &[u8]) -> u64
Encrypts 64-bit integer while preserving order. Parameters:
  • plaintext: Integer value to encrypt
  • key: Encryption key
Returns: Encrypted integer preserving order
Example:
let encrypted = ope_encrypt(42, key);
assert!(encrypted < ope_encrypt(43, key)); // Order preserved

Noise Protocol

pub fn noise_handshake(initiator: bool) -> Result<Session, NoiseError>
Establishes Noise XK protocol handshake. Parameters:
  • initiator: true if initiating handshake
Returns: Result&lt;Session, NoiseError&gt; containing session
Errors: NoiseError::HandshakeFailed if protocol fails
Example:
match noise_handshake(true) {
    Ok(session) => println!("Handshake successful"),
    Err(e) => eprintln!("Handshake failed: {}", e),
}

AEAD Encryption

pub fn aead_encrypt(plaintext: &[u8], key: &[u8], nonce: &[u8]) -> Result<Vec<u8>, CryptoError>
Encrypts data with AEAD (authenticated encryption). Parameters:
  • plaintext: Data to encrypt
  • key: 32-byte encryption key
  • nonce: 12-byte nonce (unique per message)
Returns: Result<Vec&lt;u8&gt;, CryptoError> containing ciphertext
Errors: CryptoError::InvalidKey, CryptoError::EncryptionFailed
Example:
let ciphertext = aead_encrypt(b"secret", key, nonce)?;

pub fn aead_decrypt(ciphertext: &[u8], key: &[u8], nonce: &[u8]) -> Result<Vec<u8>, CryptoError>
Decrypts AEAD-encrypted data. Parameters:
  • ciphertext: Encrypted data
  • key: 32-byte encryption key
  • nonce: 12-byte nonce used for encryption
Returns: Result<Vec&lt;u8&gt;, CryptoError> containing plaintext
Errors: CryptoError::InvalidKey, CryptoError::DecryptionFailed, CryptoError::AuthenticationFailed
Example:
let plaintext = aead_decrypt(&ciphertext, key, nonce)?;

Time Utilities

pub struct LamportClock {
    value: u64,
}

impl LamportClock {
    pub fn new() -> Self
    pub fn increment(&mut self)
    pub fn update(&mut self, other: u64)
    pub fn value(&self) -> u64
}
Lamport clock for causal ordering. Example:
let mut clock = LamportClock::new();
clock.increment();
clock.update(other_clock_value);
let ts = clock.value();

WEAVE P2P Module

Location: .tcproto/mesh-node/src/

Mesh Node

pub struct MeshNode {
    pub node_id: String,
    pub underlay: String,
    pub latency_budget_ms: u64,
}

impl MeshNode {
    pub fn new(node_id: &str, underlay: &str) -> Self
    pub fn broadcast(&mut self, message: &str) -> Result<(), WeaveError>
    pub fn receive(&self) -> Option<String>
    pub fn latency_percentile(&self) -> (f64, f64, f64) // (p50, p95, p99)
}
Represents a node in the mesh network. Example:
let mut node = MeshNode::new("node-1", "WebRTC");
node.broadcast("message")?;
let (p50, p95, p99) = node.latency_percentile();

Underlay Support

pub enum TransportUnderlay {
    WebRTC,
    QUIC,
    BLE,
    WiFiDirect,
}
Supported transport layers.

ForkNode CRDT Module

Location: .tcproto/fork-node/src/

LSEQ Identifiers

pub struct LseqIdentifier {
    pub sequence: Vec<(u64, u64)>, // (digit, replica_id) pairs
}

impl LseqIdentifier {
    pub fn new() -> Self
    pub fn between(left: &LseqIdentifier, right: &LseqIdentifier) -> Self
    pub fn compare(&self, other: &LseqIdentifier) -> Ordering
}
Position identifier for CRDT. Example:
let pos1 = LseqIdentifier::new();
let pos2 = LseqIdentifier::between(&pos1, &other);

Three-Way Merge

pub fn three_way_merge(
    base: &Timeline,
    branch_a: &Timeline,
    branch_b: &Timeline,
) -> Result<Timeline, MergeError>
Performs deterministic merge of two diverged timelines. Parameters:
  • base: Common ancestor timeline
  • branch_a: First branch
  • branch_b: Second branch
Returns: Result&lt;Timeline, MergeError&gt; containing merged timeline
Errors: MergeError::ConflictUnresolvable
Example:
let merged = three_way_merge(&base, &branch_a, &branch_b)?;

TNP Navigation Module

Location: .tcproto/tnp-node/src/

Fork Detection

pub fn detect_fork(timeline_a: &Timeline, timeline_b: &Timeline) -> Option<(u64, u64)>
Detects divergence point between timelines. Parameters:
  • timeline_a: First timeline
  • timeline_b: Second timeline
Returns: Option&lt;(u64, u64)&gt; containing (common_length, divergence_point)
Example:
if let Some((common, diverge)) = detect_fork(&timeline_a, &timeline_b) {
    println!("Fork at position {}", diverge);
}

pub fn navigate_to_operation(
    timeline: &Timeline,
    operation_id: u64,
) -> Result<Operation, NavigationError>
Retrieves operation from timeline. Parameters:
  • timeline: Timeline to search
  • operation_id: Operation ID
Returns: Result&lt;Operation, NavigationError&gt;
Errors: NavigationError::OperationNotFound
Example:
let op = navigate_to_operation(&timeline, 42)?;

VEST Audit Module

Location: .tcproto/vest-node/src/

Sealing

pub fn seal_timeline(
    timeline: &Timeline,
    keypair: &(PublicKey, SecretKey),
) -> Result<Seal, VestError>
Creates immutable seal of timeline state. Parameters:
  • timeline: Timeline to seal
  • keypair: Ed25519 keypair for signing
Returns: Result&lt;Seal, VestError&gt; containing seal
Errors: VestError::SealFailed
Example:
let seal = seal_timeline(&timeline, &keypair)?;

Audit Trail

pub struct AuditTrail {
    entries: Vec<AuditEntry>,
}

impl AuditTrail {
    pub fn new() -> Self
    pub fn record(&mut self, entry: AuditEntry)
    pub fn verify(&self) -> Result<(), VestError>
    pub fn get_entries(&self) -> &[AuditEntry]
}
Immutable audit log. Example:
let mut trail = AuditTrail::new();
trail.record(entry);
trail.verify()?;

Merkle Proofs

pub fn generate_merkle_proof(
    trail: &AuditTrail,
    entry_index: usize,
) -> Result<MerkleProof, VestError>
Generates proof of inclusion in audit trail. Parameters:
  • trail: Audit trail
  • entry_index: Index of entry to prove
Returns: Result&lt;MerkleProof, VestError&gt;
Example:
let proof = generate_merkle_proof(&trail, 0)?;

ForkNode-VEST Hybrid Module

Location: .tcproto/forknode-vest/src/

Encrypted CRDT

pub struct EncryptedTimeline {
    encrypted_data: Vec<u8>,
    public_commitments: Vec<u8>,
}

impl EncryptedTimeline {
    pub fn new(timeline: &Timeline, key: &[u8]) -> Result<Self, HybridError>
    pub fn homomorphic_merge(
        &self,
        other: &EncryptedTimeline,
    ) -> Result<EncryptedTimeline, HybridError>
    pub fn decrypt(&self, key: &[u8]) -> Result<Timeline, HybridError>
}
End-to-end encrypted CRDT with searchable index. Example:
let encrypted = EncryptedTimeline::new(&timeline, key)?;
let merged = encrypted.homomorphic_merge(&other)?;
let decrypted = merged.decrypt(key)?;

System Integration Module

Location: .tcproto/system/src/

Protocol Stack

pub struct ProtocolStack {
    layers: Vec<Box<dyn Layer>>,
}

impl ProtocolStack {
    pub fn new() -> Self
    pub fn add_layer(&mut self, layer: Box<dyn Layer>)
    pub fn execute_operation(&mut self, op: &Operation) -> Result<OperationResult, StackError>
    pub fn architecture(&self) -> ArchitectureType
}
6-layer protocol orchestration. Example:
let mut stack = ProtocolStack::new();
stack.add_layer(Box::new(CryptoLayer::new()));
let result = stack.execute_operation(&op)?;

Latency Monitor

pub struct LatencyMonitor {
    percentiles: PercentileTracker,
}

impl LatencyMonitor {
    pub fn new() -> Self
    pub fn record(&mut self, latency_ms: f64)
    pub fn p50(&self) -> f64
    pub fn p95(&self) -> f64
    pub fn p99(&self) -> f64
    pub fn mean(&self) -> f64
}
Tracks operation latency percentiles. Example:
let mut monitor = LatencyMonitor::new();
monitor.record(5.3);
println!("P99: {}ms", monitor.p99());

AEGIS Access Control Module

Location: .tcproto/aegis-node/src/

Zero-Knowledge Proofs

pub fn generate_zk_proof(
    credential: &Credential,
    statement: &Statement,
) -> Result<Proof, AegisError>
Generates server-blind ZK proof. Parameters:
  • credential: User credential
  • statement: Statement to prove
Returns: Result&lt;Proof, AegisError&gt;
Example:
let proof = generate_zk_proof(&credential, &statement)?;

Access Control

pub struct AccessControl {
    permissions: HashMap<String, Permission>,
}

impl AccessControl {
    pub fn new() -> Self
    pub fn grant_permission(&mut self, user: &str, perm: Permission)
    pub fn check_permission(&self, user: &str, action: &str) -> bool
    pub fn revoke_permission(&mut self, user: &str)
}
Permission management. Example:
let mut ac = AccessControl::new();
ac.grant_permission("user1", Permission::Read);
assert!(ac.check_permission("user1", "read"));

Deployment Module

Location: .tcproto/deployment/src/

Configuration

pub struct Config {
    pub settings: HashMap<String, String>,
}

impl Config {
    pub fn for_environment(env: &Environment) -> Result<Self, String>
    pub fn add_setting(&mut self, key: &str, value: &str)
    pub fn get_setting(&self, key: &str) -> Option<String>
    pub fn validate(&self) -> Result<(), String>
}
Environment-based configuration. Example:
let config = Config::for_environment(&Environment::Production)?;

Deployment Manager

pub struct DeploymentManager {
    pub strategy: DeploymentStrategy,
}

impl DeploymentManager {
    pub fn new(config: Config, strategy: DeploymentStrategy) -> Self
    pub fn deploy(&mut self) -> Result<(), String>
    pub fn graceful_shutdown(&mut self) -> Result<(), String>
    pub fn is_healthy(&self) -> bool
}
Deployment lifecycle management. Example:
let mut dm = DeploymentManager::new(config, DeploymentStrategy::RollingUpdate);
dm.deploy()?;

Orchestration

pub struct Orchestration {
    pub nodes: HashMap<String, NodeStatus>,
}

impl Orchestration {
    pub fn new(config: Config) -> Self
    pub fn setup(&mut self) -> Result<(), String>
    pub fn running_nodes(&self) -> usize
    pub fn total_nodes(&self) -> usize
    pub fn scale_service(&mut self, service: &str, replicas: usize) -> Result<(), String>
}
Multi-node Kubernetes coordination. Example:
let mut orch = Orchestration::new(config);
orch.setup()?;
orch.scale_service("timechain-core", 5)?;

Monitoring

pub struct Monitoring {
    pub metrics: HashMap<String, f64>,
}

impl Monitoring {
    pub fn new(config: Config) -> Self
    pub fn initialize(&mut self) -> Result<(), String>
    pub fn record_metric(&mut self, name: &str, value: f64)
    pub fn check_service_health(&mut self, service: &str) -> Result<bool, String>
}
Prometheus metrics and health monitoring. Example:
let mut mon = Monitoring::new(config);
mon.initialize()?;
mon.record_metric("requests_total", 1000.0);

Backup & Restore

pub struct BackupRestore {
    pub backups: HashMap<String, BackupMetadata>,
}

impl BackupRestore {
    pub fn new(config: Config) -> Self
    pub fn backup(&mut self, backup_id: &str) -> Result<(), String>
    pub fn restore(&mut self, backup_id: &str) -> Result<(), String>
    pub fn migrate(&mut self, source: &str, target_env: &str) -> Result<(), String>
}
Disaster recovery management. Example:
let mut br = BackupRestore::new(config);
br.backup("backup-001")?;
br.restore("backup-001")?;

Benchmarks Module

Location: .tcproto/benchmarks/

Benchmark Results

pub struct BenchmarkResult {
    pub name: String,
    pub p50_ms: f64,
    pub p95_ms: f64,
    pub p99_ms: f64,
    pub mean_ms: f64,
    pub operations: usize,
}

impl BenchmarkResult {
    pub fn new(name: &str, samples: &[f64]) -> Self
    pub fn meets_target(&self, target_ms: f64) -> bool
    pub fn print_summary(&self)
}
Performance benchmark results. Example:
let result = BenchmarkResult::new("latency", &samples);
if result.meets_target(10.0) {
    println!("SLA met!");
}
result.print_summary();

SLA Validation

pub struct SLAValidator;

impl SLAValidator {
    pub fn check_latency(name: &str, actual_ms: f64, target_ms: f64) -> bool
    pub fn check_throughput(name: &str, actual_ops_per_sec: f64, target_ops_per_sec: f64) -> bool
    pub fn check_storage_overhead(name: &str, actual_ratio: f64, target_ratio: f64) -> bool
}
SLA validation utilities. Example:
let passes = SLAValidator::check_latency("operation", 8.5, 11.0);

Error Handling

All modules return Result&lt;T, ErrorType&gt; for error handling.

Common Error Types

pub enum CryptoError {
    InvalidKey,
    SignatureFailed,
    EncryptionFailed,
    DecryptionFailed,
    AuthenticationFailed,
}

pub enum MergeError {
    ConflictUnresolvable,
    InvalidTimeline,
}

pub enum NavigationError {
    OperationNotFound,
    InvalidIndex,
}

pub enum VestError {
    SealFailed,
    VerificationFailed,
    ProofGeneration,
}

pub enum WeaveError {
    BroadcastFailed,
    ReceiveFailed,
    TransportError,
}

pub enum DeploymentErrorType {
    ConfigError(String),
    OrchestrationError(String),
    MonitoringError(String),
    BackupError(String),
    DeploymentFailed(String),
}

Example Usage

Complete End-to-End Flow

use timechain::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Cryptography
    let (pub_key, sec_key) = crypto::generate_keypair();
    let message = b"Operation data";
    let signature = crypto::sign(message, &sec_key);
    crypto::verify(message, &signature, &pub_key)?;

    // 2. P2P Broadcast
    let mut node = MeshNode::new("node-1", "WebRTC");
    node.broadcast("message")?;

    // 3. CRDT Operations
    let pos = LseqIdentifier::new();
    let timeline = create_timeline(vec![pos]);

    // 4. Audit Trail
    let seal = seal_timeline(&timeline, &(pub_key, sec_key))?;

    // 5. Deployment
    let config = Config::for_environment(&Environment::Production)?;
    let mut deployment = DeploymentManager::new(config, DeploymentStrategy::Rolling Update);
    deployment.deploy()?;

    Ok(())
}

Contributing

To extend the API:
  1. Implement trait in target module
  2. Add unit tests
  3. Update API reference
  4. Ensure backward compatibility

API Version: 1.0.0
Last Updated: December 6, 2025
Status: Production Ready ✅