Skip to content

Add proofs to rpc response #96

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Add proofs to rpc response #96

wants to merge 1 commit into from

Conversation

alpe
Copy link
Contributor

@alpe alpe commented May 14, 2025

Resolves #89

Add proofs to TX get + search response

Overview

Summary by CodeRabbit

  • New Features

    • Added support for generating and returning Merkle proofs for transactions when requested via the prove flag in transaction queries.
  • Tests

    • Introduced new tests to verify transaction proof generation and correctness when proofs are requested in transaction queries.

Copy link
Contributor

coderabbitai bot commented May 14, 2025

Walkthrough

A new mechanism for generating and returning Merkle proofs for transactions was implemented in the Tx and TxSearch RPC methods. The code now constructs valid Merkle proofs using block data from the Rollkit store when the prove flag is set, and corresponding tests were added to verify proof generation and integration.

Changes

File(s) Change Summary
pkg/rpc/core/tx.go Implemented Merkle proof generation using Rollkit block data for Tx and TxSearch RPCs. Added helper functions for proof construction and hash calculation. Updated transaction hash computation.
pkg/rpc/core/tx_test.go Added tests for transaction queries with and without proofs, including mock Rollkit store integration and proof field assertions.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RPC_Core
    participant RollkitStore

    Client->>RPC_Core: Tx / TxSearch (prove=true)
    RPC_Core->>RollkitStore: GetBlockData(height)
    RollkitStore-->>RPC_Core: BlockData (transactions)
    RPC_Core->>RPC_Core: Build Merkle proof for tx at index
    RPC_Core-->>Client: Tx result with Merkle proof
Loading

Assessment against linked issues

