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

Raunak/sig verifier test #2

Merged
merged 1 commit into from
Jan 13, 2025
Merged

Raunak/sig verifier test #2

merged 1 commit into from
Jan 13, 2025

Conversation

RnkSngh
Copy link
Collaborator

@RnkSngh RnkSngh commented Jan 13, 2025

PR to add sig verifier tests for contracts!

Summary by CodeRabbit

  • New Features

    • Added new test contracts for verifying sequencer signatures and receipt proofs
    • Introduced new utility contracts for testing blockchain-related functionality
  • Tests

    • Added multiple test files for PolymerProofLib, ReceiptMPT, and SequencerVerifier
    • Included new payload and proof files for testing blockchain transactions
  • Chores

    • Added Forge standard library as a Git submodule
    • Introduced new utility contracts and helper functions for testing
  • Documentation

    • Added new structures and contracts to support proof verification and testing

Copy link

coderabbitai bot commented Jan 13, 2025

Warning

Rate limit exceeded

@RnkSngh has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 49 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 24a3d44 and 6db1239.

📒 Files selected for processing (6)
  • contracts/libs/ReceiptParser.sol (1 hunks)
  • test/PolymerProofLib.t.sol (1 hunks)
  • test/SequencerVerifier.t.sol (1 hunks)
  • test/payload/l1_block_0x4df537.hex (1 hunks)
  • test/payload/l2_block_0x4b0.json (1 hunks)
  • test/utils/Signing.base.t.sol (1 hunks)

Walkthrough

This pull request introduces several new components to the repository, focusing on testing and proof verification for Layer 2 blockchain operations. The changes include adding a new Forge standard library submodule, creating new test contracts for receipt and sequencer proof verification, and introducing payload and proof files for Optimism and Arbitrum. The modifications aim to enhance the project's testing infrastructure and support for cross-chain proof validation.

Changes

File/Directory Change Summary
.gitmodules Added new submodule for lib/forge-std pointing to Foundry's standard library
contracts/libs/ReceiptParser.sol Introduced OpL2StateProof struct with fields for Layer 2 state proofs
test/PolymerProofLib.t.sol Added new test contract PolymerProofLibTest
test/ReceiptMPT.t.sol Created ReceiptMPT test contract with receipt verification tests
test/SequencerVerifier.t.sol Added SequencerProofVerifierStateUpdate with signature verification tests
test/payload/ Added multiple hex and JSON files for proofs and receipts (Arbitrum, Optimism, L1/L2 blocks)
test/utils/Base.t.sol Introduced Base testing utility contract
test/utils/Signing.base.t.sol Created SigningBase contract for signature-related testing

Sequence Diagram

sequenceDiagram
    participant Test as Test Contracts
    participant Verifier as Signature Verifier
    participant Proof as Proof Loader
    participant File as Payload Files

    Test->>File: Load proof/receipt data
    File-->>Test: Return hex/JSON data
    Test->>Proof: Parse and prepare proofs
    Test->>Verifier: Verify signatures/proofs
    Verifier-->>Test: Return verification result
Loading

Poem

🐰 Hop, hop, through the blockchain's maze,
Proofs and signatures in testing phase,
Forge-std submodule, a new friend arrives,
Layer 2 secrets, our rabbit code thrives!
Verifying signatures with playful delight 🔍


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

@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: 4

🧹 Nitpick comments (8)
test/ReceiptMPT.t.sol (1)

14-14: Document test data files

Add comments explaining the source and format of the test data files (op-proof.hex, op-receipt.hex, etc.) to improve maintainability.

Also applies to: 21-21

test/utils/Base.t.sol (2)

14-14: Consider making PEPTIDE_CHAIN_ID configurable

The hardcoded chain ID might not be suitable for different testing environments. Consider making it configurable through constructor parameters or environment variables.


21-21: Improve file path handling

Using string concatenation for file paths could be fragile. Consider creating a dedicated function for path resolution that handles path separators correctly across different operating systems.

Also applies to: 24-24

test/SequencerVerifier.t.sol (3)

11-13: Improve comment clarity for signature encoding

The current comment about signature order is unclear. Consider documenting the expected format:

// Signature format: |r (32 bytes)|s (32 bytes)|v (1 byte)|
// vm.sign returns (v, r, s) but we need (r, s, v) format

19-30: Add test cases for edge cases

Consider adding test cases for:

  • Zero values in r, s components
  • Maximum allowed values for v
  • Malformed signatures with valid lengths but invalid content

