← Back to Pull requests

perf(rpc): avoid historical state queries for block base fee and validators #1118

Open
JayT106 opened this pull request with 675 lines diff across 10 files
View on GitHub
JayT106 JayT106 commented on Oct 08, 2026 14:20 UTC
Author

What

eth_getBlockBy, eth_getBlockReceipts, eth_getTransactionReceipt and the header RPCs no longer query state at the block's height for base fee or validator.

Issue

On memiavl nodes without versiondb, every state query at a past height rebuilds that state (~650 ms on Cronos mainnet).

  • eth_getBlockByNumber makes 2 such queries: ~1.3 s.

  • Receipts make 1 per EIP-1559 tx.

  • Past the snapshot window the query fails and the validator (miner) comes back as the zero address.
  • Solution

  • Base fee: read from the feemarket BeginBlock event (BaseFeeFromEvents). State is queried only when there's no event. This also fixes the old fallback's int64 parse and its Attributes[0] lookup.

  • Next base fee (eth_baseFee, eth_feeHistory): derived from the stored base_fee param, as the chain does, so a governance overwrite is reflected. Skipped when the fee market is disabled.

  • Validator: resolved at the latest height (no consensus key rotation), falling back to the block's height. Cached in an LRU as a range list per validator: an entry is reused within 10k blocks of any block it was resolved for, merging touching ranges and keeping at most 64.

  • Tradeoff: if a deleted validator's consensus key is re-registered under another operator, the old blocks show the new operator. This needs the same private key, and miner is informational.

  • Other historical RPCs (eth_call at past heights, eth_feeHistory's params query, debug_trace, …) still need versiondb.
  • Diff: 675 lines (+444 / -231) across 10 files Reviewer: JayT106 Review duration: 82005m
    All Vouch review confidence checks passed
    Residual risk 0.14 = Change Risk (0.76) × (1 − Review Confidence (0.81)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.76 · 675 lines diff across 10 files
    0.76
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    81%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.390
    Self Review self_review
    0.140
    Real PR Conversation Timeline
    23 items
    codecov[bot] codecov[bot] commented on Oct 08, 2026 14:32 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 92.72727% with 4 lines in your changes missing coverage. Please review.
    :white_check_mark: Project coverage is 47.21%. Comparing base (eb8f544) to head (76d9e3b).

    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | rpc/backend/backend.go | 50.00% | 1 Missing and 1 partial :warning: |
    | rpc/backend/utils.go | 95.45% | 1 Missing and 1 partial :warning: |

    <details><summary>Additional details and impacted files</summary>

    ![Impacted file tree graph](https://app.codecov.io/gh/crypto-org-chain/ethermint/pull/1118?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=crypto-org-chain)

    @@             Coverage Diff             @@
    ##           develop    #1118      +/-   ##
    ===========================================
    + Coverage    47.18%   47.21%   +0.03%     
    ===========================================
      Files          200      200              
      Lines        17633    17633              
    ===========================================
    + Hits          8320     8326       +6     
    + Misses        8449     8446       -3     
    + Partials       864      861       -3     
    

    | Files with missing lines | Coverage Δ | |
    |---|---|---|
    | rpc/backend/blocks.go | 78.14% <100.00%> (+0.10%) | :arrow_up: |
    | rpc/backend/chain\_info.go | 73.20% <100.00%> (+0.39%) | :arrow_up: |
    | rpc/backend/backend.go | 61.53% <50.00%> (-2.10%) | :arrow_down: |
    | rpc/backend/utils.go | 61.13% <95.45%> (+4.52%) | :arrow_up: |
    </details>
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

  • </details>

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 08, 2026 14:49 UTC
    Code Review
    rpc/backend/utils.go:1
    @@ -344,17 +360,32 @@
     	return proofs
     }
     
    +// getValidatorAccount resolves the proposer's operator account at the latest height and caches it:
    +// a consensus address never moves to another validator (no consensus key rotation), while a query at
    +// the block's height rebuilds state on nodes without historical versions and fails once pruned.
    +// The block's height is only the fallback for validators gone at the latest height.
     func (b *Backend) getValidatorAccount(header *cmttypes.Header) (sdk.AccAddress, error) {
    -	res, err := b.queryClient.ValidatorAccount(
    -		types.ContextWithHeight(header.Height),
    -		&evmtypes.QueryValidatorAccountRequest{
    -			ConsAddress: sdk.ConsAddress(header.ProposerAddress).String(),
    -		},
    -	)
    +	key := string(header.ProposerAddress)
    +	if entry, ok := b.validatorAccounts.Get(key); ok && time.Now().Before(entry.expiresAt) {

    CodeQL / Calling the system time

    Calling the system time may be a possible source of non-determinism

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 08, 2026 14:49 UTC
    Code Review
    rpc/backend/utils.go:1
    @@ -344,17 +360,32 @@
     	return proofs
     }
     
    +// getValidatorAccount resolves the proposer's operator account at the latest height and caches it:
    +// a consensus address never moves to another validator (no consensus key rotation), while a query at
    +// the block's height rebuilds state on nodes without historical versions and fails once pruned.
    +// The block's height is only the fallback for validators gone at the latest height.
     func (b *Backend) getValidatorAccount(header *cmttypes.Header) (sdk.AccAddress, error) {
    -	res, err := b.queryClient.ValidatorAccount(
    -		types.ContextWithHeight(header.Height),
    -		&evmtypes.QueryValidatorAccountRequest{
    -			ConsAddress: sdk.ConsAddress(header.ProposerAddress).String(),
    -		},
    -	)
    +	key := string(header.ProposerAddress)
    +	if entry, ok := b.validatorAccounts.Get(key); ok && time.Now().Before(entry.expiresAt) {
    +		return entry.acc, nil
    +	}
    +
    +	req := &evmtypes.QueryValidatorAccountRequest{
    +		ConsAddress: sdk.ConsAddress(header.ProposerAddress).String(),
    +	}
    +	res, err := b.queryClient.ValidatorAccount(b.ctx, req)
    +	if err != nil {
    +		res, err = b.queryClient.ValidatorAccount(types.ContextWithHeight(header.Height), req)
    +		if err != nil {
    +			return nil, fmt.Errorf("failed to get validator account %w", err)
    +		}
    +	}
    +	acc, err := sdk.AccAddressFromBech32(res.AccountAddress)
     	if err != nil {
    -		return nil, fmt.Errorf("failed to get validator account %w", err)
    +		return nil, err
     	}
    -	return sdk.AccAddressFromBech32(res.AccountAddress)
    +	b.validatorAccounts.Add(key, validatorAccountEntry{acc: acc, expiresAt: time.Now().Add(validatorAccountCacheTTL)})

    CodeQL / Calling the system time

    Calling the system time may be a possible source of non-determinism

    Show more details

    JayT106 JayT106 commented on code on Oct 08, 2026 14:52 UTC
    Code Review
    rpc/backend/utils.go:1
    @@ -344,17 +360,32 @@
     	return proofs
     }
     
    +// getValidatorAccount resolves the proposer's operator account at the latest height and caches it:
    +// a consensus address never moves to another validator (no consensus key rotation), while a query at
    +// the block's height rebuilds state on nodes without historical versions and fails once pruned.
    +// The block's height is only the fallback for validators gone at the latest height.
     func (b *Backend) getValidatorAccount(header *cmttypes.Header) (sdk.AccAddress, error) {
    -	res, err := b.queryClient.ValidatorAccount(
    -		types.ContextWithHeight(header.Height),
    -		&evmtypes.QueryValidatorAccountRequest{
    -			ConsAddress: sdk.ConsAddress(header.ProposerAddress).String(),
    -		},
    -	)
    +	key := string(header.ProposerAddress)
    +	if entry, ok := b.validatorAccounts.Get(key); ok && time.Now().Before(entry.expiresAt) {

    Removed the wall-clock dependency: cache entries now expire by block height (reused only within 10k blocks of the block they were resolved for), so time.Now() is gone (c9661fe1).

    JayT106 JayT106 commented on code on Oct 08, 2026 14:52 UTC
    Code Review
    rpc/backend/utils.go:1
    @@ -344,17 +360,32 @@
     	return proofs
     }
     
    +// getValidatorAccount resolves the proposer's operator account at the latest height and caches it:
    +// a consensus address never moves to another validator (no consensus key rotation), while a query at
    +// the block's height rebuilds state on nodes without historical versions and fails once pruned.
    +// The block's height is only the fallback for validators gone at the latest height.
     func (b *Backend) getValidatorAccount(header *cmttypes.Header) (sdk.AccAddress, error) {
    -	res, err := b.queryClient.ValidatorAccount(
    -		types.ContextWithHeight(header.Height),
    -		&evmtypes.QueryValidatorAccountRequest{
    -			ConsAddress: sdk.ConsAddress(header.ProposerAddress).String(),
    -		},
    -	)
    +	key := string(header.ProposerAddress)
    +	if entry, ok := b.validatorAccounts.Get(key); ok && time.Now().Before(entry.expiresAt) {
    +		return entry.acc, nil
    +	}
    +
    +	req := &evmtypes.QueryValidatorAccountRequest{
    +		ConsAddress: sdk.ConsAddress(header.ProposerAddress).String(),
    +	}
    +	res, err := b.queryClient.ValidatorAccount(b.ctx, req)
    +	if err != nil {
    +		res, err = b.queryClient.ValidatorAccount(types.ContextWithHeight(header.Height), req)
    +		if err != nil {
    +			return nil, fmt.Errorf("failed to get validator account %w", err)
    +		}
    +	}
    +	acc, err := sdk.AccAddressFromBech32(res.AccountAddress)
     	if err != nil {
    -		return nil, fmt.Errorf("failed to get validator account %w", err)
    +		return nil, err
     	}
    -	return sdk.AccAddressFromBech32(res.AccountAddress)
    +	b.validatorAccounts.Add(key, validatorAccountEntry{acc: acc, expiresAt: time.Now().Add(validatorAccountCacheTTL)})

    Same fix as the other thread: the entry now stores the block height it was resolved for instead of a time.Now() expiry (c9661fe1).

    JayT106 JayT106 commented on Oct 08, 2026 15:09 UTC
    Author

    @claude review

    github-actions[bot] github-actions[bot] commented on Oct 08, 2026 15:09 UTC
    Bot

    Claude finished @JayT106's task in 2m 18s —— View job

    ---

    Code Review

  • Gather context and understand the request

  • Read changed files

  • Review code quality, correctness, and security

  • Post review findings
  • ---

    Summary

    This PR is a well-targeted optimization: it avoids costly historical state queries for base fee and miner in the most-called block/receipt RPCs. The approach is sound, the tests are thorough, and the tradeoffs are clearly documented. No consensus-breaking or state-breaking changes detected.

    ---

    Findings

    1. Misleading fallback comment in BaseFee() — rpc/backend/chain_info.go:90

    if baseFee := rpctypes.BaseFeeFromEvents(blockRes.FinalizeBlockEvents); baseFee != nil {
        return baseFee, nil
    }
    
    // no event: fee market inactive at this height
    res, err := b.queryClient.BaseFee(...)
    

    BaseFeeFromEvents returns nil in three distinct situations:

  • No feemarket event (fee market inactive — comment is correct here)

  • Feemarket event present but base_fee attribute absent

  • base_fee attribute present but value is malformed (tested by "pass - malformed feemarket event falls back to state query")
  • The last two cases are not "fee market inactive" — the comment overstates when the state fallback fires. Minor, but worth fixing for future readers.

    Fix this →

    ---

    2. nextBaseFeeParent in processBlock still issues a historical state query — rpc/backend/utils.go:212

    ctx := types.ContextWithHeight(blockHeight)
    params, err := b.queryClient.FeeMarket.Params(ctx, &feemarkettypes.QueryParamsRequest{})
    if err != nil {
        return err
    }
    header.BaseFee = nextBaseFeeParent(params.Params, blockHeight, header.BaseFee)
    

    processBlock is called for every block in eth_feeHistory. It queries FeeMarket.Params at blockHeight (historical state), then passes the result to nextBaseFeeParent. While the PR description explicitly scopes this optimization to eth_getBlockBy, receipts, and headers — and correctly notes eth_feeHistory still needs versiondb — the nextBaseFeeParent logic here is purely about accuracy (governance override reflected), not about eliminating the state query. The query itself is still historical.

    This is not a regression (the old code queried state too), but it is worth calling out so the scope of the optimization is clear: processBlock is not helped by this PR.

    ---

    3. Cache entry records served block height, not fetch height — rpc/backend/utils.go:380

    b.validatorAccounts.Add(key, validatorAccountEntry{acc: acc, height: header.Height})
    

    The cached height is the block height being served, not the height at which the gRPC query actually ran (latest). This is the intended design — the window check answers "is this entry close enough to the block I'm serving now?" — but it has an edge case:

    If we serve block 1000, cache with height=1000, and later serve block 11001 (beyond the 10k window), we refetch at latest. If the validator was at the same consensus address, we cache again with height=11001. Fine. But if we serve blocks out of order (e.g., a client calls eth_getBlockByNumber for block 1, then block 2, then block 3 …), every call within 10k blocks hits the cache regardless of which block they asked for. This is the correct behavior.

    The subtle case: if we serve block 50000 (cache height=50000) and then serve block 1 (gap = 49999 > 10000), we refetch. The refetch queries b.ctx (latest height = ~50000+), which may no longer know about a validator that existed at block 1. The fallback to ContextWithHeight(1) then fires. This is exactly the intended fallback path. ✓

    No bug, but worth confirming the logic is intentional (it is, per the PR description).

    ---

    4. BaseFeeFromEvents nil-return on malformed value stops attribute scan — rpc/types/utils.go:327

    for _, attr := range event.Attributes {
        if attr.Key == feemarkettypes.AttributeKeyBaseFee {
            result, success := new(big.Int).SetString(attr.Value, 10)
            if success {
                return result
            }
            return nil   // ← stops scanning, signals "no parseable fee"
        }
    }
    

    On a malformed base_fee attribute, the function returns nil (triggering the state fallback in the caller). This is safe, but means a chain event with base_fee="" causes an extra state query per block lookup. Low likelihood in practice, but the behavior is non-obvious — it would read more clearly if the early return had a brief comment, e.g.:

    return nil // malformed value; caller falls back to state
    

    Fix this →

    ---

    What's good

  • Event-first approach: prioritizing the BeginBlock event for base fee is the right call — it avoids the state query for the hot path and fixes the old Attributes[0] positional assumption and int64 truncation.

  • nextBaseFeeParent: extracting the governance-override logic into a named function makes the intent clear and is shared correctly between NextBaseFee and processBlock.

  • Cache design: block-height window instead of wall clock is a solid fix to the CodeQL finding; the 10k window is well below the unbonding period so re-registered keys can't cause stale entries.

  • Tests: the TestGetValidatorAccount table explicitly asserts that failed lookups are not* cached (line suite.Require().Zero(suite.backend.validatorAccounts.Len(), "failed lookups must not be cached")). Calling the result a second time from cache is also verified. Good coverage.

  • No state-breaking changes: the optimization is entirely in the RPC layer.
  • ---

    Overall this is clean and well-reasoned. The findings above are minor (comment accuracy, scope clarity). The code is ready to merge after addressing or acknowledging these.

    github-actions[bot] github-actions[bot] commented on code on Oct 08, 2026 15:12 UTC
    Code Review
    rpc/backend/chain_info.go:1
    @@ -81,27 +80,16 @@ func (b *Backend) GlobalMinGasPrice() (sdkmath.LegacyDec, error) {
     	return res.Params.MinGasPrice, nil
     }
     
    -// BaseFee returns the base fee tracked by the Fee Market module.
    -// If the base fee is not enabled globally, the query returns nil.
    -// If the London hard fork is not activated at the current height, the query will
    -// return nil.
    +// BaseFee returns the base fee the block's transactions paid, or nil if none.
     func (b *Backend) BaseFee(blockRes *cmtrpctypes.ResultBlockResults) (*big.Int, error) {
    -	// return BaseFee if London hard fork is activated and feemarket is enabled
    +	// the event avoids a historical state query, which memiavl without versiondb rebuilds per call
    +	if baseFee := rpctypes.BaseFeeFromEvents(blockRes.FinalizeBlockEvents); baseFee != nil {
    +		return baseFee, nil
    +	}
    +
    +	// no event: fee market inactive at this height

    The comment is slightly misleading — BaseFeeFromEvents returns nil for three cases: no feemarket event, event with no base_fee attribute, and event with a malformed base_fee value. Only the first is "fee market inactive"; the other two fall back here too.

    	// no parseable base_fee event: fall back to state (inactive fee market, missing attribute, or malformed value)
    

    JayT106 JayT106 commented on code on Oct 08, 2026 15:20 UTC
    Code Review
    rpc/backend/chain_info.go:1
    @@ -81,27 +80,16 @@ func (b *Backend) GlobalMinGasPrice() (sdkmath.LegacyDec, error) {
     	return res.Params.MinGasPrice, nil
     }
     
    -// BaseFee returns the base fee tracked by the Fee Market module.
    -// If the base fee is not enabled globally, the query returns nil.
    -// If the London hard fork is not activated at the current height, the query will
    -// return nil.
    +// BaseFee returns the base fee the block's transactions paid, or nil if none.
     func (b *Backend) BaseFee(blockRes *cmtrpctypes.ResultBlockResults) (*big.Int, error) {
    -	// return BaseFee if London hard fork is activated and feemarket is enabled
    +	// the event avoids a historical state query, which memiavl without versiondb rebuilds per call
    +	if baseFee := rpctypes.BaseFeeFromEvents(blockRes.FinalizeBlockEvents); baseFee != nil {
    +		return baseFee, nil
    +	}
    +
    +	// no event: fee market inactive at this height

    Already fixed in f7a6f4c3: the comment now reads "no parseable event (fee market inactive, or malformed event): fall back to state", which covers a missing attribute and a bad value.

    JayT106 JayT106 commented on Oct 08, 2026 21:08 UTC
    Author

    @claude review

    github-actions[bot] github-actions[bot] commented on Oct 08, 2026 21:08 UTC
    Bot

    Claude finished @JayT106's task in 3m 41s —— View job

    ---

    Code Review

  • Gather context and read changed files

  • Review rpc/backend/utils.go — validator account cache

  • Review rpc/backend/chain_info.go — BaseFee / NextBaseFee

  • Review rpc/backend/backend.go — LRU cache setup

  • Review rpc/backend/blocks.go — block formatting

  • Review tests

  • Check for correctness bugs, security, and breaking changes

  • Post inline comments and final summary
  • ---

    Summary

    The approach is sound and well-executed. The core idea — read base fee from the BeginBlock event and resolve the miner at the latest height — eliminates the expensive historical state queries on memiavl nodes without versiondb. No consensus or state-machine changes; this is purely an RPC performance improvement with no breaking changes.

    ---

    Findings

    1. nextBaseFee still performs a historical params query for eth_feeHistory

    In processBlock (called per block during eth_feeHistory), nextBaseFee calls:

    b.queryClient.FeeMarket.Params(types.ContextWithHeight(height), ...)
    

    This replaces the old params query at the same height, so there's no regression. The PR description explicitly acknowledges this. Worth a note in the CHANGELOG or PR body that eth_feeHistory's per-block param query still requires versiondb.

    2. BaseFee behavior change for pruned nodes with no event

    Old path: on state error → iterated events → returned nil (no error).
    New path: on state error → returns nil, err.

    All callers handle the error gracefully (log + treat as nil baseFee), so there's no functional regression. The new behavior is actually better — the caller now knows why the fee is missing. ✓

    3. Cache window semantics (subtle, intentional)

    validatorAccountEntry.height stores header.Height (the block being queried), not the latest height at resolution time. This means two calls for blocks > 10 000 apart will both be cache misses, even for the same validator. For a streaming workload (sequential blocks) this is fine. For random historical access it re-queries, which is the safe fallback anyway. The tradeoff is documented.

    4. Minor: missing colon before %w in error message

    rpc/backend/utils.go:363 — "failed to get validator account %w" should be "failed to get validator account: %w" per Go error wrapping convention (errors.Is/errors.As still work either way, but the message is easier to read with a colon).

    5. Uncoverable panic path in backend.go

    lru.New only fails when size ≤ 0, which can't happen with the constant 1024. The codecov 50% miss on backend.go is these two lines — structurally untestable. No action needed.

    6. processBlock base fee source change

    Old: extracted baseFeePerGas from the assembled eth block JSON map.
    New: uses targetOneFeeHistory.BaseFee (set two lines earlier from blockBaseFee).
    Both are equivalent, and the new path additionally applies the governance-stored params.BaseFee override when enabled — matching the chain's own CalculateBaseFee exactly. ✓

    7. Thread safety

    hashicorp/golang-lru/v2 uses a sync.Mutex internally; concurrent Get/Add calls are safe. Concurrent cache misses may trigger duplicate queries (last writer wins), which is harmless. ✓

    8. No breaking changes

    No consensus, no state-machine, no amino/protobuf changes. Pure RPC-layer optimization. Safe to merge to develop. ✓

    ---

    Minor inline comments posted below.

    github-actions[bot] github-actions[bot] commented on code on Oct 08, 2026 21:12 UTC
    Code Review
    rpc/backend/utils.go:1
    @@ -344,17 +344,31 @@ func GetHexProofs(proof *crypto.ProofOps) []string {
     	return proofs
     }
     
    +// getValidatorAccount resolves the proposer's account at the latest height (consensus keys don't rotate)
    +// and caches it; the slow query at the block's height is only the fallback for removed validators.
     func (b *Backend) getValidatorAccount(header *cmttypes.Header) (sdk.AccAddress, error) {
    -	res, err := b.queryClient.ValidatorAccount(
    -		types.ContextWithHeight(header.Height),
    -		&evmtypes.QueryValidatorAccountRequest{
    -			ConsAddress: sdk.ConsAddress(header.ProposerAddress).String(),
    -		},
    -	)
    +	key := string(header.ProposerAddress)
    +	entry, ok := b.validatorAccounts.Get(key)
    +	if ok && max(header.Height-entry.height, entry.height-header.Height) <= validatorAccountCacheBlocks {
    +		return entry.acc, nil
    +	}
    +
    +	req := &evmtypes.QueryValidatorAccountRequest{
    +		ConsAddress: sdk.ConsAddress(header.ProposerAddress).String(),
    +	}
    +	res, err := b.queryClient.ValidatorAccount(b.ctx, req)
     	if err != nil {
    -		return nil, fmt.Errorf("failed to get validator account %w", err)
    +		res, err = b.queryClient.ValidatorAccount(types.ContextWithHeight(header.Height), req)
    +		if err != nil {
    +			return nil, fmt.Errorf("failed to get validator account %w", err)

    Nit: missing colon before %w — Go convention is "failed to get validator account: %w".

    			return nil, fmt.Errorf("failed to get validator account: %w", err)
    

    github-actions[bot] github-actions[bot] commented on code on Oct 08, 2026 21:12 UTC
    Code Review
    rpc/backend/utils.go:1
    @@ -119,6 +119,21 @@ func (b *Backend) getAccountNonce(accAddr common.Address, pending bool, height i
     	return nonce, nil
     }
     
    +// nextBaseFee derives height+1's base fee like the chain: from the stored param, which governance
    +// may overwrite after the block's own is set, or from the block's if unset or disabled.
    +func (b *Backend) nextBaseFee(cfg *params.ChainConfig, height int64, blockBaseFee *big.Int, gasLimit, gasUsed uint64) (*big.Int, error) {
    +	res, err := b.queryClient.FeeMarket.Params(types.ContextWithHeight(height), &feemarkettypes.QueryParamsRequest{})

    ContextWithHeight(height) here is still a historical state query (for feemarket params). For NextBaseFee this is fine since height is the latest block. For processBlock (called per-block in eth_feeHistory) this is an acknowledged limitation — worth a brief comment so future readers don't remove the ContextWithHeight thinking it can be b.ctx.

    JayT106 JayT106 commented on code on Oct 08, 2026 21:16 UTC
    Code Review
    rpc/backend/utils.go:1
    @@ -344,17 +344,31 @@ func GetHexProofs(proof *crypto.ProofOps) []string {
     	return proofs
     }
     
    +// getValidatorAccount resolves the proposer's account at the latest height (consensus keys don't rotate)
    +// and caches it; the slow query at the block's height is only the fallback for removed validators.
     func (b *Backend) getValidatorAccount(header *cmttypes.Header) (sdk.AccAddress, error) {
    -	res, err := b.queryClient.ValidatorAccount(
    -		types.ContextWithHeight(header.Height),
    -		&evmtypes.QueryValidatorAccountRequest{
    -			ConsAddress: sdk.ConsAddress(header.ProposerAddress).String(),
    -		},
    -	)
    +	key := string(header.ProposerAddress)
    +	entry, ok := b.validatorAccounts.Get(key)
    +	if ok && max(header.Height-entry.height, entry.height-header.Height) <= validatorAccountCacheBlocks {
    +		return entry.acc, nil
    +	}
    +
    +	req := &evmtypes.QueryValidatorAccountRequest{
    +		ConsAddress: sdk.ConsAddress(header.ProposerAddress).String(),
    +	}
    +	res, err := b.queryClient.ValidatorAccount(b.ctx, req)
     	if err != nil {
    -		return nil, fmt.Errorf("failed to get validator account %w", err)
    +		res, err = b.queryClient.ValidatorAccount(types.ContextWithHeight(header.Height), req)
    +		if err != nil {
    +			return nil, fmt.Errorf("failed to get validator account %w", err)

    Added the colon: "failed to get validator account: %w" (0ffd4327).

    JayT106 JayT106 commented on code on Oct 08, 2026 21:16 UTC
    Code Review
    rpc/backend/utils.go:1
    @@ -119,6 +119,21 @@ func (b *Backend) getAccountNonce(accAddr common.Address, pending bool, height i
     	return nonce, nil
     }
     
    +// nextBaseFee derives height+1's base fee like the chain: from the stored param, which governance
    +// may overwrite after the block's own is set, or from the block's if unset or disabled.
    +func (b *Backend) nextBaseFee(cfg *params.ChainConfig, height int64, blockBaseFee *big.Int, gasLimit, gasUsed uint64) (*big.Int, error) {
    +	res, err := b.queryClient.FeeMarket.Params(types.ContextWithHeight(height), &feemarkettypes.QueryParamsRequest{})

    Added a one-line comment: params come from the block's height because they decide the next block's base fee, so it's a historical query for eth_feeHistory (0ffd4327).

    thomas-nguy thomas-nguy commented on code on Oct 13, 2026 01:14 UTC
    Code Review
    rpc/backend/backend.go:1
    @@ -193,8 +194,22 @@ type Backend struct {
     	indexer             ethermint.EVMTxIndexer
     	processBlocker      ProcessBlocker
     	mempoolClient       appmempool.MempoolClient
    +	// proposer consensus address -> operator account
    +	validatorAccounts *lru.Cache[string, validatorAccountEntry]
     }
     
    +type validatorAccountEntry struct {
    +	acc    sdk.AccAddress
    +	height int64 // block the account was resolved for

    Consider using a range list

    thomas-nguy thomas-nguy commented on code on Oct 13, 2026 01:15 UTC
    Code Review
    rpc/backend/chain_info.go:1
    @@ -81,27 +80,16 @@ func (b *Backend) GlobalMinGasPrice() (sdkmath.LegacyDec, error) {
     	return res.Params.MinGasPrice, nil
     }
     
    -// BaseFee returns the base fee tracked by the Fee Market module.
    -// If the base fee is not enabled globally, the query returns nil.
    -// If the London hard fork is not activated at the current height, the query will
    -// return nil.
    +// BaseFee returns the base fee the block's transactions paid, or nil if none.

    Consider caching the base fee if its simple (does not need to be in this PR)

    JayT106 JayT106 commented on code on Oct 13, 2026 13:40 UTC
    Code Review
    rpc/backend/backend.go:1
    @@ -193,8 +194,22 @@ type Backend struct {
     	indexer             ethermint.EVMTxIndexer
     	processBlocker      ProcessBlocker
     	mempoolClient       appmempool.MempoolClient
    +	// proposer consensus address -> operator account
    +	validatorAccounts *lru.Cache[string, validatorAccountEntry]
     }
     
    +type validatorAccountEntry struct {
    +	acc    sdk.AccAddress
    +	height int64 // block the account was resolved for

    Implemented in 23b77a6b: each validator's entry now keeps a sorted list of block ranges (the 10k-block window around every block it was resolved for, merged when they touch), capped at 64 ranges by dropping the one farthest from the new block.

    JayT106 JayT106 commented on code on Oct 13, 2026 13:45 UTC
    Code Review
    rpc/backend/chain_info.go:1
    @@ -81,27 +80,16 @@ func (b *Backend) GlobalMinGasPrice() (sdkmath.LegacyDec, error) {
     	return res.Params.MinGasPrice, nil
     }
     
    -// BaseFee returns the base fee tracked by the Fee Market module.
    -// If the base fee is not enabled globally, the query returns nil.
    -// If the London hard fork is not activated at the current height, the query will
    -// return nil.
    +// BaseFee returns the base fee the block's transactions paid, or nil if none.

    Tracked in #1121.

    JayT106 JayT106 commented on Oct 13, 2026 14:17 UTC
    Author

    Benchmark on Cronos mainnet data

    Setup

  • Snapshot: cronosmainnet_25-1_rocksdb-memiavl-20261013 (RocksDB + memiavl, no versiondb), on an Apple M4 Max.

  • Baseline: Cronos v1.7.9. Fixed: v1.7.9 with this PR's base fee and validator changes backported to its ethermint. Only this PR's changes; no store changes.

  • Synced ~1,900 blocks past the snapshot, then ran offline. Heights 99,600,001–99,600,999 sit 1–999 blocks after memiavl snapshot 99,600,000, so each historical load replays up to 999 blocks, as on production nodes with snapshot-interval = 1000.

  • 200 heights spread over that window (all 86 EIP-1559 txs for tx receipts), sequential and 8 concurrent.
  • Results

    | Endpoint | Concurrency | v1.7.9 mean / p99 | This PR mean / p99 |
    |---|---|---|---|
    | eth_getBlockByNumber | 1 | 83 ms / 128 ms | 0.17 ms / 0.27 ms |
    | eth_getBlockByNumber, replay 900–999 blocks | 1 | 123 ms / 133 ms | 0.19 ms / 0.66 ms |
    | eth_getBlockByNumber | 8 | 277 ms / 375 ms | 0.43 ms / 1.1 ms |
    | eth_getBlockReceipts | 1 | 4.2 ms / 65 ms | 0.21 ms / 1.4 ms |
    | eth_getBlockReceipts | 8 | 12.6 ms / 157 ms | 0.58 ms / 2.7 ms |
    | eth_getTransactionReceipt (EIP-1559) | 1 | 39 ms / 66 ms | 0.62 ms / 2.2 ms |
    | eth_getTransactionReceipt (EIP-1559) | 8 | 127 ms / 184 ms | 1.25 ms / 2.1 ms |

  • v1.7.9 grows with the replay distance and with concurrency; repeating the same heights doesn't help. With this PR, latency stays under ~1 ms regardless.

  • Receipts only pay the historical load for blocks with EIP-1559 txs; 878 of the 999 blocks were empty, hence v1.7.9's low p50.

  • Both binaries returned identical miner, baseFeePerGas and effectiveGasPrice for 90 blocks and 86 tx receipts; no errors.

  • Absolute v1.7.9 numbers are below the ~1.3 s seen in production because this window is light (~0.4 s blocks, mostly empty) and the disk is a local NVMe with no other load.
  • JayT106 JayT106 commented on Oct 13, 2026 14:22 UTC
    Author

    @claude review

    github-actions[bot] github-actions[bot] commented on Oct 13, 2026 14:22 UTC
    Bot

    Claude finished @JayT106's task in 2m 17s —— View job

    ---

    Code Review

  • Gather context and read changed files

  • Review rpc/backend/utils.go — validator cache (range-list logic)

  • Review rpc/backend/backend.go — cache initialization

  • Review rpc/backend/chain_info.go — base fee changes

  • Review rpc/backend/blocks.go — block RPC changes

  • Review test files

  • Check for correctness bugs, security issues, state-breaking changes

  • Post final review
  • ---

    Summary

    This is a well-engineered performance optimization. The benchmark results (83 ms → 0.17 ms for eth_getBlockByNumber) speak for themselves. No state-breaking changes — the PR is purely in the RPC layer.

    ---

    Breaking / Consensus Changes

    None. All changes are in rpc/backend/; no state machine, codec, or migration code is touched.

    ---

    Correctness

    BaseFee — event-first path (chain_info.go:83)

    The inversion (events first, state fallback) is correct and well-tested. One subtlety worth noting: BaseFeeFromEvents returns nil if the base_fee attribute is found but malformed, not just when it's absent. That means a malformed event causes a state fallback. The test suite now covers this explicitly ("malformed feemarket event falls back to state query" / "fail - malformed feemarket event, grpc BaseFee error"). ✅

    Old code also had a subtle bug fixed here: it hardcoded Attributes[0] (would miss base_fee at any non-zero index) and used strconv.ParseInt (silently truncated values above MaxInt64). Both are gone. ✅

    nextBaseFee — governance override (utils.go:133)

    if stored := p.BaseFee.BigInt(); p.IsBaseFeeEnabled(height+1) && stored != nil && stored.Sign() > 0 {
        parent.BaseFee = stored
    }
    

    p.BaseFee is the feemarket module's stored param, which the chain updates every block. Using it (rather than the event-derived blockBaseFee) means a governance param overwrite is reflected immediately in eth_feeHistory. In normal operation the two values are identical. The IsBaseFeeEnabled(height+1) guard correctly handles pre-London historical ranges. ✅

    The stored != nil guard is technically redundant (sdkmath.Int.BigInt() on a valid Int always returns non-nil), but it's harmless defensive code.

    getValidatorAccount — range-list cache (utils.go:349)

    The core invariant — ranges are sorted, non-overlapping, and immutable once stored — is correctly maintained by withBlock. Verified the merge logic:

  • Binary search for first range with to >= r.from-1 (touching counts) → i

  • Extend j until ranges[j].from > r.to+1

  • Merge i..j-1 into r, insert back via slices.Concat

  • Drop the range farthest from height when over the cap
  • The drop condition:

    if height-ranges[0].to > ranges[len(ranges)-1].from-height {
        ranges = ranges[1:]   // leftmost is farther
    } else {
        ranges = ranges[:len(ranges)-1]  // rightmost is farther or equal
    }
    

    If height falls inside the merged range (always true), one of these distances is negative and the other positive, so the comparisons are unambiguous. ✅

    Acknowledged concurrency tradeoff: two concurrent misses can each call withBlock independently; the second Add overwrites the first's ranges. The cost is one extra RPC call on the next miss — not a correctness issue. The comment on line 376 documents this. ✅

    ---

    Minor Observations

    1. covers binary search (utils.go:381): searches by ranges[i].to — valid because non-overlapping disjoint ranges sorted by .from are also sorted by .to. Correct.

    2. withBlock on a fresh entry (!ok path, utils.go:374): entry starts as zero-value validatorAccountEntry{} (nil ranges). withBlock on an empty slice produces [{height-w, height+w}]. Correct.

    3. BaseFee nil-base-fee path (chain_info.go:96): when no event and state returns res.BaseFee == nil (fee market disabled or pre-London), returns nil, nil. Previously this same condition fell back to events; now events are already exhausted. Behavior is equivalent. ✅

    4. lru.New error (backend.go:237): lru.New only errors when size ≤ 0. The constant validatorAccountCacheSize = 1024 makes this unreachable; the panic is safe. ✅

    ---

    Test Coverage

    The new tests in utils_test.go are thorough:

  • TestGetValidatorAccount covers: latest-height hit, historical fallback, cache reuse, range extension, account re-registration, not-found, and malformed address.

  • TestValidatorAccountEntryWithBlock covers: empty entry, non-touching, touching, spanning-merge, and all three cap-drop directions (left/middle/right of full list).
  • The 4 uncovered lines (codecov) are in the lru.New panic path and the BaseFeeFromEvents fallback inside BaseFee — both are expected gaps that don't warrant concern.

    ---

    Overall

    This is a high-quality PR. The base-fee fix (from int64-capped + Attributes[0] hardcode to big.Int + key-search) is a correctness improvement on top of the performance win. The validator cache design (immutable-slice range list, accepted concurrent-write loss) is a reasonable tradeoff between simplicity and accuracy. No issues blocking merge.

    Reviewers
    Assignees
    JayT106 JayT106
    Labels
    risk: low confidence: 81.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 76.2% (HIGH) · Higher = larger blast radius
    76.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 81.1% · Lower = rushed or shallow review
    81.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 14.4% · Safe to merge
    14.4%