Objective Addressed Explanation
Support proofs in queries (#89)

Suggested reviewers

  • randygrok
  • tac0turtle

Poem

In burrows deep, a proof was found,
Each transaction wrapped safe and sound.
With hashes tall and Merkle trees,
The queries hop with rabbit ease!
Now every search, with proof in tow,
Shows just how deep the hashes go.
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

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

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

Comment on lines +135 to +143
func proofTXExists(txs []rlktypes.Tx, i uint32) cmttypes.TxProof {
hl := hashList(txs)
root, proofs := merkle.ProofsFromByteSlices(hl)

return cmttypes.TxProof{
RootHash: root,
Data: cmttypes.Tx(txs[i]),
Proof: *proofs[i],
}
Copy link

Choose a reason for hiding this comment

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

The function proofTXExists could panic if the transaction index i is out of bounds. Consider adding validation to ensure i < len(txs) before accessing array elements. This is particularly important since the index comes from external input and could be invalid.

func proofTXExists(txs []rlktypes.Tx, i uint32) (cmttypes.TxProof, error) {
    if int(i) >= len(txs) {
        return cmttypes.TxProof{}, fmt.Errorf("tx index %d out of bounds (len=%d)", i, len(txs))
    }
    
    hl := hashList(txs)
    root, proofs := merkle.ProofsFromByteSlices(hl)
    
    return cmttypes.TxProof{
        RootHash: root,
        Data:     cmttypes.Tx(txs[i]),
        Proof:    *proofs[i],
    }, nil
}

The calling functions would need to be updated to handle the error return value.

Suggested change
func proofTXExists(txs []rlktypes.Tx, i uint32) cmttypes.TxProof {
hl := hashList(txs)
root, proofs := merkle.ProofsFromByteSlices(hl)
return cmttypes.TxProof{
RootHash: root,
Data: cmttypes.Tx(txs[i]),
Proof: *proofs[i],
}
func proofTXExists(txs []rlktypes.Tx, i uint32) (cmttypes.TxProof, error) {
if int(i) >= len(txs) {
return cmttypes.TxProof{}, fmt.Errorf("tx index %d out of bounds (len=%d)", i, len(txs))
}
hl := hashList(txs)
root, proofs := merkle.ProofsFromByteSlices(hl)
return cmttypes.TxProof{
RootHash: root,
Data: cmttypes.Tx(txs[i]),
Proof: *proofs[i],
}, nil
}

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.

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

🧹 Nitpick comments (2)
pkg/rpc/core/tx.go (1)

108-113: Repeated GetBlockData calls hurt performance – cache per block height

TxSearch may contain many transactions belonging to the same block (e.g. the
two height-10 txs in your new test).
At the moment we fetch and rebuild the whole block data once per tx, which is
O(N·B) instead of O(N+B).

A lightweight map keyed by height (or even the already-filled
proofCache[height]) would cut redundant store reads and Merkle calculations.

pkg/rpc/core/tx_test.go (1)

53-72: Consider asserting proof RootHash / Data for stronger guarantees

The current test only checks Total, Index, and that LeafHash is non-empty.
Verifying RootHash and that Proof.Data equals the original sampleTx
would provide end-to-end confidence that the proof is built from the correct
transaction bytes.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 01e9349 and bd3d075.

📒 Files selected for processing (2)
  • pkg/rpc/core/tx.go (4 hunks)
  • pkg/rpc/core/tx_test.go (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
pkg/rpc/core/tx_test.go (4)
pkg/rpc/core/mocks_test.go (1)
  • MockRollkitStore (113-115)
pkg/rpc/core/env.go (1)
  • Environment (27-33)
pkg/adapter/adapter.go (1)
  • Adapter (53-69)
pkg/rpc/core/tx.go (2)
  • Tx (22-49)
  • TxSearch (54-125)
pkg/rpc/core/tx.go (1)
pkg/adapter/adapter.go (1)
  • Adapter (53-69)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: lint / golangci-lint
  • GitHub Check: test / Run Unit Tests
  • GitHub Check: Test with Rollkit Chain

Comment on lines +135 to +144
func proofTXExists(txs []rlktypes.Tx, i uint32) cmttypes.TxProof {
hl := hashList(txs)
root, proofs := merkle.ProofsFromByteSlices(hl)

return cmttypes.TxProof{
RootHash: root,
Data: cmttypes.Tx(txs[i]),
Proof: *proofs[i],
}
}
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

Return early when txs is empty to prevent invalid proofs

merkle.ProofsFromByteSlices panics on an empty slice. A quick guard keeps the
node stable when encountering an unexpected empty block.

 func proofTXExists(txs []rlktypes.Tx, i uint32) cmttypes.TxProof {
+    if len(txs) == 0 {
+        return cmttypes.TxProof{}
+    }
     hl := hashList(txs)
📝 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
func proofTXExists(txs []rlktypes.Tx, i uint32) cmttypes.TxProof {
hl := hashList(txs)
root, proofs := merkle.ProofsFromByteSlices(hl)
return cmttypes.TxProof{
RootHash: root,
Data: cmttypes.Tx(txs[i]),
Proof: *proofs[i],
}
}
func proofTXExists(txs []rlktypes.Tx, i uint32) cmttypes.TxProof {
if len(txs) == 0 {
return cmttypes.TxProof{}
}
hl := hashList(txs)
root, proofs := merkle.ProofsFromByteSlices(hl)
return cmttypes.TxProof{
RootHash: root,
Data: cmttypes.Tx(txs[i]),
Proof: *proofs[i],
}
}

Comment on lines +127 to +133
func buildProof(ctx *rpctypes.Context, blockHeight int64, txIndex uint32) (cmttypes.TxProof, error) {
_, data, err := env.Adapter.RollkitStore.GetBlockData(ctx.Context(), uint64(blockHeight))
if err != nil {
return cmttypes.TxProof{}, fmt.Errorf("failed to get block data: %w", err)
}
return proofTXExists(data.Txs, txIndex), nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate inputs before accessing the slice

proofTXExists(data.Txs, txIndex) will panic if txIndex is out of bounds or
if data is nil. This can happen with malformed indices or a corrupted
store response.

 func buildProof(ctx *rpctypes.Context, blockHeight int64, txIndex uint32) (cmttypes.TxProof, error) {
-    _, data, err := env.Adapter.RollkitStore.GetBlockData(ctx.Context(), uint64(blockHeight))
+    _, data, err := env.Adapter.RollkitStore.GetBlockData(ctx.Context(), uint64(blockHeight))
     if err != nil {
         return cmttypes.TxProof{}, fmt.Errorf("failed to get block data: %w", err)
     }
+    if data == nil || int(txIndex) >= len(data.Txs) {
+        return cmttypes.TxProof{}, fmt.Errorf("tx index %d out of range for height %d", txIndex, blockHeight)
+    }
     return proofTXExists(data.Txs, txIndex), nil
 }
📝 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
func buildProof(ctx *rpctypes.Context, blockHeight int64, txIndex uint32) (cmttypes.TxProof, error) {
_, data, err := env.Adapter.RollkitStore.GetBlockData(ctx.Context(), uint64(blockHeight))
if err != nil {
return cmttypes.TxProof{}, fmt.Errorf("failed to get block data: %w", err)
}
return proofTXExists(data.Txs, txIndex), nil
}
func buildProof(ctx *rpctypes.Context, blockHeight int64, txIndex uint32) (cmttypes.TxProof, error) {
_, data, err := env.Adapter.RollkitStore.GetBlockData(ctx.Context(), uint64(blockHeight))
if err != nil {
return cmttypes.TxProof{}, fmt.Errorf("failed to get block data: %w", err)
}
if data == nil || int(txIndex) >= len(data.Txs) {
return cmttypes.TxProof{}, fmt.Errorf("tx index %d out of range for height %d", txIndex, blockHeight)
}
return proofTXExists(data.Txs, txIndex), nil
}

Comment on lines +35 to +40
var proof cmttypes.TxProof
if prove {
if proof, err = buildProof(ctx, height, index); err != nil {
return nil, err
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Guard against nil Adapter / RollkitStore to avoid panics

prove == true unconditionally calls buildProof, which dereferences
env.Adapter.RollkitStore. In production or other tests env.Adapter (or its
RollkitStore) may legitimately be left nil, leading to a runtime panic that
will bring the whole RPC server down.

Add an early sanity-check (either here or inside buildProof) and return a
descriptive error instead of crashing.

 if prove {
-    if proof, err = buildProof(ctx, height, index); err != nil {
+    if env == nil || env.Adapter == nil || env.Adapter.RollkitStore == nil {
+        return nil, fmt.Errorf("proof requested but rollkit store not configured")
+    }
+    if proof, err = buildProof(ctx, height, index); err != nil {
         return nil, err
     }
 }
📝 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
var proof cmttypes.TxProof
if prove {
if proof, err = buildProof(ctx, height, index); err != nil {
return nil, err
}
}
var proof cmttypes.TxProof
if prove {
if env == nil || env.Adapter == nil || env.Adapter.RollkitStore == nil {
return nil, fmt.Errorf("proof requested but rollkit store not configured")
}
if proof, err = buildProof(ctx, height, index); err != nil {
return nil, err
}
}

Comment on lines +233 to +247
t.Run("with proofs", func(t *testing.T) {
query := "tx.height >= 10"
orderBy := "asc"
mockTxIndexer.On("Search", mock.Anything, mock.AnythingOfType("*query.Query")).Run(func(args mock.Arguments) {
// Basic check if the query seems right (optional)
q := args.Get(1).(*cmtquery.Query)
require.NotNil(q)
}).Return(searchResults, nil).Once()
mockStore.On("GetBlockData", mock.Anything, uint64(res1.Height)).Return(nil,
&rktypes.Data{Txs: rktypes.Txs{[]byte{0}, []byte{1}}}, nil).Once()
mockStore.On("GetBlockData", mock.Anything, uint64(res2.Height)).Return(nil,
&rktypes.Data{Txs: rktypes.Txs{[]byte{2}}}, nil).Once()
mockStore.On("GetBlockData", mock.Anything, uint64(res3.Height)).Return(nil,
&rktypes.Data{Txs: rktypes.Txs{[]byte{3}, []byte{4}, []byte{5}}}, nil).Once()

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Mock expectation only set once for height 10 ⇒ second call fails

TxSearch builds proofs for both res1 and res3, each at height 10.
The mock is configured with .Once(), so the second invocation of
GetBlockData will trigger:

assert: mock: Unexpected Method Call

Result: the test suite fails.

Either expect the call twice…

-mockStore.On("GetBlockData", mock.Anything, uint64(res1.Height)).Return(...).Once()
+mockStore.On("GetBlockData", mock.Anything, uint64(res1.Height)).Return(...).Twice()

…or use .Maybe() / On(...).Return(...).Times(2) depending on your style.

Copy link
Contributor

@tac0turtle tac0turtle left a comment

Choose a reason for hiding this comment

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

looks good, nice cleanup

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.

[Feature Request]: Support proofs in queries
2 participants