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