mithril_common/entities/
cardano_transactions_snapshot.rs

1use serde::{Deserialize, Serialize};
2use sha2::{Digest, Sha256};
3
4use super::BlockNumber;
5
6/// Snapshot of a set of Cardano transactions
7#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
8pub struct CardanoTransactionsSnapshot {
9    /// Hash of the Cardano transactions set
10    pub hash: String,
11
12    /// Merkle root of the Cardano transactions set
13    pub merkle_root: String,
14
15    /// Beacon of the Cardano transactions set
16    pub block_number: BlockNumber,
17}
18
19impl CardanoTransactionsSnapshot {
20    /// Creates a new [CardanoTransactionsSnapshot]
21    pub fn new(merkle_root: String, block_number: BlockNumber) -> Self {
22        let mut cardano_transactions_snapshot = Self {
23            merkle_root,
24            block_number,
25            hash: "".to_string(),
26        };
27        cardano_transactions_snapshot.hash = cardano_transactions_snapshot.compute_hash();
28        cardano_transactions_snapshot
29    }
30
31    /// Cardano transactions snapshot hash computation
32    fn compute_hash(&self) -> String {
33        let mut hasher = Sha256::new();
34        hasher.update(self.merkle_root.clone().as_bytes());
35        hasher.update(self.block_number.to_be_bytes());
36
37        hex::encode(hasher.finalize())
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn test_cardano_transactions_snapshot_compute_hash() {
47        let hash_expected = "fac28cf7aa07922258d7d3ad8b16d859d8a3b812822b90050cddbc2e6671aab5";
48
49        assert_eq!(
50            hash_expected,
51            CardanoTransactionsSnapshot::new("mk-root-123".to_string(), BlockNumber(50))
52                .compute_hash()
53        );
54
55        assert_ne!(
56            hash_expected,
57            CardanoTransactionsSnapshot::new("mk-root-456".to_string(), BlockNumber(50))
58                .compute_hash()
59        );
60
61        assert_ne!(
62            hash_expected,
63            CardanoTransactionsSnapshot::new("mk-root-123".to_string(), BlockNumber(47))
64                .compute_hash()
65        );
66    }
67}