@@ -2233,6 +2233,20 @@ impl ChainStore {
22332233 }
22342234 }
22352235
2236+ /// Return the block number below which blocks should be treated as
2237+ /// not cached. Returns `0` when the feature is disabled (effectively
2238+ /// no cutoff). Returns `i32::MAX` when no chain head is known to
2239+ /// avoid serving stale data.
2240+ async fn cache_cutoff ( self : & Arc < Self > ) -> BlockNumber {
2241+ if !ENV_VARS . store . ignore_block_cache {
2242+ return 0 ;
2243+ }
2244+ match self . clone ( ) . chain_head_ptr ( ) . await {
2245+ Ok ( Some ( head) ) => head. block_number ( ) . saturating_sub ( self . cache_size ) ,
2246+ _ => i32:: MAX ,
2247+ }
2248+ }
2249+
22362250 /// Execute a cached query, avoiding thundering herd for identical requests.
22372251 /// Returns `(result, was_cached)`.
22382252 async fn cached_lookup < K , T , F > (
@@ -2458,15 +2472,20 @@ impl ChainStore {
24582472 self : & Arc < Self > ,
24592473 hashes : Vec < BlockHash > ,
24602474 ) -> Result < Vec < JsonBlock > , StoreError > {
2475+ let cutoff = self . cache_cutoff ( ) . await ;
24612476 let mut conn = self . pool . get_permitted ( ) . await ?;
24622477 let values = self . storage . blocks ( & mut conn, & self . chain , & hashes) . await ?;
2463- Ok ( values)
2478+ Ok ( values
2479+ . into_iter ( )
2480+ . filter ( |b| b. ptr . block_number ( ) >= cutoff)
2481+ . collect ( ) )
24642482 }
24652483
24662484 async fn blocks_from_store_by_numbers (
24672485 self : & Arc < Self > ,
24682486 numbers : Vec < BlockNumber > ,
24692487 ) -> Result < BTreeMap < BlockNumber , Vec < JsonBlock > > , StoreError > {
2488+ let cutoff = self . cache_cutoff ( ) . await ;
24702489 let mut conn = self . pool . get_permitted ( ) . await ?;
24712490 let values = self
24722491 . storage
@@ -2475,7 +2494,10 @@ impl ChainStore {
24752494
24762495 let mut block_map = BTreeMap :: new ( ) ;
24772496
2478- for block in values {
2497+ for block in values
2498+ . into_iter ( )
2499+ . filter ( |b| b. ptr . block_number ( ) >= cutoff)
2500+ {
24792501 let block_number = block. ptr . block_number ( ) ;
24802502 block_map
24812503 . entry ( block_number)
@@ -2870,6 +2892,12 @@ impl ChainStoreTrait for ChainStore {
28702892 block_ptr. hash_hex( )
28712893 ) ;
28722894
2895+ let target_number = block_ptr. block_number ( ) - offset;
2896+ let cutoff = self . cache_cutoff ( ) . await ;
2897+ if target_number < cutoff {
2898+ return Ok ( None ) ;
2899+ }
2900+
28732901 // Use herd cache to avoid thundering herd when multiple callers
28742902 // request the same ancestor block simultaneously. The cache check
28752903 // is inside the future so that only one caller checks and populates
0 commit comments