use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use super::hash::compute_blake3;
use super::codec::canonical_json;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value")]
pub enum MCardPayload {
Scalar(serde_json::Value),
Text(String),
Binary {
mime_type: String,
data: Vec<u8>,
},
Structured(serde_json::Value),
Uri(String),
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(transparent)]
pub struct MCard(MCardData);
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MCardData {
pub uri: String,
pub hash: String,
pub payload: MCardPayload,
pub metadata: HashMap<String, serde_json::Value>,
pub author: String,
pub sequence: u64,
pub g_time: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcard_preimage_v1: Option<super::mcard_projection::MCardPreimage>,
}
impl std::ops::Deref for MCard {
type Target = MCardData;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl<'de> Deserialize<'de> for MCard {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let card = Self(MCardData::deserialize(deserializer)?);
card.to_record().map_err(serde::de::Error::custom)?;
Ok(card)
}
}
impl MCard {
pub fn new(uri: impl Into<String>, payload: MCardPayload, author: impl Into<String>, sequence: u64) -> Self {
let uri = uri.into();
let author = author.into();
let payload_bytes = payload_to_bytes(&payload);
let hash = compute_blake3(&payload_bytes);
Self(MCardData {
uri,
hash,
payload,
metadata: HashMap::new(),
author,
sequence,
g_time: super::gtime::stamp_g_time(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3, None, None, None),
mcard_preimage_v1: None,
})
}
pub fn with_metadata(
uri: impl Into<String>,
payload: MCardPayload,
metadata: HashMap<String, serde_json::Value>,
author: impl Into<String>,
sequence: u64,
) -> Self {
let mut card = Self::new(uri, payload, author, sequence);
card.0.metadata = metadata;
card
}
pub fn payload_bytes(&self) -> Vec<u8> {
payload_to_bytes(&self.payload)
}
pub fn compute_payload_hash(&self) -> String {
self.to_record().expect("immutable verified MCard").hash
}
pub fn compute_prefixed_hash(&self) -> String {
let record = self.to_record().expect("immutable verified MCard");
let super::mcard_record::RecordVerification::DeclaredOk { algorithm } =
super::mcard_record::verify_record(&record) else { unreachable!("immutable verified MCard") };
format!("{}:{}", algorithm, record.hash.rsplit(':').next().unwrap())
}
pub fn verify_integrity(&self) -> bool {
self.to_record().is_ok()
}
pub fn to_record(&self) -> Result<super::mcard_record::MCardRecord, String> {
super::mcard_projection::verified_record(self, &self.hash, &self.g_time,
self.payload_bytes(), self.mcard_preimage_v1.as_ref())
}
pub fn to_canonical_bytes(&self) -> Result<Vec<u8>, String> {
self.to_record()?;
let json_str = canonical_json(self)?;
Ok(json_str.into_bytes())
}
}
pub fn payload_to_bytes(payload: &MCardPayload) -> Vec<u8> {
match payload {
MCardPayload::Text(s) => s.as_bytes().to_vec(),
MCardPayload::Binary { data, .. } => data.clone(),
MCardPayload::Scalar(v) | MCardPayload::Structured(v) => {
canonical_json(v).unwrap_or_else(|_| v.to_string()).into_bytes()
}
MCardPayload::Uri(u) => u.as_bytes().to_vec(),
}
}