Skip to main content

reth_downloaders/snap/
storage.rs

1//! Downloads storage ranges and authenticates them against account storage roots.
2//!
3//! Responses remain positional, and only the final partial range may use the shared boundary
4//! proof defined by the Snap protocol.
5
6use super::{
7    request::{SnapVerifier, VerifyingRequest},
8    VerifiedAccountBatch,
9};
10use alloy_primitives::{B256, U256};
11use futures::Future;
12use reth_eth_wire_types::snap::{
13    GetStorageRangesMessage, RangeBound, StorageData, StorageRangesMessage,
14};
15use reth_network_p2p::{
16    error::RequestError,
17    snap::client::{SnapClient, SnapResponse},
18};
19use reth_network_peers::PeerId;
20use reth_tasks::Runtime;
21use reth_trie_common::{range_proof::verify_range_proof, EMPTY_ROOT_HASH};
22use std::{
23    pin::Pin,
24    task::{Context, Poll},
25};
26use tracing::{debug, warn};
27
28// Keeps storage requests inclusive through the full trie keyspace.
29const MAX_HASH: B256 = B256::repeat_byte(0xff);
30
31/// Downloads storage ranges authenticated by a verified account range.
32#[derive(Debug)]
33pub struct StorageRangeDownloader<C: SnapClient>(VerifyingRequest<C, StorageRangeVerifier>);
34
35impl<C: SnapClient> StorageRangeDownloader<C> {
36    /// Validates the authenticated batch against the request before submitting it.
37    ///
38    /// `batch` must hold the accounts in `request.account_hashes` order, under the same state
39    /// root; their storage roots authenticate the returned ranges. Pairing a batch with a request
40    /// for another root would penalize a peer that answered honestly.
41    ///
42    /// Accounts without storage must be omitted, since snap responses do not preserve an
43    /// outer-list position for them. [`super::VerifiedAccountRange::storage_batch`] selects the
44    /// accounts to request, and [`VerifiedAccountBatch::range`] splits them into bounded chunks.
45    pub fn new(
46        client: C,
47        request: GetStorageRangesMessage,
48        batch: &VerifiedAccountBatch<'_>,
49        runtime: Runtime,
50    ) -> Result<Self, InvalidStorageRangeRequest> {
51        let origin = request.starting_hash.unwrap_or(B256::ZERO);
52        let limit = request.limit_hash.unwrap_or(MAX_HASH);
53        if origin > limit {
54            return Err(InvalidStorageRangeRequest::ReversedBounds { origin, limit })
55        }
56        if request.account_hashes.is_empty() {
57            return Err(InvalidStorageRangeRequest::NoAccounts)
58        }
59        // Servers disagree on whether a finite limit applies only to the first account or every
60        // account, so the final proof cannot be assigned reliably for this request shape.
61        if request.account_hashes.len() > 1 && origin.is_zero() && limit != MAX_HASH {
62            return Err(InvalidStorageRangeRequest::LimitedMultipleAccounts {
63                accounts: request.account_hashes.len(),
64            })
65        }
66        // Snap defines a starting slot only for a single account, so a server answering several
67        // accounts whole would send slots below it and be rejected.
68        if request.account_hashes.len() > 1 && !origin.is_zero() {
69            return Err(InvalidStorageRangeRequest::ResumedMultipleAccounts {
70                accounts: request.account_hashes.len(),
71            })
72        }
73        batch.verify_batch(&request)?;
74        let mut storage_roots = Vec::with_capacity(batch.accounts().len());
75        for (index, (account_hash, account)) in batch.accounts().iter().enumerate() {
76            if account.storage_root == EMPTY_ROOT_HASH {
77                return Err(InvalidStorageRangeRequest::EmptyStorageRoot {
78                    index,
79                    account_hash: *account_hash,
80                })
81            }
82            storage_roots.push(account.storage_root);
83        }
84
85        let verifier = StorageRangeVerifier { request: request.clone(), storage_roots };
86        Ok(Self(VerifyingRequest::new(client, request, verifier, runtime)))
87    }
88}
89
90impl<C> Future for StorageRangeDownloader<C>
91where
92    C: SnapClient + Unpin,
93{
94    type Output = Result<StorageRangeOutcome, RequestError>;
95
96    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
97        self.get_mut().0.poll_verified(cx)
98    }
99}
100
101/// Result of an authenticated storage-ranges request.
102#[derive(Clone, Debug, PartialEq, Eq)]
103pub enum StorageRangeOutcome {
104    /// The responder lacks the requested state or account.
105    Unavailable {
106        /// Peer that returned the empty response.
107        peer_id: PeerId,
108    },
109    /// Ranges authenticated against their account storage roots.
110    Verified(VerifiedStorageRanges),
111}
112
113/// Positional storage ranges authenticated against their accounts.
114///
115/// Carries the request it answers so [`Self::follow_up`] can resume it.
116#[derive(Clone, Debug, PartialEq, Eq)]
117pub struct VerifiedStorageRanges {
118    // Slots per account. Private so they stay consistent with the position to resume at.
119    ranges: Vec<VerifiedStorageRange>,
120    // Where a follow-up resumes, or none when every requested account is complete.
121    continuation: Option<StorageRangeContinuation>,
122    // The request these ranges answer. Retained so a follow-up cannot be built against another.
123    request: Box<GetStorageRangesMessage>,
124}
125
126impl VerifiedStorageRanges {
127    /// Consumes the result and returns the ranges it authenticated.
128    pub fn into_ranges(self) -> Vec<VerifiedStorageRange> {
129        self.ranges
130    }
131
132    /// Resumes this response, narrowing `batch` to the accounts the new request covers.
133    ///
134    /// `Ok(None)` once the request is complete, or an error for a batch from another request. Each
135    /// resumption asks for less than the last, and a part-way account is requested alone, leaving
136    /// the accounts after it to the caller.
137    pub fn follow_up<'a>(
138        &self,
139        request_id: u64,
140        batch: VerifiedAccountBatch<'a>,
141    ) -> Result<
142        Option<(GetStorageRangesMessage, VerifiedAccountBatch<'a>)>,
143        InvalidStorageRangeRequest,
144    > {
145        batch.verify_batch(&self.request)?;
146        let Some(continuation) = self.continuation else { return Ok(None) };
147        let accounts = self.request.account_hashes.len();
148        let (index, end, starting_hash, limit_hash) = match continuation {
149            StorageRangeContinuation::Partial { account_index: 0, starting_hash, .. } => {
150                (0, 1, starting_hash.into(), self.request.limit_hash)
151            }
152            StorageRangeContinuation::Partial { account_index, starting_hash, .. } => {
153                (account_index, account_index + 1, starting_hash.into(), RangeBound::default())
154            }
155            StorageRangeContinuation::NextAccount { account_index, .. } => {
156                (account_index, accounts, RangeBound::default(), RangeBound::default())
157            }
158        };
159
160        let request = GetStorageRangesMessage {
161            request_id,
162            account_hashes: self.request.account_hashes[index..end].to_vec(),
163            starting_hash,
164            limit_hash,
165            ..(*self.request).clone()
166        };
167        let narrowed = batch.range(index..end).expect("checked batch covers the continuation");
168        Ok(Some((request, narrowed)))
169    }
170}
171
172/// Decoded storage slots authenticated against one account.
173#[derive(Clone, Debug, PartialEq, Eq)]
174pub struct VerifiedStorageRange {
175    /// Hashed address of the owning account.
176    pub account_hash: B256,
177    /// Non-zero slots in increasing hashed-key order.
178    pub slots: Vec<(B256, U256)>,
179}
180
181// Resume position for an incomplete storage-ranges response.
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183enum StorageRangeContinuation {
184    /// The final returned account remains incomplete.
185    Partial {
186        /// Position in the original account list.
187        account_index: usize,
188        /// Hashed address at `account_index`.
189        account_hash: B256,
190        /// Inclusive slot origin for the next request.
191        starting_hash: B256,
192    },
193    /// A later requested account was not returned.
194    NextAccount {
195        /// Position in the original account list.
196        account_index: usize,
197        /// Hashed address at `account_index`.
198        account_hash: B256,
199    },
200}
201
202/// A storage request that does not match its authenticated accounts.
203#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
204pub enum InvalidStorageRangeRequest {
205    /// The request targets a different state root than the one that authenticated the accounts.
206    #[error(
207        "storage range requests state root {requested}, but accounts are authenticated by {authenticated}"
208    )]
209    StateRootMismatch {
210        /// State root in the wire request.
211        requested: B256,
212        /// State root the account batch was verified against.
213        authenticated: B256,
214    },
215    /// No account was requested.
216    #[error("storage range request contains no accounts")]
217    NoAccounts,
218    /// A finite limit with a zero origin was requested for multiple accounts.
219    #[error("limited storage range request contains {accounts} accounts")]
220    LimitedMultipleAccounts {
221        /// Number of requested accounts.
222        accounts: usize,
223    },
224    /// The inclusive bounds are reversed.
225    #[error("storage range origin {origin} exceeds limit {limit}")]
226    ReversedBounds {
227        /// Requested inclusive origin.
228        origin: B256,
229        /// Requested inclusive limit.
230        limit: B256,
231    },
232    /// The request and authenticated batch have different lengths.
233    #[error("storage range request has {requested} accounts but {supplied} were supplied")]
234    AccountCount {
235        /// Number of requested accounts.
236        requested: usize,
237        /// Number of authenticated accounts.
238        supplied: usize,
239    },
240    /// A requested account differs from its authenticated position.
241    #[error(
242        "storage range account {index} requests {requested}, but authenticated account is {supplied}"
243    )]
244    AccountMismatch {
245        /// Position of the mismatch.
246        index: usize,
247        /// Hash in the wire request.
248        requested: B256,
249        /// Hash in the authenticated batch.
250        supplied: B256,
251    },
252    /// An account has no storage to download.
253    #[error("storage range account {index} ({account_hash}) has an empty storage root")]
254    EmptyStorageRoot {
255        /// Position of the account in the request.
256        index: usize,
257        /// Hashed address of the account.
258        account_hash: B256,
259    },
260    /// A non-zero origin was requested for multiple accounts.
261    #[error("storage range request resumes part way with {accounts} accounts")]
262    ResumedMultipleAccounts {
263        /// Number of requested accounts.
264        accounts: usize,
265    },
266}
267
268// Checks a storage response against the request and the account roots it was built from.
269#[derive(Clone, Debug)]
270struct StorageRangeVerifier {
271    // The request being answered, which every response is bound to.
272    request: GetStorageRangesMessage,
273    // Authenticated storage root per requested account, in the same order.
274    storage_roots: Vec<B256>,
275}
276
277impl SnapVerifier for StorageRangeVerifier {
278    type Request = GetStorageRangesMessage;
279    type Output = StorageRangeOutcome;
280
281    fn verify(self, peer_id: PeerId, response: SnapResponse) -> Result<Self::Output, RequestError> {
282        self.verify_response(peer_id, response)
283    }
284}
285
286impl StorageRangeVerifier {
287    // Every returned list must match the account at the same request position.
288    fn verify_response(
289        &self,
290        peer_id: PeerId,
291        response: SnapResponse,
292    ) -> Result<StorageRangeOutcome, RequestError> {
293        let Some(response) = self.accepted_response(response)? else {
294            return Ok(StorageRangeOutcome::Unavailable { peer_id })
295        };
296
297        // Only the last returned range may carry the response's shared boundary proof.
298        let proof_index =
299            response.slots.len().checked_sub(1).filter(|_| !response.proof.is_empty());
300        let mut ranges = Vec::with_capacity(response.slots.len());
301        let mut bounded_next = None;
302
303        for (index, slots) in response.slots.iter().enumerate() {
304            let proof = if proof_index == Some(index) { response.proof.as_slice() } else { &[] };
305            let verified = self.verify_range(index, slots, proof)?;
306            ranges.push(verified.range);
307            bounded_next = verified.within_limit;
308        }
309
310        let continuation = self.continuation(&ranges, bounded_next);
311        Ok(StorageRangeOutcome::Verified(VerifiedStorageRanges {
312            ranges,
313            continuation,
314            request: Box::new(self.request.clone()),
315        }))
316    }
317
318    // Binds the reply to this request before any peer-supplied data is trusted. `None` means the
319    // responder simply lacks the state.
320    fn accepted_response(
321        &self,
322        response: SnapResponse,
323    ) -> Result<Option<StorageRangesMessage>, RequestError> {
324        let SnapResponse::StorageRanges(mut response) = response else {
325            debug!(target: "downloaders::snap", "Expected storage ranges response");
326            return Err(RequestError::BadResponse)
327        };
328        if response.request_id != self.request.request_id {
329            debug!(
330                target: "downloaders::snap",
331                expected = self.request.request_id,
332                got = response.request_id,
333                "Storage ranges response id mismatch"
334            );
335            return Err(RequestError::BadResponse)
336        }
337        if response.slots.len() > self.request.account_hashes.len() {
338            debug!(target: "downloaders::snap", "Storage response contains extra ranges");
339            return Err(RequestError::BadResponse)
340        }
341        if response.slots.is_empty() {
342            if response.proof.is_empty() {
343                return Ok(None)
344            }
345            // A boundary proof can authenticate an empty suffix without an encoded inner list.
346            response.slots.push(Vec::new());
347        }
348        Ok(Some(response))
349    }
350
351    // Authenticates one account's slots against its storage root.
352    fn verify_range(
353        &self,
354        index: usize,
355        slots: &[StorageData],
356        proof: &[alloy_primitives::Bytes],
357    ) -> Result<VerifiedRange, RequestError> {
358        let account_hash = self.request.account_hashes[index];
359        // Only the first account inherits the request bounds; the rest are whole tries.
360        let (origin, limit) = if index == 0 {
361            (
362                self.request.starting_hash.unwrap_or(B256::ZERO),
363                self.request.limit_hash.unwrap_or(MAX_HASH),
364            )
365        } else {
366            (B256::ZERO, MAX_HASH)
367        };
368
369        // One boundary slot may sit past the inclusive limit and is verified before removal.
370        if slots.iter().filter(|slot| slot.hash > limit).nth(1).is_some() {
371            debug!(target: "downloaders::snap", %account_hash, "Storage range exceeds limit");
372            return Err(RequestError::BadResponse)
373        }
374
375        let mut decoded = Self::decode_slots(account_hash, origin, slots)?;
376        let leaves = decoded.iter().map(|(hash, value)| (*hash, alloy_rlp::encode(value)));
377        let next = verify_range_proof(self.storage_roots[index], origin, limit, leaves, proof)
378            .map_err(|error| {
379                debug!(
380                    target: "downloaders::snap",
381                    %account_hash,
382                    %error,
383                    "Invalid storage range proof"
384                );
385                RequestError::BadResponse
386            })?;
387
388        // Resuming at or before the origin would reissue this request forever, so a peer that
389        // reports one has withheld a slot it was asked for.
390        if next.is_some_and(|next| next <= origin) {
391            debug!(target: "downloaders::snap", %account_hash, "Storage range does not advance");
392            return Err(RequestError::BadResponse)
393        }
394
395        decoded.truncate(decoded.partition_point(|(hash, _)| *hash <= limit));
396        Ok(VerifiedRange {
397            range: VerifiedStorageRange { account_hash, slots: decoded },
398            within_limit: next.filter(|next| *next <= limit),
399        })
400    }
401
402    // A response is incomplete either part way through its last account, or because a requested
403    // account was omitted entirely.
404    fn continuation(
405        &self,
406        ranges: &[VerifiedStorageRange],
407        final_next: Option<B256>,
408    ) -> Option<StorageRangeContinuation> {
409        if let Some(starting_hash) = final_next {
410            return Some(StorageRangeContinuation::Partial {
411                account_index: ranges.len() - 1,
412                account_hash: ranges.last().expect("a response range exists").account_hash,
413                starting_hash,
414            })
415        }
416        let account_index = ranges.len();
417        self.request.account_hashes.get(account_index).copied().map(|account_hash| {
418            StorageRangeContinuation::NextAccount { account_index, account_hash }
419        })
420    }
421
422    // Storage values are canonical non-zero trie leaves.
423    fn decode_slots(
424        account_hash: B256,
425        origin: B256,
426        slots: &[StorageData],
427    ) -> Result<Vec<(B256, U256)>, RequestError> {
428        let mut decoded = Vec::with_capacity(slots.len());
429        let mut previous = None;
430
431        for (slot_index, slot) in slots.iter().enumerate() {
432            if slot.hash < origin || previous.is_some_and(|previous| slot.hash <= previous) {
433                warn!(
434                    target: "downloaders::snap",
435                    %account_hash,
436                    %origin,
437                    slot_index,
438                    slot_hash = %slot.hash,
439                    previous_hash = ?previous,
440                    slot_count = slots.len(),
441                    "Storage slots precede origin or are not strictly ordered"
442                );
443                return Err(RequestError::BadResponse)
444            }
445            let value = slot.value().map_err(|error| {
446                debug!(target: "downloaders::snap", %account_hash, %error, "Invalid storage value");
447                RequestError::BadResponse
448            })?;
449            if value.is_zero() {
450                debug!(target: "downloaders::snap", %account_hash, "Storage trie contains zero leaf");
451                return Err(RequestError::BadResponse)
452            }
453            previous = Some(slot.hash);
454            decoded.push((slot.hash, value));
455        }
456        Ok(decoded)
457    }
458}
459
460// One account's verified slots and whether it continues within the request limit.
461struct VerifiedRange {
462    // The account's slots, once its proof checked out.
463    range: VerifiedStorageRange,
464    // First slot after the range when it remains within the requested limit.
465    within_limit: Option<B256>,
466}
467
468#[cfg(test)]
469mod tests {
470    use super::{
471        super::{request::MAX_RETRIES, test_utils::TestSnapClient, VerifiedAccountRange},
472        *,
473    };
474    use alloy_primitives::Bytes;
475    use reth_network_p2p::{error::PeerRequestResult, priority::Priority};
476    use reth_network_peers::WithPeerId;
477    use reth_trie_common::{
478        proof::ProofRetainer, HashBuilder, Nibbles, TrieAccount, EMPTY_ROOT_HASH,
479    };
480    use std::sync::Arc;
481
482    fn key(value: u64) -> B256 {
483        B256::left_padding_from(&value.to_be_bytes())
484    }
485
486    // Storage leaves are RLP-encoded non-zero integers, so the trie value is the encoded slot.
487    fn slots(values: &[(B256, u64)]) -> Vec<(B256, U256)> {
488        values.iter().map(|(hash, value)| (*hash, U256::from(*value))).collect()
489    }
490
491    fn storage_root(slots: &[(B256, U256)], targets: &[B256]) -> (B256, Vec<Bytes>) {
492        let targets = targets.iter().copied().map(Nibbles::unpack).collect();
493        let mut builder = HashBuilder::default().with_proof_retainer(ProofRetainer::new(targets));
494        for (hash, value) in slots {
495            builder.add_leaf(Nibbles::unpack(*hash), &alloy_rlp::encode(value));
496        }
497        let root = builder.root();
498        let proof = builder
499            .take_proof_nodes()
500            .into_nodes_sorted()
501            .into_iter()
502            .map(|(_, node)| node)
503            .collect();
504        (root, proof)
505    }
506
507    // Every request in these tests targets the state root that authenticated its accounts.
508    const STATE_ROOT: B256 = B256::repeat_byte(0xaa);
509
510    // Accounts reach the downloader only through a range that authenticated them.
511    fn verified_range(accounts: &[(B256, TrieAccount)]) -> VerifiedAccountRange {
512        VerifiedAccountRange {
513            state_root: STATE_ROOT,
514            origin: B256::ZERO,
515            accounts: accounts.to_vec(),
516            has_more: false,
517            next: None,
518        }
519    }
520
521    fn account(storage_root: B256) -> TrieAccount {
522        TrieAccount { nonce: 1, balance: U256::from(2), storage_root, ..Default::default() }
523    }
524
525    fn wire_slots(slots: &[(B256, U256)]) -> Vec<StorageData> {
526        slots.iter().map(|(hash, value)| StorageData::from_value(*hash, *value)).collect()
527    }
528
529    fn account_refs(accounts: &[(B256, TrieAccount)]) -> Vec<(B256, &TrieAccount)> {
530        accounts.iter().map(|(hash, account)| (*hash, account)).collect()
531    }
532
533    fn request(accounts: &[(B256, TrieAccount)]) -> GetStorageRangesMessage {
534        GetStorageRangesMessage {
535            request_id: 1,
536            root_hash: STATE_ROOT,
537            account_hashes: accounts.iter().map(|(hash, _)| *hash).collect(),
538            starting_hash: B256::ZERO.into(),
539            limit_hash: MAX_HASH.into(),
540            response_bytes: 512 * 1024,
541        }
542    }
543
544    fn response(
545        peer: PeerId,
546        request_id: u64,
547        slots: Vec<Vec<StorageData>>,
548        proof: Vec<Bytes>,
549    ) -> PeerRequestResult<SnapResponse> {
550        Ok(WithPeerId::new(
551            peer,
552            SnapResponse::StorageRanges(StorageRangesMessage { request_id, slots, proof }),
553        ))
554    }
555
556    fn rejecting_client(
557        response: impl Fn(PeerId) -> PeerRequestResult<SnapResponse>,
558    ) -> Arc<TestSnapClient> {
559        let peer = PeerId::random();
560        Arc::new(TestSnapClient::new((0..=MAX_RETRIES).map(|_| response(peer))))
561    }
562
563    fn downloader<C: SnapClient>(
564        client: C,
565        request: GetStorageRangesMessage,
566        accounts: &[(B256, TrieAccount)],
567    ) -> Result<StorageRangeDownloader<C>, InvalidStorageRangeRequest> {
568        let range = verified_range(accounts);
569        StorageRangeDownloader::new(client, request, &range.batch(), Runtime::test())
570    }
571
572    #[tokio::test]
573    async fn complete_ranges_for_multiple_accounts_are_verified() {
574        let first = slots(&[(key(1), 11), (key(2), 12)]);
575        let second = slots(&[(key(3), 13)]);
576        let (first_root, _) = storage_root(&first, &[]);
577        let (second_root, proof) = storage_root(&second, &[key(3)]);
578        let accounts = vec![(key(100), account(first_root)), (key(200), account(second_root))];
579        let client = Arc::new(TestSnapClient::new([response(
580            PeerId::random(),
581            1,
582            vec![wire_slots(&first), wire_slots(&second)],
583            proof,
584        )]));
585
586        let outcome =
587            downloader(Arc::clone(&client), request(&accounts), &accounts).unwrap().await.unwrap();
588
589        let StorageRangeOutcome::Verified(verified) = outcome else { panic!("verified ranges") };
590        assert_eq!(verified.ranges.len(), 2);
591        assert_eq!(verified.ranges[0].slots, first);
592        assert_eq!(verified.ranges[1].slots, second);
593        assert_eq!(verified.continuation, None);
594        assert!(client.reported().is_empty());
595    }
596
597    #[tokio::test]
598    async fn partial_final_range_reports_its_slot_continuation() {
599        let all = slots(&[(key(1), 11), (key(2), 12), (key(3), 13)]);
600        let (root, proof) = storage_root(&all, &[B256::ZERO, key(1)]);
601        let accounts = vec![(key(100), account(root))];
602        let client = Arc::new(TestSnapClient::new([response(
603            PeerId::random(),
604            1,
605            vec![wire_slots(&all[..1])],
606            proof,
607        )]));
608
609        let outcome =
610            downloader(Arc::clone(&client), request(&accounts), &accounts).unwrap().await.unwrap();
611
612        let StorageRangeOutcome::Verified(verified) = outcome else { panic!("verified ranges") };
613        assert_eq!(verified.ranges[0].slots, all[..1]);
614        assert_eq!(
615            verified.continuation,
616            Some(StorageRangeContinuation::Partial {
617                account_index: 0,
618                account_hash: key(100),
619                starting_hash: key(2),
620            })
621        );
622        assert!(client.reported().is_empty());
623    }
624
625    #[tokio::test]
626    async fn an_omitted_account_resumes_at_the_next_position() {
627        let first = slots(&[(key(1), 11)]);
628        let (first_root, _) = storage_root(&first, &[]);
629        let accounts =
630            vec![(key(100), account(first_root)), (key(200), account(B256::repeat_byte(0xbb)))];
631        let client = Arc::new(TestSnapClient::new([response(
632            PeerId::random(),
633            1,
634            vec![wire_slots(&first)],
635            Vec::new(),
636        )]));
637
638        let outcome =
639            downloader(Arc::clone(&client), request(&accounts), &accounts).unwrap().await.unwrap();
640
641        let StorageRangeOutcome::Verified(verified) = outcome else { panic!("verified ranges") };
642        assert_eq!(verified.ranges.len(), 1);
643        assert_eq!(
644            verified.continuation,
645            Some(StorageRangeContinuation::NextAccount {
646                account_index: 1,
647                account_hash: key(200),
648            })
649        );
650    }
651
652    #[test]
653    fn empty_storage_roots_must_be_filtered_before_submission() {
654        let accounts = vec![
655            (key(100), account(B256::repeat_byte(0xaa))),
656            (key(200), account(EMPTY_ROOT_HASH)),
657            (key(300), account(B256::repeat_byte(0xbb))),
658        ];
659        let client = TestSnapClient::new([response(PeerId::random(), 1, Vec::new(), Vec::new())]);
660
661        assert_eq!(
662            downloader(&client, request(&accounts), &accounts).unwrap_err(),
663            InvalidStorageRangeRequest::EmptyStorageRoot { index: 1, account_hash: key(200) }
664        );
665        assert!(client.priorities().is_empty());
666
667        let range = verified_range(&accounts);
668        let batch = range.storage_batch();
669        let mut storage_request = request(&accounts);
670        storage_request.account_hashes = batch.accounts().iter().map(|(hash, _)| *hash).collect();
671        assert_eq!(storage_request.account_hashes, vec![key(100), key(300)]);
672        assert!(
673            StorageRangeDownloader::new(&client, storage_request, &batch, Runtime::test()).is_ok()
674        );
675        assert_eq!(*client.priorities(), [Priority::Normal]);
676    }
677
678    #[tokio::test]
679    async fn a_response_without_slots_or_proof_reports_the_state_unavailable() {
680        let batches = [
681            vec![(key(100), account(B256::repeat_byte(0xbb)))],
682            vec![
683                (key(100), account(B256::repeat_byte(0xaa))),
684                (key(200), account(B256::repeat_byte(0xbb))),
685            ],
686        ];
687        for accounts in batches {
688            let peer = PeerId::random();
689            let client = Arc::new(TestSnapClient::new([response(peer, 1, Vec::new(), Vec::new())]));
690
691            let outcome = downloader(Arc::clone(&client), request(&accounts), &accounts)
692                .unwrap()
693                .await
694                .unwrap();
695
696            assert_eq!(outcome, StorageRangeOutcome::Unavailable { peer_id: peer });
697            // Lacking the state is not misbehaviour.
698            assert!(client.reported().is_empty());
699        }
700    }
701
702    #[tokio::test]
703    async fn a_mismatched_request_id_exhausts_the_retry_budget() {
704        let all = slots(&[(key(1), 11)]);
705        let (root, _) = storage_root(&all, &[]);
706        let accounts = vec![(key(100), account(root))];
707
708        let client = rejecting_client(|peer| response(peer, 9, vec![wire_slots(&all)], Vec::new()));
709        let error = downloader(Arc::clone(&client), request(&accounts), &accounts)
710            .unwrap()
711            .await
712            .unwrap_err();
713
714        assert_eq!(error, RequestError::BadResponse);
715        // One penalty per attempt, then the budget is spent.
716        assert_eq!(client.reported().len(), usize::from(MAX_RETRIES) + 1);
717    }
718
719    #[tokio::test]
720    async fn a_range_proved_against_another_root_is_rejected() {
721        let all = slots(&[(key(1), 11)]);
722        let accounts = vec![(key(100), account(B256::repeat_byte(0xcc)))];
723
724        let client = rejecting_client(|peer| response(peer, 1, vec![wire_slots(&all)], Vec::new()));
725        let error = downloader(Arc::clone(&client), request(&accounts), &accounts)
726            .unwrap()
727            .await
728            .unwrap_err();
729
730        assert_eq!(error, RequestError::BadResponse);
731        assert_eq!(client.reported().len(), usize::from(MAX_RETRIES) + 1);
732    }
733
734    #[tokio::test]
735    async fn slots_that_are_not_strictly_ordered_penalize_the_peer_before_a_retry_succeeds() {
736        let all = slots(&[(key(1), 11), (key(2), 12)]);
737        let (root, _) = storage_root(&all, &[]);
738        let accounts = vec![(key(100), account(root))];
739        let bad_peer = PeerId::random();
740        let good_peer = PeerId::random();
741        let mut reversed = wire_slots(&all);
742        reversed.reverse();
743        let client = Arc::new(TestSnapClient::new([
744            response(bad_peer, 1, vec![reversed], Vec::new()),
745            response(good_peer, 1, vec![wire_slots(&all)], Vec::new()),
746        ]));
747
748        let outcome =
749            downloader(Arc::clone(&client), request(&accounts), &accounts).unwrap().await.unwrap();
750
751        let StorageRangeOutcome::Verified(verified) = outcome else { panic!("verified ranges") };
752        assert_eq!(verified.ranges[0].slots, all);
753        assert_eq!(*client.reported(), [bad_peer]);
754        assert_eq!(*client.priorities(), [Priority::Normal, Priority::High]);
755    }
756
757    #[test]
758    fn a_request_that_does_not_match_its_accounts_is_refused() {
759        let accounts = vec![(key(100), account(EMPTY_ROOT_HASH))];
760        let client = TestSnapClient::new([]);
761
762        let mut mismatched = request(&accounts);
763        mismatched.account_hashes = vec![key(999)];
764        let error = downloader(&client, mismatched, &accounts).unwrap_err();
765        assert_eq!(
766            error,
767            InvalidStorageRangeRequest::AccountMismatch {
768                index: 0,
769                requested: key(999),
770                supplied: key(100),
771            }
772        );
773
774        let mut empty = request(&accounts);
775        empty.account_hashes.clear();
776        assert_eq!(
777            downloader(&client, empty, &accounts).unwrap_err(),
778            InvalidStorageRangeRequest::NoAccounts
779        );
780
781        let mut reversed = request(&accounts);
782        reversed.starting_hash = key(9).into();
783        reversed.limit_hash = key(1).into();
784        assert_eq!(
785            downloader(&client, reversed, &accounts).unwrap_err(),
786            InvalidStorageRangeRequest::ReversedBounds { origin: key(9), limit: key(1) }
787        );
788    }
789
790    #[test]
791    fn a_request_for_another_state_root_is_refused() {
792        let accounts = vec![(key(100), account(EMPTY_ROOT_HASH))];
793        let client = TestSnapClient::new([]);
794
795        let mut other_root = request(&accounts);
796        other_root.root_hash = B256::repeat_byte(0xcc);
797        assert_eq!(
798            downloader(&client, other_root, &accounts).unwrap_err(),
799            InvalidStorageRangeRequest::StateRootMismatch {
800                requested: B256::repeat_byte(0xcc),
801                authenticated: STATE_ROOT,
802            }
803        );
804    }
805
806    #[tokio::test]
807    async fn a_trie_continuing_past_the_limit_needs_no_follow_up() {
808        let all = slots(&[(key(1), 11), (key(2), 12), (key(3), 13)]);
809        let (root, proof) = storage_root(&all, &[B256::ZERO, key(2)]);
810        let accounts = vec![(key(100), account(root))];
811        let client = Arc::new(TestSnapClient::new([response(
812            PeerId::random(),
813            1,
814            vec![wire_slots(&all[..2])],
815            proof,
816        )]));
817        let mut bounded = request(&accounts);
818        bounded.limit_hash = key(2).into();
819
820        let outcome = downloader(Arc::clone(&client), bounded, &accounts).unwrap().await.unwrap();
821
822        let StorageRangeOutcome::Verified(verified) = outcome else { panic!("verified ranges") };
823        let range = verified_range(&accounts);
824        assert_eq!(verified.follow_up(2, range.batch()).unwrap(), None);
825        assert_eq!(verified.into_ranges()[0].slots, all[..2]);
826    }
827
828    #[tokio::test]
829    async fn a_follow_up_keeps_the_limit_only_at_the_first_account() {
830        let all = slots(&[(key(1), 11), (key(2), 12), (key(3), 13)]);
831        let (root, proof) = storage_root(&all, &[B256::ZERO, key(1)]);
832        let accounts = vec![(key(100), account(root))];
833        let client = Arc::new(TestSnapClient::new([response(
834            PeerId::random(),
835            1,
836            vec![wire_slots(&all[..1])],
837            proof,
838        )]));
839        let mut bounded = request(&accounts);
840        bounded.limit_hash = key(5).into();
841
842        let outcome =
843            downloader(Arc::clone(&client), bounded.clone(), &accounts).unwrap().await.unwrap();
844
845        let StorageRangeOutcome::Verified(verified) = outcome else { panic!("verified ranges") };
846        let range = verified_range(&accounts);
847        let (follow_up, narrowed) = verified.follow_up(2, range.batch()).unwrap().unwrap();
848        assert_eq!(narrowed.accounts(), account_refs(&accounts));
849        assert_eq!(follow_up.request_id, 2);
850        assert_eq!(follow_up.root_hash, bounded.root_hash);
851        assert_eq!(follow_up.account_hashes, bounded.account_hashes);
852        assert_eq!(follow_up.starting_hash, key(2).into());
853        assert_eq!(follow_up.limit_hash, key(5).into());
854    }
855
856    // Every account after the first is authenticated as a whole trie, so its follow-up must drop
857    // the bounds the first account was requested with.
858    #[tokio::test]
859    async fn a_follow_up_past_the_first_account_is_unbounded() {
860        let first = slots(&[(key(1), 11)]);
861        let second = slots(&[(key(1), 21), (key(2), 22)]);
862        let (first_root, _) = storage_root(&first, &[]);
863        let (second_root, proof) = storage_root(&second, &[B256::ZERO, key(1)]);
864        let accounts = vec![
865            (key(100), account(first_root)),
866            (key(200), account(second_root)),
867            (key(300), account(first_root)),
868        ];
869        let client = Arc::new(TestSnapClient::new([response(
870            PeerId::random(),
871            1,
872            vec![wire_slots(&first), wire_slots(&second[..1])],
873            proof,
874        )]));
875
876        let outcome =
877            downloader(Arc::clone(&client), request(&accounts), &accounts).unwrap().await.unwrap();
878
879        let StorageRangeOutcome::Verified(verified) = outcome else { panic!("verified ranges") };
880        assert_eq!(
881            verified.continuation,
882            Some(StorageRangeContinuation::Partial {
883                account_index: 1,
884                account_hash: key(200),
885                starting_hash: key(2),
886            })
887        );
888
889        let range = verified_range(&accounts);
890        let (follow_up, narrowed) = verified.follow_up(2, range.batch()).unwrap().unwrap();
891        // The account resuming part way is requested alone, without the one after it.
892        assert_eq!(narrowed.accounts(), account_refs(&accounts[1..2]));
893        assert_eq!(follow_up.account_hashes, vec![key(200)]);
894        assert_eq!(follow_up.starting_hash, key(2).into());
895        assert_eq!(follow_up.limit_hash, RangeBound::default());
896    }
897
898    // A first account cut off part way resumes alone, without the whole accounts after it.
899    #[tokio::test]
900    async fn a_first_account_resuming_part_way_is_followed_up_alone() {
901        let first = slots(&[(key(1), 11), (key(2), 12)]);
902        let second = slots(&[(key(1), 21)]);
903        let (first_root, proof) = storage_root(&first, &[B256::ZERO, key(1)]);
904        let (second_root, _) = storage_root(&second, &[]);
905        let accounts = vec![(key(100), account(first_root)), (key(200), account(second_root))];
906        let client = Arc::new(TestSnapClient::new([response(
907            PeerId::random(),
908            1,
909            vec![wire_slots(&first[..1])],
910            proof,
911        )]));
912        let requested = request(&accounts);
913
914        let outcome =
915            downloader(Arc::clone(&client), requested.clone(), &accounts).unwrap().await.unwrap();
916
917        let StorageRangeOutcome::Verified(verified) = outcome else { panic!("verified ranges") };
918        let range = verified_range(&accounts);
919        let (follow_up, narrowed) = verified.follow_up(2, range.batch()).unwrap().unwrap();
920        assert_eq!(narrowed.accounts(), account_refs(&accounts[..1]));
921        assert_eq!(follow_up.account_hashes, vec![key(100)]);
922        assert_eq!(follow_up.starting_hash, key(2).into());
923        assert_eq!(follow_up.limit_hash, requested.limit_hash);
924    }
925
926    // Each follow-up must resume strictly past the last one, so the loop terminates.
927    #[tokio::test]
928    async fn resuming_a_partial_range_advances_until_the_trie_is_exhausted() {
929        let all = slots(&[(key(1), 11), (key(2), 12), (key(3), 13)]);
930        let (root, _) = storage_root(&all, &[]);
931        let accounts = vec![(key(100), account(root))];
932        let range = verified_range(&accounts);
933        let mut request = request(&accounts);
934        let mut origins = Vec::new();
935        let mut collected = Vec::new();
936
937        for served in 0..all.len() {
938            let origin = request.starting_hash.unwrap_or(B256::ZERO);
939            origins.push(origin);
940            let (_, proof) = storage_root(&all, &[origin, all[served].0]);
941            let client = Arc::new(TestSnapClient::new([response(
942                PeerId::random(),
943                request.request_id,
944                vec![wire_slots(&all[served..=served])],
945                proof,
946            )]));
947
948            let outcome =
949                downloader(Arc::clone(&client), request.clone(), &accounts).unwrap().await.unwrap();
950            let StorageRangeOutcome::Verified(verified) = outcome else {
951                panic!("verified ranges")
952            };
953            collected.extend(verified.ranges[0].slots.clone());
954
955            let Some((follow_up, _)) =
956                verified.follow_up(request.request_id + 1, range.batch()).unwrap()
957            else {
958                assert_eq!(served, all.len() - 1);
959                break
960            };
961            request = follow_up;
962        }
963
964        assert_eq!(collected, all);
965        assert_eq!(origins, vec![B256::ZERO, key(2), key(3)]);
966    }
967
968    #[test]
969    fn a_zero_origin_limited_request_must_not_carry_several_accounts() {
970        let accounts = vec![
971            (key(100), account(B256::repeat_byte(0xaa))),
972            (key(200), account(B256::repeat_byte(0xbb))),
973        ];
974        let client =
975            TestSnapClient::new([response(PeerId::random(), 1, vec![Vec::new()], Vec::new())]);
976
977        let mut bounded = request(&accounts);
978        bounded.limit_hash = key(5).into();
979        assert_eq!(
980            downloader(&client, bounded, &accounts).unwrap_err(),
981            InvalidStorageRangeRequest::LimitedMultipleAccounts { accounts: 2 }
982        );
983    }
984
985    // Servers answering several accounts whole would send the slots below a starting slot, which
986    // the first account's verification rejects, so only a single account may resume part way.
987    #[test]
988    fn a_resumed_request_must_carry_a_single_account() {
989        let accounts = vec![
990            (key(100), account(B256::repeat_byte(0xaa))),
991            (key(200), account(B256::repeat_byte(0xbb))),
992        ];
993        // Accepted requests are submitted on construction, so the client must have replies ready.
994        let client =
995            TestSnapClient::new([response(PeerId::random(), 1, vec![Vec::new()], Vec::new())]);
996
997        let mut resumed = request(&accounts);
998        resumed.starting_hash = key(1).into();
999        assert_eq!(
1000            downloader(&client, resumed.clone(), &accounts).unwrap_err(),
1001            InvalidStorageRangeRequest::ResumedMultipleAccounts { accounts: 2 }
1002        );
1003
1004        resumed.limit_hash = key(5).into();
1005        assert_eq!(
1006            downloader(&client, resumed, &accounts).unwrap_err(),
1007            InvalidStorageRangeRequest::ResumedMultipleAccounts { accounts: 2 }
1008        );
1009
1010        let mut single = request(&accounts[..1]);
1011        single.starting_hash = key(1).into();
1012        assert!(downloader(&client, single, &accounts[..1]).is_ok());
1013    }
1014
1015    // Consecutive account transitions must chain: each follow-up is driven by the batch the
1016    // previous one returned, never by accounts the caller re-derived.
1017    #[tokio::test]
1018    async fn consecutive_account_transitions_carry_their_batch_forward() {
1019        let served = slots(&[(key(1), 11)]);
1020        let (root, _) = storage_root(&served, &[]);
1021        let accounts =
1022            vec![(key(100), account(root)), (key(200), account(root)), (key(300), account(root))];
1023        let range = verified_range(&accounts);
1024        let mut request = request(&accounts);
1025        let mut batch = range.batch();
1026
1027        for remaining in (1..accounts.len()).rev() {
1028            let client = Arc::new(TestSnapClient::new([response(
1029                PeerId::random(),
1030                request.request_id,
1031                vec![wire_slots(&served)],
1032                Vec::new(),
1033            )]));
1034            let outcome = StorageRangeDownloader::new(
1035                Arc::clone(&client),
1036                request.clone(),
1037                &batch,
1038                Runtime::test(),
1039            )
1040            .unwrap()
1041            .await
1042            .unwrap();
1043
1044            let StorageRangeOutcome::Verified(verified) = outcome else {
1045                panic!("verified ranges")
1046            };
1047            let (follow_up, narrowed) =
1048                verified.follow_up(request.request_id + 1, batch).unwrap().unwrap();
1049            assert_eq!(follow_up.account_hashes.len(), remaining);
1050            assert_eq!(narrowed.accounts(), account_refs(&accounts[accounts.len() - remaining..]));
1051            request = follow_up;
1052            batch = narrowed;
1053        }
1054
1055        assert_eq!(request.account_hashes, vec![key(300)]);
1056    }
1057
1058    #[tokio::test]
1059    async fn a_follow_up_refuses_a_batch_from_another_request() {
1060        let served = slots(&[(key(1), 11)]);
1061        let (root, _) = storage_root(&served, &[]);
1062        let accounts = vec![(key(100), account(root)), (key(200), account(root))];
1063        let client = Arc::new(TestSnapClient::new([response(
1064            PeerId::random(),
1065            1,
1066            vec![wire_slots(&served)],
1067            Vec::new(),
1068        )]));
1069
1070        let outcome =
1071            downloader(Arc::clone(&client), request(&accounts), &accounts).unwrap().await.unwrap();
1072        let StorageRangeOutcome::Verified(verified) = outcome else { panic!("verified ranges") };
1073
1074        let others = vec![(key(900), account(root)), (key(901), account(root))];
1075        let other_range = verified_range(&others);
1076        assert_eq!(
1077            verified.follow_up(2, other_range.batch()).unwrap_err(),
1078            InvalidStorageRangeRequest::AccountMismatch {
1079                index: 0,
1080                requested: key(100),
1081                supplied: key(900),
1082            }
1083        );
1084    }
1085}