zots-core 0.1.0

Core library for zOpenTimestamps - hashing, proof format, verification
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! Timestamp proof format and serialization.
//!
//! This module provides types for representing and serializing timestamp proofs.
//!
//! ## Formats
//!
//! Two serialization formats are supported:
//!
//! ### JSON Format (.zots files)
//!
//! Human-readable JSON for transparency and interoperability:
//!
//! ```json
//! {
//!   "version": 1,
//!   "hash_algorithm": "sha256",
//!   "hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
//!   "attestations": [...]
//! }
//! ```
//!
//! ### Compact Format (embeddable)
//!
//! CBOR+Base64url encoding for embedding in files, metadata, or QR codes:
//!
//! ```text
//! zots1o2d2ZXJzaW9uAWRoYXNoeEBhYmNkZWYxMjM0NTY3ODkw...
//! ```
//!
//! ## Example
//!
//! ```rust
//! use zots_core::{TimestampProof, ZcashAttestation, Network};
//!
//! // Create a proof
//! let hash = [0u8; 32];
//! let mut proof = TimestampProof::new(hash);
//!
//! // Serialize to JSON
//! let json = proof.serialize().unwrap();
//!
//! // Serialize to compact format
//! let compact = proof.to_compact().unwrap();
//! assert!(compact.starts_with("zots1"));
//! ```

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};

/// Prefix for compact CBOR+Base64 encoded proofs
pub const COMPACT_PREFIX: &str = "zots1";

/// Magic header for ZOTS timestamp memo: \x00zOTS\x00\x00\x01
/// Used in blockchain memo fields to identify timestamp data
pub const ZOTS_MAGIC: [u8; 8] = [0x00, 0x7A, 0x4F, 0x54, 0x53, 0x00, 0x00, 0x01];

/// Current proof format version
pub const PROOF_VERSION: u8 = 1;

/// Network type (mainnet or testnet)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Network {
    Mainnet,
    Testnet,
}

impl Network {
    /// Get the block explorer URL for this network
    pub fn explorer_url(&self) -> &'static str {
        match self {
            Network::Mainnet => "https://explorer.zec.rocks",
            Network::Testnet => "https://testnet.zcashexplorer.app",
        }
    }

    /// Get network name as string
    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())
    }
}

/// A Zcash blockchain attestation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZcashAttestation {
    /// Network where the transaction was broadcast
    pub network: Network,
    /// Transaction ID (hex string, display byte order)
    pub txid: String,
    /// Block height where transaction was confirmed
    pub block_height: u32,
    /// Block timestamp (Unix timestamp)
    pub block_time: u32,
    /// Offset in memo field where hash is stored
    pub memo_offset: u16,
}

impl ZcashAttestation {
    /// Create a new attestation from raw txid bytes (internal byte order)
    pub fn new(
        network: Network,
        txid_bytes: [u8; 32],
        block_height: u32,
        block_time: u32,
        memo_offset: u16,
    ) -> Self {
        // Convert to display byte order (reversed) and hex string
        let mut reversed = txid_bytes;
        reversed.reverse();
        let txid = hex::encode(reversed);

        Self {
            network,
            txid,
            block_height,
            block_time,
            memo_offset,
        }
    }

    /// Get the transaction ID as a hex string (display byte order)
    pub fn txid_hex(&self) -> &str {
        &self.txid
    }

    /// Get the txid as raw bytes (internal byte order)
    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);
        // Reverse back to internal byte order
        arr.reverse();
        Ok(arr)
    }

    /// Get the full explorer link for this transaction
    pub fn explorer_link(&self) -> String {
        format!("{}/tx/{}", self.network.explorer_url(), self.txid)
    }

    /// Get the block timestamp as a DateTime
    pub fn timestamp(&self) -> DateTime<Utc> {
        DateTime::from_timestamp(self.block_time as i64, 0).unwrap_or_default()
    }
}

/// A timestamp proof containing hash and attestations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimestampProof {
    /// Proof format version
    pub version: u8,
    /// Hash of the timestamped data (hex string)
    pub hash: String,
    /// Hash algorithm used to produce `hash`
    #[serde(default)]
    pub hash_algorithm: HashAlgorithm,
    /// List of blockchain attestations
    pub attestations: Vec<ZcashAttestation>,
}

impl TimestampProof {
    /// Create a new proof for a hash (no attestations yet)
    pub fn new(hash: Hash256) -> Self {
        Self::new_with_algorithm(hash, HashAlgorithm::Sha256)
    }

    /// Create a new proof specifying the hash algorithm
    pub fn new_with_algorithm(hash: Hash256, algorithm: HashAlgorithm) -> Self {
        Self {
            version: PROOF_VERSION,
            hash: hex::encode(hash),
            hash_algorithm: algorithm,
            attestations: Vec::new(),
        }
    }

    /// Get the hash as raw bytes
    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)
    }

    /// Get the hash algorithm used for this proof
    pub fn hash_algorithm(&self) -> HashAlgorithm {
        self.hash_algorithm
    }

    /// Add an attestation to the proof
    pub fn add_attestation(&mut self, att: ZcashAttestation) {
        self.attestations.push(att);
    }

    /// Check if the proof has any confirmed attestations
    pub fn is_confirmed(&self) -> bool {
        !self.attestations.is_empty()
    }

    /// Serialize the proof to JSON
    pub fn serialize(&self) -> Result<String> {
        serde_json::to_string_pretty(self)
            .map_err(|e| Error::InvalidProof(format!("JSON serialization failed: {e}")))
    }

    /// Deserialize a proof from JSON
    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
            )));
        }

        // Validate hash is valid hex
        let _ = proof.hash_bytes()?;

        // Validate all txids are valid hex
        for att in &proof.attestations {
            let _ = att.txid_bytes()?;
        }

        Ok(proof)
    }

    /// Save the proof to a file
    pub fn save(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
        let json = self.serialize()?;
        std::fs::write(path, json)?;
        Ok(())
    }

    /// Load a proof from a file
    pub fn load(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let data = std::fs::read_to_string(path)?;
        Self::deserialize(&data)
    }

    /// Encode the proof to compact CBOR+Base64 format
    ///
    /// Returns a string like "zots1..." that can be embedded in files,
    /// EXIF metadata, git commit messages, etc.
    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}"))
    }

    /// Decode a proof from compact CBOR+Base64 format
    ///
    /// Accepts strings starting with "zots1..."
    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
            )));
        }

        // Validate hash is valid hex
        let _ = proof.hash_bytes()?;

        // Validate all txids are valid hex
        for att in &proof.attestations {
            let _ = att.txid_bytes()?;
        }

        Ok(proof)
    }

    /// Check if a string is a valid compact proof format
    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);

        // Display order is reversed
        let hex = att.txid_hex();
        assert_eq!(hex.len(), 64);
        assert!(hex.chars().all(|c| c == 'a' || c == 'b'));

        // Round-trip back to bytes
        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();

        // Verify it's human-readable JSON
        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);

        // Cleanup
        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();

        // Compact should be significantly shorter
        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() {
        // Test compact encoding of a pending proof (no attestations)
        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());
    }
}