Skip to content

Conversation

anhductn2001
Copy link
Contributor

@anhductn2001 anhductn2001 commented Aug 18, 2025

Description

This PR fixes a critical integer overflow vulnerability in the gas store (store/gaskv/store.go) by implementing safe multiplication for gas calculations. The fix prevents potential gas manipulation attacks and ensures the system remains secure when handling large data operations.

Problem

The original code had unsafe integer multiplication in gas calculations:

// TODO overflow-safe math?
gs.gasMeter.ConsumeGas(gs.gasConfig.ReadCostPerByte*types.Gas(len(key)), types.GasReadPerByteDesc)
gs.gasMeter.ConsumeGas(gs.gasConfig.WriteCostPerByte*types.Gas(len(key)), types.GasWritePerByteDesc)

This could lead to:

  • Integer overflow when multiplying large gas costs with large data lengths
  • Potential gas undercharging/overcharging attacks
  • System instability or crashes

Summary by CodeRabbit

  • Bug Fixes

    • Prevents gas calculation overflows during reads, writes, and iteration.
    • Ensures accurate gas charging for large keys/values; caps consumption at a safe maximum when limits are exceeded.
    • Improves stability and predictability of operations under extreme input sizes.
  • Tests

    • Adds comprehensive unit and integration tests covering edge cases, large payloads, and boundary conditions to validate safe gas calculations and overall robustness.

Copy link
Contributor

coderabbitai bot commented Aug 18, 2025

📝 Walkthrough

Walkthrough

Introduces overflow-safe gas calculations via a new SafeMul helper and replaces direct multiplications in Get, Set, and iterator gas consumption. On overflow or invalid length, it consumes max gas for the specific descriptor. Adds tests for SafeMul edge cases and integration with gaskv.Store.

Changes

Cohort / File(s) Summary
Gas safety and consumption logic
store/gaskv/store.go
Added SafeMul(cost types.Gas, length int) with overflow and input validation; integrated SafeMul into Get, Set, and iterator seek gas consumption; imports updated. On overflow, consumes maximum gas for the specific per-byte descriptor.
Unit and integration tests
store/gaskv/store_test.go
Added TestSafeMul with edge cases (zero, large, max boundary, overflow, negative length). Added TestSafeMulIntegration validating gaskv.Store behavior and gas bounds with normal and large payloads.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Store
  participant SafeMul
  participant GasMeter

  Client->>Store: Get/Set(key, value)
  Store->>SafeMul: costPerKeyByte × len(key)
  alt overflow or invalid
    SafeMul-->>Store: error
    Store->>GasMeter: Consume(maxGasForKeyBytes)
  else ok
    SafeMul-->>Store: gasForKeyBytes
    Store->>GasMeter: Consume(gasForKeyBytes)
  end
  Store->>SafeMul: costPerValueByte × len(value)
  alt overflow or invalid
    SafeMul-->>Store: error
    Store->>GasMeter: Consume(maxGasForValueBytes)
  else ok
    SafeMul-->>Store: gasForValueBytes
    Store->>GasMeter: Consume(gasForValueBytes)
  end
  Store-->>Client: result
Loading
sequenceDiagram
  participant Iterator
  participant SafeMul
  participant GasMeter

  Iterator->>SafeMul: costPerKeyByte × len(key)
  alt overflow/invalid
    SafeMul-->>Iterator: error
    Iterator->>GasMeter: Consume(maxGasForKeyBytes)
  else
    SafeMul-->>Iterator: gasForKeyBytes
    Iterator->>GasMeter: Consume(gasForKeyBytes)
  end
  Iterator->>SafeMul: costPerValueByte × len(value)
  alt overflow/invalid
    SafeMul-->>Iterator: error
    Iterator->>GasMeter: Consume(maxGasForValueBytes)
  else
    SafeMul-->>Iterator: gasForValueBytes
    Iterator->>GasMeter: Consume(gasForValueBytes)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (6)
store/gaskv/store.go (3)

200-207: Iterator: charging per-key bytes deviates from documented behavior and likely alters gas accounting

The method comment (Lines 193–195) says the variable gas is based on the current value's length. This block now also charges for key length and uses GasValuePerByteDesc for it. This is a behavior change that can break existing gas invariants/tests and mixes descriptors.

  • If the intent is to keep existing semantics, remove the key charge.
  • If you really want to start charging per-key bytes, update the docs, consider a distinct descriptor, and revisit all tests relying on exact gas tallies.

Suggested revert (remove key-length charge):

-		// Safe gas calculation for key length
-		if gasCost, err := SafeMul(gi.gasConfig.ReadCostPerByte, len(key)); err == nil {
-			gi.gasMeter.ConsumeGas(gasCost, types.GasValuePerByteDesc)
-		} else {
-			// If overflow occurs, consume maximum gas as a safety measure
-			gi.gasMeter.ConsumeGas(types.Gas(^uint64(0)), types.GasValuePerByteDesc)
-		}

216-217: Nit: consider charging the flat seek cost before the per-byte cost (consistency)

Minor, but historically many flows charge the flat cost first, then per-byte. Not functionally significant.


219-234: SafeMul is correct; consider minor API and readability refinements

  • Using int for length aligns with len(), but exposes 32-bit arch pitfalls in callers/tests. Consider using uint64 for length and casting once at call sites.
  • Prefer math.MaxUint64 over ^uint64(0) for readability (or hoist a package-level const var maxGas = types.Gas(math.MaxUint64)).
  • Early-return for length == 0 (in addition to cost == 0) improves readability.

