use crate::layer0::gtime::{DEFAULT_G_TIME_LOCALE, LEGACY_G_TIME_PREFIX};
#[cfg(any(feature = "native", feature = "db"))]
use rusqlite::Connection;
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
pub const CLM_SCHEMA_PCARD_DESCRIPTOR_V1: &str = crate::layer0::vocabulary::HANDLE_CLM_LAYER1_PCARD_DESCRIPTOR_V1;
pub const CLM_SCHEMA_DIRECTORY_MANIFEST_V1: &str = crate::layer0::vocabulary::HANDLE_CLM_LAYER2_DIRECTORY_MANIFEST_V1;
pub const CLM_SCHEMA_CHUNK_MANIFEST_V1: &str = crate::layer0::vocabulary::HANDLE_CLM_LAYER2_CHUNK_MANIFEST_V1;
pub const CLM_SCHEMA_PRUNING_ANCHOR_V1: &str = crate::layer0::vocabulary::HANDLE_CLM_LAYER2_PRUNING_ANCHOR_V1;
pub const CLM_SCHEMA_CONVERSATIONAL_TURN_V1: &str = crate::layer0::vocabulary::HANDLE_CLM_LAYER4_CONVERSATIONAL_TURN_V1;
pub fn normalize_schema_uri(uri: &str) -> String {
match uri {
crate::layer0::vocabulary::HANDLE_MCARD_SCHEMAS_CONVERSATIONAL_TURN_V1 => CLM_SCHEMA_CONVERSATIONAL_TURN_V1.to_string(),
_ => uri.to_string(),
}
}
pub fn is_valid_clm_schema_uri(uri: &str) -> bool {
let Some(rest) = uri.strip_prefix(crate::layer0::vocabulary::HANDLE_CLM_LAYER) else { return false; };
let Some((layer, rest)) = rest.split_once('/') else { return false; };
if layer.len() != 1 || !layer.as_bytes()[0].is_ascii_digit() || layer.as_bytes()[0] > b'5' {
return false;
}
let Some((artifact, version)) = rest.rsplit_once("/v") else { return false; };
!artifact.is_empty()
&& artifact.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
&& !version.is_empty()
&& version.chars().all(|c| c.is_ascii_digit())
}
pub fn validate_schema_fields(schema: Option<&str>, schema_uri: Option<&str>) -> Result<(), String> {
if let (Some(schema), Some(schema_uri)) = (schema, schema_uri) {
if normalize_schema_uri(schema) != normalize_schema_uri(schema_uri) {
return Err(format!("Schema mismatch: {schema} vs {schema_uri}"));
}
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct MCardRecord {
pub hash: String,
pub content: Vec<u8>,
#[serde(alias = "gTime")]
pub g_time: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RecordVerification {
DeclaredOk { algorithm: String },
DeclaredMismatch { algorithm: String, computed_hash: String },
LegacyClassified { algorithm: String },
LegacyUnclassified,
LegacyAmbiguous,
Malformed { reason: String },
}
fn valid_timestamp(timestamp: &str) -> bool {
timestamp == timestamp.trim()
&& crate::layer0::gtime::normalize_g_time_timestamp(timestamp).is_ok()
}
impl MCardRecord {
pub fn create(content: &[u8], algorithm: Option<&str>) -> Result<Self, String> {
Self::create_at(content, algorithm, None, DEFAULT_G_TIME_LOCALE)
}
pub fn create_at(
content: &[u8],
algorithm: Option<&str>,
timestamp: Option<&str>,
locale: &str,
) -> Result<Self, String> {
let selected = algorithm
.unwrap_or(crate::hash::config().active_algorithm)
.trim()
.trim_end_matches(':')
.to_lowercase();
let hash = crate::hash::raw_hash_bytes_for(&selected, content)?;
let g_time = match timestamp {
Some(value) => crate::layer0::gtime::format_canonical_g_time(&selected, value, locale, None),
None => crate::layer0::gtime::stamp_g_time(&selected, None, Some(locale), None),
};
Ok(Self {
hash,
content: content.to_vec(),
g_time,
})
}
}
pub fn create_record(content: &[u8], algorithm: Option<&str>) -> Result<MCardRecord, String> {
MCardRecord::create(content, algorithm)
}
pub fn verify_record(record: &MCardRecord) -> RecordVerification {
if record.hash.trim().is_empty() || record.g_time.trim().is_empty() {
return RecordVerification::Malformed {
reason: "empty hash or g_time".to_string(),
};
}
let (hash_prefix, target_hash) = match record.hash.split_once(':') {
Some((prefix, raw)) if prefix == prefix.trim() => (Some(crate::layer0::gtime::canonical_algorithm_name(prefix)), raw.to_lowercase()),
Some(_) => return RecordVerification::Malformed { reason: "invalid hash prefix".to_string() },
None => (None, record.hash.to_lowercase()),
};
let is_pipe = record.g_time.contains('|');
if is_pipe || record.g_time.starts_with(LEGACY_G_TIME_PREFIX) {
if let crate::layer0::gtime::ParsedGTime::Malformed(error) =
crate::layer0::gtime::parse_g_time(&record.g_time)
{
return RecordVerification::Malformed { reason: error.reason };
}
}
if is_pipe {
let mut parts = record.g_time.split('|');
let algorithm = crate::layer0::gtime::canonical_algorithm_name(parts.next().unwrap_or_default());
let timestamp = parts.next().unwrap_or_default().trim();
let locale = parts.next();
if algorithm.is_empty() || locale.is_none() || !valid_timestamp(timestamp) {
return RecordVerification::Malformed {
reason: "invalid canonical pipe g_time".to_string(),
};
}
if hash_prefix.as_deref().is_some_and(|prefix| prefix != algorithm) {
return RecordVerification::DeclaredMismatch {
algorithm,
computed_hash: String::new(),
};
}
let computed = match crate::hash::raw_hash_bytes_for(&algorithm, &record.content) {
Ok(value) => value,
Err(reason) => return RecordVerification::Malformed { reason },
};
return if computed == target_hash {
RecordVerification::DeclaredOk { algorithm }
} else {
RecordVerification::DeclaredMismatch {
algorithm,
computed_hash: computed,
}
};
}
if record.g_time.starts_with(LEGACY_G_TIME_PREFIX) {
let mut fields = HashMap::new();
for segment in record.g_time.split(';') {
let Some((key, value)) = segment.split_once(':') else {
return RecordVerification::Malformed {
reason: "invalid legacy TypeScript g_time segment".to_string(),
};
};
if fields.insert(key, value).is_some() {
return RecordVerification::Malformed {
reason: "duplicate legacy TypeScript g_time key".to_string(),
};
}
}
let algorithm = crate::layer0::gtime::canonical_algorithm_name(fields.get("a").copied().unwrap_or_default());
let timestamp = fields.get("t").copied().unwrap_or_default();
if algorithm.is_empty() || !valid_timestamp(timestamp) {
return RecordVerification::Malformed {
reason: "invalid legacy TypeScript g_time coordinates".to_string(),
};
}
if hash_prefix.as_deref().is_some_and(|prefix| prefix != algorithm) {
return RecordVerification::DeclaredMismatch {
algorithm,
computed_hash: String::new(),
};
}
let computed = match crate::hash::raw_hash_bytes_for(&algorithm, &record.content) {
Ok(value) => value,
Err(reason) => return RecordVerification::Malformed { reason },
};
return if computed == target_hash {
RecordVerification::DeclaredOk { algorithm }
} else {
RecordVerification::DeclaredMismatch {
algorithm,
computed_hash: computed,
}
};
}
if !valid_timestamp(record.g_time.trim()) {
return RecordVerification::Malformed {
reason: "unrecognized g_time shape".to_string(),
};
}
let mut matches = Vec::new();
for prefix in crate::hash::list_algorithms() {
let algorithm = prefix.trim_end_matches(':');
if let Ok(computed) = crate::hash::raw_hash_bytes_for(algorithm, &record.content) {
if computed == target_hash {
matches.push(algorithm.to_string());
}
}
}
match matches.len() {
1 => RecordVerification::LegacyClassified {
algorithm: matches.remove(0),
},
n if n > 1 => RecordVerification::LegacyAmbiguous,
_ => RecordVerification::LegacyUnclassified,
}
}
#[cfg(any(feature = "native", feature = "db"))]
pub fn write_record(
connection: &Connection,
content: &[u8],
algorithm: Option<&str>,
) -> Result<MCardRecord, String> {
let record = create_record(content, algorithm)?;
if !matches!(verify_record(&record), RecordVerification::DeclaredOk { .. }) {
return Err("new Rust record did not verify before persistence".to_string());
}
let persisted_hash = crate::tape::put(connection, &record.content, &record.g_time)?;
if persisted_hash != record.hash {
return Err("tape writer changed the selected MCardRecord digest".to_string());
}
let read_back = connection
.query_row(
"SELECT hash, content, g_time FROM card WHERE hash = ?1",
[&record.hash],
|row| {
Ok(MCardRecord {
hash: row.get(0)?,
content: row.get(1)?,
g_time: row.get(2)?,
})
},
)
.map_err(|error| format!("failed to read back MCardRecord: {error}"))?;
match verify_record(&read_back) {
RecordVerification::DeclaredOk { .. } => Ok(read_back),
verdict => Err(format!("persisted MCardRecord failed verification: {verdict:?}")),
}
}