miden_objects/batch/
ordered_batches.rs

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