Skip to main content

reth_downloaders/snap/
mod.rs

1//! Downloads and verifies snap/2 ranges against
2//! [EIP-8189](https://eips.ethereum.org/EIPS/eip-8189) pivot state roots.
3//!
4//! Persistence and range selection are handled by the snap sync orchestrator.
5
6use alloy_primitives::{map::B256Set, B256, KECCAK256_EMPTY};
7use futures::Future;
8use reth_eth_wire_types::snap::{
9    AccountData, AccountRangeMessage, GetAccountRangeMessage, GetStorageRangesMessage,
10};
11use reth_network_p2p::{
12    error::RequestError,
13    snap::client::{SnapClient, SnapResponse},
14};
15use reth_network_peers::PeerId;
16use reth_tasks::Runtime;
17use reth_trie_common::{range_proof::verify_range_proof, TrieAccount, EMPTY_ROOT_HASH};
18use std::{
19    ops::Range,
20    pin::Pin,
21    task::{Context, Poll},
22};
23use tracing::debug;
24
25mod block_access_list;
26mod bytecode;
27mod request;
28mod storage;
29#[cfg(test)]
30mod test_utils;
31
32pub use block_access_list::*;
33pub use bytecode::*;
34use request::{SnapVerifier, VerifyingRequest};
35pub use storage::*;
36
37/// Downloads and verifies one account range against its requested state root.
38///
39/// Invalid responses penalize their peer and retry at high priority. Proof verification runs on
40/// the blocking pool.
41#[derive(Debug)]
42pub struct AccountRangeDownloader<C: SnapClient>(VerifyingRequest<C, GetAccountRangeMessage>);
43
44impl<C: SnapClient> AccountRangeDownloader<C> {
45    /// Creates a downloader using `runtime` for proof verification and submits the initial request.
46    /// Returns an error when the origin exceeds the limit.
47    pub fn new(
48        client: C,
49        request: GetAccountRangeMessage,
50        runtime: Runtime,
51    ) -> Result<Self, InvalidAccountRange> {
52        if request.starting_hash > request.limit_hash {
53            return Err(InvalidAccountRange {
54                origin: request.starting_hash,
55                limit: request.limit_hash,
56            })
57        }
58        let verifier = request.clone();
59        Ok(Self(VerifyingRequest::new(client, request, verifier, runtime)))
60    }
61}
62
63impl<C> Future for AccountRangeDownloader<C>
64where
65    C: SnapClient + Unpin,
66{
67    type Output = Result<AccountRangeOutcome, RequestError>;
68
69    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
70        self.get_mut().0.poll_verified(cx)
71    }
72}
73
74/// The result of an authenticated account-range request.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub enum AccountRangeOutcome {
77    /// The peer does not have the requested state root and was not penalized.
78    Unavailable {
79        /// The peer that answered.
80        peer_id: PeerId,
81    },
82    /// An account range authenticated against the requested state root.
83    Verified(VerifiedAccountRange),
84}
85
86/// A decoded account range authenticated against a state root.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct VerifiedAccountRange {
89    // Root the accounts were proven against. Private so a range cannot be relabelled with a root
90    // that did not authenticate it.
91    state_root: B256,
92    // Inclusive key the proof was verified from. Private for the same reason as the root.
93    origin: B256,
94    // Accounts as the response returned them, in the order every positional check assumes.
95    accounts: Vec<(B256, TrieAccount)>,
96    // Whether the requested interval may continue past this response.
97    has_more: bool,
98    // First key after the response, or none when the range ran out of trie.
99    next: Option<B256>,
100}
101
102impl VerifiedAccountRange {
103    /// State root the accounts were authenticated against.
104    pub const fn state_root(&self) -> B256 {
105        self.state_root
106    }
107
108    /// Key the range was requested from, proven to have nothing before the first account.
109    pub const fn origin(&self) -> B256 {
110        self.origin
111    }
112
113    /// Accounts in strictly increasing hashed-key order.
114    pub fn accounts(&self) -> &[(B256, TrieAccount)] {
115        &self.accounts
116    }
117
118    /// Whether another request may be needed to complete the interval.
119    ///
120    /// Conservative: can be `true` for an interval that is already complete.
121    pub const fn has_more(&self) -> bool {
122        self.has_more
123    }
124
125    /// Authenticated lower bound for the first key after the response, or `None` when the range
126    /// exhausted the trie.
127    pub const fn next(&self) -> Option<B256> {
128        self.next
129    }
130
131    /// Borrows the accounts together with the root that authenticated them.
132    pub fn batch(&self) -> VerifiedAccountBatch<'_> {
133        VerifiedAccountBatch {
134            state_root: self.state_root,
135            accounts: self.accounts.iter().map(|(hash, account)| (*hash, account)).collect(),
136        }
137    }
138
139    /// Code hashes the accounts reference, once each and in the order they appear.
140    ///
141    /// Accounts sharing code therefore yield one hash, so it is downloaded and stored once.
142    pub fn code_hashes(&self) -> Vec<B256> {
143        let mut seen = B256Set::default();
144        self.accounts
145            .iter()
146            .map(|(_, account)| account.code_hash)
147            .filter(|hash| *hash != KECCAK256_EMPTY && seen.insert(*hash))
148            .collect()
149    }
150
151    /// Borrows only the accounts that have storage, together with the root that authenticated
152    /// them.
153    ///
154    /// Accounts without storage are omitted because snap storage responses do not preserve an
155    /// outer-list position for them. Empty when no account in the range has storage.
156    pub fn storage_batch(&self) -> VerifiedAccountBatch<'_> {
157        VerifiedAccountBatch {
158            state_root: self.state_root,
159            accounts: self
160                .accounts
161                .iter()
162                .filter(|(_, account)| account.storage_root != EMPTY_ROOT_HASH)
163                .map(|(hash, account)| (*hash, account))
164                .collect(),
165        }
166    }
167}
168
169/// Accounts and the state root they were authenticated against.
170///
171/// Only obtainable from [`VerifiedAccountRange`], so requests built from it can always be checked
172/// against the root the accounts came from.
173#[derive(Clone, Debug, PartialEq, Eq)]
174pub struct VerifiedAccountBatch<'a> {
175    // Root and accounts travel together, so neither can be swapped for another generation's.
176    state_root: B256,
177    // Accounts the root authenticated, in response order.
178    accounts: Vec<(B256, &'a TrieAccount)>,
179}
180
181impl<'a> VerifiedAccountBatch<'a> {
182    /// State root the accounts were authenticated against.
183    pub const fn state_root(&self) -> B256 {
184        self.state_root
185    }
186
187    /// Accounts in the order the range returned them.
188    pub fn accounts(&self) -> &[(B256, &'a TrieAccount)] {
189        &self.accounts
190    }
191
192    /// Borrows a positional subrange of the batch, so storage can be requested in bounded chunks
193    /// without losing the root that authenticated the accounts.
194    ///
195    /// `None` when the range falls outside the batch.
196    pub fn range(&self, range: Range<usize>) -> Option<Self> {
197        self.accounts
198            .get(range)
199            .map(|accounts| Self { state_root: self.state_root, accounts: accounts.to_vec() })
200    }
201
202    // Confirms the batch is the one `request` was built from, so every returned range is checked
203    // against the root that authenticated its account.
204    pub(super) fn verify_batch(
205        &self,
206        request: &GetStorageRangesMessage,
207    ) -> Result<(), InvalidStorageRangeRequest> {
208        if request.root_hash != self.state_root {
209            return Err(InvalidStorageRangeRequest::StateRootMismatch {
210                requested: request.root_hash,
211                authenticated: self.state_root,
212            })
213        }
214        if request.account_hashes.len() != self.accounts.len() {
215            return Err(InvalidStorageRangeRequest::AccountCount {
216                requested: request.account_hashes.len(),
217                supplied: self.accounts.len(),
218            })
219        }
220        for (index, (requested, (supplied, _))) in
221            request.account_hashes.iter().zip(&self.accounts).enumerate()
222        {
223            if requested != supplied {
224                return Err(InvalidStorageRangeRequest::AccountMismatch {
225                    index,
226                    requested: *requested,
227                    supplied: *supplied,
228                })
229            }
230        }
231        Ok(())
232    }
233}
234
235/// An account-range request whose origin exceeds its limit.
236#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
237#[error("account range origin {origin} exceeds limit {limit}")]
238pub struct InvalidAccountRange {
239    /// Inclusive origin the range was requested from.
240    pub origin: B256,
241    /// Inclusive limit the range was requested to.
242    pub limit: B256,
243}
244
245// The request itself carries everything needed to authenticate its response.
246impl SnapVerifier for GetAccountRangeMessage {
247    type Request = Self;
248    type Output = AccountRangeOutcome;
249
250    fn verify(self, peer_id: PeerId, response: SnapResponse) -> Result<Self::Output, RequestError> {
251        let SnapResponse::AccountRange(response) = response else {
252            debug!(target: "downloaders::snap", "Expected account range response");
253            return Err(RequestError::BadResponse)
254        };
255        if response.request_id != self.request_id {
256            debug!(
257                target: "downloaders::snap",
258                expected = self.request_id,
259                got = response.request_id,
260                "Account range response id mismatch"
261            );
262            return Err(RequestError::BadResponse)
263        }
264        if response.accounts.is_empty() && response.proof.is_empty() {
265            return if self.root_hash == EMPTY_ROOT_HASH {
266                Ok(AccountRangeOutcome::Verified(VerifiedAccountRange {
267                    state_root: self.root_hash,
268                    origin: self.starting_hash,
269                    accounts: Vec::new(),
270                    has_more: false,
271                    next: None,
272                }))
273            } else {
274                Ok(AccountRangeOutcome::Unavailable { peer_id })
275            }
276        }
277
278        verify_account_range(&self, response).map(AccountRangeOutcome::Verified)
279    }
280}
281
282// Authenticates the full response before trimming its optional boundary account.
283fn verify_account_range(
284    request: &GetAccountRangeMessage,
285    response: AccountRangeMessage,
286) -> Result<VerifiedAccountRange, RequestError> {
287    // Allow only the single out-of-range account needed as a boundary witness.
288    if response.accounts.iter().filter(|data| data.hash > request.limit_hash).nth(1).is_some() {
289        debug!(target: "downloaders::snap", "Account range runs past the requested limit");
290        return Err(RequestError::BadResponse)
291    }
292
293    let mut accounts =
294        response.accounts.into_iter().map(AccountData::into_trie_entry).collect::<Vec<_>>();
295    let next = verify_proof(request, &accounts, &response.proof)?;
296
297    // Authenticate the boundary account before removing it from the requested range. Once
298    // removed, it is the first key after the response, so resuming from it cannot skip it.
299    let kept = accounts.partition_point(|(hash, _)| *hash <= request.limit_hash);
300    let next = accounts.get(kept).map(|(hash, _)| *hash).or(next);
301    accounts.truncate(kept);
302    let has_more = next.is_some_and(|next| next <= request.limit_hash);
303
304    Ok(VerifiedAccountRange {
305        state_root: request.root_hash,
306        origin: request.starting_hash,
307        accounts,
308        has_more,
309        next,
310    })
311}
312
313// Re-encodes decoded accounts so the proof authenticates their canonical trie values.
314fn verify_proof(
315    request: &GetAccountRangeMessage,
316    accounts: &[(B256, TrieAccount)],
317    proof: &[alloy_primitives::Bytes],
318) -> Result<Option<B256>, RequestError> {
319    let leaves = accounts.iter().map(|(hash, account)| (*hash, alloy_rlp::encode(account)));
320    verify_range_proof(request.root_hash, request.starting_hash, request.limit_hash, leaves, proof)
321        .map_err(|error| {
322            debug!(target: "downloaders::snap", %error, "Invalid account range proof");
323            RequestError::BadResponse
324        })
325}
326
327#[cfg(test)]
328#[allow(clippy::clone_on_copy)]
329mod tests {
330    use super::{request::MAX_RETRIES, test_utils::TestSnapClient, *};
331    use alloy_primitives::{Bytes, U256};
332    use reth_eth_wire_types::snap::ByteCodesMessage;
333    use reth_network_p2p::{error::PeerRequestResult, priority::Priority};
334    use reth_network_peers::WithPeerId;
335    use reth_trie_common::{proof::ProofRetainer, root::state_root, HashBuilder, Nibbles};
336    use std::sync::Arc;
337
338    const MAX_HASH: B256 = B256::repeat_byte(0xff);
339
340    fn key(value: u64) -> B256 {
341        B256::left_padding_from(&value.to_be_bytes())
342    }
343
344    fn account(nonce: u64) -> TrieAccount {
345        TrieAccount { nonce, balance: U256::ONE, ..Default::default() }
346    }
347
348    fn root(accounts: &[(B256, TrieAccount)]) -> B256 {
349        state_root(accounts.to_vec())
350    }
351
352    fn root_and_proof(accounts: &[(B256, TrieAccount)], targets: &[B256]) -> (B256, Vec<Bytes>) {
353        let targets = targets.iter().copied().map(Nibbles::unpack).collect();
354        let mut builder = HashBuilder::default().with_proof_retainer(ProofRetainer::new(targets));
355        for (key, account) in accounts {
356            builder.add_leaf(Nibbles::unpack(*key), &alloy_rlp::encode(account));
357        }
358        let root = builder.root();
359        let proof = builder
360            .take_proof_nodes()
361            .into_nodes_sorted()
362            .into_iter()
363            .map(|(_, node)| node)
364            .collect();
365        (root, proof)
366    }
367
368    fn request(root_hash: B256) -> GetAccountRangeMessage {
369        GetAccountRangeMessage {
370            request_id: 1,
371            root_hash,
372            starting_hash: B256::ZERO,
373            limit_hash: MAX_HASH,
374            response_bytes: 512 * 1024,
375        }
376    }
377
378    fn response(peer: PeerId, message: AccountRangeMessage) -> PeerRequestResult<SnapResponse> {
379        Ok(WithPeerId::new(peer, SnapResponse::AccountRange(message)))
380    }
381
382    fn downloader(
383        client: Arc<TestSnapClient>,
384        request: GetAccountRangeMessage,
385    ) -> Result<AccountRangeDownloader<Arc<TestSnapClient>>, InvalidAccountRange> {
386        AccountRangeDownloader::new(client, request, Runtime::test())
387    }
388
389    #[test]
390    fn verifies_and_decodes_without_an_ambient_runtime() {
391        let accounts = vec![(key(1), account(7)), (key(2), account(8))];
392        let root_hash = root(&accounts);
393        let peer = PeerId::random();
394        let message = AccountRangeMessage {
395            request_id: 1,
396            accounts: accounts
397                .iter()
398                .map(|(key, account)| AccountData::from_trie_account(*key, account))
399                .collect(),
400            proof: Vec::new(),
401        };
402        let client = Arc::new(TestSnapClient::new([response(peer, message)]));
403
404        let downloader = downloader(Arc::clone(&client), request(root_hash)).unwrap();
405        let outcome = futures::executor::block_on(downloader).unwrap();
406
407        assert_eq!(
408            outcome,
409            AccountRangeOutcome::Verified(VerifiedAccountRange {
410                state_root: root_hash,
411                origin: B256::ZERO,
412                accounts,
413                has_more: false,
414                next: None,
415            })
416        );
417        assert!(client.reported().is_empty());
418        assert_eq!(*client.priorities(), [Priority::Normal]);
419    }
420
421    #[tokio::test]
422    async fn invalid_peer_is_reported_and_request_is_retried_at_high_priority() {
423        let accounts = vec![(key(1), account(7))];
424        let root_hash = root(&accounts);
425        let bad_peer = PeerId::random();
426        let good_peer = PeerId::random();
427        let bad = Ok(WithPeerId::new(
428            bad_peer,
429            SnapResponse::ByteCodes(ByteCodesMessage { request_id: 1, codes: Vec::new() }),
430        ));
431        let good = response(
432            good_peer,
433            AccountRangeMessage {
434                request_id: 1,
435                accounts: vec![AccountData::from_trie_account(accounts[0].0, &accounts[0].1)],
436                proof: Vec::new(),
437            },
438        );
439        let client = Arc::new(TestSnapClient::new([bad, good]));
440
441        let outcome = downloader(Arc::clone(&client), request(root_hash)).unwrap().await.unwrap();
442
443        assert!(matches!(outcome, AccountRangeOutcome::Verified(_)));
444        assert_eq!(*client.reported(), [bad_peer]);
445        assert_eq!(*client.priorities(), [Priority::Normal, Priority::High]);
446    }
447
448    #[tokio::test]
449    async fn unavailable_state_is_not_a_bad_peer_response() {
450        let peer = PeerId::random();
451        let message =
452            AccountRangeMessage { request_id: 1, accounts: Vec::new(), proof: Vec::new() };
453        let client = Arc::new(TestSnapClient::new([response(peer, message)]));
454
455        let outcome = downloader(Arc::clone(&client), request(B256::repeat_byte(0x11)))
456            .unwrap()
457            .await
458            .unwrap();
459
460        assert_eq!(outcome, AccountRangeOutcome::Unavailable { peer_id: peer });
461        assert!(client.reported().is_empty());
462    }
463
464    #[test]
465    fn code_hashes_are_listed_once_in_the_order_the_accounts_reference_them() {
466        let shared = B256::repeat_byte(0x11);
467        let mut first = account(1);
468        first.code_hash = shared;
469        let mut third = account(3);
470        third.code_hash = shared;
471        let mut fourth = account(4);
472        fourth.code_hash = B256::repeat_byte(0x44);
473        let accounts =
474            vec![(key(1), first), (key(2), account(2)), (key(3), third), (key(4), fourth)];
475        let range = VerifiedAccountRange {
476            state_root: root(&accounts),
477            origin: B256::ZERO,
478            accounts,
479            has_more: false,
480            next: None,
481        };
482
483        assert_eq!(range.code_hashes(), vec![shared, B256::repeat_byte(0x44)]);
484    }
485
486    #[test]
487    fn storage_batch_omits_interleaved_accounts_without_storage() {
488        let mut first = account(1);
489        first.storage_root = B256::repeat_byte(0x11);
490        let empty = account(2);
491        let mut third = account(3);
492        third.storage_root = B256::repeat_byte(0x33);
493        let accounts = vec![(key(1), first), (key(2), empty), (key(3), third)];
494        let root_hash = root(&accounts);
495        let range = VerifiedAccountRange {
496            state_root: root_hash,
497            origin: B256::ZERO,
498            accounts,
499            has_more: false,
500            next: None,
501        };
502
503        let batch = range.storage_batch();
504
505        assert_eq!(batch.state_root(), root_hash);
506        assert_eq!(
507            batch.accounts().iter().map(|(hash, _)| *hash).collect::<Vec<_>>(),
508            vec![key(1), key(3)]
509        );
510
511        let chunk = batch.range(1..2).expect("chunk is inside the batch");
512        assert_eq!(
513            chunk.accounts().iter().map(|(hash, _)| *hash).collect::<Vec<_>>(),
514            vec![key(3)]
515        );
516        assert_eq!(chunk.state_root(), root_hash);
517
518        // The batch holds only the two accounts with storage, so this range is out of bounds.
519        assert_eq!(batch.range(1..3), None);
520    }
521
522    #[test]
523    fn invalid_request_range_is_rejected_before_submission() {
524        let client = Arc::new(TestSnapClient::new(std::iter::empty()));
525        let mut request = request(B256::repeat_byte(0x11));
526        request.starting_hash = key(2);
527        request.limit_hash = key(1);
528
529        assert!(matches!(
530            downloader(Arc::clone(&client), request),
531            Err(InvalidAccountRange { .. })
532        ));
533        assert!(client.priorities().is_empty());
534    }
535
536    #[tokio::test]
537    async fn authenticates_then_trims_an_account_past_the_limit() {
538        let accounts = vec![(key(1), account(7)), (key(3), account(8)), (key(4), account(9))];
539        let (root_hash, proof) = root_and_proof(&accounts, &[key(1), key(3)]);
540        let peer = PeerId::random();
541        let message = AccountRangeMessage {
542            request_id: 1,
543            accounts: accounts[..2]
544                .iter()
545                .map(|(key, account)| AccountData::from_trie_account(*key, account))
546                .collect(),
547            proof,
548        };
549        let client = Arc::new(TestSnapClient::new([response(peer, message)]));
550        let mut request = request(root_hash);
551        request.limit_hash = key(2);
552
553        let outcome = downloader(Arc::clone(&client), request).unwrap().await.unwrap();
554
555        assert_eq!(
556            outcome,
557            AccountRangeOutcome::Verified(VerifiedAccountRange {
558                state_root: root_hash,
559                origin: B256::ZERO,
560                accounts: vec![accounts[0].clone()],
561                has_more: false,
562                next: Some(key(3)),
563            })
564        );
565        assert!(client.reported().is_empty());
566    }
567
568    #[tokio::test]
569    async fn range_running_past_the_limit_is_rejected() {
570        let accounts = vec![(key(1), account(7)), (key(3), account(8)), (key(4), account(9))];
571        let (root_hash, proof) = root_and_proof(&accounts, &[key(1), key(4)]);
572        let peer = PeerId::random();
573        let message = AccountRangeMessage {
574            request_id: 1,
575            accounts: accounts
576                .iter()
577                .map(|(key, account)| AccountData::from_trie_account(*key, account))
578                .collect(),
579            proof,
580        };
581        let attempts = usize::from(MAX_RETRIES) + 1;
582        let client = Arc::new(TestSnapClient::new(
583            std::iter::repeat_with(|| response(peer, message.clone())).take(attempts),
584        ));
585        let mut request = request(root_hash);
586        request.limit_hash = key(2);
587
588        let error = downloader(Arc::clone(&client), request).unwrap().await.unwrap_err();
589
590        assert_eq!(error, RequestError::BadResponse);
591        assert_eq!(client.reported().len(), attempts);
592    }
593
594    #[tokio::test]
595    async fn account_at_the_limit_completes_the_requested_interval() {
596        let accounts = vec![(key(1), account(7)), (key(2), account(8)), (key(3), account(9))];
597        let (root_hash, proof) = root_and_proof(&accounts, &[key(1), key(2)]);
598        let peer = PeerId::random();
599        let message = AccountRangeMessage {
600            request_id: 1,
601            accounts: accounts[..2]
602                .iter()
603                .map(|(key, account)| AccountData::from_trie_account(*key, account))
604                .collect(),
605            proof,
606        };
607        let client = Arc::new(TestSnapClient::new([response(peer, message)]));
608        let mut request = request(root_hash);
609        request.limit_hash = key(2);
610
611        let outcome = downloader(Arc::clone(&client), request).unwrap().await.unwrap();
612
613        assert_eq!(
614            outcome,
615            AccountRangeOutcome::Verified(VerifiedAccountRange {
616                state_root: root_hash,
617                origin: B256::ZERO,
618                accounts: accounts[..2].to_vec(),
619                has_more: false,
620                next: Some(key(3)),
621            })
622        );
623        assert!(client.reported().is_empty());
624    }
625
626    // The first account after the limit proves an empty interval.
627    #[tokio::test]
628    async fn empty_interval_is_proven_by_the_first_account_after_the_limit() {
629        let accounts = vec![(key(1), account(7)), (key(9), account(8))];
630        let (root_hash, proof) = root_and_proof(&accounts, &[key(3), key(9)]);
631        let peer = PeerId::random();
632        let message = AccountRangeMessage {
633            request_id: 1,
634            accounts: vec![AccountData::from_trie_account(accounts[1].0, &accounts[1].1)],
635            proof,
636        };
637        let client = Arc::new(TestSnapClient::new([response(peer, message)]));
638        let mut request = request(root_hash);
639        request.starting_hash = key(3);
640        request.limit_hash = key(5);
641
642        let outcome = downloader(Arc::clone(&client), request).unwrap().await.unwrap();
643
644        assert_eq!(
645            outcome,
646            AccountRangeOutcome::Verified(VerifiedAccountRange {
647                state_root: root_hash,
648                origin: key(3),
649                accounts: Vec::new(),
650                has_more: false,
651                next: Some(key(9)),
652            })
653        );
654        assert!(client.reported().is_empty());
655    }
656
657    #[tokio::test]
658    async fn empty_interval_is_proven_without_a_boundary_account() {
659        let accounts = vec![(key(1), account(7)), (key(9), account(8))];
660        let (root_hash, proof) = root_and_proof(&accounts, &[key(3), key(5)]);
661        let peer = PeerId::random();
662        let message = AccountRangeMessage { request_id: 1, accounts: Vec::new(), proof };
663        let client = Arc::new(TestSnapClient::new([response(peer, message)]));
664        let mut request = request(root_hash);
665        request.starting_hash = key(3);
666        request.limit_hash = key(5);
667
668        let outcome = downloader(Arc::clone(&client), request).unwrap().await.unwrap();
669
670        assert_eq!(
671            outcome,
672            AccountRangeOutcome::Verified(VerifiedAccountRange {
673                state_root: root_hash,
674                origin: key(3),
675                accounts: Vec::new(),
676                has_more: false,
677                next: Some(key(9)),
678            })
679        );
680        assert!(client.reported().is_empty());
681    }
682
683    // A proof that continues past the limit completes the requested interval.
684    #[tokio::test]
685    async fn range_ending_before_the_limit_needs_no_further_request() {
686        let accounts = vec![(key(1), account(7)), (key(9), account(8))];
687        let (root_hash, proof) = root_and_proof(&accounts, &[key(1)]);
688        let peer = PeerId::random();
689        let message = AccountRangeMessage {
690            request_id: 1,
691            accounts: vec![AccountData::from_trie_account(accounts[0].0, &accounts[0].1)],
692            proof,
693        };
694        let client = Arc::new(TestSnapClient::new([response(peer, message)]));
695        let mut request = request(root_hash);
696        request.limit_hash = key(5);
697
698        let outcome = downloader(Arc::clone(&client), request).unwrap().await.unwrap();
699
700        assert_eq!(
701            outcome,
702            AccountRangeOutcome::Verified(VerifiedAccountRange {
703                state_root: root_hash,
704                origin: B256::ZERO,
705                accounts: vec![accounts[0].clone()],
706                has_more: false,
707                next: Some(key(9)),
708            })
709        );
710    }
711
712    #[tokio::test]
713    async fn range_ending_before_a_covered_key_reports_more() {
714        let accounts = vec![(key(1), account(7)), (key(3), account(8))];
715        let (root_hash, proof) = root_and_proof(&accounts, &[key(1)]);
716        let peer = PeerId::random();
717        let message = AccountRangeMessage {
718            request_id: 1,
719            accounts: vec![AccountData::from_trie_account(accounts[0].0, &accounts[0].1)],
720            proof,
721        };
722        let client = Arc::new(TestSnapClient::new([response(peer, message)]));
723        let mut request = request(root_hash);
724        request.limit_hash = key(5);
725
726        let outcome = downloader(Arc::clone(&client), request).unwrap().await.unwrap();
727
728        assert_eq!(
729            outcome,
730            AccountRangeOutcome::Verified(VerifiedAccountRange {
731                state_root: root_hash,
732                origin: B256::ZERO,
733                accounts: vec![accounts[0].clone()],
734                has_more: true,
735                next: Some(key(3)),
736            })
737        );
738    }
739
740    #[tokio::test]
741    async fn request_errors_retry_without_duplicate_peer_penalties() {
742        let accounts = vec![(key(1), account(7))];
743        let root_hash = root(&accounts);
744        let peer = PeerId::random();
745        let good = response(
746            peer,
747            AccountRangeMessage {
748                request_id: 1,
749                accounts: vec![AccountData::from_trie_account(accounts[0].0, &accounts[0].1)],
750                proof: Vec::new(),
751            },
752        );
753        let client = Arc::new(TestSnapClient::new([
754            Err(RequestError::Timeout),
755            Err(RequestError::BadResponse),
756            good,
757        ]));
758
759        downloader(Arc::clone(&client), request(root_hash)).unwrap().await.unwrap();
760
761        assert!(client.reported().is_empty());
762        assert_eq!(*client.priorities(), [Priority::Normal, Priority::High, Priority::High]);
763    }
764
765    #[tokio::test]
766    async fn stops_after_the_retry_budget_is_exhausted() {
767        let peers = [PeerId::random(), PeerId::random(), PeerId::random()];
768        let responses = peers.map(|peer| {
769            Ok(WithPeerId::new(
770                peer,
771                SnapResponse::ByteCodes(ByteCodesMessage { request_id: 1, codes: Vec::new() }),
772            ))
773        });
774        let client = Arc::new(TestSnapClient::new(responses));
775
776        let error = downloader(Arc::clone(&client), request(B256::repeat_byte(0x11)))
777            .unwrap()
778            .await
779            .unwrap_err();
780
781        assert_eq!(error, RequestError::BadResponse);
782        assert_eq!(*client.reported(), peers);
783        assert_eq!(*client.priorities(), [Priority::Normal, Priority::High, Priority::High]);
784    }
785}