reth_rpc_eth_types/
utils.rs

1//! Commonly used code snippets
2
3use super::{EthApiError, EthResult};
4use reth_primitives_traits::{Recovered, SignedTransaction};
5use std::future::Future;
6
7/// Recovers a [`SignedTransaction`] from an enveloped encoded byte stream.
8///
9/// This is a helper function that returns the appropriate RPC-specific error if the input data is
10/// malformed.
11///
12/// See [`alloy_eips::eip2718::Decodable2718::decode_2718`]
13pub fn recover_raw_transaction<T: SignedTransaction>(mut data: &[u8]) -> EthResult<Recovered<T>> {
14    if data.is_empty() {
15        return Err(EthApiError::EmptyRawTransactionData)
16    }
17
18    let transaction =
19        T::decode_2718(&mut data).map_err(|_| EthApiError::FailedToDecodeSignedTransaction)?;
20
21    transaction.try_into_recovered().or(Err(EthApiError::InvalidTransactionSignature))
22}
23
24/// Performs a binary search within a given block range to find the desired block number.
25///
26/// The binary search is performed by calling the provided asynchronous `check` closure on the
27/// blocks of the range. The closure should return a future representing the result of performing
28/// the desired logic at a given block. The future resolves to an `bool` where:
29/// - `true` indicates that the condition has been matched, but we can try to find a lower block to
30///   make the condition more matchable.
31/// - `false` indicates that the condition not matched, so the target is not present in the current
32///   block and should continue searching in a higher range.
33///
34/// Args:
35/// - `low`: The lower bound of the block range (inclusive).
36/// - `high`: The upper bound of the block range (inclusive).
37/// - `check`: A closure that performs the desired logic at a given block.
38pub async fn binary_search<F, Fut, E>(low: u64, high: u64, check: F) -> Result<u64, E>
39where
40    F: Fn(u64) -> Fut,
41    Fut: Future<Output = Result<bool, E>>,
42{
43    let mut low = low;
44    let mut high = high;
45    let mut num = high;
46
47    while low <= high {
48        let mid = (low + high) / 2;
49        if check(mid).await? {
50            high = mid - 1;
51            num = mid;
52        } else {
53            low = mid + 1
54        }
55    }
56
57    Ok(num)
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[tokio::test]
65    async fn test_binary_search() {
66        // in the middle
67        let num: Result<_, ()> =
68            binary_search(1, 10, |mid| Box::pin(async move { Ok(mid >= 5) })).await;
69        assert_eq!(num, Ok(5));
70
71        // in the upper
72        let num: Result<_, ()> =
73            binary_search(1, 10, |mid| Box::pin(async move { Ok(mid >= 7) })).await;
74        assert_eq!(num, Ok(7));
75
76        // in the lower
77        let num: Result<_, ()> =
78            binary_search(1, 10, |mid| Box::pin(async move { Ok(mid >= 1) })).await;
79        assert_eq!(num, Ok(1));
80
81        // higher than the upper
82        let num: Result<_, ()> =
83            binary_search(1, 10, |mid| Box::pin(async move { Ok(mid >= 11) })).await;
84        assert_eq!(num, Ok(10));
85    }
86}