clm-kernel 0.0.22

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use crate::Commands;

pub fn run_cross_pkc_cli(command: Commands, _clm_root: &str)  {
    match command {
        Commands::CrossPkcDispatch { pcard, target, input, endpoint } => {
            use clm_rust_core::federation::{CrossPkcDispatchRequest, dispatch_cross_pkc, co_sign_vcard};
            use clm_rust_core::quic_transport::QuicEndpoint;
            use clm_rust_core::sheaf::Marking;

            let target_endpoint = endpoint.unwrap_or_else(|| {
                eprintln!("[cross-pkc-dispatch] --endpoint is required");
                std::process::exit(1);
            });

            let input_marking: Marking = serde_json::from_str(&input)
                .unwrap_or_else(|e| {
                    eprintln!("[cross-pkc-dispatch] Failed to parse --input JSON: {}", e);
                    std::process::exit(1);
                });

            let source_did = clm_rust_core::layer0::environment::var(clm_rust_core::layer0::vocabulary_env::ENV_CLM_NODE_DID)
                .unwrap_or_else(|_| clm_rust_core::layer0::vocabulary_identities::DID_PKC_LOCAL.to_string());

            let request = CrossPkcDispatchRequest {
                pcard_hash: pcard.clone(),
                input_marking,
                source_pkc_did: source_did.clone(),
                target_pkc_did: target.clone(),
            };

            let client = QuicEndpoint::new_client().unwrap_or_else(|e| {
                eprintln!("[cross-pkc-dispatch] Failed to create QUIC client: {}", e);
                std::process::exit(1);
            });

            let rt = tokio::runtime::Runtime::new().unwrap();
            let result = rt.block_on(async {
                tokio::time::timeout(
                    std::time::Duration::from_secs(5),
                    async {
                        let conn = client.connect(&target_endpoint, "cross-pkc-dispatch").await?;
                        dispatch_cross_pkc(&request, &conn).await
                    },
                ).await
            });

            match result {
                Ok(Ok(response)) => {
                    let co_signed = co_sign_vcard(&response, &source_did, &target);
                    println!("{}", serde_json::to_string_pretty(&co_signed).unwrap());
                    std::process::exit(0);
                }
                Ok(Err(e)) => {
                    eprintln!("[cross-pkc-dispatch] Dispatch failed: {}", e);
                    std::process::exit(1);
                }
                Err(_) => {
                    eprintln!("[cross-pkc-dispatch] Timeout: target PKC unreachable after 5s");
                    std::process::exit(1);
                }
            }
        }
        _ => std::process::exit(0),
    }
}

