Crate gun

Crate gun 

Source
Expand description

§Gun.rs - A Real-time, Decentralized, Offline-First Graph Database

Gun.rs is a Rust implementation of the Gun.js protocol, providing a real-time, decentralized, offline-first graph database. It enables peer-to-peer data synchronization without requiring a central server.

§Features

  • Real-time Synchronization: Automatic data synchronization with connected peers
  • Decentralized: P2P mesh networking - no central server required
  • Offline-First: Works locally and syncs when connected
  • Graph Database: Store data as a graph with nodes and relationships
  • Conflict Resolution: Automatic conflict resolution using state timestamps (HAM algorithm)
  • Cryptographic Security: BLS signatures for message authentication
  • Pluggable Storage: Memory, file-based (localStorage-like), or Sled database
  • WebRTC Support: Direct peer-to-peer connections with NAT traversal
  • WebSocket Support: Relay server connections for NAT traversal

§Quick Start

use gun::{Gun, GunOptions};
use chia_bls::{SecretKey, PublicKey};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Generate BLS key pair
    let secret_key = SecretKey::from_seed(&[0u8; 32]);
    let public_key = secret_key.public_key();

    // Create a local Gun instance
    let gun = Gun::new(secret_key, public_key);

    // Store data
    gun.get("user").put(json!({
        "name": "Alice",
        "age": 30
    })).await?;

    // Read data once
    gun.get("user").once(|data, _key| {
        println!("User: {:?}", data);
    }).await?;

    // Subscribe to updates
    gun.get("user").on(|data, _key| {
        println!("User updated: {:?}", data);
    });

    // Connect to peers (optional)
    let options = GunOptions {
        peers: vec!["ws://relay.example.com/gun".to_string()],
        ..Default::default()
    };
    let gun_with_peers = Gun::with_options(secret_key, public_key, options).await?;

    Ok(())
}

§Architecture

§Core Components

  • Gun: Main entry point - creates and manages Gun instances
  • Chain: Fluent API for data operations (get, put, on, once, map, set)
  • GunCore: Core engine managing graph, state, events, and storage
  • Graph: In-memory graph storage with conflict resolution
  • Mesh: DAM protocol implementation for P2P message routing
  • Storage: Pluggable storage backend trait

§Data Model

Gun uses a graph data model where:

  • Nodes: Identified by a unique “soul” (UUID-like string)
  • Properties: Key-value pairs on nodes
  • References: Links between nodes using soul references {"#": "soul_id"}
  • State: Timestamps for conflict resolution

§Conflict Resolution

Gun uses the HAM (Hypothetical Amnesia Machine) algorithm:

  • Each property update gets a state timestamp
  • Higher state wins in conflicts
  • Automatic merge of non-conflicting updates

§Network Protocol

Gun uses the DAM (Directed Acyclic Mesh) protocol:

  • Message deduplication to prevent loops
  • Automatic routing through peer mesh
  • Support for WebSocket relays and WebRTC direct connections

§Examples

See the examples/ directory for comprehensive examples including:

  • Basic operations (put, get, once, on)
  • Chain operations (get, put, back, map, set)
  • Network synchronization
  • Storage backends
  • WebRTC connections
  • Certificate-based security (SEA)

§Security

Gun.rs supports cryptographic security through:

  • BLS Signatures: All messages are signed and verified
  • SEA (Security, Encryption, Authorization): Certificate-based access control
  • Message Predicates: Custom filtering logic for incoming messages

§Performance

  • In-memory graph for fast reads
  • Persistent storage options for durability
  • Message batching and deduplication
  • Efficient conflict resolution algorithm

§Compatibility

Gun.rs aims to be compatible with Gun.js:

  • Same protocol and message format
  • Compatible graph structure
  • Interoperable with JavaScript peers

§License

See the LICENSE file for license information.

Re-exports§

pub use chain::Chain;
pub use error::GunError;
pub use gun::Gun;
pub use gun::GunOptions;
pub use types::MessagePredicate;
pub use valid::valid;
pub use valid::is_valid_data;
pub use valid::valid_soul;
pub use webrtc::WebRTCManager;
pub use webrtc::WebRTCOptions;
pub use webrtc::WebRTCPeer;
pub use sea::*;

Modules§

chain
core
dam
DAM (Directed Acyclic Mesh) protocol implementation
dup
Message deduplication for DAM protocol
error
Error types for Gun.rs
events
Event system for reactive updates
graph
Graph storage and conflict resolution
gun
sea
SEA (Security, Encryption, Authorization) module Based on Gun.js sea/ directory Provides encryption, authentication, and authorization capabilities
state
State management for conflict resolution
storage
Pluggable storage backends for persistent data
types
valid
Data validation and soul reference detection
webrtc
WebRTC implementation for direct peer-to-peer connections
websocket
WebSocket support for peer connections