use crate::layer0::vocabulary_identities::{DID_KEY_Z};
use std::collections::BTreeMap;
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use serde::{Deserialize, Serialize};
use super::gtime::{format_canonical_g_time, parse_g_time, GTimeForm, ParsedGTime};
pub const SIGNING_PREFIX: &str = "mcard-gtime-sig-v1\n";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttributionResult {
pub valid: bool,
pub signed: bool,
pub did: Option<String>,
pub reason: Option<String>,
}
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)
}
pub fn did_to_pubkey_bytes(did: &str) -> Result<[u8; 32], String> {
if !did.starts_with(crate::layer0::vocabulary_identities::DID_KEY_Z) {
return Err(format!("Invalid did:key prefix: {}", did));
}
let b58_part = &did[9..];
let decoded = bs58::decode(b58_part).into_vec().map_err(|e| e.to_string())?;
if decoded.len() < 34 || decoded[0] != 0xed || decoded[1] != 0x01 {
return Err(format!("Invalid multicodec prefix in did:key: {}", did));
}
let mut out = [0u8; 32];
out.copy_from_slice(&decoded[2..34]);
Ok(out)
}
pub fn signing_input(qualified_ref: &str, canonical_without_sig: &str) -> Vec<u8> {
format!("{}{}\n{}", SIGNING_PREFIX, qualified_ref, canonical_without_sig).into_bytes()
}
pub fn sign_g_time(
algo: &str,
qualified_ref: &str,
did: &str,
signing_key: &SigningKey,
timestamp: Option<&str>,
locale: Option<&str>,
kid: Option<&str>,
extra_extensions: Option<&BTreeMap<String, String>>,
) -> String {
let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
let ts = timestamp.unwrap_or(&now);
let loc = locale.unwrap_or("UTC");
let mut base_exts = BTreeMap::new();
base_exts.insert("did".to_string(), did.to_string());
if let Some(k) = kid {
base_exts.insert("kid".to_string(), k.to_string());
}
if let Some(extras) = extra_extensions {
for (k, v) in extras {
if k != "sig" {
base_exts.insert(k.clone(), v.clone());
}
}
}
let gtime_without_sig = format_canonical_g_time(algo, ts, loc, Some(&base_exts));
let preimage = signing_input(qualified_ref, >ime_without_sig);
let sig: Signature = signing_key.sign(&preimage);
let sig_hex = hex::encode(sig.to_bytes());
base_exts.insert("sig".to_string(), sig_hex);
format_canonical_g_time(algo, ts, loc, Some(&base_exts))
}
fn format_legacy_ts_gtime(
algo: &str,
timestamp: &str,
locale: &str,
extensions: &BTreeMap<String, String>,
) -> String {
let mut res = format!("a:{};t:{};c:{}", algo, timestamp, locale);
for (k, v) in extensions {
if !v.is_empty() {
res.push_str(&format!(";{}:{}", k, v));
}
}
res
}
pub fn verify_attribution(
hash: &str,
g_time: &str,
allowed_dids: Option<&[&str]>,
require_signature: bool,
) -> AttributionResult {
let parsed = parse_g_time(g_time);
match parsed {
ParsedGTime::Malformed(m) => AttributionResult {
valid: false,
signed: false,
did: None,
reason: Some(format!("Malformed g_time: {}", m.reason)),
},
ParsedGTime::Legacy(_) => {
if require_signature {
AttributionResult {
valid: false,
signed: false,
did: None,
reason: Some("Legacy g_time cannot carry an author signature".to_string()),
}
} else {
AttributionResult {
valid: true,
signed: false,
did: None,
reason: None,
}
}
}
ParsedGTime::Declared(declared) => {
let did = declared.extensions.get("did");
let sig_hex = declared.extensions.get("sig");
let Some(did_val) = did else {
return if require_signature {
AttributionResult {
valid: false,
signed: false,
did: None,
reason: Some("Missing author DID in declared g_time".to_string()),
}
} else {
AttributionResult {
valid: true,
signed: false,
did: None,
reason: None,
}
};
};
if let Some(allowed) = allowed_dids {
if !allowed.contains(&did_val.as_str()) {
return AttributionResult {
valid: false,
signed: sig_hex.is_some(),
did: Some(did_val.clone()),
reason: Some(format!("Author DID {} not in allowed list", did_val)),
};
}
}
let Some(sig_str) = sig_hex else {
return if require_signature {
AttributionResult {
valid: false,
signed: false,
did: Some(did_val.clone()),
reason: Some("Author DID declared but signature is missing".to_string()),
}
} else {
AttributionResult {
valid: true,
signed: false,
did: Some(did_val.clone()),
reason: None,
}
};
};
let sig_bytes = match hex::decode(sig_str) {
Ok(b) if b.len() == 64 => b,
Ok(b) => {
return AttributionResult {
valid: false,
signed: false,
did: Some(did_val.clone()),
reason: Some(format!("Invalid Ed25519 signature length: {} (expected 64)", b.len())),
};
}
Err(e) => {
return AttributionResult {
valid: false,
signed: false,
did: Some(did_val.clone()),
reason: Some(format!("Invalid signature hex: {}", e)),
};
}
};
let mut exts_without_sig = declared.extensions.clone();
exts_without_sig.remove("sig");
let canonical_without_sig = match declared.form {
GTimeForm::Pipe => format_canonical_g_time(
&declared.algorithm,
&declared.timestamp,
&declared.locale,
Some(&exts_without_sig),
),
GTimeForm::LegacyTs => format_legacy_ts_gtime(
&declared.algorithm,
&declared.timestamp,
&declared.locale,
&exts_without_sig,
),
};
let qualified_ref = if hash.contains(':') {
hash.to_string()
} else {
format!("{}:{}", declared.algorithm, hash)
};
let preimage = signing_input(&qualified_ref, &canonical_without_sig);
let pubkey_bytes = match did_to_pubkey_bytes(did_val) {
Ok(b) => b,
Err(e) => {
return AttributionResult {
valid: false,
signed: false,
did: Some(did_val.clone()),
reason: Some(format!("Failed to extract public key from DID: {}", e)),
};
}
};
let verifying_key = match VerifyingKey::from_bytes(&pubkey_bytes) {
Ok(k) => k,
Err(e) => {
return AttributionResult {
valid: false,
signed: false,
did: Some(did_val.clone()),
reason: Some(format!("Invalid VerifyingKey: {}", e)),
};
}
};
let mut sig_arr = [0u8; 64];
sig_arr.copy_from_slice(&sig_bytes);
let signature = Signature::from_bytes(&sig_arr);
match verifying_key.verify(&preimage, &signature) {
Ok(()) => AttributionResult {
valid: true,
signed: true,
did: Some(did_val.clone()),
reason: None,
},
Err(e) => AttributionResult {
valid: false,
signed: false,
did: Some(did_val.clone()),
reason: Some(format!("Ed25519 signature verification failed: {}", e)),
},
}
}
}
}