1use 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
28const MAX_HASH: B256 = B256::repeat_byte(0xff);
30
31#[derive(Debug)]
33pub struct StorageRangeDownloader<C: SnapClient>(VerifyingRequest<C, StorageRangeVerifier>);
34
35impl<C: SnapClient> StorageRangeDownloader<C> {
36 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 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 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#[derive(Clone, Debug, PartialEq, Eq)]
103pub enum StorageRangeOutcome {
104 Unavailable {
106 peer_id: PeerId,
108 },
109 Verified(VerifiedStorageRanges),
111}
112
113#[derive(Clone, Debug, PartialEq, Eq)]
117pub struct VerifiedStorageRanges {
118 ranges: Vec<VerifiedStorageRange>,
120 continuation: Option<StorageRangeContinuation>,
122 request: Box<GetStorageRangesMessage>,
124}
125
126impl VerifiedStorageRanges {
127 pub fn into_ranges(self) -> Vec<VerifiedStorageRange> {
129 self.ranges
130 }
131
132 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#[derive(Clone, Debug, PartialEq, Eq)]
174pub struct VerifiedStorageRange {
175 pub account_hash: B256,
177 pub slots: Vec<(B256, U256)>,
179}
180
181#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183enum StorageRangeContinuation {
184 Partial {
186 account_index: usize,
188 account_hash: B256,
190 starting_hash: B256,
192 },
193 NextAccount {
195 account_index: usize,
197 account_hash: B256,
199 },
200}
201
202#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
204pub enum InvalidStorageRangeRequest {
205 #[error(
207 "storage range requests state root {requested}, but accounts are authenticated by {authenticated}"
208 )]
209 StateRootMismatch {
210 requested: B256,
212 authenticated: B256,
214 },
215 #[error("storage range request contains no accounts")]
217 NoAccounts,
218 #[error("limited storage range request contains {accounts} accounts")]
220 LimitedMultipleAccounts {
221 accounts: usize,
223 },
224 #[error("storage range origin {origin} exceeds limit {limit}")]
226 ReversedBounds {
227 origin: B256,
229 limit: B256,
231 },
232 #[error("storage range request has {requested} accounts but {supplied} were supplied")]
234 AccountCount {
235 requested: usize,
237 supplied: usize,
239 },
240 #[error(
242 "storage range account {index} requests {requested}, but authenticated account is {supplied}"
243 )]
244 AccountMismatch {
245 index: usize,
247 requested: B256,
249 supplied: B256,
251 },
252 #[error("storage range account {index} ({account_hash}) has an empty storage root")]
254 EmptyStorageRoot {
255 index: usize,
257 account_hash: B256,
259 },
260 #[error("storage range request resumes part way with {accounts} accounts")]
262 ResumedMultipleAccounts {
263 accounts: usize,
265 },
266}
267
268#[derive(Clone, Debug)]
270struct StorageRangeVerifier {
271 request: GetStorageRangesMessage,
273 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 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 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 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 response.slots.push(Vec::new());
347 }
348 Ok(Some(response))
349 }
350
351 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 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 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 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 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 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
460struct VerifiedRange {
462 range: VerifiedStorageRange,
464 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 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 const STATE_ROOT: B256 = B256::repeat_byte(0xaa);
509
510 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 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 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 #[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 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 #[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 #[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 #[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 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 #[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}