Alternative signature and implementation for consideration:

// SafeMul performs overflow-safe multiplication of gas cost by length.
// Note: len(...) is always non-negative, so a uint64 length avoids negative checks.
func SafeMul(cost types.Gas, length uint64) (types.Gas, error) {
	if cost == 0 || length == 0 {
		return 0, nil
	}
	max := types.Gas(^uint64(0))
	// Overflow if cost * length > max
	if cost > max/types.Gas(length) {
		return 0, fmt.Errorf("gas calculation overflow: cost=%d, length=%d", cost, length)
	}
	return cost * types.Gas(length), nil
}
store/gaskv/store_test.go (3)

20-21: Fix comment capitalization to match exported function name

Use SafeMul (not safeMul) in the test description.

-// TestSafeMul tests the safeMul function for various scenarios
+// TestSafeMul tests the SafeMul function for various scenarios

156-160: Strengthen the integration assertion

Asserting gasConsumed < MaxUint64 is tautological. Assert it does not exceed the meter limit.

-	require.Greater(t, gasConsumed, types.Gas(0))
-	require.Less(t, gasConsumed, types.Gas(^uint64(0))) // Should not be max uint64
+	require.Greater(t, gasConsumed, types.Gas(0))
+	require.LessOrEqual(t, gasConsumed, meter.Limit())

131-160: Consider adding an overflow-path integration test to prove the OOG fallback

Right now we don't cover the overflow path that leads to OOG consumption. You could craft a custom gasConfig with extremely large per-byte costs to force SafeMul overflow and assert that Set/Get/iterator operations panic with out-of-gas due to the precise OOG consumption.

I can draft a minimal test that overrides gasConfig.ReadCostPerByte/WriteCostPerByte to near-MaxUint64 and verifies panic on Set/Get for modest key/value sizes. Want me to push that snippet?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 8a9467c and e3166f0.

📒 Files selected for processing (2)
  • store/gaskv/store.go (4 hunks)
  • store/gaskv/store_test.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Summary
🔇 Additional comments (4)
store/gaskv/store.go (4)

208-214: Iterator (value length): use dedicated OOG helper on overflow

To ensure consistent out-of-gas errors instead of saturating at MaxUint64, replace the raw max-gas consumption with a call to consumeOutOfGas. If this helper isn’t defined yet, please add it (for example, wrapping Meter.ConsumeGas(meter.Limit(), desc) or invoking a proper OOG signal) so that all overflow branches trigger a proper OOG error.

– In store/gaskv/store.go around line 212:

-   // If overflow occurs, consume maximum gas as a safety measure
-   gi.gasMeter.ConsumeGas(types.Gas(^uint64(0)), types.GasValuePerByteDesc)
+   // On overflow, trigger out-of-gas via helper for precise OOG semantics
+   consumeOutOfGas(gi.gasMeter, types.GasValuePerByteDesc)

66-73: Incorrect suggestion: helper consumeOutOfGas doesn’t exist
The proposed replacement calls consumeOutOfGas(...), but no such function is defined in the codebase. To trigger a precise out-of-gas instead of using ^uint64(0), you should either:

• Inline the logic:

remaining := gs.gasMeter.GasRemaining()
gs.gasMeter.ConsumeGas(remaining+1, types.GasWritePerByteDesc)

• Or define the helper before using it:

func consumeOutOfGas(meter types.GasMeter, desc string) {
    remaining := meter.GasRemaining()
    meter.ConsumeGas(remaining+1, desc)
}

And then replace the overflow branch with:

-   gs.gasMeter.ConsumeGas(types.Gas(^uint64(0)), types.GasWritePerByteDesc)
+   consumeOutOfGas(gs.gasMeter, types.GasWritePerByteDesc)

Likely an incorrect or invalid review comment.


74-80: No consumeOutOfGas helper exists—suggestion invalid

I couldn’t find any consumeOutOfGas function in the repo. You have two options:

  • Keep the current explicit overflow branch call:
    gs.gasMeter.ConsumeGas(types.Gas(^uint64(0)), types.GasWritePerByteDesc)
  • Or first extract a helper, for example:
    func consumeOutOfGas(m storetypes.GasMeter, desc string) {
        m.ConsumeGas(types.Gas(^uint64(0)), desc)
    }
    and then call that in each overflow branch.

[suggest_essential_refactor removed]

Likely an incorrect or invalid review comment.


49-55: Undefined helper consumeOutOfGas referenced
The suggested refactor calls a helper that doesn’t exist in the codebase. The existing pattern—explicitly consuming types.Gas(^uint64(0)) on overflow—is consistently applied across all gas calculations and has corresponding tests. You can either ignore this refactor or introduce and implement a new consumeOutOfGas helper before applying it.

Affected locations for overflow handling (no helper currently defined):

  • store/gaskv/store.go lines 45–47 and 53–55 (Get key/value)
  • store/gaskv/store.go lines 69–71 and 77–79 (Write key/value)
  • store/gaskv/store.go lines 203–206 and 209–214 (Iterator)

Likely an incorrect or invalid review comment.

@aljo242
Copy link
Contributor

aljo242 commented Aug 18, 2025

lint failing and needing a changelog

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants