Skip to main content

ab_core_primitives/transaction/
owned.rs

1//! Data structures related to the owned version of [`Transaction`]
2
3#[cfg(test)]
4mod tests;
5
6use crate::transaction::{
7    SerializedTransactionLengths, Transaction, TransactionHash, TransactionHeader, TransactionSlot,
8};
9use ab_aligned_buffer::alignment::Align16;
10use ab_aligned_buffer::{OwnedAlignedBuffer, SharedAlignedBuffer};
11use ab_io_type::alignment::Alignment;
12use ab_io_type::trivial_type::TrivialType;
13use triomphe::Arc;
14use yoke::{Yoke, Yokeable};
15
16/// Errors for [`OwnedTransaction`]
17#[derive(Debug, thiserror::Error)]
18pub enum OwnedTransactionError {
19    /// Too many read slots
20    #[error("Too many read slots")]
21    TooManyReadSlots,
22    /// Too many write slots
23    #[error("Too many write slots")]
24    TooManyWriteSlots,
25    /// Payload too large
26    #[error("The payload is too large")]
27    PayloadTooLarge,
28    /// Seal too large
29    #[error("The seal is too large")]
30    SealTooLarge,
31    /// Transaction too large
32    #[error("The transaction is too large")]
33    TransactionTooLarge,
34    /// Invalid transaction, see [`Transaction::try_from_bytes()`]
35    #[error("Invalid transaction")]
36    InvalidTransaction,
37    /// Expected number of bytes
38    #[error("Expected number of bytes: {actual} != {expected}")]
39    UnexpectedNumberOfBytes {
40        /// Actual number of bytes
41        actual: u32,
42        /// Expected number of bytes
43        expected: u32,
44    },
45}
46
47// TODO: Derive `Yokeable` for `Transaction` directly once `syn` can parse `mut` restrictions of its
48//  fields: https://github.com/dtolnay/syn/issues/1987
49#[derive(Debug, Yokeable)]
50struct YokeableTransaction<'a>(Transaction<'a>);
51
52/// An owned version of [`Transaction`].
53///
54/// It is correctly aligned in memory and well suited for sending and receiving over the network
55/// efficiently or storing in memory or on disk.
56#[derive(Debug, Clone)]
57pub struct OwnedTransaction {
58    inner: Arc<Yoke<YokeableTransaction<'static>, SharedAlignedBuffer>>,
59}
60
61impl OwnedTransaction {
62    /// Create owned transaction from its parts
63    pub fn from_parts(
64        header: &TransactionHeader,
65        read_slots: &[TransactionSlot],
66        write_slots: &[TransactionSlot],
67        payload: &[u128],
68        seal: &[u8],
69    ) -> Result<Self, OwnedTransactionError> {
70        // The size of the transaction is known upfront, so a transaction that doesn't fit into a
71        // buffer is rejected before anything is allocated or copied
72        #[cfg_attr(
73            target_pointer_width = "64",
74            expect(
75                clippy::absurd_extreme_comparisons,
76                reason = "`MAX_CAPACITY` is `u32::MAX` where `usize` is 64-bit"
77            )
78        )]
79        let size = (size_of::<TransactionHeader>() + size_of::<SerializedTransactionLengths>())
80            .checked_add(size_of_val(read_slots))
81            .and_then(|size| size.checked_add(size_of_val(write_slots)))
82            .and_then(|size| size.checked_add(size_of_val(payload)))
83            .and_then(|size| size.checked_add(size_of_val(seal)))
84            .and_then(|size| u32::try_from(size).ok())
85            .filter(|&size| size <= OwnedAlignedBuffer::<Align16>::MAX_CAPACITY)
86            .ok_or(OwnedTransactionError::TransactionTooLarge)?;
87        let mut buffer = OwnedAlignedBuffer::with_capacity(size);
88
89        Self::from_parts_into(header, read_slots, write_slots, payload, seal, &mut buffer)?;
90
91        let transaction = Self::from_buffer(buffer.into_shared())
92            .expect("`from_parts_into()` wrote a valid transaction into an empty buffer; qed");
93
94        Ok(transaction)
95    }
96
97    /// Create owned transaction from its parts and write it into provided buffer.
98    ///
99    /// On error, part of the transaction might have already been appended to the buffer.
100    pub fn from_parts_into(
101        header: &TransactionHeader,
102        read_slots: &[TransactionSlot],
103        write_slots: &[TransactionSlot],
104        payload: &[u128],
105        seal: &[u8],
106        buffer: &mut OwnedAlignedBuffer,
107    ) -> Result<(), OwnedTransactionError> {
108        const {
109            // Writing `OwnedTransactionLengths` after `TransactionHeader` must be aligned
110            assert!(
111                size_of::<TransactionHeader>()
112                    .is_multiple_of(align_of::<SerializedTransactionLengths>())
113            );
114        }
115
116        let transaction_lengths = SerializedTransactionLengths {
117            read_slots: read_slots
118                .len()
119                .try_into()
120                .map_err(|_error| OwnedTransactionError::TooManyReadSlots)?,
121            write_slots: write_slots
122                .len()
123                .try_into()
124                .map_err(|_error| OwnedTransactionError::TooManyWriteSlots)?,
125            payload: size_of_val(payload)
126                .try_into()
127                .map_err(|_error| OwnedTransactionError::PayloadTooLarge)?,
128            seal: seal
129                .len()
130                .try_into()
131                .map_err(|_error| OwnedTransactionError::SealTooLarge)?,
132            padding: [0; _],
133        };
134
135        buffer
136            .append(header.as_bytes())
137            .map_err(|_error| OwnedTransactionError::TransactionTooLarge)?;
138        buffer
139            .append(transaction_lengths.as_bytes())
140            .map_err(|_error| OwnedTransactionError::TransactionTooLarge)?;
141
142        const {
143            // Writing `TransactionSlot` after `OwnedTransactionLengths` and `TransactionHeader`
144            // must be aligned
145            assert!(
146                (size_of::<TransactionHeader>() + size_of::<SerializedTransactionLengths>())
147                    .is_multiple_of(align_of::<TransactionSlot>())
148            );
149        }
150        if transaction_lengths.read_slots > 0 {
151            buffer
152                .append(TransactionSlot::slice_as_bytes(read_slots))
153                .map_err(|_error| OwnedTransactionError::TransactionTooLarge)?;
154        }
155        if transaction_lengths.write_slots > 0 {
156            buffer
157                .append(TransactionSlot::slice_as_bytes(write_slots))
158                .map_err(|_error| OwnedTransactionError::TransactionTooLarge)?;
159        }
160
161        const {
162            // Writing after `OwnedTransactionLengths`, `TransactionHeader` and (optionally)
163            // `TransactionSlot` must be aligned to `Alignment::MAX`
164            assert!(
165                (size_of::<TransactionHeader>() + size_of::<SerializedTransactionLengths>())
166                    .is_multiple_of(usize::from(Alignment::MAX.get()))
167            );
168            assert!(
169                (size_of::<TransactionHeader>()
170                    + size_of::<SerializedTransactionLengths>()
171                    + size_of::<TransactionSlot>())
172                .is_multiple_of(usize::from(Alignment::MAX.get()))
173            );
174        }
175        if transaction_lengths.payload > 0 {
176            buffer
177                .append(u128::slice_as_bytes(payload))
178                .map_err(|_error| OwnedTransactionError::TransactionTooLarge)?;
179        }
180
181        if transaction_lengths.seal > 0 {
182            buffer
183                .append(seal)
184                .map_err(|_error| OwnedTransactionError::TransactionTooLarge)?;
185        }
186
187        Ok(())
188    }
189
190    /// Create owned transaction from a reference
191    #[inline]
192    pub fn from_transaction(transaction: Transaction<'_>) -> Result<Self, OwnedTransactionError> {
193        // Appending to an empty buffer allocates exactly the necessary capacity
194        let mut buffer = OwnedAlignedBuffer::with_capacity(0);
195        buffer
196            .append(transaction.bytes)
197            .map_err(|_error| OwnedTransactionError::TransactionTooLarge)?;
198
199        let transaction = Self::from_buffer(buffer.into_shared()).expect(
200            "The same bytes were already parsed with all checks, which only depend on the address \
201            being 16-byte aligned, and owned buffers are 16-byte aligned; qed",
202        );
203
204        Ok(transaction)
205    }
206
207    /// Create owned transaction from a buffer.
208    ///
209    /// Returns [`OwnedTransactionError::InvalidTransaction`] if the buffer doesn't start with a
210    /// valid transaction, and [`OwnedTransactionError::UnexpectedNumberOfBytes`] if it is longer
211    /// than the transaction it encodes.
212    pub fn from_buffer(buffer: SharedAlignedBuffer) -> Result<Self, OwnedTransactionError> {
213        let buffer_len = buffer.len();
214        let inner = Yoke::try_attach_to_cart(buffer, |bytes| {
215            // Alignment is guaranteed by `SharedAlignedBuffer`, so this only fails due to the
216            // contents
217            let (transaction, remainder) = Transaction::try_from_bytes(bytes)
218                .ok_or(OwnedTransactionError::InvalidTransaction)?;
219
220            if !remainder.is_empty() {
221                return Err(OwnedTransactionError::UnexpectedNumberOfBytes {
222                    actual: buffer_len,
223                    expected: u32::try_from(transaction.encoded_size())
224                        .expect("Smaller than the buffer, whose length is `u32`; qed"),
225                });
226            }
227
228            Ok(YokeableTransaction(transaction))
229        })?;
230
231        Ok(Self {
232            inner: Arc::new(inner),
233        })
234    }
235
236    /// Inner buffer with owned transaction contents
237    #[inline(always)]
238    pub fn buffer(&self) -> &SharedAlignedBuffer {
239        self.inner.backing_cart()
240    }
241
242    /// Transaction hash, the same as [`Transaction::hash()`], computed once and shared by clones
243    #[inline(always)]
244    pub fn hash(&self) -> TransactionHash {
245        *self.transaction().hash()
246    }
247
248    /// Get [`Transaction`] out of [`OwnedTransaction`]
249    #[inline(always)]
250    pub fn transaction(&self) -> &Transaction<'_> {
251        let YokeableTransaction(transaction) = self.inner.get();
252        transaction
253    }
254}