Skip to main content

reth_trie/hashed_cursor/
post_state.rs

1use super::{HashedCursor, HashedCursorFactory, HashedStorageCursor};
2use crate::{cursor_position::CursorPosition, forward_cursor::ForwardInMemoryCursor};
3use alloy_primitives::{B256, U256};
4use reth_primitives_traits::Account;
5use reth_storage_errors::db::DatabaseError;
6use reth_trie_common::HashedPostStateSorted;
7use std::ops::Bound;
8
9/// The hashed cursor factory for the post state.
10#[derive(Clone, Debug)]
11pub struct HashedPostStateCursorFactory<CF, T> {
12    cursor_factory: CF,
13    post_state: T,
14}
15
16impl<CF, T> HashedPostStateCursorFactory<CF, T> {
17    /// Create a new factory.
18    pub const fn new(cursor_factory: CF, post_state: T) -> Self {
19        Self { cursor_factory, post_state }
20    }
21}
22
23impl<'overlay, CF, T> HashedCursorFactory for HashedPostStateCursorFactory<CF, &'overlay T>
24where
25    CF: HashedCursorFactory,
26    T: AsRef<HashedPostStateSorted>,
27{
28    type AccountCursor<'cursor>
29        = HashedPostStateCursor<'overlay, CF::AccountCursor<'cursor>, Option<Account>>
30    where
31        Self: 'cursor;
32    type StorageCursor<'cursor>
33        = HashedPostStateCursor<'overlay, CF::StorageCursor<'cursor>, U256>
34    where
35        Self: 'cursor;
36
37    fn hashed_account_cursor(&self) -> Result<Self::AccountCursor<'_>, DatabaseError> {
38        let cursor = self.cursor_factory.hashed_account_cursor()?;
39        Ok(HashedPostStateCursor::new_account(cursor, self.post_state.as_ref()))
40    }
41
42    fn hashed_storage_cursor(
43        &self,
44        hashed_address: B256,
45    ) -> Result<Self::StorageCursor<'_>, DatabaseError> {
46        let post_state = self.post_state.as_ref();
47        let cursor = self.cursor_factory.hashed_storage_cursor(hashed_address)?;
48        Ok(HashedPostStateCursor::new_storage(cursor, post_state, hashed_address))
49    }
50}
51
52/// Trait for types that can be used with [`HashedPostStateCursor`] as a value.
53///
54/// This enables uniform handling of deletions across different wrapper types:
55/// - `Option<Account>`: `None` indicates deletion
56/// - `U256`: `U256::ZERO` indicates deletion (maps to `None`)
57///
58/// This design allows us to use `U256::ZERO`, rather than an Option, to indicate deletion for
59/// storage (which maps cleanly to how changesets are stored in the DB) while not requiring two
60/// different cursor implementations.
61pub trait HashedPostStateCursorValue: Clone {
62    /// The non-zero type returned by `into_option`.
63    /// For `Option<Account>`, this is `Account`.
64    /// For `U256`, this is `U256`.
65    type NonZero: Clone + std::fmt::Debug;
66
67    /// Returns `Some(&NonZero)` if the value is present, `None` if deleted.
68    fn into_option(self) -> Option<Self::NonZero>;
69}
70
71impl HashedPostStateCursorValue for Option<Account> {
72    type NonZero = Account;
73
74    fn into_option(self) -> Option<Self::NonZero> {
75        self
76    }
77}
78
79impl HashedPostStateCursorValue for U256 {
80    type NonZero = Self;
81
82    fn into_option(self) -> Option<Self::NonZero> {
83        (!self.is_zero()).then_some(self)
84    }
85}
86
87/// A cursor to iterate over state updates and corresponding database entries.
88/// It will always give precedence to the data from the post state updates.
89#[derive(Debug)]
90pub struct HashedPostStateCursor<'a, C, V>
91where
92    V: HashedPostStateCursorValue,
93{
94    /// The underlying cursor.
95    cursor: C,
96    /// Tracks whether the DB cursor is available, positioned, or exhausted.
97    db_cursor_state: DbCursorState<V::NonZero>,
98    /// Forward-only in-memory cursor over underlying V.
99    post_state_cursor: ForwardInMemoryCursor<'a, B256, V>,
100    /// The logical result and the request range covered by the cursor positions.
101    position: CursorPosition<B256>,
102    /// Reference to the full post state.
103    post_state: &'a HashedPostStateSorted,
104}
105
106#[derive(Debug)]
107enum DbCursorState<V> {
108    NeedsPosition,
109    Positioned((B256, V)),
110    Exhausted,
111}
112
113impl<V> DbCursorState<V> {
114    const fn entry(&self) -> Option<&(B256, V)> {
115        match self {
116            Self::Positioned(entry) => Some(entry),
117            Self::NeedsPosition | Self::Exhausted => None,
118        }
119    }
120
121    fn set_entry(&mut self, entry: Option<(B256, V)>) {
122        *self = match entry {
123            Some(entry) => Self::Positioned(entry),
124            None => Self::Exhausted,
125        };
126    }
127}
128
129impl<'a, C> HashedPostStateCursor<'a, C, Option<Account>>
130where
131    C: HashedCursor<Value = Account>,
132{
133    /// Create new account cursor which combines a DB cursor and the post state.
134    pub fn new_account(cursor: C, post_state: &'a HashedPostStateSorted) -> Self {
135        let post_state_cursor = ForwardInMemoryCursor::new(&post_state.accounts);
136        Self {
137            cursor,
138            db_cursor_state: DbCursorState::NeedsPosition,
139            post_state_cursor,
140            position: CursorPosition::Unseeked,
141            post_state,
142        }
143    }
144}
145
146impl<'a, C> HashedPostStateCursor<'a, C, U256>
147where
148    C: HashedStorageCursor<Value = U256>,
149{
150    /// Create new storage cursor with full post state reference.
151    /// This allows the cursor to switch between storage tries when `set_hashed_address` is called.
152    pub fn new_storage(
153        cursor: C,
154        post_state: &'a HashedPostStateSorted,
155        hashed_address: B256,
156    ) -> Self {
157        let post_state_cursor = Self::get_storage_overlay(post_state, hashed_address);
158        Self {
159            cursor,
160            db_cursor_state: DbCursorState::NeedsPosition,
161            post_state_cursor,
162            position: CursorPosition::Unseeked,
163            post_state,
164        }
165    }
166
167    /// Returns the storage overlay for `hashed_address`.
168    fn get_storage_overlay(
169        post_state: &'a HashedPostStateSorted,
170        hashed_address: B256,
171    ) -> ForwardInMemoryCursor<'a, B256, U256> {
172        let post_state_storage = post_state.storages.get(&hashed_address);
173        let storage_slots = post_state_storage.map(|u| u.storage_slots_ref()).unwrap_or(&[]);
174
175        ForwardInMemoryCursor::new(storage_slots)
176    }
177}
178
179impl<'a, C, V> HashedPostStateCursor<'a, C, V>
180where
181    C: HashedCursor<Value = V::NonZero>,
182    V: HashedPostStateCursorValue,
183{
184    const fn get_cursor_mut(&mut self) -> &mut C {
185        &mut self.cursor
186    }
187
188    /// Positions the DB cursor state using the underlying cursor when needed.
189    /// Errors invalidate both cursor positions so a later seek can safely retry.
190    fn cursor_seek(&mut self, key: B256) -> Result<(), DatabaseError> {
191        // Only seek if:
192        // 1. We have a cursor entry and need to seek forward (entry.0 < key), OR
193        // 2. The DB cursor needs to be positioned.
194        let should_seek = match &self.db_cursor_state {
195            DbCursorState::NeedsPosition => true,
196            DbCursorState::Positioned((entry_key, _)) => entry_key < &key,
197            DbCursorState::Exhausted => false,
198        };
199
200        if should_seek {
201            let entry = self.get_cursor_mut().seek(key).inspect_err(|_| self.reset())?;
202            self.db_cursor_state.set_entry(entry);
203        }
204
205        Ok(())
206    }
207
208    /// Advances the DB cursor state to the subsequent entry using the underlying cursor.
209    /// Errors invalidate both cursor positions so a later seek can safely retry.
210    fn cursor_next(&mut self) -> Result<(), DatabaseError> {
211        debug_assert!(!matches!(self.position, CursorPosition::Unseeked));
212
213        // Exhausted DB state is stable; only advance when the DB cursor is positioned at an entry.
214        if matches!(self.db_cursor_state, DbCursorState::Positioned(_)) {
215            let entry = self.get_cursor_mut().next().inspect_err(|_| self.reset())?;
216            self.db_cursor_state.set_entry(entry);
217        }
218
219        Ok(())
220    }
221
222    /// Compares the current in-memory entry with the current entry of the cursor, and applies the
223    /// in-memory entry to the cursor entry as an overlay.
224    ///
225    /// This may consume and move forward the current entries when the overlay indicates a removed
226    /// node.
227    fn choose_next_entry(&mut self) -> Result<Option<(B256, V::NonZero)>, DatabaseError> {
228        loop {
229            let post_state_current =
230                self.post_state_cursor.current().cloned().map(|(k, v)| (k, v.into_option()));
231            let db_entry = self.db_cursor_state.entry();
232
233            match (post_state_current, db_entry) {
234                (Some((mem_key, None)), _)
235                    if db_entry.is_none_or(|(db_key, _)| &mem_key < db_key) =>
236                {
237                    // If overlay has a removed value but DB cursor is exhausted or ahead of the
238                    // in-memory cursor then move ahead in-memory, as there might be further
239                    // non-removed overlay values.
240                    self.post_state_cursor.first_after(&mem_key);
241                }
242                (Some((mem_key, None)), Some((db_key, _))) if &mem_key == db_key => {
243                    // If overlay has a removed value which is returned from DB then move both
244                    // cursors ahead to the next key.
245                    self.post_state_cursor.first_after(&mem_key);
246                    self.cursor_next()?;
247                }
248                (Some((mem_key, Some(value))), _)
249                    if db_entry.is_none_or(|(db_key, _)| &mem_key <= db_key) =>
250                {
251                    // If overlay returns a value prior to the DB's value, or the DB is exhausted,
252                    // then we return the overlay's value.
253                    return Ok(Some((mem_key, value)))
254                }
255                // All other cases:
256                // - mem_key > db_key
257                // - overlay is exhausted
258                // Return the db_entry. If DB is also exhausted then this returns None.
259                _ => return Ok(db_entry.cloned()),
260            }
261        }
262    }
263}
264
265impl<C, V> HashedCursor for HashedPostStateCursor<'_, C, V>
266where
267    C: HashedCursor<Value = V::NonZero>,
268    V: HashedPostStateCursorValue,
269{
270    type Value = V::NonZero;
271
272    /// Seek the next entry for a given hashed key.
273    ///
274    /// If the post state contains the exact match for the key, return it.
275    /// Otherwise, retrieve the next entries that are greater than or equal to the key from the
276    /// database and the post state. The two entries are compared and the lowest is returned.
277    ///
278    /// The returned account key is memoized and the cursor remains positioned at that key until
279    /// [`HashedCursor::seek`] or [`HashedCursor::next`] are called.
280    fn seek(&mut self, key: B256) -> Result<Option<(B256, Self::Value)>, DatabaseError> {
281        // A returned successor may be ahead of the request after scanning deleted entries.
282        // Rewind only when the request precedes the range those scans established.
283        if self.position.must_rewind(key) {
284            self.reset();
285        }
286        self.position.set_lower_bound(Bound::Included(key));
287        let post_state_entry =
288            self.post_state_cursor.seek(&key).cloned().map(|(k, v)| (k, v.into_option()));
289
290        if let Some((mem_key, Some(value))) = post_state_entry &&
291            mem_key == key
292        {
293            // An exact overlay hit is the first logical entry at or after `key`, so the DB cursor
294            // can stay lazy until a later operation needs it.
295            if matches!(&self.db_cursor_state, DbCursorState::Positioned((db_key, _)) if db_key < &key)
296            {
297                self.db_cursor_state = DbCursorState::NeedsPosition;
298            }
299
300            let entry = Some((key, value));
301            self.position.set_key(entry.as_ref().map(|entry| entry.0));
302            return Ok(entry)
303        }
304
305        self.cursor_seek(key)?;
306
307        let entry = self.choose_next_entry()?;
308        self.position.set_key(entry.as_ref().map(|entry| entry.0));
309        Ok(entry)
310    }
311
312    /// Retrieve the next entry from the cursor.
313    ///
314    /// If the cursor is positioned at the entry, return the entry with next greater key.
315    /// Returns [None] if the previous memoized or the next greater entries are missing.
316    ///
317    /// NOTE: This function will not return any entry unless [`HashedCursor::seek`] has been called.
318    fn next(&mut self) -> Result<Option<(B256, Self::Value)>, DatabaseError> {
319        debug_assert!(
320            !matches!(self.position, CursorPosition::Unseeked),
321            "Cursor must be seek'd before next is called",
322        );
323
324        // A missing logical result leaves the reusable request bound unchanged.
325        let Some(last_key) = self.position.key() else {
326            return Ok(None);
327        };
328
329        // Consuming the current entry makes it unavailable to subsequent seeks at or below it.
330        self.position.set_lower_bound(Bound::Excluded(last_key));
331
332        // If either cursor is currently pointing to the last entry which was returned then consume
333        // that entry so that `choose_next_entry` is looking at the subsequent one.
334        if let Some((key, _)) = self.post_state_cursor.current() &&
335            key == &last_key
336        {
337            self.post_state_cursor.first_after(&last_key);
338        }
339
340        if matches!(self.db_cursor_state, DbCursorState::NeedsPosition) {
341            self.cursor_seek(last_key)?;
342        }
343
344        if let Some((key, _)) = self.db_cursor_state.entry() &&
345            key == &last_key
346        {
347            self.cursor_next()?;
348        }
349
350        let entry = self.choose_next_entry()?;
351        self.position.set_key(entry.as_ref().map(|entry| entry.0));
352        Ok(entry)
353    }
354
355    fn reset(&mut self) {
356        let Self { cursor, db_cursor_state, post_state_cursor, position, .. } = self;
357
358        cursor.reset();
359        post_state_cursor.reset();
360
361        *db_cursor_state = DbCursorState::NeedsPosition;
362        *position = CursorPosition::Unseeked;
363    }
364}
365
366/// The cursor to iterate over post state hashed values and corresponding database entries.
367/// It will always give precedence to the data from the post state.
368impl<C> HashedStorageCursor for HashedPostStateCursor<'_, C, U256>
369where
370    C: HashedStorageCursor<Value = U256>,
371{
372    /// Returns `true` if the account has no storage entries.
373    ///
374    /// This function should be called before attempting to call [`HashedCursor::seek`] or
375    /// [`HashedCursor::next`].
376    fn is_storage_empty(&mut self) -> Result<bool, DatabaseError> {
377        let is_empty = self.seek(B256::ZERO)?.is_none();
378        self.reset();
379        Ok(is_empty)
380    }
381
382    fn set_hashed_address(&mut self, hashed_address: B256) {
383        self.reset();
384        self.cursor.set_hashed_address(hashed_address);
385        let post_state_cursor =
386            HashedPostStateCursor::<C, U256>::get_storage_overlay(self.post_state, hashed_address);
387        self.post_state_cursor = post_state_cursor;
388        self.db_cursor_state = DbCursorState::NeedsPosition;
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395    use crate::hashed_cursor::mock::{MockHashedCursor, MockHashedCursorFactory};
396    use alloy_primitives::map::B256Map;
397    use reth_concurrency::sync::parking_lot::Mutex;
398    use reth_trie_common::{HashedPostState, HashedStorage};
399    use std::{collections::BTreeMap, sync::Arc};
400
401    fn key(byte: u8) -> B256 {
402        B256::repeat_byte(byte)
403    }
404
405    fn storage_post_state(storage_slots: Vec<(B256, U256)>) -> HashedPostStateSorted {
406        let storage_sorted = reth_trie_common::HashedStorageSorted { storage_slots };
407        let mut storages = alloy_primitives::map::B256Map::default();
408        storages.insert(B256::ZERO, storage_sorted);
409        HashedPostStateSorted::new(Vec::new(), storages)
410    }
411
412    #[reth_concurrency::test]
413    fn test_seek_overlay_exact_hit_does_not_touch_db_until_next() {
414        let db_nodes = vec![(key(0x02), U256::from(2)), (key(0x03), U256::from(3))];
415        let post_state_nodes = vec![(key(0x02), U256::from(42))];
416
417        let db_nodes_map: BTreeMap<B256, U256> = db_nodes.into_iter().collect();
418        let db_nodes_arc = Arc::new(db_nodes_map);
419        let visited_keys = Arc::new(Mutex::new(Vec::new()));
420        let mock_cursor = MockHashedCursor::new(db_nodes_arc, visited_keys.clone());
421
422        let post_state = storage_post_state(post_state_nodes);
423        let mut cursor = HashedPostStateCursor::new_storage(mock_cursor, &post_state, B256::ZERO);
424
425        let result = cursor.seek(key(0x02)).unwrap();
426        assert_eq!(result, Some((key(0x02), U256::from(42))));
427        assert!(visited_keys.lock().is_empty(), "exact overlay hit should not touch the DB cursor");
428
429        let result = cursor.next().unwrap();
430        assert_eq!(result, Some((key(0x03), U256::from(3))));
431        assert!(!visited_keys.lock().is_empty(), "next should lazily position the DB cursor");
432    }
433
434    #[reth_concurrency::test]
435    fn test_seek_overlay_exact_hit_repositions_stale_db_on_next() {
436        let db_nodes = vec![(key(0x01), U256::ONE), (key(0x03), U256::from(3))];
437        let post_state_nodes = vec![(key(0x02), U256::from(2))];
438
439        let db_nodes_map: BTreeMap<B256, U256> = db_nodes.into_iter().collect();
440        let db_nodes_arc = Arc::new(db_nodes_map);
441        let visited_keys = Arc::new(Mutex::new(Vec::new()));
442        let mock_cursor = MockHashedCursor::new(db_nodes_arc, visited_keys.clone());
443
444        let post_state = storage_post_state(post_state_nodes);
445        let mut cursor = HashedPostStateCursor::new_storage(mock_cursor, &post_state, B256::ZERO);
446
447        let result = cursor.seek(key(0x01)).unwrap();
448        assert_eq!(result, Some((key(0x01), U256::ONE)));
449        assert_eq!(visited_keys.lock().len(), 1);
450
451        let result = cursor.seek(key(0x02)).unwrap();
452        assert_eq!(result, Some((key(0x02), U256::from(2))));
453        assert_eq!(visited_keys.lock().len(), 1, "exact overlay hit should not seek the DB");
454
455        let result = cursor.next().unwrap();
456        assert_eq!(result, Some((key(0x03), U256::from(3))));
457    }
458
459    #[reth_concurrency::test]
460    fn test_seek_overlay_exact_deletion_still_seeks_db() {
461        let db_nodes = vec![(key(0x02), U256::from(2)), (key(0x03), U256::from(3))];
462        let post_state_nodes = vec![(key(0x02), U256::ZERO)];
463
464        let db_nodes_map: BTreeMap<B256, U256> = db_nodes.into_iter().collect();
465        let db_nodes_arc = Arc::new(db_nodes_map);
466        let visited_keys = Arc::new(Mutex::new(Vec::new()));
467        let mock_cursor = MockHashedCursor::new(db_nodes_arc, visited_keys.clone());
468
469        let post_state = storage_post_state(post_state_nodes);
470        let mut cursor = HashedPostStateCursor::new_storage(mock_cursor, &post_state, B256::ZERO);
471
472        let result = cursor.seek(key(0x02)).unwrap();
473        assert_eq!(result, Some((key(0x03), U256::from(3))));
474        assert!(!visited_keys.lock().is_empty(), "exact overlay deletion should consult the DB");
475    }
476
477    mod proptest_tests {
478        use super::*;
479        use itertools::Itertools;
480        use proptest::prelude::*;
481
482        /// Merge `db_nodes` with `post_state_nodes`, applying the post state overlay.
483        /// This properly handles deletions (ZERO values for U256, None for Account).
484        fn merge_with_overlay<V>(
485            db_nodes: Vec<(B256, V::NonZero)>,
486            post_state_nodes: Vec<(B256, V)>,
487        ) -> Vec<(B256, V::NonZero)>
488        where
489            V: HashedPostStateCursorValue,
490            V::NonZero: Clone,
491        {
492            db_nodes
493                .into_iter()
494                .merge_join_by(post_state_nodes, |db_entry, mem_entry| db_entry.0.cmp(&mem_entry.0))
495                .filter_map(|entry| match entry {
496                    // Only in db: keep it
497                    itertools::EitherOrBoth::Left((key, node)) => Some((key, node)),
498                    // Only in post state: keep if not a deletion
499                    itertools::EitherOrBoth::Right((key, wrapped)) => {
500                        wrapped.into_option().map(|val| (key, val))
501                    }
502                    // In both: post state takes precedence (keep if not a deletion)
503                    itertools::EitherOrBoth::Both(_, (key, wrapped)) => {
504                        wrapped.into_option().map(|val| (key, val))
505                    }
506                })
507                .collect()
508        }
509
510        /// Generate a strategy for U256 values
511        fn u256_strategy() -> impl Strategy<Value = U256> {
512            any::<u64>().prop_map(U256::from)
513        }
514
515        /// Generate a sorted vector of (B256, U256) entries
516        fn sorted_db_nodes_strategy() -> impl Strategy<Value = Vec<(B256, U256)>> {
517            prop::collection::vec((any::<u8>(), u256_strategy()), 0..20).prop_map(|entries| {
518                let mut result: Vec<(B256, U256)> = entries
519                    .into_iter()
520                    .map(|(byte, value)| (B256::repeat_byte(byte), value))
521                    .collect();
522                result.sort_by_key(|a| a.0);
523                result.dedup_by(|a, b| a.0 == b.0);
524                result
525            })
526        }
527
528        /// Generate a sorted vector of (B256, U256) entries (including deletions as ZERO)
529        fn sorted_post_state_nodes_strategy() -> impl Strategy<Value = Vec<(B256, U256)>> {
530            // Explicitly inject ZERO values to model post-state deletions.
531            prop::collection::vec((any::<u8>(), u256_strategy(), any::<bool>()), 0..20).prop_map(
532                |entries| {
533                    let mut result: Vec<(B256, U256)> = entries
534                        .into_iter()
535                        .map(|(byte, value, is_deletion)| {
536                            let effective_value = if is_deletion { U256::ZERO } else { value };
537                            (B256::repeat_byte(byte), effective_value)
538                        })
539                        .collect();
540                    result.sort_by_key(|a| a.0);
541                    result.dedup_by(|a, b| a.0 == b.0);
542                    result
543                },
544            )
545        }
546
547        proptest! {
548            #![proptest_config(ProptestConfig::with_cases(1000))]
549
550            /// Compares arbitrary cursor operations with the merged state and checks that
551            /// forward requests inside known gaps do not repeat database work.
552            #[reth_concurrency::test]
553            fn proptest_hashed_post_state_cursor(
554                db_nodes in sorted_db_nodes_strategy(),
555                post_state_nodes in sorted_post_state_nodes_strategy(),
556                operations in prop::collection::vec((0u8..3, any::<u8>()), 10..500),
557            ) {
558                let merged = merge_with_overlay::<U256>(db_nodes.clone(), post_state_nodes.clone())
559                    .into_iter().collect::<BTreeMap<_, _>>();
560                // Include deleted and absent keys, not just surviving keys returned by the cursor.
561                let seek_keys = db_nodes.iter().map(|(key, _)| *key)
562                    .chain(post_state_nodes.iter().map(|(key, _)| *key))
563                    .chain(operations.iter().map(|(_, byte)| B256::repeat_byte(*byte)))
564                    .sorted().dedup().collect::<Vec<_>>();
565                let visited = Arc::new(Mutex::new(Vec::new()));
566                let db = MockHashedCursor::new(
567                    Arc::new(db_nodes.into_iter().collect()), visited.clone(),
568                );
569                let post_state = storage_post_state(post_state_nodes);
570                let mut cursor = HashedPostStateCursor::new_storage(db, &post_state, B256::ZERO);
571                let mut previous: Option<Option<B256>> = None;
572                for key in seek_keys {
573                    let visits = visited.lock().len();
574                    let actual = cursor.seek(key).unwrap();
575                    let expected = merged.range(key..).next().map(|(key, value)| (*key, *value));
576                    prop_assert_eq!(actual, expected);
577                    if previous.is_some_and(|successor| successor.is_none_or(|next| key <= next)) {
578                        prop_assert_eq!(visited.lock().len(), visits,
579                            "forward seek inside a known gap repeated DB work at {:?}", key);
580                    }
581                    previous = Some(expected.map(|(key, _)| key));
582                }
583
584                cursor.reset();
585                let mut expected = merged.first_key_value().map(|(key, value)| (*key, *value));
586                prop_assert_eq!(cursor.seek(B256::ZERO).unwrap(), expected);
587                for (operation, byte) in operations {
588                    let actual = if operation == 0 {
589                        expected = expected.and_then(|(key, _)| {
590                            merged.range((Bound::Excluded(key), Bound::Unbounded))
591                                .next().map(|(key, value)| (*key, *value))
592                        });
593                        cursor.next().unwrap()
594                    } else {
595                        if operation == 2 {
596                            cursor.reset();
597                        }
598                        let key = B256::repeat_byte(byte);
599                        expected = merged.range(key..).next().map(|(key, value)| (*key, *value));
600                        cursor.seek(key).unwrap()
601                    };
602                    prop_assert_eq!(actual, expected);
603                }
604            }
605        }
606    }
607
608    #[reth_concurrency::test]
609    fn seeks_after_next_preserve_gaps_and_rewind_consumed_entries() {
610        let visited = Arc::new(Mutex::new(Vec::new()));
611        let db = MockHashedCursor::new(
612            Arc::new([1, 2, 3, 4, 7].into_iter().map(|byte| (key(byte), U256::ONE)).collect()),
613            visited.clone(),
614        );
615        let post_state = storage_post_state(vec![(key(2), U256::ZERO), (key(3), U256::ZERO)]);
616        let mut cursor = HashedPostStateCursor::new_storage(db, &post_state, B256::ZERO);
617        assert_eq!(cursor.seek(key(0)).unwrap(), Some((key(1), U256::ONE)));
618        assert_eq!(cursor.next().unwrap(), Some((key(4), U256::ONE)));
619        let operations = visited.lock().len();
620        assert_eq!(cursor.seek(key(2)).unwrap(), Some((key(4), U256::ONE)));
621        assert_eq!(visited.lock().len(), operations);
622        assert_eq!(cursor.seek(key(1)).unwrap(), Some((key(1), U256::ONE)));
623        assert_eq!(cursor.seek(key(4)).unwrap(), Some((key(4), U256::ONE)));
624        assert_eq!(cursor.next().unwrap(), Some((key(7), U256::ONE)));
625        assert_eq!(cursor.seek(key(5)).unwrap(), Some((key(7), U256::ONE)));
626        assert_eq!(cursor.next().unwrap(), None);
627        let operations = visited.lock().len();
628        assert_eq!(cursor.next().unwrap(), None);
629        assert_eq!(cursor.seek(key(8)).unwrap(), None);
630        assert_eq!(visited.lock().len(), operations);
631        assert_eq!(cursor.seek(key(7)).unwrap(), Some((key(7), U256::ONE)));
632    }
633
634    #[reth_concurrency::test]
635    fn storage_address_switch_resets_seek_range() {
636        let first = B256::ZERO;
637        let second = key(1);
638        let db = MockHashedCursorFactory::new(
639            BTreeMap::new(),
640            B256Map::from_iter([
641                (first, BTreeMap::from([(key(8), U256::ONE)])),
642                (second, BTreeMap::from([(key(1), U256::ONE), (key(2), U256::ONE)])),
643            ]),
644        );
645        let post_state = HashedPostState::default()
646            .with_storages([
647                (first, HashedStorage::from_iter([(key(8), U256::ZERO)])),
648                (second, HashedStorage::from_iter([(key(1), U256::ZERO)])),
649            ])
650            .into_sorted();
651        let mut cursor = HashedPostStateCursor::new_storage(
652            db.hashed_storage_cursor(first).unwrap(),
653            &post_state,
654            first,
655        );
656        assert_eq!(cursor.seek(key(8)).unwrap(), None);
657        cursor.set_hashed_address(second);
658        assert_eq!(cursor.seek(key(0)).unwrap(), Some((key(2), U256::ONE)));
659        cursor.set_hashed_address(first);
660        assert_eq!(cursor.seek(key(0)).unwrap(), None);
661    }
662
663    #[derive(Debug)]
664    struct FailingHashedCursor {
665        cursor: MockHashedCursor<U256>,
666        fail_seek: bool,
667        fail_next: bool,
668    }
669
670    impl HashedCursor for FailingHashedCursor {
671        type Value = U256;
672
673        fn seek(&mut self, key: B256) -> Result<Option<(B256, U256)>, DatabaseError> {
674            let entry = self.cursor.seek(key)?;
675            if self.fail_seek {
676                self.fail_seek = false;
677                return Err(DatabaseError::Decode);
678            }
679            Ok(entry)
680        }
681
682        fn next(&mut self) -> Result<Option<(B256, U256)>, DatabaseError> {
683            let entry = self.cursor.next()?;
684            if self.fail_next {
685                self.fail_next = false;
686                return Err(DatabaseError::Decode);
687            }
688            Ok(entry)
689        }
690
691        fn reset(&mut self) {
692            self.cursor.reset();
693        }
694    }
695
696    impl HashedStorageCursor for FailingHashedCursor {
697        fn is_storage_empty(&mut self) -> Result<bool, DatabaseError> {
698            self.cursor.is_storage_empty()
699        }
700
701        fn set_hashed_address(&mut self, hashed_address: B256) {
702            self.cursor.set_hashed_address(hashed_address);
703        }
704    }
705
706    #[reth_concurrency::test]
707    fn cursor_errors_invalidate_reusable_positions() {
708        for operation in 0..3 {
709            let db = MockHashedCursor::new(
710                Arc::new([1, 2, 3].into_iter().map(|byte| (key(byte), U256::ONE)).collect()),
711                Default::default(),
712            );
713            let post_state = storage_post_state(vec![(key(2), U256::ZERO)]);
714            let mut cursor = HashedPostStateCursor::new_storage(
715                FailingHashedCursor {
716                    cursor: db,
717                    fail_seek: operation == 0,
718                    fail_next: operation != 0,
719                },
720                &post_state,
721                B256::ZERO,
722            );
723            let error = match operation {
724                0 => cursor.seek(key(1)),
725                1 => {
726                    assert_eq!(cursor.seek(key(1)).unwrap(), Some((key(1), U256::ONE)));
727                    cursor.next()
728                }
729                _ => cursor.seek(key(2)),
730            };
731            assert!(matches!(error, Err(DatabaseError::Decode)));
732            assert_eq!(cursor.position, CursorPosition::Unseeked);
733            assert!(matches!(cursor.db_cursor_state, DbCursorState::NeedsPosition));
734            assert_eq!(cursor.seek(key(2)).unwrap(), Some((key(3), U256::ONE)));
735            assert_eq!(cursor.seek(key(1)).unwrap(), Some((key(1), U256::ONE)));
736            assert_eq!(cursor.next().unwrap(), Some((key(3), U256::ONE)));
737        }
738    }
739}