miden_objects/batch/
batch_id.rs1use alloc::string::String;
2use alloc::vec::Vec;
3
4use crate::account::AccountId;
5use crate::transaction::{ProvenTransaction, TransactionId};
6use crate::utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable};
7use crate::{Felt, Hasher, Word, ZERO};
8
9#[derive(Debug, Copy, Clone, Eq, Ord, PartialEq, PartialOrd, Hash)]
19pub struct BatchId(Word);
20
21impl BatchId {
22    pub fn from_transactions<'tx, T>(txs: T) -> Self
24    where
25        T: Iterator<Item = &'tx ProvenTransaction>,
26    {
27        Self::from_ids(txs.map(|tx| (tx.id(), tx.account_id())))
28    }
29
30    pub fn from_ids(iter: impl IntoIterator<Item = (TransactionId, AccountId)>) -> Self {
32        let mut elements: Vec<Felt> = Vec::new();
33        for (tx_id, account_id) in iter {
34            elements.extend_from_slice(tx_id.as_elements());
35            let [account_id_prefix, account_id_suffix] = <[Felt; 2]>::from(account_id);
36            elements.extend_from_slice(&[account_id_prefix, account_id_suffix, ZERO, ZERO]);
37        }
38
39        Self(Hasher::hash_elements(&elements))
40    }
41
42    pub fn as_elements(&self) -> &[Felt] {
44        self.0.as_elements()
45    }
46
47    pub fn as_bytes(&self) -> [u8; 32] {
49        self.0.as_bytes()
50    }
51
52    pub fn to_hex(&self) -> String {
54        self.0.to_hex()
55    }
56}
57
58impl core::fmt::Display for BatchId {
59    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
60        write!(f, "{}", self.to_hex())
61    }
62}
63
64impl Serializable for BatchId {
68    fn write_into<W: ByteWriter>(&self, target: &mut W) {
69        self.0.write_into(target);
70    }
71}
72
73impl Deserializable for BatchId {
74    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
75        Ok(Self(Word::read_from(source)?))
76    }
77}