clm-kernel 0.0.17

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! DID Generation, agent_identities.db Seeding, and Soul Bound Token (SBT) Capability Binding
//! Unifying Decentralized Identifiers (did:key) and non-transferable capability tokens.

use ed25519_dalek::SigningKey;
use rand::rngs::OsRng;
use serde::{Deserialize, Serialize};
#[cfg(any(feature = "native", feature = "db"))]
use std::fs;
#[cfg(any(feature = "native", feature = "db"))]
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Ed25519Identity {
    pub did: String,
    pub public_key_bs58: String,
    pub private_key_hex: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DidRecord {
    pub did: String,
    pub public_key: String,
    pub created_at: String,
    pub status: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SbtTokenRecord {
    pub token_id: String,
    pub did_binding: String,
    pub sbt_type: String,
    pub capability: String,
    pub issued_at: String,
    pub is_active: bool,
}

/// Generates an Ed25519 keypair and derives the corresponding W3C `did:key:z6Mk...` identifier.
pub fn generate_ed25519_keypair() -> Result<Ed25519Identity, String> {
    let mut csprng = OsRng;
    let signing_key = SigningKey::generate(&mut csprng);
    let verifying_key = signing_key.verifying_key();

    let pubkey_bytes = verifying_key.as_bytes();
    let privkey_bytes = signing_key.to_bytes();

    let did = derive_did_key(pubkey_bytes);
    let public_key_bs58 = bs58::encode(pubkey_bytes).into_string();
    let private_key_hex = hex::encode(privkey_bytes);

    Ok(Ed25519Identity {
        did,
        public_key_bs58,
        private_key_hex,
    })
}

/// Derives a `did:key` string from a 32-byte Ed25519 public key using multicodec prefix 0xed01.
pub fn derive_did_key(pubkey_bytes: &[u8]) -> String {
    let mut multicodec = Vec::with_capacity(2 + pubkey_bytes.len());
    multicodec.push(0xed);
    multicodec.push(0x01);
    multicodec.extend_from_slice(pubkey_bytes);

    let base58_encoded = bs58::encode(&multicodec).into_string();
    format!("did:key:z{}", base58_encoded)
}

/// Resolves database path for `agent_identities.db`.
#[cfg(any(feature = "native", feature = "db"))]
fn resolve_identity_db_path(db_name_or_path: &str, clm_root: Option<&str>) -> PathBuf {
    let p = Path::new(db_name_or_path);
    if p.is_absolute() || db_name_or_path.contains('/') || db_name_or_path.ends_with(".db") {
        p.to_path_buf()
    } else {
        let root = clm_root.map(PathBuf::from).unwrap_or_else(|| {
            std::env::var("CLM_ROOT").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from("."))
        });
        root.join("db").join(db_name_or_path)
    }
}

/// Ensures required SQLite tables exist in `agent_identities.db`.
#[cfg(any(feature = "native", feature = "db"))]
fn ensure_identity_tables(conn: &rusqlite::Connection) -> Result<(), String> {
    conn.execute(
        "CREATE TABLE IF NOT EXISTS agent_did (
            did TEXT PRIMARY KEY,
            public_key TEXT NOT NULL,
            created_at TEXT NOT NULL,
            status TEXT NOT NULL
        );",
        [],
    ).map_err(|e| format!("Failed to create agent_did table: {}", e))?;

    conn.execute(
        "CREATE TABLE IF NOT EXISTS sbt_token (
            token_id TEXT PRIMARY KEY,
            did_binding TEXT NOT NULL,
            sbt_type TEXT NOT NULL,
            capability TEXT NOT NULL,
            issued_at TEXT NOT NULL,
            is_active INTEGER NOT NULL,
            FOREIGN KEY(did_binding) REFERENCES agent_did(did)
        );",
        [],
    ).map_err(|e| format!("Failed to create sbt_token table: {}", e))?;

    Ok(())
}

/// Registers a DID identity into `agent_identities.db`.
#[cfg(any(feature = "native", feature = "db"))]
pub fn register_did(db_name_or_path: &str, clm_root: Option<&str>, did: &str, public_key: &str) -> Result<DidRecord, String> {
    let db_path = resolve_identity_db_path(db_name_or_path, clm_root);
    if let Some(parent) = db_path.parent() {
        let _ = fs::create_dir_all(parent);
    }

    let conn = rusqlite::Connection::open(&db_path).map_err(|e| e.to_string())?;
    ensure_identity_tables(&conn)?;

    let now = chrono::Utc::now().to_rfc3339();
    let status = "active";

    conn.execute(
        "INSERT OR REPLACE INTO agent_did (did, public_key, created_at, status) VALUES (?1, ?2, ?3, ?4);",
        rusqlite::params![did, public_key, now, status],
    ).map_err(|e| format!("Failed to register DID in SQLite: {}", e))?;

    Ok(DidRecord {
        did: did.to_string(),
        public_key: public_key.to_string(),
        created_at: now,
        status: status.to_string(),
    })
}

