use crate::{Error, Hash256, HashAlgorithm, Result};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
pub const COMPACT_PREFIX: &str = "zots1";
pub const ZOTS_MAGIC: [u8; 8] = [0x00, 0x7A, 0x4F, 0x54, 0x53, 0x00, 0x00, 0x01];
pub const PROOF_VERSION: u8 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Network {
Mainnet,
Testnet,
}
impl Network {
pub fn explorer_url(&self) -> &'static str {
match self {
Network::Mainnet => "https://explorer.zec.rocks",
Network::Testnet => "https://testnet.zcashexplorer.app",
}
}
pub fn name(&self) -> &'static str {
match self {
Network::Mainnet => "mainnet",
Network::Testnet => "testnet",
}
}
}
impl std::fmt::Display for Network {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZcashAttestation {
pub network: Network,
pub txid: String,
pub block_height: u32,
pub block_time: u32,
pub memo_offset: u16,
}
impl ZcashAttestation {
pub fn new(
network: Network,
txid_bytes: [u8; 32],
block_height: u32,
block_time: u32,
memo_offset: u16,
) -> Self {
let mut reversed = txid_bytes;
reversed.reverse();
let txid = hex::encode(reversed);
Self {
network,
txid,
block_height,
block_time,
memo_offset,
}
}
pub fn txid_hex(&self) -> &str {
&self.txid
}
pub fn txid_bytes(&self) -> Result<[u8; 32]> {
let bytes = hex::decode(&self.txid)
.map_err(|e| Error::InvalidProof(format!("Invalid txid hex: {e}")))?;
if bytes.len() != 32 {
return Err(Error::InvalidProof("TXID must be 32 bytes".into()));
}
let mut arr = [0u8; 32];
arr.copy_from_slice(&bytes);
arr.reverse();
Ok(arr)
}
pub fn explorer_link(&self) -> String {
format!("{}/tx/{}", self.network.explorer_url(), self.txid)
}
pub fn timestamp(&self) -> DateTime<Utc> {
DateTime::from_timestamp(self.block_time as i64, 0).unwrap_or_default()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimestampProof {
pub version: u8,
pub hash: String,
#[serde(default)]
pub hash_algorithm: HashAlgorithm,
pub attestations: Vec<ZcashAttestation>,
}
impl TimestampProof {
pub fn new(hash: Hash256) -> Self {
Self::new_with_algorithm(hash, HashAlgorithm::Sha256)
}
pub fn new_with_algorithm(hash: Hash256, algorithm: HashAlgorithm) -> Self {
Self {
version: PROOF_VERSION,
hash: hex::encode(hash),
hash_algorithm: algorithm,
attestations: Vec::new(),
}
}
pub fn hash_bytes(&self) -> Result<Hash256> {
let bytes = hex::decode(&self.hash)
.map_err(|e| Error::InvalidProof(format!("Invalid hash hex: {e}")))?;
if bytes.len() != 32 {
return Err(Error::InvalidProof("Hash must be 32 bytes".into()));
}
let mut arr = [0u8; 32];
arr.copy_from_slice(&bytes);
Ok(arr)
}
pub fn hash_algorithm(&self) -> HashAlgorithm {
self.hash_algorithm
}
pub fn add_attestation(&mut self, att: ZcashAttestation) {
self.attestations.push(att);
}
pub fn is_confirmed(&self) -> bool {
!self.attestations.is_empty()
}
pub fn serialize(&self) -> Result<String> {
serde_json::to_string_pretty(self)
.map_err(|e| Error::InvalidProof(format!("JSON serialization failed: {e}")))
}
pub fn deserialize(data: &str) -> Result<Self> {
let proof: Self = serde_json::from_str(data)
.map_err(|e| Error::InvalidProof(format!("JSON parse error: {e}")))?;
if proof.version != PROOF_VERSION {
return Err(Error::InvalidProof(format!(
"Unsupported version: {}",
proof.version
)));
}
let _ = proof.hash_bytes()?;
for att in &proof.attestations {
let _ = att.txid_bytes()?;
}
Ok(proof)
}
pub fn save(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
let json = self.serialize()?;
std::fs::write(path, json)?;
Ok(())
}
pub fn load(path: impl AsRef<std::path::Path>) -> Result<Self> {
let data = std::fs::read_to_string(path)?;
Self::deserialize(&data)
}
pub fn to_compact(&self) -> Result<String> {
let mut cbor_data = Vec::new();
ciborium::into_writer(self, &mut cbor_data)
.map_err(|e| Error::InvalidProof(format!("CBOR encoding failed: {e}")))?;
let encoded = URL_SAFE_NO_PAD.encode(&cbor_data);
Ok(format!("{COMPACT_PREFIX}{encoded}"))
}
pub fn from_compact(compact: &str) -> Result<Self> {
let data = compact.trim();
if !data.starts_with(COMPACT_PREFIX) {
return Err(Error::InvalidProof(format!(
"Invalid compact format: must start with '{COMPACT_PREFIX}'"
)));
}
let encoded = &data[COMPACT_PREFIX.len()..];
let cbor_data = URL_SAFE_NO_PAD
.decode(encoded)
.map_err(|e| Error::InvalidProof(format!("Base64 decode failed: {e}")))?;
let proof: Self = ciborium::from_reader(&cbor_data[..])
.map_err(|e| Error::InvalidProof(format!("CBOR decode failed: {e}")))?;
if proof.version != PROOF_VERSION {
return Err(Error::InvalidProof(format!(
"Unsupported version: {}",
proof.version
)));
}
let _ = proof.hash_bytes()?;
for att in &proof.attestations {
let _ = att.txid_bytes()?;
}
Ok(proof)
}
pub fn is_compact_format(s: &str) -> bool {
s.trim().starts_with(COMPACT_PREFIX)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_network_serialization() {
assert_eq!(
serde_json::to_string(&Network::Mainnet).unwrap(),
"\"mainnet\""
);
assert_eq!(
serde_json::to_string(&Network::Testnet).unwrap(),
"\"testnet\""
);
}
#[test]
fn test_network_deserialization() {
let mainnet: Network = serde_json::from_str("\"mainnet\"").unwrap();
let testnet: Network = serde_json::from_str("\"testnet\"").unwrap();
assert_eq!(mainnet, Network::Mainnet);
assert_eq!(testnet, Network::Testnet);
}
#[test]
fn test_attestation_txid() {
let txid_bytes = [0xAB; 32];
let att = ZcashAttestation::new(Network::Testnet, txid_bytes, 100, 1700000000, 0);
let hex = att.txid_hex();
assert_eq!(hex.len(), 64);
assert!(hex.chars().all(|c| c == 'a' || c == 'b'));
let recovered = att.txid_bytes().unwrap();
assert_eq!(recovered, txid_bytes);
}
#[test]
fn test_proof_new() {
let hash = [0x42u8; 32];
let proof = TimestampProof::new(hash);
assert_eq!(proof.version, PROOF_VERSION);
assert_eq!(proof.hash, hex::encode(hash));
assert_eq!(proof.hash_algorithm, HashAlgorithm::Sha256);
assert!(proof.attestations.is_empty());
assert!(!proof.is_confirmed());
}
#[test]
fn test_proof_hash_bytes() {
let hash = [0x42u8; 32];
let proof = TimestampProof::new(hash);
assert_eq!(proof.hash_bytes().unwrap(), hash);
}
#[test]
fn test_proof_new_with_algorithm() {
let hash = [0x22u8; 32];
let proof = TimestampProof::new_with_algorithm(hash, HashAlgorithm::Blake3);
assert_eq!(proof.version, PROOF_VERSION);
assert_eq!(proof.hash, hex::encode(hash));
assert_eq!(proof.hash_algorithm, HashAlgorithm::Blake3);
}
#[test]
fn test_proof_deserialize_defaults_algorithm() {
let json = r#"{"version": 1, "hash": "0000000000000000000000000000000000000000000000000000000000000000", "attestations": []}"#;
let proof = TimestampProof::deserialize(json).unwrap();
assert_eq!(proof.hash_algorithm, HashAlgorithm::Sha256);
}
#[test]
fn test_proof_roundtrip() {
let hash = [0xABu8; 32];
let mut proof = TimestampProof::new(hash);
proof.add_attestation(ZcashAttestation::new(
Network::Testnet,
[0xCDu8; 32],
3721456,
1734567890,
8,
));
assert!(proof.is_confirmed());
let json = proof.serialize().unwrap();
let deserialized = TimestampProof::deserialize(&json).unwrap();
assert_eq!(deserialized.version, proof.version);
assert_eq!(deserialized.hash, proof.hash);
assert_eq!(deserialized.hash_algorithm, proof.hash_algorithm);
assert_eq!(deserialized.attestations.len(), 1);
assert_eq!(deserialized.attestations[0].network, Network::Testnet);
assert_eq!(deserialized.attestations[0].block_height, 3721456);
assert_eq!(deserialized.attestations[0].block_time, 1734567890);
assert_eq!(deserialized.attestations[0].memo_offset, 8);
}
#[test]
fn test_proof_json_is_readable() {
let hash = [
0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC,
0xDE, 0xF0, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x12, 0x34, 0x56, 0x78,
0x9A, 0xBC, 0xDE, 0xF0,
];
let mut proof = TimestampProof::new(hash);
proof.add_attestation(ZcashAttestation::new(
Network::Testnet,
[0x11; 32],
12345,
1700000000,
0,
));
let json = proof.serialize().unwrap();
assert!(json.contains("\"version\": 1"));
assert!(json.contains("\"hash\":"));
assert!(json.contains("\"hash_algorithm\": \"sha256\""));
assert!(json.contains("\"attestations\":"));
assert!(json.contains("\"network\": \"testnet\""));
assert!(json.contains("\"block_height\": 12345"));
}
#[test]
fn test_proof_multiple_attestations() {
let hash = [0x00u8; 32];
let mut proof = TimestampProof::new(hash);
proof.add_attestation(ZcashAttestation::new(
Network::Testnet,
[0x01u8; 32],
100,
1000,
0,
));
proof.add_attestation(ZcashAttestation::new(
Network::Mainnet,
[0x02u8; 32],
200,
2000,
0,
));
let json = proof.serialize().unwrap();
let deserialized = TimestampProof::deserialize(&json).unwrap();
assert_eq!(deserialized.attestations.len(), 2);
assert_eq!(deserialized.attestations[0].network, Network::Testnet);
assert_eq!(deserialized.attestations[1].network, Network::Mainnet);
}
#[test]
fn test_proof_invalid_json() {
assert!(TimestampProof::deserialize("not json").is_err());
}
#[test]
fn test_proof_invalid_hash() {
let json = r#"{"version": 1, "hash": "not_hex", "attestations": []}"#;
assert!(TimestampProof::deserialize(json).is_err());
}
#[test]
fn test_proof_file_roundtrip() {
let hash = [0x55u8; 32];
let mut proof = TimestampProof::new(hash);
proof.add_attestation(ZcashAttestation::new(
Network::Testnet,
[0x66u8; 32],
12345,
1700000000,
0,
));
let temp_path = std::env::temp_dir().join("test_proof.zots");
proof.save(&temp_path).unwrap();
let loaded = TimestampProof::load(&temp_path).unwrap();
assert_eq!(loaded.hash, proof.hash);
assert_eq!(loaded.hash_algorithm, proof.hash_algorithm);
assert_eq!(loaded.attestations.len(), 1);
std::fs::remove_file(&temp_path).ok();
}
#[test]
fn test_compact_roundtrip() {
let hash = [0xABu8; 32];
let mut proof = TimestampProof::new(hash);
proof.add_attestation(ZcashAttestation::new(
Network::Testnet,
[0xCDu8; 32],
3721456,
1734567890,
8,
));
let compact = proof.to_compact().unwrap();
assert!(compact.starts_with(COMPACT_PREFIX));
let decoded = TimestampProof::from_compact(&compact).unwrap();
assert_eq!(decoded.version, proof.version);
assert_eq!(decoded.hash, proof.hash);
assert_eq!(decoded.hash_algorithm, proof.hash_algorithm);
assert_eq!(decoded.attestations.len(), 1);
assert_eq!(decoded.attestations[0].network, Network::Testnet);
assert_eq!(decoded.attestations[0].block_height, 3721456);
}
#[test]
fn test_compact_is_shorter_than_json() {
let hash = [0xABu8; 32];
let mut proof = TimestampProof::new(hash);
proof.add_attestation(ZcashAttestation::new(
Network::Testnet,
[0xCDu8; 32],
3721456,
1734567890,
8,
));
let json = proof.serialize().unwrap();
let compact = proof.to_compact().unwrap();
assert!(
compact.len() < json.len(),
"Compact ({}) should be shorter than JSON ({})",
compact.len(),
json.len()
);
}
#[test]
fn test_compact_invalid_prefix() {
assert!(TimestampProof::from_compact("invalid").is_err());
assert!(TimestampProof::from_compact("zots2abc").is_err());
}
#[test]
fn test_compact_invalid_base64() {
assert!(TimestampProof::from_compact("zots1!!!invalid!!!").is_err());
}
#[test]
fn test_is_compact_format() {
assert!(TimestampProof::is_compact_format("zots1abc123"));
assert!(TimestampProof::is_compact_format(" zots1abc123 "));
assert!(!TimestampProof::is_compact_format("abc123"));
assert!(!TimestampProof::is_compact_format("{\"version\": 1}"));
}
#[test]
fn test_compact_pending_proof() {
let hash = [0x42u8; 32];
let proof = TimestampProof::new(hash);
let compact = proof.to_compact().unwrap();
let decoded = TimestampProof::from_compact(&compact).unwrap();
assert_eq!(decoded.hash, proof.hash);
assert!(decoded.attestations.is_empty());
}
}