use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use rand::rngs::OsRng;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct IntentReceipt {
pub sponsor_did: String,
pub pcard_handle: String,
pub intent: String,
pub intent_hash: String,
pub signature: String,
pub timestamp: String,
}
pub fn derive_did_key(pubkey_bytes: &[u8; 32]) -> String {
let mut multicodec = Vec::with_capacity(34);
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)
}
pub fn did_to_pubkey_bytes(did: &str) -> Result<[u8; 32], String> {
let b58_part = did
.strip_prefix("did:key:z")
.ok_or_else(|| format!("Invalid did:key format: {}", did))?;
let decoded = bs58::decode(b58_part)
.into_vec()
.map_err(|e| format!("Base58 decode failed: {}", e))?;
if decoded.len() < 34 || decoded[0] != 0xed || decoded[1] != 0x01 {
return Err("Invalid multicodec prefix for Ed25519 did:key".to_string());
}
let mut key_bytes = [0u8; 32];
key_bytes.copy_from_slice(&decoded[2..34]);
Ok(key_bytes)
}
pub fn generate_keypair() -> (SigningKey, String) {
let signing_key = SigningKey::generate(&mut OsRng);
let verifying_key = signing_key.verifying_key();
let did = derive_did_key(verifying_key.as_bytes());
(signing_key, did)
}
pub fn format_sign_payload(pcard_handle: &str, intent_hash: &str, timestamp: &str) -> Vec<u8> {
format!("{}:{}:{}", pcard_handle, intent_hash, timestamp).into_bytes()
}
pub fn sign_intent(
signing_key: &SigningKey,
pcard_handle: &str,
intent: &str,
timestamp: &str,
) -> IntentReceipt {
let intent_hash = crate::layer0::hash::compute_blake3(intent.as_bytes());
let sponsor_did = derive_did_key(signing_key.verifying_key().as_bytes());
let payload = format_sign_payload(pcard_handle, &intent_hash, timestamp);
let signature = signing_key.sign(&payload);
let sig_hex = hex::encode(signature.to_bytes());
IntentReceipt {
sponsor_did,
pcard_handle: pcard_handle.to_string(),
intent: intent.to_string(),
intent_hash,
signature: sig_hex,
timestamp: timestamp.to_string(),
}
}
pub fn verify_signature(
sponsor_did: &str,
pcard_handle: &str,
intent_hash: &str,
timestamp: &str,
signature_hex: &str,
) -> bool {
let pubkey_bytes = match did_to_pubkey_bytes(sponsor_did) {
Ok(b) => b,
Err(_) => return false,
};
let verifying_key = match VerifyingKey::from_bytes(&pubkey_bytes) {
Ok(vk) => vk,
Err(_) => return false,
};
let sig_bytes = match hex::decode(signature_hex) {
Ok(sb) => sb,
Err(_) => return false,
};
if sig_bytes.len() != 64 {
return false;
}
let mut sig_arr = [0u8; 64];
sig_arr.copy_from_slice(&sig_bytes);
let signature = Signature::from_bytes(&sig_arr);
let payload = format_sign_payload(pcard_handle, intent_hash, timestamp);
verifying_key.verify(&payload, &signature).is_ok()
}