Skip to main content

miden_protocol/batch/
ordered_batches.rs

1use alloc::vec::Vec;
2
3use crate::batch::ProvenBatch;
4use crate::transaction::OrderedTransactionHeaders;
5use crate::utils::serde::{
6    ByteReader,
7    ByteWriter,
8    Deserializable,
9    DeserializationError,
10    Serializable,
11};
12
13// ORDERED BATCHES
14// ================================================================================================
15
16/// The ordered set of batches in a [`ProposedBlock`](crate::block::ProposedBlock).
17///
18/// This is a newtype wrapper representing the set of batches in a proposed block. It can only be
19/// retrieved from a proposed block. This type exists only to encapsulate the conversion to
20/// [`OrderedTransactionHeaders`].
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct OrderedBatches(Vec<ProvenBatch>);
23
24impl OrderedBatches {
25    /// Creates a new set of ordered batches from the provided vector.
26    pub fn new(batches: Vec<ProvenBatch>) -> Self {
27        Self(batches)
28    }
29
30    /// Returns a reference to the underlying proven batches.
31    pub fn as_slice(&self) -> &[ProvenBatch] {
32        &self.0
33    }
34
35    /// Converts the transactions in batches into ordered transaction headers.
36    pub fn to_transactions(&self) -> OrderedTransactionHeaders {
37        OrderedTransactionHeaders::new_unchecked(
38            self.0
39                .iter()
40                .flat_map(|batch| batch.transactions().as_slice().iter())
41                .cloned()
42                .collect(),
43        )
44    }
45
46    /// Consumes self and converts the transactions in batches into ordered transaction headers.
47    pub fn into_transactions(self) -> OrderedTransactionHeaders {
48        OrderedTransactionHeaders::new_unchecked(
49            self.0
50                .into_iter()
51                .flat_map(|batch| batch.into_transactions().into_vec().into_iter())
52                .collect(),
53        )
54    }
55
56    /// Returns the sum of created notes across all batches.
57    pub fn num_created_notes(&self) -> usize {
58        self.0.as_slice().iter().fold(0, |acc, batch| acc + batch.output_notes().len())
59    }
60
61    /// Consumes self and returns the underlying vector of batches.
62    pub fn into_vec(self) -> Vec<ProvenBatch> {
63        self.0
64    }
65}
66
67// SERIALIZATION
68// ================================================================================================
69
70impl Serializable for OrderedBatches {
71    fn write_into<W: ByteWriter>(&self, target: &mut W) {
72        self.0.write_into(target)
73    }
74}
75
76impl Deserializable for OrderedBatches {
77    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
78        source.read().map(OrderedBatches::new)
79    }
80}