alloy_network_primitives/
block.rs

1use alloy_primitives::B256;
2use serde::{Deserialize, Serialize};
3
4use crate::TransactionResponse;
5use alloc::{vec, vec::Vec};
6use alloy_consensus::error::ValueError;
7use alloy_eips::Encodable2718;
8use core::slice;
9
10/// Block Transactions depending on the boolean attribute of `eth_getBlockBy*`,
11/// or if used by `eth_getUncle*`
12#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(untagged)]
14pub enum BlockTransactions<T> {
15    /// Full transactions
16    Full(Vec<T>),
17    /// Only hashes
18    Hashes(Vec<B256>),
19    /// Special case for uncle response.
20    Uncle,
21}
22
23impl<T> Default for BlockTransactions<T> {
24    fn default() -> Self {
25        Self::Hashes(Vec::default())
26    }
27}
28
29impl<T> BlockTransactions<T> {
30    /// Check if the enum variant is used for hashes.
31    #[inline]
32    pub const fn is_hashes(&self) -> bool {
33        matches!(self, Self::Hashes(_))
34    }
35
36    /// Fallibly cast to a slice of hashes.
37    pub fn as_hashes(&self) -> Option<&[B256]> {
38        match self {
39            Self::Hashes(hashes) => Some(hashes),
40            _ => None,
41        }
42    }
43
44    /// Returns true if the enum variant is used for full transactions.
45    #[inline]
46    pub const fn is_full(&self) -> bool {
47        matches!(self, Self::Full(_))
48    }
49
50    /// Converts the transaction type by applying a function to each transaction.
51    ///
52    /// Returns the block with the new transaction type.
53    pub fn map<U>(self, f: impl FnMut(T) -> U) -> BlockTransactions<U> {
54        match self {
55            Self::Full(txs) => BlockTransactions::Full(txs.into_iter().map(f).collect()),
56            Self::Hashes(hashes) => BlockTransactions::Hashes(hashes),
57            Self::Uncle => BlockTransactions::Uncle,
58        }
59    }
60
61    /// Converts the transaction type by applying a fallible function to each transaction.
62    ///
63    /// Returns the block with the new transaction type if all transactions were successfully.
64    pub fn try_map<U, E>(
65        self,
66        f: impl FnMut(T) -> Result<U, E>,
67    ) -> Result<BlockTransactions<U>, E> {
68        match self {
69            Self::Full(txs) => {
70                Ok(BlockTransactions::Full(txs.into_iter().map(f).collect::<Result<_, _>>()?))
71            }
72            Self::Hashes(hashes) => Ok(BlockTransactions::Hashes(hashes)),
73            Self::Uncle => Ok(BlockTransactions::Uncle),
74        }
75    }
76
77    /// Fallibly cast to a slice of transactions.
78    ///
79    /// Returns `None` if the enum variant is not `Full`.
80    pub fn as_transactions(&self) -> Option<&[T]> {
81        match self {
82            Self::Full(txs) => Some(txs),
83            _ => None,
84        }
85    }
86
87    /// Calculate the transaction root for the full transactions.
88    ///
89    /// Returns `None` if this is not the [`BlockTransactions::Full`] variant
90    pub fn calculate_transactions_root(&self) -> Option<B256>
91    where
92        T: Encodable2718,
93    {
94        self.as_transactions().map(alloy_consensus::proofs::calculate_transaction_root)
95    }
96
97    /// Returns true if the enum variant is used for an uncle response.
98    #[inline]
99    pub const fn is_uncle(&self) -> bool {
100        matches!(self, Self::Uncle)
101    }
102
103    /// Returns an iterator over the transactions (if any). This will be empty
104    /// if the block is an uncle or if the transaction list contains only
105    /// hashes.
106    #[doc(alias = "transactions")]
107    pub fn txns(&self) -> impl Iterator<Item = &T> {
108        self.as_transactions().map(|txs| txs.iter()).unwrap_or_else(|| [].iter())
109    }
110
111    /// Returns an iterator over the transactions (if any). This will be empty if the block is not
112    /// full.
113    pub fn into_transactions(self) -> vec::IntoIter<T> {
114        match self {
115            Self::Full(txs) => txs.into_iter(),
116            _ => vec::IntoIter::default(),
117        }
118    }
119
120    /// Consumes the type and returns the transactions as a vector.
121    ///
122    /// Note: if this is an uncle or hashes, this will return an empty vector.
123    pub fn into_transactions_vec(self) -> Vec<T> {
124        match self {
125            Self::Full(txs) => txs,
126            _ => vec![],
127        }
128    }
129
130    /// Attempts to unwrap the [`Self::Full`] variant.
131    ///
132    /// Returns an error if the type is different variant.
133    pub fn try_into_transactions(self) -> Result<Vec<T>, ValueError<Self>> {
134        match self {
135            Self::Full(txs) => Ok(txs),
136            txs @ Self::Hashes(_) => Err(ValueError::new_static(txs, "Unexpected hashes variant")),
137            txs @ Self::Uncle => Err(ValueError::new_static(txs, "Unexpected uncle variant")),
138        }
139    }
140
141    /// Returns an instance of BlockTransactions with the Uncle special case.
142    #[inline]
143    pub const fn uncle() -> Self {
144        Self::Uncle
145    }
146
147    /// Returns the number of transactions.
148    #[inline]
149    pub fn len(&self) -> usize {
150        match self {
151            Self::Hashes(h) => h.len(),
152            Self::Full(f) => f.len(),
153            Self::Uncle => 0,
154        }
155    }
156
157    /// Whether the block has no transactions.
158    #[inline]
159    pub fn is_empty(&self) -> bool {
160        self.len() == 0
161    }
162}
163
164impl<T: TransactionResponse> BlockTransactions<T> {
165    /// Creates a new [`BlockTransactions::Hashes`] variant from the given iterator of transactions.
166    pub fn new_hashes(txs: impl IntoIterator<Item = impl AsRef<T>>) -> Self {
167        Self::Hashes(txs.into_iter().map(|tx| tx.as_ref().tx_hash()).collect())
168    }
169
170    /// Converts `self` into `Hashes`.
171    #[inline]
172    pub fn convert_to_hashes(&mut self) {
173        if !self.is_hashes() {
174            *self = Self::Hashes(self.hashes().collect());
175        }
176    }
177
178    /// Converts `self` into `Hashes`.
179    #[inline]
180    pub fn into_hashes(mut self) -> Self {
181        self.convert_to_hashes();
182        self
183    }
184
185    /// Returns an iterator over the transaction hashes.
186    #[deprecated = "use `hashes` instead"]
187    #[inline]
188    pub fn iter(&self) -> BlockTransactionHashes<'_, T> {
189        self.hashes()
190    }
191
192    /// Returns an iterator over references to the transaction hashes.
193    #[inline]
194    pub fn hashes(&self) -> BlockTransactionHashes<'_, T> {
195        BlockTransactionHashes::new(self)
196    }
197}
198
199impl<T> From<Vec<B256>> for BlockTransactions<T> {
200    fn from(hashes: Vec<B256>) -> Self {
201        Self::Hashes(hashes)
202    }
203}
204
205impl<T: TransactionResponse> From<Vec<T>> for BlockTransactions<T> {
206    fn from(transactions: Vec<T>) -> Self {
207        Self::Full(transactions)
208    }
209}
210
211/// An iterator over the transaction hashes of a block.
212///
213/// See [`BlockTransactions::hashes`].
214#[derive(Clone, Debug)]
215pub struct BlockTransactionHashes<'a, T>(BlockTransactionHashesInner<'a, T>);
216
217#[derive(Clone, Debug)]
218enum BlockTransactionHashesInner<'a, T> {
219    Hashes(slice::Iter<'a, B256>),
220    Full(slice::Iter<'a, T>),
221    Uncle,
222}
223
224impl<'a, T> BlockTransactionHashes<'a, T> {
225    #[inline]
226    fn new(txs: &'a BlockTransactions<T>) -> Self {
227        Self(match txs {
228            BlockTransactions::Hashes(txs) => BlockTransactionHashesInner::Hashes(txs.iter()),
229            BlockTransactions::Full(txs) => BlockTransactionHashesInner::Full(txs.iter()),
230            BlockTransactions::Uncle => BlockTransactionHashesInner::Uncle,
231        })
232    }
233}
234
235impl<T: TransactionResponse> Iterator for BlockTransactionHashes<'_, T> {
236    type Item = B256;
237
238    #[inline]
239    fn next(&mut self) -> Option<Self::Item> {
240        match &mut self.0 {
241            BlockTransactionHashesInner::Hashes(txs) => txs.next().copied(),
242            BlockTransactionHashesInner::Full(txs) => txs.next().map(|tx| tx.tx_hash()),
243            BlockTransactionHashesInner::Uncle => None,
244        }
245    }
246
247    #[inline]
248    fn size_hint(&self) -> (usize, Option<usize>) {
249        match &self.0 {
250            BlockTransactionHashesInner::Full(txs) => txs.size_hint(),
251            BlockTransactionHashesInner::Hashes(txs) => txs.size_hint(),
252            BlockTransactionHashesInner::Uncle => (0, Some(0)),
253        }
254    }
255}
256
257impl<T: TransactionResponse> ExactSizeIterator for BlockTransactionHashes<'_, T> {
258    #[inline]
259    fn len(&self) -> usize {
260        match &self.0 {
261            BlockTransactionHashesInner::Full(txs) => txs.len(),
262            BlockTransactionHashesInner::Hashes(txs) => txs.len(),
263            BlockTransactionHashesInner::Uncle => 0,
264        }
265    }
266}
267
268impl<T: TransactionResponse> DoubleEndedIterator for BlockTransactionHashes<'_, T> {
269    #[inline]
270    fn next_back(&mut self) -> Option<Self::Item> {
271        match &mut self.0 {
272            BlockTransactionHashesInner::Full(txs) => txs.next_back().map(|tx| tx.tx_hash()),
273            BlockTransactionHashesInner::Hashes(txs) => txs.next_back().copied(),
274            BlockTransactionHashesInner::Uncle => None,
275        }
276    }
277}
278
279#[cfg(feature = "std")]
280impl<T: TransactionResponse> std::iter::FusedIterator for BlockTransactionHashes<'_, T> {}
281
282/// Determines how the `transactions` field of block should be filled.
283///
284/// This essentially represents the `full:bool` argument in RPC calls that determine whether the
285/// response should include full transaction objects or just the hashes.
286#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
287pub enum BlockTransactionsKind {
288    /// Only include hashes: [BlockTransactions::Hashes]
289    #[default]
290    Hashes,
291    /// Include full transaction objects: [BlockTransactions::Full]
292    Full,
293}
294
295impl BlockTransactionsKind {
296    /// Returns true if this is [`BlockTransactionsKind::Hashes`]
297    pub const fn is_hashes(&self) -> bool {
298        matches!(self, Self::Hashes)
299    }
300
301    /// Returns true if this is [`BlockTransactionsKind::Full`]
302    pub const fn is_full(&self) -> bool {
303        matches!(self, Self::Full)
304    }
305}
306
307impl From<bool> for BlockTransactionsKind {
308    fn from(is_full: bool) -> Self {
309        if is_full {
310            Self::Full
311        } else {
312            Self::Hashes
313        }
314    }
315}
316
317impl From<BlockTransactionsKind> for bool {
318    fn from(kind: BlockTransactionsKind) -> Self {
319        match kind {
320            BlockTransactionsKind::Full => true,
321            BlockTransactionsKind::Hashes => false,
322        }
323    }
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329
330    #[test]
331    fn test_full_conversion() {
332        let full = true;
333        assert_eq!(BlockTransactionsKind::Full, full.into());
334
335        let full = false;
336        assert_eq!(BlockTransactionsKind::Hashes, full.into());
337    }
338
339    #[test]
340    fn test_block_transactions_default() {
341        let default: BlockTransactions<()> = BlockTransactions::default();
342        assert!(default.is_hashes());
343        assert_eq!(default.len(), 0);
344    }
345
346    #[test]
347    fn test_block_transactions_is_methods() {
348        let hashes: BlockTransactions<()> = BlockTransactions::Hashes(vec![B256::ZERO]);
349        let full: BlockTransactions<u32> = BlockTransactions::Full(vec![42]);
350        let uncle: BlockTransactions<()> = BlockTransactions::Uncle;
351
352        assert!(hashes.is_hashes());
353        assert!(!hashes.is_full());
354        assert!(!hashes.is_uncle());
355
356        assert!(full.is_full());
357        assert!(!full.is_hashes());
358        assert!(!full.is_uncle());
359
360        assert!(uncle.is_uncle());
361        assert!(!uncle.is_full());
362        assert!(!uncle.is_hashes());
363    }
364
365    #[test]
366    fn test_as_hashes() {
367        let hashes = vec![B256::ZERO, B256::repeat_byte(1)];
368        let tx_hashes: BlockTransactions<()> = BlockTransactions::Hashes(hashes.clone());
369
370        assert_eq!(tx_hashes.as_hashes(), Some(hashes.as_slice()));
371    }
372
373    #[test]
374    fn test_as_transactions() {
375        let transactions = vec![42, 43];
376        let txs = BlockTransactions::Full(transactions.clone());
377
378        assert_eq!(txs.as_transactions(), Some(transactions.as_slice()));
379    }
380
381    #[test]
382    fn test_block_transactions_len_and_is_empty() {
383        let hashes: BlockTransactions<()> = BlockTransactions::Hashes(vec![B256::ZERO]);
384        let full = BlockTransactions::Full(vec![42]);
385        let uncle: BlockTransactions<()> = BlockTransactions::Uncle;
386
387        assert_eq!(hashes.len(), 1);
388        assert_eq!(full.len(), 1);
389        assert_eq!(uncle.len(), 0);
390
391        assert!(!hashes.is_empty());
392        assert!(!full.is_empty());
393        assert!(uncle.is_empty());
394    }
395
396    #[test]
397    fn test_block_transactions_txns_iterator() {
398        let transactions = vec![42, 43];
399        let txs = BlockTransactions::Full(transactions);
400        let mut iter = txs.txns();
401
402        assert_eq!(iter.next(), Some(&42));
403        assert_eq!(iter.next(), Some(&43));
404        assert_eq!(iter.next(), None);
405    }
406
407    #[test]
408    fn test_block_transactions_into_transactions() {
409        let transactions = vec![42, 43];
410        let txs = BlockTransactions::Full(transactions.clone());
411        let collected: Vec<_> = txs.into_transactions().collect();
412
413        assert_eq!(collected, transactions);
414    }
415
416    #[test]
417    fn test_block_transactions_kind_conversion() {
418        let full: BlockTransactionsKind = true.into();
419        assert_eq!(full, BlockTransactionsKind::Full);
420
421        let hashes: BlockTransactionsKind = false.into();
422        assert_eq!(hashes, BlockTransactionsKind::Hashes);
423
424        let bool_full: bool = BlockTransactionsKind::Full.into();
425        assert!(bool_full);
426
427        let bool_hashes: bool = BlockTransactionsKind::Hashes.into();
428        assert!(!bool_hashes);
429    }
430}