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

Problem: no testnet benchmark command #1667

Merged
merged 11 commits into from
Oct 28, 2024

Conversation

yihuang
Copy link
Collaborator

@yihuang yihuang commented Oct 28, 2024

temp

testnet command

changelog

👮🏻👮🏻👮🏻 !!!! REFERENCE THE PROBLEM YOUR ARE SOLVING IN THE PR TITLE AND DESCRIBE YOUR SOLUTION HERE !!!! DO NOT FORGET !!!! 👮🏻👮🏻👮🏻

PR Checklist:

  • Have you read the CONTRIBUTING.md?
  • Does your PR follow the C4 patch requirements?
  • Have you rebased your work on top of the latest master?
  • Have you checked your code compiles? (make)
  • Have you included tests for any non-trivial functionality?
  • Have you checked your code passes the unit tests? (make test)
  • Have you checked your code formatting is correct? (go fmt)
  • Have you checked your basic code style is fine? (golangci-lint run)
  • If you added any dependencies, have you checked they do not contain any known vulnerabilities? (go list -json -m all | nancy sleuth)
  • If your changes affect the client infrastructure, have you run the integration test?
  • If your changes affect public APIs, does your PR follow the C4 evolution of public contracts?
  • If your code changes public APIs, have you incremented the crate version numbers and documented your changes in the CHANGELOG.md?
  • If you are contributing for the first time, please read the agreement in CONTRIBUTING.md now and add a comment to this pull request stating that your PR is in accordance with the Developer's Certificate of Origin.

Thank you for your code, it's appreciated! :)

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced support for asynchronous transaction checks in the relayer precompile.
    • Added a command-line interface for testnet interactions, including funding accounts, checking account status, generating transactions, and dumping block statistics.
  • Improvements

    • Enhanced transaction handling with dynamic options for gas price and chain ID.
    • Updated block statistics retrieval for improved flexibility with RPC endpoints.
    • Improved test transaction generation and parallel processing.
  • Bug Fixes

    • Resolved issues with single validator benchmarks and node shutdown processes.
    • Fixed state overwrites in debug trace APIs.
    • Addressed multisig account issues and ensured governance parameters pass validation.
  • Documentation

    • Updated CHANGELOG to reflect new features, improvements, and bug fixes.

temp

testnet command

changelog
Copy link
Contributor

coderabbitai bot commented Oct 28, 2024

Walkthrough

The changes in this pull request encompass updates to the CHANGELOG.md, new features in the benchmarking suite, and enhancements to transaction handling. A new CLI for testnet interactions is introduced, alongside modifications to various Python files to improve flexibility in RPC endpoint usage and transaction configurations. Additionally, new classes related to Ethereum transactions are added, and several function signatures are updated for better configurability. The Nix configuration and Python project settings are also adjusted to accommodate these new features.

Changes

File Path Change Summary
CHANGELOG.md Updated to include new features, improvements, and bug fixes; added support for asynchronous transaction checks and testnet benchmark command; updated cometbft library version.
testground/benchmark/benchmark/cosmostx.py Added classes MsgEthereumTx and LegacyTx with various fields to enhance protocol buffer definitions related to Ethereum transactions.
testground/benchmark/benchmark/stats.py Modified functions to accept additional RPC parameters for enhanced block information retrieval and statistics dumping; updated logic for flexible block range processing.
testground/benchmark/benchmark/testnet.py Introduced a CLI for testnet interactions with commands for funding accounts, checking status, generating transactions, sending transactions, and dumping block statistics.
testground/benchmark/benchmark/transaction.py Updated transaction functions to accept options for dynamic gas price and chain ID; added new functions for building Ethereum messages; modified sending functions for RPC.
testground/benchmark/benchmark/utils.py Updated function signatures to accept RPC parameters, enhancing flexibility for block-related functions.
testground/benchmark/flake.nix Added a new application entry testnet for the testnet CLI within the Nix flake configuration.
testground/benchmark/pyproject.toml Added a new script entry for the testnet CLI in the pyproject.toml file.

Possibly related PRs

Suggested labels

