use super::mcard_record::{verify_record, MCardRecord, RecordVerification};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value;
const CONTENT_FORMAT: &str = "clm.mcard.content.v1";
const ADDRESS_FIELDS: [&str; 3] = ["hash", "g_time", "mcard_preimage_v1"];
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MCardPreimage {
pub algorithm: String,
pub bytes: Vec<u8>,
}
fn view(mut value: Value) -> Result<Value, String> {
let object = value.as_object_mut().ok_or("MCard content must be an object")?;
for key in ADDRESS_FIELDS { object.remove(key); }
if let Some(format) = object.remove("format") {
if format != CONTENT_FORMAT { return Err("unsupported MCard content format".to_string()); }
}
Ok(value)
}
pub fn encode_content<T: Serialize>(card: &T) -> Result<Vec<u8>, String> {
let mut value = view(serde_json::to_value(card).map_err(|error| error.to_string())?)?;
value.as_object_mut().unwrap().insert("format".into(), CONTENT_FORMAT.into());
super::codec::canonical_json(&value).map(String::into_bytes)
}
pub fn project_record<T: DeserializeOwned>(record: &MCardRecord) -> Result<T, String> {
let algorithm = match verify_record(record) {
RecordVerification::DeclaredOk { algorithm } => algorithm,
_ => return Err("cannot project an unverified stored record".to_string()),
};
let mut value = view(serde_json::from_slice(&record.content).map_err(|error| error.to_string())?)?;
let object = value.as_object_mut().unwrap();
object.insert("hash".into(), record.hash.clone().into());
object.insert("g_time".into(), record.g_time.clone().into());
object.insert("mcard_preimage_v1".into(), serde_json::to_value(MCardPreimage {
algorithm, bytes: record.content.clone(),
}).map_err(|error| error.to_string())?);
serde_json::from_value(value).map_err(|error| error.to_string())
}
pub fn verified_record<T: Serialize>(card: &T, hash: &str, g_time: &str,
payload_bytes: Vec<u8>, preimage: Option<&MCardPreimage>) -> Result<MCardRecord, String> {
let record = MCardRecord { hash: hash.to_string(), g_time: g_time.to_string(),
content: preimage.map_or(payload_bytes, |value| value.bytes.clone()) };
let algorithm = match verify_record(&record) {
RecordVerification::DeclaredOk { algorithm } => algorithm,
_ => return Err("MCard does not match its declared content address".to_string()),
};
if let Some(preimage) = preimage {
if super::gtime::canonical_algorithm_name(&preimage.algorithm) != algorithm {
return Err("MCard preimage algorithm conflicts with g_time".to_string());
}
let decoded = view(serde_json::from_slice(&preimage.bytes).map_err(|error| error.to_string())?)?;
if decoded != view(serde_json::to_value(card).map_err(|error| error.to_string())?)? {
return Err("MCard view differs from its stored content".to_string());
}
}
Ok(record)
}