/// Issues a Soul Bound Token (SBT) bound to a DID in `agent_identities.db`.
/// Enforces non-transferability: an existing token bound to another DID cannot be re-assigned.
#[cfg(any(feature = "native", feature = "db"))]
pub fn issue_sbt(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    did: &str,
    sbt_type: &str,
    capability: &str,
) -> Result<SbtTokenRecord, String> {
    let db_path = resolve_identity_db_path(db_name_or_path, clm_root);
    if let Some(parent) = db_path.parent() {
        let _ = fs::create_dir_all(parent);
    }

    let conn = rusqlite::Connection::open(&db_path).map_err(|e| e.to_string())?;
    ensure_identity_tables(&conn)?;

    let raw_seed = format!("sbt:{}:{}:{}", did, sbt_type, capability);
    let token_id = crate::hash::raw_hash_bytes(raw_seed.as_bytes());

    // Check if token_id exists bound to a different DID
    let existing_binding: Result<String, _> = conn.query_row(
        "SELECT did_binding FROM sbt_token WHERE token_id = ?1;",
        rusqlite::params![token_id],
        |row| row.get(0),
    );

    if let Ok(existing_did) = existing_binding
        && existing_did != did {
            return Err(format!(
                "SBT non-transferable error: token {} bound to DID {} cannot be re-assigned to {}",
                token_id, existing_did, did
            ));
        }

    let now = chrono::Utc::now().to_rfc3339();

    conn.execute(
        "INSERT OR REPLACE INTO sbt_token (token_id, did_binding, sbt_type, capability, issued_at, is_active) VALUES (?1, ?2, ?3, ?4, ?5, 1);",
        rusqlite::params![token_id, did, sbt_type, capability, now],
    ).map_err(|e| format!("Failed to issue SBT token: {}", e))?;

    Ok(SbtTokenRecord {
        token_id,
        did_binding: did.to_string(),
        sbt_type: sbt_type.to_string(),
        capability: capability.to_string(),
        issued_at: now,
        is_active: true,
    })
}

/// Verifies whether a DID holds an active Soul Bound Token (SBT) of a given sbt_type.
#[cfg(any(feature = "native", feature = "db"))]
pub fn verify_sbt(
    db_name_or_path: &str,
    clm_root: Option<&str>,
    did: &str,
    sbt_type: &str,
) -> Result<bool, String> {
    let db_path = resolve_identity_db_path(db_name_or_path, clm_root);
    if !db_path.exists() {
        return Ok(false);
    }

    let conn = rusqlite::Connection::open(&db_path).map_err(|e| e.to_string())?;
    ensure_identity_tables(&conn)?;

    let count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM sbt_token WHERE did_binding = ?1 AND sbt_type = ?2 AND is_active = 1;",
        rusqlite::params![did, sbt_type],
        |row| row.get(0),
    ).unwrap_or(0);

    Ok(count > 0)
}

// ── Unit Tests ─────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_did_key_derivation_format() {
        let identity = generate_ed25519_keypair().unwrap();
        assert!(identity.did.starts_with("did:key:z6Mk"), "DID should start with did:key:z6Mk, got {}", identity.did);
        assert!(!identity.public_key_bs58.is_empty());
        assert!(!identity.private_key_hex.is_empty());
    }

    #[test]
    #[cfg(any(feature = "native", feature = "db"))]
    fn test_identity_db_registration_and_sbt_non_transferable() {
        let tmp_db = std::env::temp_dir().join("clm_test_agent_identities.db");
        let _ = fs::remove_file(&tmp_db);

        let id = generate_ed25519_keypair().unwrap();
        let db_str = tmp_db.to_str().unwrap();

        // 1. Register DID
        let rec = register_did(db_str, None, &id.did, &id.public_key_bs58).unwrap();
        assert_eq!(rec.did, id.did);

        // 2. Issue SBT
        let sbt = issue_sbt(db_str, None, &id.did, "executor", "gate:agent_authorized").unwrap();
        assert_eq!(sbt.did_binding, id.did);

        // 3. Verify SBT
        let has_sbt = verify_sbt(db_str, None, &id.did, "executor").unwrap();
        assert!(has_sbt);

        let no_sbt = verify_sbt(db_str, None, &id.did, "non_existent_role").unwrap();
        assert!(!no_sbt);

        let _ = fs::remove_file(&tmp_db);
    }
}