backport/v1.3.x

Suggested reviewers

  • JayT106
  • mmsqe
  • devashishdxt

Poem

In the meadow where rabbits play,
New features hop in bright array.
With testnets and transactions grand,
We frolic and leap across the land.
Changes bloom like flowers in spring,
Join us, dear friends, let’s dance and sing! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f6224ff and 02165d6.

📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md

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 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

codecov bot commented Oct 28, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 16.88%. Comparing base (6de40de) to head (02165d6).
Report is 1 commits behind head on main.

❗ There is a different number of reports uploaded between BASE (6de40de) and HEAD (02165d6). Click for more details.

HEAD has 12 uploads less than BASE
Flag BASE (6de40de) HEAD (02165d6)
2 0
integration_tests 20 10
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##             main    #1667       +/-   ##
===========================================
- Coverage   35.17%   16.88%   -18.29%     
===========================================
  Files         123       72       -51     
  Lines       11740     6149     -5591     
===========================================
- Hits         4129     1038     -3091     
+ Misses       7197     4988     -2209     
+ Partials      414      123      -291     

see 69 files with indirect coverage changes

CHANGELOG.md Outdated Show resolved Hide resolved
Signed-off-by: yihuang <[email protected]>
@yihuang yihuang marked this pull request as ready for review October 28, 2024 06:46
@yihuang yihuang requested a review from a team as a code owner October 28, 2024 06:46
@yihuang yihuang requested review from mmsqe and thomas-nguy and removed request for a team October 28, 2024 06:46
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: 11

🧹 Outside diff range and nitpick comments (3)
testground/benchmark/benchmark/cosmostx.py (1)

81-87: Add class documentation and improve field naming.

The class needs documentation to explain its purpose in the Ethereum transaction handling context. Also, consider the following improvements:

  1. Replace from_ with a standard protobuf naming convention
  2. Add deprecation notice for deprecated_hash

Apply this diff:

 class MsgEthereumTx(ProtoEntity):
+    """Represents an Ethereum transaction message in the Cosmos protocol.
+    
+    This message type encapsulates Ethereum transactions for processing in the Cosmos chain.
+    """
     MSG_URL = "/ethermint.evm.v1.MsgEthereumTx"
 
     data = Field(ProtoAny, 1)
+    # @deprecated: Use an alternative field (specify which)
     deprecated_hash = Field("string", 3)
-    from_ = Field("bytes", 5)
+    sender = Field("bytes", 5)  # 'from' is reserved in protobuf
     raw = Field("bytes", 6)
testground/benchmark/benchmark/utils.py (2)

Line range hint 174-182: Add error handling for Ethereum block retrieval.

The function should validate the JSON-RPC response and handle potential errors properly.

Consider adding error handling:

 def block_eth(height: int, json_rpc=LOCAL_JSON_RPC):
-    return requests.post(
-        json_rpc,
-        json={
-            "jsonrpc": "2.0",
-            "method": "eth_getBlockByNumber",
-            "params": [hex(height), False],
-            "id": 1,
-        },
-    ).json()["result"]
+    try:
+        rsp = requests.post(
+            json_rpc,
+            json={
+                "jsonrpc": "2.0",
+                "method": "eth_getBlockByNumber",
+                "params": [hex(height), False],
+                "id": 1,
+            },
+            timeout=10
+        ).json()
+        if "error" in rsp:
+            raise ValueError(f"JSON-RPC error: {rsp['error']}")
+        if "result" not in rsp:
+            raise ValueError("Invalid JSON-RPC response: missing 'result'")
+        return rsp["result"]
+    except (requests.RequestException, ValueError) as e:
+        raise RuntimeError(f"Failed to fetch Ethereum block {height} from {json_rpc}: {str(e)}")

Line range hint 165-187: Well-structured RPC endpoint configurability.

The changes follow a consistent pattern of making RPC endpoints configurable while maintaining backward compatibility. This architectural improvement aligns well with the PR's objective of supporting testnet benchmarking by allowing the functions to work with different networks.

