@@ -259,10 +259,18 @@ func (s *StateReader) getHistoricalValue(prefix []byte, blockNum uint64) (felt.F
259259}
260260
261261// Returns the value at the given block number.
262- // First, it attempts to seek for the key at the given block number.
263- // If the key exists, it means that the key was modified at the given block number.
264- // Otherwise, it moves the iterator one step back.
265- // If a key-value pair exists, we have found the value.
262+ // Seeks to the entry for blockNum if it exists; otherwise steps back to the
263+ // last recorded block strictly less than blockNum. Returns ErrNoHistoryValue
264+ // if no entry exists at or before blockNum.
265+ //
266+ // Each history entry stores the post-update value at the block it was written.
267+ // Example — a nonce updated at blocks 10 and 25:
268+ //
269+ // stored: (prefix, 10) -> 7 (prefix, 25) -> 42
270+ // query @ 5 -> no entry <= 5 -> ErrNoHistoryValue (-> Zero)
271+ // query @ 10 -> exact hit on (prefix, 10) -> 7
272+ // query @ 20 -> Seek lands on 25, Prev -> 10 -> 7
273+ // query @ 30 -> Seek fails, Prev -> 25 -> 42
266274func (s * StateReader ) valueAt (prefix []byte , blockNum uint64 , cb func (val []byte ) error ) error {
267275 it , err := s .db .disk .NewIterator (prefix , true )
268276 if err != nil {
@@ -271,44 +279,19 @@ func (s *StateReader) valueAt(prefix []byte, blockNum uint64, cb func(val []byte
271279 defer it .Close ()
272280
273281 seekKey := binary .BigEndian .AppendUint64 (prefix , blockNum )
274- if ! it .Seek (seekKey ) {
275- // All existing keys (if any) are before seekKey.
276- // The last stored value is the correct answer for this blockNum.
277- if ! it .Prev () {
278- // Iterator is truly empty for this prefix — no history exists.
279- return ErrNoHistoryValue
280- }
281- val , err := it .Value ()
282- if err != nil {
283- return err
284- }
285- return cb (val )
286- }
287282
288283 key := it .Key ()
289284 keyBlockNum := binary .BigEndian .Uint64 (key [len (prefix ):])
290- if keyBlockNum == blockNum {
291- // Found the value
292- val , err := it .Value ()
293- if err != nil {
294- return err
285+ if ! it .Seek (seekKey ) || keyBlockNum != blockNum {
286+ if ! it .Prev () {
287+ return ErrNoHistoryValue
295288 }
296-
297- return cb (val )
298- }
299-
300- // Otherwise, move the iterator backwards
301- if ! it .Prev () {
302- // Moving iterator backwards is invalid, this means we were already at the first key
303- // No values will be found beyond the first key
304- return ErrNoHistoryValue
305289 }
306290
307291 val , err := it .Value ()
308292 if err != nil {
309293 return err
310294 }
311-
312295 return cb (val )
313296}
314297
0 commit comments