Skip to main content

reth_snap_sync/storage/
store.rs

1//! Persists contract storage response by response, ahead of the account range committing to it.
2//!
3//! Progress is tied to the attempt and the range, and survives pivot moves: catch-up carries the
4//! persisted slots forward with block access lists, and downloads resume at the new root.
5
6use crate::{common::SnapRecord, SnapAccountStore, SnapAttemptStore, SnapSyncError, SnapWrite};
7use alloy_primitives::{B256, U256};
8use reth_db_api::{
9    cursor::DbDupCursorRO,
10    tables,
11    transaction::{DbTx, DbTxMut},
12};
13use reth_storage_api::{DBProvider, MetadataProvider, MetadataWriter, SnapAttemptId, StateWriter};
14use reth_trie_common::{root::storage_root, HashedPostState, HashedStorage, EMPTY_ROOT_HASH};
15use serde::{Deserialize, Serialize};
16
17/// Persistence for contract storage downloaded ahead of its account range.
18///
19/// Blanket-implemented over the node's writers, so slots and progress join the caller's
20/// transaction and commit together or not at all.
21pub trait SnapStorageStore {
22    /// Returns how far the storage of the range requested from `origin` is persisted.
23    ///
24    /// A contract part way through when the pivot moved resumes with its root unproved.
25    fn storage_progress(
26        &self,
27        write: SnapWrite,
28        origin: B256,
29    ) -> Result<StorageProgress, SnapSyncError>;
30
31    /// Persists `chunk` for the range requested from `origin`, where the coverage must continue.
32    ///
33    /// A contract starts at the zero slot, dropping whatever an earlier attempt left for it, and
34    /// otherwise continues only where its last chunk ended.
35    fn commit_storage_chunk(
36        &self,
37        write: SnapWrite,
38        origin: B256,
39        chunk: StorageChunk,
40    ) -> Result<StorageProgress, SnapSyncError>
41    where
42        Self: MetadataWriter + StateWriter + DBProvider<Tx: DbTxMut>;
43}
44
45/// Verified slots of one contract, from the slot they were requested at.
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct StorageChunk {
48    // Hashed address of the contract.
49    account: B256,
50    // Root the slots were proved against.
51    storage_root: B256,
52    // Slot the chunk was requested from.
53    from: B256,
54    // Non-zero slots in key order.
55    slots: Vec<(B256, U256)>,
56    // Slot the storage continues at, or none once the trie is exhausted.
57    next: Option<B256>,
58}
59
60impl StorageChunk {
61    /// Creates a chunk of `account`'s storage requested from `from` and continuing at `next`.
62    pub const fn new(
63        account: B256,
64        storage_root: B256,
65        from: B256,
66        slots: Vec<(B256, U256)>,
67        next: Option<B256>,
68    ) -> Self {
69        Self { account, storage_root, from, slots, next }
70    }
71}
72
73/// How far the contracts of the account range being downloaded have their storage persisted.
74///
75/// Contracts complete in key order, so only one is part way through per pivot, plus those carried
76/// across pivot moves.
77#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
78pub struct StorageProgress {
79    // Contracts up to this key have all their storage persisted.
80    complete: Option<B256>,
81    // Contracts part way through, in key order.
82    partial: Vec<PartialStorage>,
83}
84
85impl StorageProgress {
86    /// No storage persisted yet.
87    pub const START: Self = Self { complete: None, partial: Vec::new() };
88
89    /// Returns whether all of `account`'s storage is persisted.
90    pub fn is_complete(&self, account: B256) -> bool {
91        self.complete.is_some_and(|complete| account <= complete)
92    }
93
94    /// Returns whether `account` has storage persisted ahead of its range.
95    pub fn has_slots(&self, account: B256) -> bool {
96        self.is_complete(account) || self.partial_of(account).is_some()
97    }
98
99    // Progress of `account` if it is part way through.
100    fn partial_of(&self, account: B256) -> Option<&PartialStorage> {
101        self.partial.iter().find(|partial| partial.account == account)
102    }
103
104    // End of a request for at most `max` of `contracts` from `first`, starting at slot `from`.
105    // Snap defines a starting slot only for a single-account request, so a contract resuming part
106    // way is requested alone, and one later in the batch ends the request before it.
107    pub(crate) fn request_end<T>(
108        &self,
109        contracts: &[(B256, T)],
110        first: usize,
111        from: B256,
112        max: usize,
113    ) -> usize {
114        if !from.is_zero() {
115            return first + 1
116        }
117        let end = contracts.len().min(first.saturating_add(max));
118        contracts[first + 1..end]
119            .iter()
120            .position(|(account, _)| self.partial_of(*account).is_some())
121            .map_or(end, |offset| first + 1 + offset)
122    }
123
124    // Hands the progress of contracts past a committed range to the range continuing at `next`.
125    pub(crate) fn carry_to(
126        mut self,
127        provider: &impl MetadataWriter,
128        write: SnapWrite,
129        next: B256,
130    ) -> Result<(), SnapSyncError> {
131        self.complete = self.complete.filter(|complete| *complete >= next);
132        self.partial.retain(|partial| partial.account >= next);
133        if self != Self::START {
134            StoredProgress::new(write, next, self).write(provider)?;
135        }
136        Ok(())
137    }
138
139    /// Slot `account`'s storage resumes at: zero before it starts, `None` once it is complete.
140    pub fn resume_at(&self, account: B256) -> Option<B256> {
141        if self.is_complete(account) {
142            return None
143        }
144        Some(self.partial_of(account).map_or(B256::ZERO, |partial| partial.next))
145    }
146
147    // The same progress with every partial contract's root unproved, after the pivot moved.
148    fn carried(mut self) -> Self {
149        for partial in &mut self.partial {
150            partial.storage_root = None;
151        }
152        self
153    }
154
155    // The progress after `chunk`, which must continue its contract or start the next one.
156    //
157    // A contract carried across a pivot move does not block others: the new root can hold
158    // contracts before it, or no longer hold it at all.
159    fn advance(mut self, chunk: &StorageChunk) -> Result<Self, SnapSyncError> {
160        let blocked = self
161            .partial
162            .iter()
163            .any(|partial| partial.account < chunk.account && partial.storage_root.is_some());
164        if blocked || self.resume_at(chunk.account) != Some(chunk.from) {
165            return Err(SnapSyncError::OutOfOrderStorage {
166                account: chunk.account,
167                from: chunk.from,
168            })
169        }
170        if let Some(partial) = self.partial_of(chunk.account) &&
171            let Some(expected) = partial.storage_root &&
172            expected != chunk.storage_root
173        {
174            return Err(SnapSyncError::StorageRootMismatch {
175                account: chunk.account,
176                expected,
177                got: chunk.storage_root,
178            })
179        }
180        if chunk.next.is_some_and(|next| next <= chunk.from) {
181            return Err(SnapSyncError::NoProgress { origin: chunk.from })
182        }
183        // Carried contracts past this one stay resumable, those before it were skipped, so the new
184        // root no longer holds them.
185        self.partial.retain(|partial| partial.account > chunk.account);
186        match chunk.next {
187            Some(next) => {
188                let storage_root = Some(chunk.storage_root);
189                self.partial
190                    .insert(0, PartialStorage { account: chunk.account, storage_root, next });
191            }
192            None => self.complete = Some(chunk.account),
193        }
194        Ok(self)
195    }
196}
197
198// A contract whose storage is persisted up to, but not including, `next`.
199#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
200struct PartialStorage {
201    // Hashed address of the contract.
202    account: B256,
203    // Root its slots were proved against, none once the pivot moved past it.
204    storage_root: Option<B256>,
205    // Slot its storage resumes at.
206    next: B256,
207}
208
209// The progress record as persisted, tied to the write and range that recorded it.
210#[derive(Serialize, Deserialize)]
211pub(crate) struct StoredProgress {
212    // Encoding version, checked before the rest is decoded.
213    version: u32,
214    // Attempt the slots belong to.
215    attempt: SnapAttemptId,
216    // Pivot generation the last chunk was proved against.
217    state_version: u64,
218    // Key the account range was requested from.
219    origin: B256,
220    // How far that range's contracts have got.
221    progress: StorageProgress,
222}
223
224impl SnapRecord for StoredProgress {
225    const KEY: &'static str = "snap_storage_progress";
226    const VERSION: u32 = 2;
227}
228
229impl StoredProgress {
230    // `progress` for `write`'s range at `origin` at this build's version.
231    const fn new(write: SnapWrite, origin: B256, progress: StorageProgress) -> Self {
232        Self {
233            version: Self::VERSION,
234            attempt: write.attempt(),
235            state_version: write.state_version(),
236            origin,
237            progress,
238        }
239    }
240
241    // The recorded progress, if it belongs to `write`'s attempt and the range at `origin`.
242    fn into_progress(self, write: SnapWrite, origin: B256) -> Option<StorageProgress> {
243        if self.attempt != write.attempt() || self.origin != origin {
244            return None
245        }
246        Some(if self.state_version == write.state_version() {
247            self.progress
248        } else {
249            self.progress.carried()
250        })
251    }
252}
253
254impl<T: MetadataProvider> SnapStorageStore for T {
255    // A record left by another attempt or range reads as nothing persisted.
256    fn storage_progress(
257        &self,
258        write: SnapWrite,
259        origin: B256,
260    ) -> Result<StorageProgress, SnapSyncError> {
261        self.authorize_snap_write(write)?;
262        let Some(stored) = StoredProgress::read(self)? else { return Ok(StorageProgress::START) };
263        Ok(stored.into_progress(write, origin).unwrap_or(StorageProgress::START))
264    }
265
266    // Every check runs before the first write, so a refused chunk changes nothing.
267    fn commit_storage_chunk(
268        &self,
269        write: SnapWrite,
270        origin: B256,
271        chunk: StorageChunk,
272    ) -> Result<StorageProgress, SnapSyncError>
273    where
274        Self: MetadataWriter + StateWriter + DBProvider<Tx: DbTxMut>,
275    {
276        let coverage = self.account_coverage(write)?.ok_or(SnapSyncError::NoCoverage)?;
277        if coverage.next() != Some(origin) {
278            return Err(SnapSyncError::OutOfOrderRange { expected: coverage.next(), got: origin })
279        }
280        if chunk.account < origin || chunk.storage_root == EMPTY_ROOT_HASH {
281            return Err(SnapSyncError::UnexpectedStorage { account: chunk.account })
282        }
283        let progress = self.storage_progress(write, origin)?;
284        let complete = progress.complete;
285        let progress = progress.advance(&chunk)?;
286
287        if chunk.next.is_none() {
288            // Skipped accounts have empty storage at this pivot. Clear earlier attempts' slots
289            // before the completion watermark makes them eligible for reuse and BAL updates.
290            let start = complete.map_or(Some(origin), |account| {
291                U256::from_be_bytes(account.0).checked_add(U256::ONE).map(B256::from)
292            });
293            if let Some(start) = start {
294                self.remove::<tables::HashedStorages>(start..chunk.account)?;
295            }
296        }
297        if chunk.from.is_zero() {
298            self.remove::<tables::HashedStorages>(chunk.account..=chunk.account)?;
299        }
300        let state = HashedPostState::default()
301            .with_storages([(chunk.account, HashedStorage::from_iter(chunk.slots))])
302            .into_sorted();
303        self.write_hashed_state(&state)?;
304        let stored = StoredProgress::new(write, origin, progress);
305        stored.write(self)?;
306        Ok(stored.progress)
307    }
308}
309
310/// Root of the storage persisted for `account`, streamed so a large contract is never held in
311/// memory.
312pub(crate) fn persisted_storage_root(tx: &impl DbTx, account: B256) -> Result<B256, SnapSyncError> {
313    let mut cursor = tx.cursor_dup_read::<tables::HashedStorages>()?;
314    let mut failed = None;
315    let slots = cursor.walk_dup(Some(account), None)?.map_while(|entry| {
316        entry.map(|(_, slot)| (slot.key, slot.value)).map_err(|error| failed = Some(error)).ok()
317    });
318    let root = storage_root(slots);
319    failed.map_or(Ok(root), |error| Err(error.into()))
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325    use crate::test_utils::{
326        account, generation, hashed_factory_with_roots, state_root, storage_root_of, stored_slots,
327    };
328    use reth_provider::{
329        test_utils::MockNodeTypesWithDB, DatabaseProviderFactory, ProviderFactory,
330    };
331    use std::ops::Range;
332
333    const CONTRACT: B256 = B256::repeat_byte(0x22);
334
335    fn slot(value: u8) -> B256 {
336        B256::with_last_byte(value)
337    }
338
339    fn slots() -> Vec<(B256, U256)> {
340        vec![(slot(1), U256::from(11)), (slot(2), U256::from(12)), (slot(3), U256::from(13))]
341    }
342
343    fn root() -> B256 {
344        storage_root_of(&slots())
345    }
346
347    // `slots()[served]` requested from `from`, continuing at `next`.
348    fn chunk(served: Range<usize>, from: B256, next: Option<B256>) -> StorageChunk {
349        StorageChunk::new(CONTRACT, root(), from, slots()[served].to_vec(), next)
350    }
351
352    // An attempt whose account coverage has not reached the contract yet.
353    fn started() -> (ProviderFactory<MockNodeTypesWithDB>, SnapWrite) {
354        let mut contract = account(1);
355        contract.storage_root = root();
356        let state_root = state_root(&[(CONTRACT, contract)]);
357        let factory = hashed_factory_with_roots(&[state_root]);
358        let provider = factory.database_provider_rw().unwrap();
359        let generation = generation(1, state_root);
360        let write = provider.start_snap_attempt(generation).unwrap();
361        provider.start_account_coverage(write).unwrap();
362        provider.commit().unwrap();
363        (factory, write)
364    }
365
366    #[test]
367    fn an_interrupted_chunk_commit_keeps_the_last_committed_progress() {
368        let (factory, write) = started();
369        let provider = factory.database_provider_rw().unwrap();
370        let first = chunk(0..1, B256::ZERO, Some(slot(2)));
371        let progress = provider.commit_storage_chunk(write, B256::ZERO, first).unwrap();
372        provider.commit().unwrap();
373        assert_eq!(progress.resume_at(CONTRACT), Some(slot(2)));
374
375        let provider = factory.database_provider_rw().unwrap();
376        let rest = chunk(1..3, slot(2), None);
377        assert!(provider
378            .commit_storage_chunk(write, B256::ZERO, rest)
379            .unwrap()
380            .is_complete(CONTRACT));
381        drop(provider);
382
383        let provider = factory.database_provider_rw().unwrap();
384        assert_eq!(provider.storage_progress(write, B256::ZERO).unwrap(), progress);
385        assert_eq!(stored_slots(&provider, CONTRACT), slots()[..1]);
386    }
387
388    #[test]
389    fn a_chunk_must_continue_its_contract_before_another_starts() {
390        let (factory, write) = started();
391        let provider = factory.database_provider_rw().unwrap();
392        let first = chunk(0..1, B256::ZERO, Some(slot(2)));
393        let progress = provider.commit_storage_chunk(write, B256::ZERO, first).unwrap();
394
395        let refused = [
396            // Restarted, skipping ahead, or another contract while this one is part way through.
397            chunk(0..1, B256::ZERO, Some(slot(2))),
398            chunk(2..3, slot(3), None),
399            StorageChunk::new(B256::repeat_byte(0x44), root(), B256::ZERO, slots(), None),
400        ];
401        for chunk in refused {
402            assert!(matches!(
403                provider.commit_storage_chunk(write, B256::ZERO, chunk),
404                Err(SnapSyncError::OutOfOrderStorage { .. })
405            ));
406        }
407        let stalled = chunk(1..1, slot(2), Some(slot(2)));
408        assert!(matches!(
409            provider.commit_storage_chunk(write, B256::ZERO, stalled),
410            Err(SnapSyncError::NoProgress { .. })
411        ));
412        let other_root = StorageChunk::new(
413            CONTRACT,
414            B256::repeat_byte(0x33),
415            slot(2),
416            slots()[1..].to_vec(),
417            None,
418        );
419        assert!(matches!(
420            provider.commit_storage_chunk(write, B256::ZERO, other_root),
421            Err(SnapSyncError::StorageRootMismatch { .. })
422        ));
423
424        assert_eq!(provider.storage_progress(write, B256::ZERO).unwrap(), progress);
425        assert_eq!(stored_slots(&provider, CONTRACT), slots()[..1]);
426    }
427
428    #[test]
429    fn starting_a_contract_replaces_what_an_earlier_attempt_left() {
430        let (factory, write) = started();
431        let provider = factory.database_provider_rw().unwrap();
432        let leftover = HashedStorage::from_iter([(slot(7), U256::from(77))]);
433        let leftover = HashedPostState::default().with_storages([(CONTRACT, leftover)]);
434        provider.write_hashed_state(&leftover.into_sorted()).unwrap();
435
436        provider.commit_storage_chunk(write, B256::ZERO, chunk(0..3, B256::ZERO, None)).unwrap();
437
438        assert_eq!(stored_slots(&provider, CONTRACT), slots());
439        assert_eq!(persisted_storage_root(provider.tx_ref(), CONTRACT).unwrap(), root());
440    }
441
442    // `CONTRACT` part way through at pivot 1, then the pivot moved to block 2.
443    fn carried() -> (ProviderFactory<MockNodeTypesWithDB>, SnapWrite, SnapWrite) {
444        let (factory, write) = started();
445        let provider = factory.database_provider_rw().unwrap();
446        let first = chunk(0..1, B256::ZERO, Some(slot(2)));
447        provider.commit_storage_chunk(write, B256::ZERO, first).unwrap();
448        let advanced =
449            provider.advance_snap_pivot(write, generation(2, B256::repeat_byte(2))).unwrap();
450        provider.commit().unwrap();
451        (factory, write, advanced)
452    }
453
454    // Whole storage of `account`, proved against `root()`.
455    fn whole(account: B256) -> StorageChunk {
456        StorageChunk::new(account, root(), B256::ZERO, slots(), None)
457    }
458
459    #[test]
460    fn progress_survives_the_pivot_moving_with_its_root_unproved() {
461        let (factory, write, advanced) = carried();
462        let provider = factory.database_provider_rw().unwrap();
463
464        assert_eq!(provider.storage_progress(advanced, slot(9)).unwrap(), StorageProgress::START);
465        let progress = provider.storage_progress(advanced, B256::ZERO).unwrap();
466        assert_eq!(progress.resume_at(CONTRACT), Some(slot(2)));
467        assert!(matches!(
468            provider.commit_storage_chunk(write, B256::ZERO, chunk(1..3, slot(2), None)),
469            Err(SnapSyncError::StaleWrite { .. })
470        ));
471
472        // The new root's slots continue the carried ones, whatever root those were proved against.
473        let rest = StorageChunk::new(
474            CONTRACT,
475            B256::repeat_byte(0x33),
476            slot(2),
477            slots()[1..].to_vec(),
478            None,
479        );
480        let progress = provider.commit_storage_chunk(advanced, B256::ZERO, rest).unwrap();
481        assert!(progress.is_complete(CONTRACT));
482        assert_eq!(stored_slots(&provider, CONTRACT), slots());
483    }
484
485    #[test]
486    fn a_carried_contract_does_not_block_the_contracts_the_new_root_holds() {
487        let (factory, _, advanced) = carried();
488        let provider = factory.database_provider_rw().unwrap();
489
490        // A contract created before it since the pivot moved finishes first, keeping it resumable.
491        let before = B256::repeat_byte(0x11);
492        let progress = provider.commit_storage_chunk(advanced, B256::ZERO, whole(before)).unwrap();
493        assert!(progress.is_complete(before));
494        assert_eq!(progress.resume_at(CONTRACT), Some(slot(2)));
495
496        // One after it means the new root no longer holds it as a contract.
497        let after = B256::repeat_byte(0x44);
498        let progress = provider.commit_storage_chunk(advanced, B256::ZERO, whole(after)).unwrap();
499        assert!(progress.is_complete(after));
500        assert!(progress.partial.is_empty());
501    }
502
503    #[test]
504    fn a_new_contract_part_way_keeps_the_carried_one_resumable() {
505        let (factory, _, advanced) = carried();
506        let provider = factory.database_provider_rw().unwrap();
507        let before = B256::repeat_byte(0x11);
508        let first =
509            StorageChunk::new(before, root(), B256::ZERO, slots()[..1].to_vec(), Some(slot(2)));
510        provider.commit_storage_chunk(advanced, B256::ZERO, first).unwrap();
511
512        // Both stay resumable, even across another pivot move.
513        let advanced =
514            provider.advance_snap_pivot(advanced, generation(3, B256::repeat_byte(3))).unwrap();
515        let progress = provider.storage_progress(advanced, B256::ZERO).unwrap();
516        assert_eq!(progress.resume_at(before), Some(slot(2)));
517        assert_eq!(progress.resume_at(CONTRACT), Some(slot(2)));
518
519        let rest = StorageChunk::new(before, root(), slot(2), slots()[1..].to_vec(), None);
520        let progress = provider.commit_storage_chunk(advanced, B256::ZERO, rest).unwrap();
521        assert!(progress.is_complete(before));
522        assert_eq!(progress.resume_at(CONTRACT), Some(slot(2)));
523    }
524
525    #[test]
526    fn a_contract_resuming_part_way_leads_its_request() {
527        let progress = StorageProgress {
528            complete: None,
529            partial: vec![PartialStorage { account: CONTRACT, storage_root: None, next: slot(2) }],
530        };
531        let contracts = [(slot(1), ()), (CONTRACT, ()), (B256::repeat_byte(0x33), ())];
532
533        assert_eq!(progress.request_end(&contracts, 0, B256::ZERO, 10), 1);
534        assert_eq!(progress.request_end(&contracts, 1, slot(2), 10), 2);
535        assert_eq!(progress.request_end(&contracts, 1, slot(2), 1), 2);
536        assert_eq!(progress.request_end(&contracts, 2, B256::ZERO, 10), 3);
537        assert_eq!(StorageProgress::START.request_end(&contracts, 0, B256::ZERO, 10), 3);
538    }
539
540    #[test]
541    fn storage_outside_the_range_being_downloaded_is_refused() {
542        let (factory, write) = started();
543        let provider = factory.database_provider_rw().unwrap();
544
545        let ahead = provider.commit_storage_chunk(write, slot(9), chunk(0..3, B256::ZERO, None));
546        let empty = StorageChunk::new(CONTRACT, EMPTY_ROOT_HASH, B256::ZERO, Vec::new(), None);
547        let empty = provider.commit_storage_chunk(write, B256::ZERO, empty);
548
549        assert!(matches!(ahead, Err(SnapSyncError::OutOfOrderRange { .. })));
550        assert!(matches!(empty, Err(SnapSyncError::UnexpectedStorage { .. })));
551        assert!(stored_slots(&provider, CONTRACT).is_empty());
552    }
553
554    #[test]
555    fn a_record_this_build_cannot_read_is_reported() {
556        let (factory, write) = started();
557
558        for record in [br#"{"version":999}"#.to_vec(), b"{}".to_vec()] {
559            let provider = factory.database_provider_rw().unwrap();
560            provider.write_metadata(StoredProgress::KEY, record).unwrap();
561
562            assert!(matches!(
563                provider.storage_progress(write, B256::ZERO),
564                Err(SnapSyncError::UnsupportedRecord { .. })
565            ));
566        }
567
568        for record in [b"not json".to_vec(), br#"{"version":2}"#.to_vec()] {
569            let provider = factory.database_provider_rw().unwrap();
570            provider.write_metadata(StoredProgress::KEY, record).unwrap();
571
572            assert!(matches!(
573                provider.storage_progress(write, B256::ZERO),
574                Err(SnapSyncError::UnreadableRecord { .. })
575            ));
576        }
577    }
578}