However, consider extracting common RPC error handling logic into a decorator or utility function to maintain DRY principles and ensure consistent error handling across all RPC calls.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 27f1a59 and f6224ff.

📒 Files selected for processing (8)
  • CHANGELOG.md (1 hunks)
  • testground/benchmark/benchmark/cosmostx.py (1 hunks)
  • testground/benchmark/benchmark/stats.py (2 hunks)
  • testground/benchmark/benchmark/testnet.py (1 hunks)
  • testground/benchmark/benchmark/transaction.py (7 hunks)
  • testground/benchmark/benchmark/utils.py (2 hunks)
  • testground/benchmark/flake.nix (1 hunks)
  • testground/benchmark/pyproject.toml (1 hunks)
🔇 Additional comments (12)
testground/benchmark/flake.nix (2)

36-39: LGTM! Clean addition of the testnet app.

The new testnet app entry follows the established pattern and maintains consistency with existing app declarations.


36-39: Verify the testnet binary in benchmark-testcase package.

Let's ensure the referenced binary testnet is properly installed in the package.

✅ Verification successful

Let me check the content of the testnet.py file and look for any binary installation or build configurations.


Let me check the build configuration in pyproject.toml to verify how the testnet binary is defined.


Let me check the overlay.nix file to see how the benchmark-testcase package is built.


The testnet binary is properly configured and will be installed correctly

The verification shows that:

  1. The testnet script is properly defined in pyproject.toml under [tool.poetry.scripts] section, pointing to benchmark.testnet:cli
  2. The implementation exists in testground/benchmark/benchmark/testnet.py with a proper CLI entrypoint
  3. The nix package is correctly configured to build using poetry2nix and expose the binary through the apps.testnet attribute in flake.nix
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the testnet binary installation in the package

# Test 1: Check if the binary is declared in setup files
echo "Checking setup files for testnet binary declaration..."
rg -l "testnet" --type python | grep -E "setup\.py|pyproject\.toml"

# Test 2: Look for the testnet.py source file
echo "Looking for testnet implementation..."
fd testnet.py

Length of output: 360


Script:

#!/bin/bash
# Check the content of testnet.py
cat testground/benchmark/benchmark/testnet.py

# Look for any build or installation configurations
fd -e nix -e toml -e cabal . | xargs rg -l "testnet"

Length of output: 4327


Script:

#!/bin/bash
# Check pyproject.toml for binary configuration
cat testground/benchmark/pyproject.toml

# Check the nix package definition
cat testground/benchmark/flake.nix

Length of output: 2272


Script:

#!/bin/bash
# Check the package overlay definition
cat testground/benchmark/overlay.nix

Length of output: 1560

testground/benchmark/benchmark/stats.py (3)

3-3: LGTM: Import changes are appropriate.

The new imports support the configurable RPC endpoints feature.


22-26: LGTM: RPC endpoint configuration added correctly.

The function properly handles the new rpc parameter. Let's verify its usage across the codebase.

#!/bin/bash
# Description: Check if there are any direct calls to get_block_info_cosmos without the rpc parameter
# This could identify places that need to be updated

ast-grep --pattern 'get_block_info_cosmos($height)' || echo "No calls found with single parameter"

29-33: LGTM: JSON-RPC endpoint configuration added correctly.

The function properly handles the new json_rpc parameter. Let's verify its usage across the codebase.

✅ Verification successful

LGTM: All calls to get_block_info_eth properly include the json_rpc parameter

The search results show that the function is only called once in the codebase at testground/benchmark/benchmark/stats.py, and this call correctly includes the json_rpc parameter. No updates are needed in other parts of the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there are any direct calls to get_block_info_eth without the json_rpc parameter
# This could identify places that need to be updated

ast-grep --pattern 'get_block_info_eth($height)' || echo "No calls found with single parameter"

Length of output: 50


Script:

#!/bin/bash
# Let's try a more comprehensive search for any calls to get_block_info_eth
rg "get_block_info_eth" -A 2

Length of output: 559


Script:

#!/bin/bash
# Also search for function definition to understand its usage pattern
ast-grep --pattern 'def get_block_info_eth($$$)'

Length of output: 50


