@@ -2386,6 +2386,20 @@ impl ChainStore {
23862386 }
23872387 }
23882388
2389+ /// Return the block number below which blocks should be treated as
2390+ /// not cached. Returns `0` when the feature is disabled (effectively
2391+ /// no cutoff). Returns `i32::MAX` when no chain head is known to
2392+ /// avoid serving stale data.
2393+ async fn cache_cutoff ( self : & Arc < Self > ) -> BlockNumber {
2394+ if !ENV_VARS . store . ignore_block_cache {
2395+ return 0 ;
2396+ }
2397+ match self . clone ( ) . chain_head_ptr ( ) . await {
2398+ Ok ( Some ( head) ) => head. block_number ( ) . saturating_sub ( self . cache_size ) ,
2399+ _ => i32:: MAX ,
2400+ }
2401+ }
2402+
23892403 /// Execute a cached query, avoiding thundering herd for identical requests.
23902404 /// Returns `(result, was_cached)`.
23912405 async fn cached_lookup < K , T , F > (
@@ -2611,15 +2625,20 @@ impl ChainStore {
26112625 self : & Arc < Self > ,
26122626 hashes : Vec < BlockHash > ,
26132627 ) -> Result < Vec < JsonBlock > , StoreError > {
2628+ let cutoff = self . cache_cutoff ( ) . await ;
26142629 let mut conn = self . pool . get_permitted ( ) . await ?;
26152630 let values = self . storage . blocks ( & mut conn, & self . chain , & hashes) . await ?;
2616- Ok ( values)
2631+ Ok ( values
2632+ . into_iter ( )
2633+ . filter ( |b| b. ptr . block_number ( ) >= cutoff)
2634+ . collect ( ) )
26172635 }
26182636
26192637 async fn blocks_from_store_by_numbers (
26202638 self : & Arc < Self > ,
26212639 numbers : Vec < BlockNumber > ,
26222640 ) -> Result < BTreeMap < BlockNumber , Vec < JsonBlock > > , StoreError > {
2641+ let cutoff = self . cache_cutoff ( ) . await ;
26232642 let mut conn = self . pool . get_permitted ( ) . await ?;
26242643 let values = self
26252644 . storage
@@ -2628,7 +2647,10 @@ impl ChainStore {
26282647
26292648 let mut block_map = BTreeMap :: new ( ) ;
26302649
2631- for block in values {
2650+ for block in values
2651+ . into_iter ( )
2652+ . filter ( |b| b. ptr . block_number ( ) >= cutoff)
2653+ {
26322654 let block_number = block. ptr . block_number ( ) ;
26332655 block_map
26342656 . entry ( block_number)
@@ -3023,6 +3045,12 @@ impl ChainStoreTrait for ChainStore {
30233045 block_ptr. hash_hex( )
30243046 ) ;
30253047
3048+ let target_number = block_ptr. block_number ( ) - offset;
3049+ let cutoff = self . cache_cutoff ( ) . await ;
3050+ if target_number < cutoff {
3051+ return Ok ( None ) ;
3052+ }
3053+
30263054 // Use herd cache to avoid thundering herd when multiple callers
30273055 // request the same ancestor block simultaneously. The cache check
30283056 // is inside the future so that only one caller checks and populates
0 commit comments