Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(evm): randao support for evm #2151

Merged
merged 3 commits into from
Jan 9, 2025
Merged

feat(evm): randao support for evm #2151

merged 3 commits into from
Jan 9, 2025

Conversation

onikonychev
Copy link
Contributor

@onikonychev onikonychev commented Jan 8, 2025

Although without this feature, instead of a panic described by auditor contract simply returns 0.

contract RandomConsumer {
    function getRandom() public view returns (uint256) {
        return block.prevrandao; // Will panic on Nibiru <-- not really, 0 is returned
    }
}

Summary by CodeRabbit

Release Notes

  • New Features

    • Added randao support for EVM, enabling access to block randomness.
    • Introduced TestRandom smart contract to retrieve the previous block's random value.
  • Testing

    • Added a comprehensive test suite for random value generation in the EVM context.
  • Documentation

    • Updated changelog to reflect new EVM randomness functionality.

These enhancements improve the EVM's capabilities by providing a mechanism to access block-level randomness, beneficial for various blockchain applications.

@onikonychev onikonychev requested a review from a team as a code owner January 8, 2025 14:53
Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

Walkthrough

This pull request introduces randao support for the Ethereum Virtual Machine (EVM) in the Nibiru blockchain project. The changes include adding a new TestRandom smart contract that retrieves the block.prevrandao value, updating the EVM context to generate a pseudo-random value, and creating corresponding test cases. The implementation allows accessing the previous block's randomness, which is a key feature for blockchain applications requiring verifiable randomness.

Changes

File Change Summary
CHANGELOG.md Added new entry for "randao support for evm" under Unreleased section
x/evm/embeds/contracts/TestRandom.sol New Solidity contract with getRandom() function to access block.prevrandao
x/evm/embeds/artifacts/contracts/TestRandom.sol/TestRandom.json New contract artifact with ABI and bytecode
x/evm/embeds/embeds.go Added new embedded contract SmartContract_TestRandom
x/evm/embeds/embeds_test.go Updated test to load new TestRandom contract
x/evm/keeper/msg_server.go Modified to generate pseudo-random value in EVM context
x/evm/keeper/random_test.go New test file to validate random value generation

Sequence Diagram

sequenceDiagram
    participant Block as Previous Block
    participant EVM as Ethereum Virtual Machine
    participant Contract as TestRandom Contract
    
    Block-->>EVM: Provides prevrandao value
    EVM->>Contract: Calls getRandom()
    Contract-->>EVM: Returns block.prevrandao
Loading

Possibly related PRs

Suggested reviewers

  • Unique-Divine

Poem

🐰 A Rabbit's Randomness Rhyme 🎲

In blocks of bytes, a number springs,
Prevrandao whispers secret things,
A dance of digits, wild and free,
Blockchain's own random melody!
Nibiru's EVM now knows the way
To spin the cosmic dice today! 🌈


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d67b40f and 6f3ebba.

📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: lint
  • GitHub Check: e2e-evm
  • GitHub Check: unit-tests
  • GitHub Check: integration-tests
  • GitHub Check: build

Finishing Touches

  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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: 3

🧹 Nitpick comments (3)
x/evm/embeds/contracts/TestRandom.sol (1)

1-2: Fix incorrect contract name in comment header

The comment header indicates "TestERC20.sol" but the file is "TestRandom.sol".

-// contracts/TestERC20.sol
+// contracts/TestRandom.sol
x/evm/embeds/embeds.go (1)

139-143: Enhance documentation for TestRandom contract

The current comment is too brief and doesn't explain the RANDAO functionality or its implications.

-	// SmartContract_TestRandom is a test contract which tests random function
+	// SmartContract_TestRandom is a test contract that demonstrates RANDAO functionality
+	// by accessing block.prevrandao values. This contract is used to verify that the EVM
+	// correctly supports post-merge randomness operations. Note that this randomness
+	// source has limitations and should not be used directly for high-stakes applications.
 	SmartContract_TestRandom = CompiledEvmContract{
 		Name:      "TestRandom.sol",
 		EmbedJSON: testRandom,
 	}
x/evm/keeper/msg_server.go (1)

125-127: Implementation of RANDAO support looks correct but has predictability concerns.

The implementation correctly provides RANDAO support by generating pseudo-random values from block time and last commit hash. However, be aware that these sources of entropy are predictable by validators, which may not be suitable for use cases requiring strong randomness.

Consider enhancing the randomness by incorporating additional entropy sources like:

  • VDF (Verifiable Delay Function) output
  • Multiple previous block hashes
  • Validator signatures

Also applies to: 139-139

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7aebf75 and c6b71f6.

📒 Files selected for processing (7)
  • CHANGELOG.md (1 hunks)
  • x/evm/embeds/artifacts/contracts/TestRandom.sol/TestRandom.json (1 hunks)
  • x/evm/embeds/contracts/TestRandom.sol (1 hunks)
  • x/evm/embeds/embeds.go (3 hunks)
  • x/evm/embeds/embeds_test.go (1 hunks)
  • x/evm/keeper/msg_server.go (3 hunks)
  • x/evm/keeper/random_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • x/evm/embeds/artifacts/contracts/TestRandom.sol/TestRandom.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: integration-tests
🔇 Additional comments (4)
x/evm/embeds/embeds_test.go (1)

24-24: LGTM!

The addition of SmartContract_TestRandom.MustLoad() follows the established pattern for contract loading tests.

x/evm/embeds/embeds.go (2)