pub fn run_logic(command: Commands, clm_root: &str) -> (i32, String, String) {
    let mut stdout = String::new();
    let mut stderr = String::new();

    match command {
        Commands::DidGenerate => {
            match clm_rust_core::identity::generate_ed25519_keypair() {
                Ok(identity) => {
                    stdout.push_str(&format!("[DID GENERATE] Generated identity:\n  DID: {}\n  Public Key (bs58): {}\n  Private Key (hex): {}\n", identity.did, identity.public_key_bs58, identity.private_key_hex));
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[DID GENERATE ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::DidRegister { did, public_key, db } => {
            match clm_rust_core::identity::register_did(&db, Some(clm_root), &did, &public_key) {
                Ok(rec) => {
                    stdout.push_str(&format!("[DID REGISTER] Registered DID {} in {}\n", rec.did, db));
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[DID REGISTER ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::SbtIssue { did, sbt_type, capability, db } => {
            match clm_rust_core::identity::issue_sbt(&db, Some(clm_root), &did, &sbt_type, &capability) {
                Ok(sbt) => {
                    stdout.push_str(&format!("[SBT ISSUE] Issued token {} bound to {} ({}:{})\n", sbt.token_id, sbt.did_binding, sbt.sbt_type, sbt.capability));
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[SBT ISSUE ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::SbtVerify { did, sbt_type, db } => {
            match clm_rust_core::identity::verify_sbt(&db, Some(clm_root), &did, &sbt_type) {
                Ok(is_valid) => {
                    if is_valid {
                        stdout.push_str(&format!("[SBT VERIFY] ✅ DID {} holds active SBT type {}\n", did, sbt_type));
                        (0, stdout, stderr)
                    } else {
                        stdout.push_str(&format!("[SBT VERIFY] ❌ DID {} does NOT hold active SBT type {}\n", did, sbt_type));
                        (1, stdout, stderr)
                    }
                }
                Err(e) => {
                    stderr.push_str(&format!("[SBT VERIFY ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::AuthConfigMint { handle, content, db } => {
            match clm_rust_core::auth_namespace::mint_auth_mcard(&db, Some(clm_root), &handle, &content) {
                Ok(hash) => {
                    stdout.push_str(&format!("[AUTH MINT] Minted auth MCard {} -> hash {}\n", handle, hash));
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[AUTH MINT ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::AuthConfigList { pattern, db } => {
            match clm_rust_core::auth_namespace::list_auth_mcards(&db, Some(clm_root), &pattern) {
                Ok(list) => {
                    stdout.push_str(&format!("[AUTH LIST] Found {} auth MCard(s) in {}:\n", list.len(), db));
                    for (h, hash) in &list {
                        stdout.push_str(&format!("  - {} -> {}\n", h, hash));
                    }
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[AUTH LIST ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::AuthChallenge { did } => {
            let record = clm_rust_core::auth_did::generate_auth_challenge(&did);
            stdout.push_str(&format!("[AUTH CHALLENGE] Generated challenge for {}:\n  Nonce: {}\n  Challenge: {}\n", record.did, record.nonce, record.challenge));
            (0, stdout, stderr)
        }
        Commands::AuthSign { challenge, private_key } => {
            match clm_rust_core::auth_did::sign_auth_challenge(&challenge, &private_key) {
                Ok(sig) => {
                    stdout.push_str(&format!("[AUTH SIGN] Signature: {}\n", sig));
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[AUTH SIGN ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::AuthVerify { did, public_key, challenge, signature, db } => {
            match clm_rust_core::auth_did::verify_auth_challenge(&did, &public_key, &challenge, &signature) {
                Ok(is_valid) => {
                    if is_valid {
                        match clm_rust_core::auth_did::mint_vcard_auth_token(&db, Some(clm_root), &did, 3600) {
                            Ok(token) => {
                                stdout.push_str(&format!("[AUTH VERIFY] ✅ Ed25519 signature valid!\n[VCARD TOKEN MINTED] Session ID: {}\n  Handle: {}\n  Expiry: {}\n", token.session_id, token.handle, token.expiry));
                                (0, stdout, stderr)
                            }
                            Err(e) => {
                                stderr.push_str(&format!("[AUTH TOKEN MINT ERROR] {}\n", e));
                                (1, stdout, stderr)
                            }
                        }
                    } else {
                        stdout.push_str("[AUTH VERIFY] ❌ Ed25519 signature verification failed!\n");
                        (1, stdout, stderr)
                    }
                }
                Err(e) => {
                    stderr.push_str(&format!("[AUTH VERIFY ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::AuthTokenVerify { session_id, db } => {
            match clm_rust_core::auth_did::verify_vcard_auth_token(&db, Some(clm_root), &session_id) {
                Ok(is_valid) => {
                    if is_valid {
                        stdout.push_str(&format!("[AUTH TOKEN VERIFY] ✅ Session token {} is active and valid\n", session_id));
                        (0, stdout, stderr)
                    } else {
                        stdout.push_str(&format!("[AUTH TOKEN VERIFY] ❌ Session token {} is expired or invalid\n", session_id));
                        (1, stdout, stderr)
                    }
                }
                Err(e) => {
                    stderr.push_str(&format!("[AUTH TOKEN VERIFY ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::IdpRegister { provider_id, provider_type, issuer_url, client_id, db } => {
            match clm_rust_core::auth_oidc::register_idp_provider(&db, Some(clm_root), &provider_id, &provider_type, &issuer_url, &client_id) {
                Ok(rec) => {
                    stdout.push_str(&format!("[IDP REGISTER] Registered IdP {} ({}) at {}\n  Handle: {}\n  Hash: {}\n", rec.provider_id, rec.provider_type, rec.issuer_url, rec.handle, rec.content_hash));
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[IDP REGISTER ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::IdpList { db } => {
            match clm_rust_core::auth_oidc::list_registered_idps(&db, Some(clm_root)) {
                Ok(list) => {
                    stdout.push_str(&format!("[IDP LIST] Found {} registered IdP provider(s) in {}:\n", list.len(), db));
                    for (h, hash) in &list {
                        stdout.push_str(&format!("  - {} -> {}\n", h, hash));
                    }
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[IDP LIST ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::AuthOidcExchange { provider_id, sub, email, db } => {
            match clm_rust_core::auth_oidc::bridge_oidc_jwt_to_did(&db, Some(clm_root), &provider_id, &sub, email.as_deref()) {
                Ok(res) => {
                    stdout.push_str(&format!("[OIDC EXCHANGE] ✅ OIDC JWT bridged for {} (sub: {})\n  Mapped DID: {}\n  Session ID: {}\n  Token Handle: {}\n", res.provider_id, res.subject, res.mapped_did, res.session_id, res.token_handle));
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[OIDC EXCHANGE ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::AuthSiweExchange { wallet, signature, message, db } => {
            match clm_rust_core::auth_oidc::bridge_siwe_to_did(&db, Some(clm_root), &wallet, &signature, &message) {
                Ok(res) => {
                    stdout.push_str(&format!("[SIWE EXCHANGE] ✅ SIWE Web3 wallet bridged for {}\n  Mapped DID: {}\n  Session ID: {}\n  Token Handle: {}\n", res.subject, res.mapped_did, res.session_id, res.token_handle));
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[SIWE EXCHANGE ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::PaymentRailRegister { rail_id, rail_type, db } => {
            match clm_rust_core::payment::register_payment_rail(&db, Some(clm_root), &rail_id, &rail_type, None) {
                Ok(rec) => {
                    stdout.push_str(&format!("[PAYMENT RAIL REGISTER] Registered rail {} ({}) in {}\n  Handle: {}\n  Hash: {}\n", rec.rail_id, rec.rail_type, db, rec.handle, rec.content_hash));
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[PAYMENT RAIL REGISTER ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::PaymentInvoiceCreate { buyer, merchant, amount, currency, db } => {
            match clm_rust_core::payment::create_payment_invoice(&db, Some(clm_root), &buyer, &merchant, amount, &currency) {
                Ok(inv) => {
                    stdout.push_str(&format!("[PAYMENT INVOICE CREATE] Created invoice {} for {} -> {} ({} {})\n  Handle: {}\n  Hash: {}\n", inv.invoice_id, inv.buyer_did, inv.merchant_did, inv.amount, inv.currency, inv.handle, inv.content_hash));
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[PAYMENT INVOICE CREATE ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::PaymentProcess { invoice_id, rail_id, db } => {
            match clm_rust_core::payment::process_payment_pcard(&db, Some(clm_root), &invoice_id, &rail_id, None) {
                Ok(rec) => {
                    stdout.push_str(&format!("[PAYMENT PROCESS] ✅ Settled invoice {} via rail {}\n  Transaction ID: {}\n  Receipt Handle: {}\n  Status: {}\n", rec.invoice_id, rec.rail_id, rec.tx_id, rec.handle, rec.status));
                    (0, stdout, stderr)
                }
                Err(e) => {
                    stderr.push_str(&format!("[PAYMENT PROCESS ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        Commands::PaymentReceiptVerify { tx_id, db } => {
            match clm_rust_core::payment::verify_payment_receipt(&db, Some(clm_root), &tx_id) {
                Ok(is_valid) => {
                    if is_valid {
                        stdout.push_str(&format!("[PAYMENT RECEIPT VERIFY] ✅ Payment receipt {} is valid and settled\n", tx_id));
                        (0, stdout, stderr)
                    } else {
                        stdout.push_str(&format!("[PAYMENT RECEIPT VERIFY] ❌ Payment receipt {} is invalid or unsettled\n", tx_id));
                        (1, stdout, stderr)
                    }
                }
                Err(e) => {
                    stderr.push_str(&format!("[PAYMENT RECEIPT VERIFY ERROR] {}\n", e));
                    (1, stdout, stderr)
                }
            }
        }
        _ => (0, String::new(), String::new()),
    }
}