Skip to main content

reth_network_p2p/test_utils/
full_block.rs

1use crate::{
2    block_access_lists::client::{BalRequirement, BlockAccessListsClient},
3    bodies::client::BodiesClient,
4    download::DownloadClient,
5    error::PeerRequestResult,
6    headers::client::{HeadersClient, HeadersRequest},
7    priority::Priority,
8    BlockClient,
9};
10use alloy_consensus::Header;
11use alloy_eips::{BlockHashOrNumber, BlockNumHash};
12use alloy_primitives::{map::B256Map, Bytes, B256};
13use parking_lot::Mutex;
14use reth_eth_wire_types::{BlockAccessLists, HeadersDirection};
15use reth_ethereum_primitives::{Block, BlockBody};
16use reth_network_peers::{PeerId, WithPeerId};
17use reth_primitives_traits::{SealedBlock, SealedHeader};
18use std::{
19    ops::RangeInclusive,
20    sync::{
21        atomic::{AtomicUsize, Ordering},
22        Arc,
23    },
24};
25
26/// A headers+bodies client that stores the headers and bodies in memory, with an artificial soft
27/// bodies response limit that is set to 20 by default.
28///
29/// This full block client can be [Clone]d and shared between multiple tasks.
30#[derive(Clone, Debug)]
31pub struct TestFullBlockClient {
32    headers: Arc<Mutex<B256Map<Header>>>,
33    bodies: Arc<Mutex<B256Map<BlockBody>>>,
34    access_lists: Arc<Mutex<B256Map<Bytes>>>,
35    // soft response limit, max number of bodies to respond with
36    soft_limit: usize,
37    // number of reported bad messages
38    bad_messages: Arc<AtomicUsize>,
39}
40
41impl Default for TestFullBlockClient {
42    fn default() -> Self {
43        Self {
44            headers: Arc::new(Mutex::new(B256Map::default())),
45            bodies: Arc::new(Mutex::new(B256Map::default())),
46            access_lists: Arc::new(Mutex::new(B256Map::default())),
47            soft_limit: 20,
48            bad_messages: Arc::default(),
49        }
50    }
51}
52
53impl TestFullBlockClient {
54    /// Insert a header and body into the client maps.
55    pub fn insert(&self, header: SealedHeader, body: BlockBody) {
56        let hash = header.hash();
57        self.headers.lock().insert(hash, header.unseal());
58        self.bodies.lock().insert(hash, body);
59    }
60
61    /// Insert a raw block access list served for the given block hash.
62    pub fn insert_access_list(&self, hash: B256, access_list: Bytes) {
63        self.access_lists.lock().insert(hash, access_list);
64    }
65
66    /// Set the soft response limit.
67    pub const fn set_soft_limit(&mut self, limit: usize) {
68        self.soft_limit = limit;
69    }
70
71    /// Get the block with the highest block number.
72    pub fn highest_block(&self) -> Option<SealedBlock<Block>> {
73        self.headers.lock().iter().max_by_key(|(_, header)| header.number).and_then(
74            |(hash, header)| {
75                self.bodies.lock().get(hash).map(|body| {
76                    SealedBlock::from_parts_unchecked(header.clone(), body.clone(), *hash)
77                })
78            },
79        )
80    }
81
82    /// Returns the number of bad messages reported so far.
83    pub fn bad_messages(&self) -> usize {
84        self.bad_messages.load(Ordering::Relaxed)
85    }
86}
87
88impl DownloadClient for TestFullBlockClient {
89    /// Counts a bad message from a specific peer.
90    fn report_bad_message(&self, _peer_id: PeerId) {
91        self.bad_messages.fetch_add(1, Ordering::Relaxed);
92    }
93
94    /// Retrieves the number of connected peers.
95    ///
96    /// Returns the number of connected peers in the test scenario (1).
97    fn num_connected_peers(&self) -> usize {
98        1
99    }
100}
101
102/// Implements the `HeadersClient` trait for the `TestFullBlockClient` struct.
103impl HeadersClient for TestFullBlockClient {
104    type Header = Header;
105    /// Specifies the associated output type.
106    type Output = futures::future::Ready<PeerRequestResult<Vec<Header>>>;
107
108    /// Retrieves headers with a given priority level.
109    ///
110    /// # Arguments
111    ///
112    /// * `request` - A `HeadersRequest` indicating the headers to retrieve.
113    /// * `_priority` - A `Priority` level for the request.
114    ///
115    /// # Returns
116    ///
117    /// A `Ready` future containing a `PeerRequestResult` with a vector of retrieved headers.
118    fn get_headers_with_priority(
119        &self,
120        request: HeadersRequest,
121        _priority: Priority,
122    ) -> Self::Output {
123        let headers = self.headers.lock();
124
125        // Initializes the block hash or number.
126        let mut block: BlockHashOrNumber = match request.start {
127            BlockHashOrNumber::Hash(hash) => headers.get(&hash).cloned(),
128            BlockHashOrNumber::Number(num) => headers.values().find(|h| h.number == num).cloned(),
129        }
130        .map(|h| h.number.into())
131        .unwrap();
132
133        // Retrieves headers based on the provided limit and request direction.
134        let resp = (0..request.limit)
135            .filter_map(|_| {
136                headers.iter().find_map(|(hash, header)| {
137                    // Checks if the header matches the specified block or number.
138                    BlockNumHash::new(header.number, *hash).matches_block_or_num(&block).then(
139                        || {
140                            match request.direction {
141                                HeadersDirection::Falling => block = header.parent_hash.into(),
142                                HeadersDirection::Rising => block = (header.number + 1).into(),
143                            }
144                            header.clone()
145                        },
146                    )
147                })
148            })
149            .collect::<Vec<_>>();
150
151        // Returns a future containing the retrieved headers with a random peer ID.
152        futures::future::ready(Ok(WithPeerId::new(PeerId::random(), resp)))
153    }
154}
155
156/// Implements the `BodiesClient` trait for the `TestFullBlockClient` struct.
157impl BodiesClient for TestFullBlockClient {
158    type Body = BlockBody;
159    /// Defines the output type of the function.
160    type Output = futures::future::Ready<PeerRequestResult<Vec<BlockBody>>>;
161
162    /// Retrieves block bodies corresponding to provided hashes with a given priority.
163    ///
164    /// # Arguments
165    ///
166    /// * `hashes` - A vector of block hashes to retrieve bodies for.
167    /// * `_priority` - Priority level for block body retrieval (unused in this implementation).
168    ///
169    /// # Returns
170    ///
171    /// A future containing the result of the block body retrieval operation.
172    fn get_block_bodies_with_priority_and_range_hint(
173        &self,
174        hashes: Vec<B256>,
175        _priority: Priority,
176        _range_hint: Option<RangeInclusive<u64>>,
177    ) -> Self::Output {
178        // Acquire a lock on the bodies.
179        let bodies = self.bodies.lock();
180
181        // Create a future that immediately returns the result of the block body retrieval
182        // operation.
183        futures::future::ready(Ok(WithPeerId::new(
184            PeerId::random(),
185            hashes
186                .iter()
187                .filter_map(|hash| bodies.get(hash).cloned())
188                .take(self.soft_limit)
189                .collect(),
190        )))
191    }
192}
193
194impl BlockClient for TestFullBlockClient {
195    type Block = reth_ethereum_primitives::Block;
196}
197
198impl BlockAccessListsClient for TestFullBlockClient {
199    type Output = futures::future::Ready<PeerRequestResult<BlockAccessLists>>;
200
201    fn get_block_access_lists_with_priority_and_requirement(
202        &self,
203        hashes: Vec<B256>,
204        _priority: Priority,
205        _requirement: BalRequirement,
206    ) -> Self::Output {
207        let access_lists = self.access_lists.lock();
208        futures::future::ready(Ok(WithPeerId::new(
209            PeerId::random(),
210            BlockAccessLists(hashes.iter().map(|hash| access_lists.get(hash).cloned()).collect()),
211        )))
212    }
213}