44-45: LGTM!

The embedding of the TestRandom contract JSON follows the established pattern.


160-160: LGTM!

The initialization of TestRandom contract follows the established pattern.

CHANGELOG.md (1)

66-66: Changelog entry is well-formatted and clear.

The entry properly documents the RANDAO support feature with correct PR reference and clear description.

Comment on lines +7 to +9
function getRandom() public view returns (uint256) {
return block.prevrandao;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add documentation and security considerations for randomness generation

The getRandom function directly exposes block.prevrandao which has important security implications:

  1. The value is predictable by validators
  2. Can be manipulated in certain scenarios
  3. Should not be used directly for high-stakes randomness

Add comprehensive NatSpec documentation:

+    /// @notice Retrieves the previous block's RANDAO value
+    /// @dev WARNING: This randomness source has limitations:
+    ///      - Predictable by validators
+    ///      - Should not be used for high-stakes applications
+    ///      - Consider using a commit-reveal scheme for better unpredictability
+    /// @return uint256 The previous block's RANDAO value
     function getRandom() public view returns (uint256) {
         return block.prevrandao;
     }

Consider implementing a more secure randomness mechanism:

  1. Use a commit-reveal scheme
  2. Combine multiple entropy sources
  3. Consider using VRF (Verifiable Random Function) for critical applications
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function getRandom() public view returns (uint256) {
return block.prevrandao;
}
/// @notice Retrieves the previous block's RANDAO value
/// @dev WARNING: This randomness source has limitations:
/// - Predictable by validators
/// - Should not be used for high-stakes applications
/// - Consider using a commit-reveal scheme for better unpredictability
/// @return uint256 The previous block's RANDAO value
function getRandom() public view returns (uint256) {
return block.prevrandao;
}

Comment on lines 9 to 22
// TestRandom tests the random value generation within the EVM.
func (s *Suite) TestRandom() {
deps := evmtest.NewTestDeps()
deployResp, err := evmtest.DeployContract(&deps, embeds.SmartContract_TestRandom)
s.Require().NoError(err)
randomContractAddr := deployResp.ContractAddr

// highjacked LoadERC20BigInt method as it perfectly fits the need of this test
resp, err := deps.EvmKeeper.LoadERC20BigInt(
deps.Ctx, embeds.SmartContract_TestRandom.ABI, randomContractAddr, "getRandom",
)
s.Require().NoError(err)
s.Require().Greater(resp.Int64(), int64(0))
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage for random value generation

The current test only verifies that the random value is greater than zero. This is insufficient for testing randomness properties.

Add comprehensive test cases:

func (s *Suite) TestRandom() {
    deps := evmtest.NewTestDeps()
    deployResp, err := evmtest.DeployContract(&deps, embeds.SmartContract_TestRandom)
    s.Require().NoError(err)
    randomContractAddr := deployResp.ContractAddr

    // Test multiple blocks to ensure values change
    values := make(map[int64]bool)
    for i := 0; i < 5; i++ {
        resp, err := deps.EvmKeeper.LoadRandomValue(
            deps.Ctx, embeds.SmartContract_TestRandom.ABI, randomContractAddr, "getRandom",
        )
        s.Require().NoError(err)
        s.Require().Greater(resp.Int64(), int64(0))
        
        // Verify uniqueness across blocks
        s.Require().False(values[resp.Int64()], "Duplicate random value detected")
        values[resp.Int64()] = true
        
        // Advance block
        deps.Ctx = deps.Ctx.WithBlockHeight(deps.Ctx.BlockHeight() + 1)
    }
}

Comment on lines 16 to 19
// highjacked LoadERC20BigInt method as it perfectly fits the need of this test
resp, err := deps.EvmKeeper.LoadERC20BigInt(
deps.Ctx, embeds.SmartContract_TestRandom.ABI, randomContractAddr, "getRandom",
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid repurposing ERC20 methods for non-ERC20 functionality

The comment acknowledges that LoadERC20BigInt is being "hijacked" for this test. This is a code smell that could lead to maintenance issues.

Consider creating a dedicated method for loading random values:

-	// highjacked LoadERC20BigInt method as it perfectly fits the need of this test
-	resp, err := deps.EvmKeeper.LoadERC20BigInt(
+	resp, err := deps.EvmKeeper.LoadRandomValue(
 		deps.Ctx, embeds.SmartContract_TestRandom.ABI, randomContractAddr, "getRandom",
 	)

Committable suggestion skipped: line range outside the PR's diff.

Copy link

codecov bot commented Jan 8, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 65.20%. Comparing base (8c6e021) to head (6f3ebba).
Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2151      +/-   ##
==========================================
- Coverage   65.21%   65.20%   -0.01%     
==========================================
  Files         277      277              
  Lines       22197    22208      +11     
==========================================
+ Hits        14475    14480       +5     
- Misses       6732     6739       +7     
+ Partials      990      989       -1     
Files with missing lines Coverage Δ
x/evm/embeds/embeds.go 75.00% <100.00%> (+0.80%) ⬆️
x/evm/keeper/msg_server.go 77.19% <100.00%> (+0.19%) ⬆️

... and 1 file with indirect coverage changes

@k-yang k-yang enabled auto-merge (squash) January 9, 2025 00:10
@k-yang k-yang merged commit 8e477cb into main Jan 9, 2025
15 checks passed
@k-yang k-yang deleted the feat/evm-random branch January 9, 2025 00:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants