ab_core_primitives/transaction/
owned.rs1#[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#[derive(Debug, thiserror::Error)]
18pub enum OwnedTransactionError {
19 #[error("Too many read slots")]
21 TooManyReadSlots,
22 #[error("Too many write slots")]
24 TooManyWriteSlots,
25 #[error("The payload is too large")]
27 PayloadTooLarge,
28 #[error("The seal is too large")]
30 SealTooLarge,
31 #[error("The transaction is too large")]
33 TransactionTooLarge,
34 #[error("Invalid transaction")]
36 InvalidTransaction,
37 #[error("Expected number of bytes: {actual} != {expected}")]
39 UnexpectedNumberOfBytes {
40 actual: u32,
42 expected: u32,
44 },
45}
46
47#[derive(Debug, Yokeable)]
50struct YokeableTransaction<'a>(Transaction<'a>);
51
52#[derive(Debug, Clone)]
57pub struct OwnedTransaction {
58 inner: Arc<Yoke<YokeableTransaction<'static>, SharedAlignedBuffer>>,
59}
60
61impl OwnedTransaction {
62 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 #[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 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 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 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 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 #[inline]
192 pub fn from_transaction(transaction: Transaction<'_>) -> Result<Self, OwnedTransactionError> {
193 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 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 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 #[inline(always)]
238 pub fn buffer(&self) -> &SharedAlignedBuffer {
239 self.inner.backing_cart()
240 }
241
242 #[inline(always)]
244 pub fn hash(&self) -> TransactionHash {
245 *self.transaction().hash()
246 }
247
248 #[inline(always)]
250 pub fn transaction(&self) -> &Transaction<'_> {
251 let YokeableTransaction(transaction) = self.inner.get();
252 transaction
253 }
254}