miden_objects/batch/
ordered_batches.rs

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