Script:

#!/bin/bash
# Search for any test files that might use this function
fd "test.*\.py" --exec grep -l "get_block_info_eth" {}

Length of output: 56

testground/benchmark/benchmark/cosmostx.py (1)

89-100: 🛠️ Refactor suggestion

Add documentation and field validation for Ethereum transaction parameters.

The class needs documentation and field validation to ensure transaction integrity:

  1. Add class documentation explaining the legacy transaction format
  2. Add validation for hex string fields
  3. Add size validation for signature components

Apply this diff:

 class LegacyTx(ProtoEntity):
+    """Represents a legacy Ethereum transaction (EIP-155).
+
+    Contains all fields necessary for a pre-EIP-2718 Ethereum transaction:
+    - nonce: Account transaction sequence
+    - gas_price: Price per gas unit in wei
+    - gas: Gas limit
+    - to: Recipient address (hex string)
+    - value: Transaction value in wei
+    - data: Transaction input data
+    - v, r, s: Transaction signature components
+    """
     MSG_URL = "/ethermint.evm.v1.LegacyTx"
 
     nonce = Field("uint64", 1)
     gas_price = Field("string", 2)
     gas = Field("uint64", 3)
     to = Field("string", 4)
     value = Field("string", 5)
     data = Field("bytes", 6)
     v = Field("bytes", 7)
     r = Field("bytes", 8)
     s = Field("bytes", 9)
+
+    def validate(self):
+        """Validate transaction fields."""
+        if self.to and not self.to.startswith('0x'):
+            raise ValueError("'to' address must be hex string starting with '0x'")
+        if not self.value.isnumeric():
+            raise ValueError("'value' must be a numeric string")
+        for sig in (self.r, self.s):
+            if len(sig) != 32:
+                raise ValueError("r, s must be 32 bytes")

Let's verify if there are any existing validation implementations:

testground/benchmark/benchmark/utils.py (1)

186-187: LGTM!

The function correctly propagates the RPC endpoint to the block function and maintains a clean separation of concerns.

CHANGELOG.md (1)

12-12: LGTM!

The changelog entry is well-formatted, concise, and correctly documents the addition of the testnet benchmark command.

testground/benchmark/benchmark/transaction.py (4)

44-52: Enhancement of simple_transfer_tx function improves flexibility

The addition of the options parameter and the dynamic retrieval of gas_price and chain_id allow for more flexible transaction configurations.


55-66: Enhancement of erc20_transfer_tx function improves flexibility

The addition of the options parameter and the dynamic retrieval of gas_price and chain_id allow for more flexible transaction configurations.


75-116: Introduction of build_evm_msg_1_3 and build_evm_msg_1_4 adds version support

The new functions for building Ethereum messages for different versions enhance compatibility with various protocol versions.


243-246: Addition of rpc and sync parameters to async_sendtx increases flexibility

Allowing the specification of the RPC endpoint and choosing between synchronous and asynchronous broadcasting enhance the function's usability.

testground/benchmark/pyproject.toml Show resolved Hide resolved
testground/benchmark/benchmark/stats.py Show resolved Hide resolved
testground/benchmark/benchmark/utils.py Show resolved Hide resolved
testground/benchmark/benchmark/utils.py Show resolved Hide resolved
testground/benchmark/benchmark/testnet.py Show resolved Hide resolved
testground/benchmark/benchmark/testnet.py Show resolved Hide resolved
testground/benchmark/benchmark/testnet.py Show resolved Hide resolved
testground/benchmark/benchmark/testnet.py Show resolved Hide resolved
testground/benchmark/benchmark/testnet.py Show resolved Hide resolved
testground/benchmark/benchmark/transaction.py Show resolved Hide resolved
@yihuang yihuang added this pull request to the merge queue Oct 28, 2024
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks Oct 28, 2024
@yihuang yihuang added this pull request to the merge queue Oct 28, 2024
Merged via the queue into crypto-org-chain:main with commit 0f94930 Oct 28, 2024
34 of 35 checks passed
@yihuang yihuang deleted the testnet-script branch October 28, 2024 10: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