use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use super::hash::{compute_blake3, prefixed_hash, verify_hash};
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, Deserialize)]
pub struct MCard {
pub uri: String,
pub hash: String,
pub payload: MCardPayload,
pub metadata: HashMap<String, serde_json::Value>,
pub author: String,
pub sequence: u64,
}
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 {
uri,
hash,
payload,
metadata: HashMap::new(),
author,
sequence,
}
}
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.metadata = metadata;
card
}
pub fn payload_bytes(&self) -> Vec<u8> {
payload_to_bytes(&self.payload)
}
pub fn compute_payload_hash(&self) -> String {
compute_blake3(&self.payload_bytes())
}
pub fn compute_prefixed_hash(&self) -> String {
prefixed_hash(&self.payload_bytes())
}
pub fn verify_integrity(&self) -> bool {
verify_hash(&self.payload_bytes(), &self.hash)
}
pub fn to_canonical_bytes(&self) -> Result<Vec<u8>, String> {
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(),
}
}