50-50: Extract magic number to a constant

The + 1 increment should be extracted to a named constant for clarity:

-        sigVerifier.verifyStateUpdate(peptideBlockNumber + 1, peptideAppHash, l1BlockHash, signature);
+        uint256 constant BLOCK_INCREMENT = 1;
+        sigVerifier.verifyStateUpdate(peptideBlockNumber + BLOCK_INCREMENT, peptideAppHash, l1BlockHash, signature);
test/utils/Signing.base.t.sol (1)

21-21: Document domain usage

The comment about the domain being empty needs more context. Explain why it's acceptable to leave it as zero bytes and any implications for production use.

contracts/libs/ReceiptParser.sol (1)

44-51: Enhance documentation for OpL2StateProof struct.

While the struct is well-structured, consider adding detailed documentation for each field to improve maintainability:

  • Purpose of each proof field
  • Expected format/structure of the proofs
  • Relationship between these proofs in the L2 state verification process

Example documentation:

 // This is the proof we use to verify the apphash (state) updates.
 struct OpL2StateProof {
+    /// @notice Merkle proof of the account state
+    /// @dev Array of RLP-encoded nodes forming the Merkle proof
     bytes[] accountProof;
+    /// @notice Merkle proof of the L2 output root
+    /// @dev Array of RLP-encoded nodes proving the output root
     bytes[] outputRootProof;
+    /// @notice Key used to identify the L2 output proposal
     bytes32 l2OutputProposalKey;
+    /// @notice Hash of the L2 block being proven
     bytes32 l2BlockHash;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ab03ac6 and 24a3d44.

📒 Files selected for processing (16)
  • .gitmodules (1 hunks)
  • contracts/libs/ReceiptParser.sol (1 hunks)
  • lib/forge-std (1 hunks)
  • test/PolymerProofLib.t.sol (1 hunks)
  • test/ReceiptMPT.t.sol (1 hunks)
  • test/SequencerVerifier.t.sol (1 hunks)
  • test/payload/arb-proof.hex (1 hunks)
  • test/payload/arb-receipt-proof.hex (1 hunks)
  • test/payload/arb-receipt.hex (1 hunks)
  • test/payload/l1_block_0x4df537.hex (1 hunks)
  • test/payload/l2_block_0x4b0.json (1 hunks)
  • test/payload/op-proof.hex (1 hunks)
  • test/payload/op-receipt-proof.hex (1 hunks)
  • test/payload/op-receipt.hex (1 hunks)
  • test/utils/Base.t.sol (1 hunks)
  • test/utils/Signing.base.t.sol (1 hunks)
✅ Files skipped from review due to trivial changes (10)
  • lib/forge-std
  • test/PolymerProofLib.t.sol
  • test/payload/arb-proof.hex
  • test/payload/arb-receipt.hex
  • test/payload/op-receipt.hex
  • test/payload/op-proof.hex
  • test/payload/l1_block_0x4df537.hex
  • test/payload/arb-receipt-proof.hex
  • test/payload/op-receipt-proof.hex
  • test/payload/l2_block_0x4b0.json
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: verify-bindings
  • GitHub Check: lint
🔇 Additional comments (2)
test/utils/Base.t.sol (1)

36-38: Add validation for storage manipulation

The storage write operation lacks validation. Consider adding checks:

  • Verify lightClient address is not zero
  • Validate proof height is within reasonable bounds
  • Add error handling for storage write failures
.gitmodules (1)

10-12: Verify forge-std submodule version.

The addition of forge-std is appropriate for testing. However, let's verify we're using a recent stable version.

✅ Verification successful

forge-std version is appropriate

The submodule is using a very recent commit from January 2025, which is newer than the latest release (v1.9.5). This is acceptable for a testing library, as recent versions often include important bug fixes and improvements.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the forge-std submodule version and latest release

# Get current commit hash
cd lib/forge-std && git rev-parse HEAD

# Get latest release tag and date
git ls-remote --tags https://github.com/foundry-rs/forge-std | sort -t '/' -k 3 -V | tail -n1

Length of output: 232


Script:

#!/bin/bash
# Get commit details and its relationship to latest release

cd lib/forge-std

# Get commit date and branch
git show -s --format=%ci 24a3d44659b267336c15a397f65506491d8fdf8c
git branch -r --contains 24a3d44659b267336c15a397f65506491d8fdf8c

# Check if commit is ahead of latest release
git merge-base --is-ancestor b93cf4bc34ff214c099dc970b153f85ade8c9f66 24a3d44659b267336c15a397f65506491d8fdf8c
echo $?

Length of output: 480


// Testing receipt proofs are as the relayer encodes them.
contract ReceiptMPT is Base {
function setUp() public {}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Implement setUp() function to initialize test state

The empty setUp() function should be implemented to properly initialize the test state, following Forge testing best practices.

Comment on lines 12 to 16
function test_optimism_receipt() public {
(bytes memory receiptIdx, bytes[] memory receiptProof, bytes32 receiptRoot, bytes memory receiptRLP) =
load_receipt("/test/payload/op-proof.hex", "/test/payload/op-receipt.hex");
assertEq(receiptRLP, MerkleTrie.get(receiptIdx, receiptProof, receiptRoot));
}
Copy link

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 with negative test cases

Both test functions only verify the happy path. Consider adding test cases for:

  • Invalid/malformed proofs
  • Incorrect receipt indices
  • Invalid root hashes
  • Empty or malformed RLP data

Also applies to: 19-23

Comment on lines +32 to +56
constructor() {
(sequencer, sequencerPkey) = makeAddrAndKey("alice");
(, notSequencerPkey) = makeAddrAndKey(unicode"bob😈");
sigVerifier = new SequencerSignatureVerifier(sequencer, PEPTIDE_CHAIN_ID);

// generate the channel_proof.hex file with the following command:
// cd test-data-generator && go run ./cmd/ --type l1 > ../test/payload/l1_block_0x4df537.hex
// this is the "rlp" half-encoded header that would be sent by the relayer. this was produced
// by the test-data-generator tool.
L1Header memory l1header = abi.decode(
vm.parseBytes(vm.readFile(string.concat(rootDir, "/test/payload/l1_block_0x4df537.hex"))), (L1Header)
);

l1BlockHash = keccak256(RLPWriter.writeList(l1header.header)); // Blockhash that will be signed by sequencer

peptideBlockNumber = 101;

// this happens to be the polymer height when the L2OO was updated with the output proposal
// we are using in the test
string memory l2BlockJson = vm.readFile(string.concat(rootDir, "/test/payload/l2_block_0x4b0.json"));
peptideAppHash = abi.decode(l2BlockJson.parseRaw(".result.stateRoot"), (bytes32));

bytes32 payloadHash = keccak256(abi.encodePacked(peptideBlockNumber, peptideAppHash, l1BlockHash));
hashToSign = keccak256(bytes.concat(domain, PEPTIDE_CHAIN_ID, payloadHash));
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor constructor to reduce complexity

The constructor has too many responsibilities. Consider breaking it down into smaller, focused functions:

  • initializeAddresses()
  • loadL1Header()
  • loadPeptideState()
  • computeHashes()

Comment on lines +59 to +62
function readBytes32FromJson(string memory fileName, string memory property) public view returns (bytes32) {
string memory blockJson = vm.readFile(string.concat(rootDir, fileName));
return abi.decode(blockJson.parseRaw(property), (bytes32));
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for JSON parsing

The JSON parsing functions should include error handling for:

  • Missing files
  • Invalid JSON format
  • Missing properties
  • Invalid property types

Example implementation:

 function readBytes32FromJson(string memory fileName, string memory property) public view returns (bytes32) {
+    if (bytes(fileName).length == 0 || bytes(property).length == 0) {
+        revert("Invalid file name or property");
+    }
     string memory blockJson = vm.readFile(string.concat(rootDir, fileName));
+    if (bytes(blockJson).length == 0) {
+        revert("File not found or empty");
+    }
     return abi.decode(blockJson.parseRaw(property), (bytes32));
 }

Also applies to: 65-68

@RnkSngh RnkSngh force-pushed the raunak/sigVerifierTest branch 2 times, most recently from e0e8840 to c3f4a94 Compare January 13, 2025 20:59
@RnkSngh RnkSngh force-pushed the raunak/sigVerifierTest branch from c3f4a94 to 6db1239 Compare January 13, 2025 21:00
@RnkSngh RnkSngh merged commit 88317da into main Jan 13, 2025
5 checks passed
@RnkSngh RnkSngh deleted the raunak/sigVerifierTest branch January 13, 2025 21:05
@coderabbitai coderabbitai bot mentioned this pull request Jan 15, 2025
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.

1 participant