Skip to content

feat: Start network module#140

Merged
alpe merged 26 commits intomainfrom
alex/val_net_hack
Jun 27, 2025
Merged

feat: Start network module#140
alpe merged 26 commits intomainfrom
alex/val_net_hack

Conversation

@alpe
Copy link
Contributor

@alpe alpe commented Jun 19, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive "network" module for validator attestations, attester set management, epoch and checkpoint processing, and soft block confirmation.
    • Added CLI and gRPC query commands for network parameters, attestation bitmaps, epoch info, validator indices, and soft confirmation status.
    • Added CLI and gRPC transaction commands for submitting attestations and managing attester set membership.
    • Enabled conditional block publishing based on network soft confirmation status, configurable via a new command-line flag.
    • Provided flexible adapter options for custom block publishing filters and metrics integration.
  • Bug Fixes

    • Enhanced error handling and input validation across network module operations and CLI commands.
  • Documentation

    • Improved README formatting and added clarifications on optional parameters.
  • Tests

    • Added unit tests covering attester set membership scenarios and validator state handling.
  • Chores

    • Extended build configuration to move additional protobuf files and updated dependencies to include direct protobuf requirements.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 19, 2025

"""

Walkthrough

This change introduces a new "network" module for a Cosmos SDK-based blockchain, including its protobuf definitions, keeper, message and query servers, CLI commands, dependency injection wiring, and genesis state logic. The adapter is extended with a configurable block filter, supporting soft confirmation via the network module. The Makefile, README, and startup logic are updated to support these additions and configuration options.

Changes

File(s) Change Summary
Makefile, go.mod Extended proto-gen to move generated network module protobufs; moved google.golang.org/protobuf to direct dependency in go.mod.
README.md Updated ABCI executor example with optional parameters; minor formatting tweaks to Mermaid and class diagrams for consistency.
modules/proto/rollkitsdk/network/** Added protobuf definitions for network module: params, types, genesis, query, tx, and module config.
modules/network/types/** Introduced types for params, genesis, keys, messages, codec registration, and expected keeper interfaces for the network module.
modules/network/keeper/** Implemented keeper logic, bitmap utilities, ABCI lifecycle hooks, gRPC query server, message server, and tests for attester set management.
modules/network/client/cli/query.go, modules/network/client/cli/tx.go Added CLI commands for network module queries and transactions using Cobra.
modules/network/autocli.go Implemented AutoCLIOptions for automatic CLI command generation for the network module.
modules/network/depinject.go Set up dependency injection wiring for the network module, including keeper and app module construction.
modules/network/genesis.go Implemented genesis state initialization and export for the network module.
modules/network/module.go Provided Cosmos SDK module integration: AppModule, AppModuleBasic, service registration, block hooks, and genesis logic.
pkg/adapter/adapter.go, pkg/adapter/options.go, pkg/adapter/adapter_test.go Added block filter interface and stacking logic to Adapter; introduced network soft confirmation filter; updated constructor and related test.
server/flags.go, server/start.go Added CLI flag for network soft confirmation; updated node/executor setup to use option pattern and enable soft confirmation filter if flagged.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant App (Cosmos SDK)
    participant NetworkKeeper
    participant NetworkModule
    participant Adapter

    User->>CLI: run tx or query command
    CLI->>App: gRPC Msg/Query (via network module)
    App->>NetworkKeeper: handle Msg/Query
    NetworkKeeper-->>App: response (state updated or queried)
    App-->>CLI: response

    User->>Adapter: submit block
    Adapter->>NetworkModule: query soft confirmation status (if enabled)
    NetworkModule-->>Adapter: is_soft_confirmed?
    Adapter-->>User: publish or stack block commit event based on status
Loading

Possibly related PRs

Suggested labels

released

Suggested reviewers

  • tac0turtle
  • randygrok

Poem

In the warren, code does grow,
A network module hops in tow.
With keepers, queries, CLI delight,
And block events that wait for right,
Soft-confirmed by peer review—
This bunny’s blockchain dreams come true!
🐇✨
"""

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


📜 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 d82ac2c and 873682b.

📒 Files selected for processing (1)
  • go.mod (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • go.mod
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test / Run Unit Tests
  • GitHub Check: lint / golangci-lint
  • GitHub Check: Test with Rollkit Chain
  • GitHub Check: Test Migration from Cosmos SDK to Rollkit

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.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @alpe, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the go-execution-abci project by integrating a new 'network' module focused on validator attestation and consensus. It establishes a robust local testing environment for inter-blockchain communication (IBC) and network module interactions. Furthermore, it refactors the core block execution adapter to support pluggable components for metrics and block filtering, notably enabling a soft confirmation mechanism based on the new network module's attestations.

Highlights

  • New Network Module: A dedicated network module has been introduced, managing validator attestations, checkpoints, and consensus-related functionalities. It includes its own state management, message handlers, and query services.
  • Attestation and Checkpoint Logic: The network module now handles BeginBlocker and EndBlocker logic to process checkpoints, calculate voted power, check quorum for soft confirmation, and manage epoch-based validator participation. This includes emitting detailed checkpoint events.
  • Local Development & Testing Environment: A comprehensive suite of new hack scripts and configuration files has been added. This enables easy local setup of Gaia and Rollkit chains, establishing IBC connections using Hermes, and testing ICS20 token transfers, along with a Go-based attester client.
  • Adapter Refactoring for Extensibility: The core Adapter (executor) has been refactored to accept functional options, allowing for flexible injection of metrics and a new BlockFilter interface. This improves the modularity and configurability of the system.
  • Soft Confirmation Integration: A NetworkSoftConfirmationBlockFilter has been introduced, enabling the Rollkit node to leverage the network module's soft confirmation status. This means blocks can now be queued and only published once they achieve soft confirmation from the attester network, enhancing finality guarantees.
  • Protobuf Definitions & CLI: New protobuf definitions for the network module's messages, queries, and types have been added, along with auto-generated CLI commands for interacting with the module, making it accessible via the command line.
  • Audit Document: A detailed audit.md file is included, outlining current TODOs, incomplete features, and potential security vulnerabilities within the newly introduced network module. This provides a clear roadmap for future development and hardening efforts.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces the network module and integrates it into the Rollkit execution adapter. Key changes include adding module logic for validator attestations and epochs, updating build scripts, and adding a test attester client. The review identified several areas for improvement, including critical security vulnerabilities related to signature verification and rate limiting, high correctness issues regarding the use of current validator set data for historical calculations, and various medium-severity issues related to incomplete features, test script practices, and error handling. The hardcoded mnemonics in test scripts are also noted as a security risk.

@alpe alpe force-pushed the alex/val_net_hack branch from e63febd to 2242e95 Compare June 23, 2025 10:07
@alpe alpe force-pushed the alex/val_net_hack branch 2 times, most recently from 1433e2f to fb36822 Compare June 23, 2025 10:11
@alpe alpe force-pushed the alex/val_net_hack branch from fb36822 to c8cc207 Compare June 23, 2025 10:43
@alpe alpe marked this pull request as ready for review June 23, 2025 14:49
@alpe alpe requested a review from a team as a code owner June 23, 2025 14:49
@alpe alpe changed the title WIP: network integration feat: Start network module Jun 23, 2025
@alpe alpe mentioned this pull request Jun 23, 2025
10 tasks
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: 21

♻️ Duplicate comments (14)
hack/ibc-connection-hermes.sh (1)

20-20: Security concern: Hardcoded mnemonic in repository.

hack/init-gaia.sh (2)

13-15: Security concern with hardcoded mnemonics remains unaddressed.

The hardcoded mnemonics in plaintext are still a security risk, even for test environments.


26-26: Forceful process termination issue remains.

The use of kill -9 without attempting graceful shutdown first is still present.

modules/network/keeper/abci.go (2)

20-23: TODO: Implement IBC_ONLY sign mode.

Would you like me to help implement the IBC_ONLY sign mode logic or create an issue to track this?


154-155: TODO: Implement validator ejection for low participation.

Would you like me to help implement the validator ejection logic or create an issue to track this?

modules/network/keeper/msg_server.go (2)

134-134: Validator set updates should occur at epoch boundaries

The TODO suggests that validator set updates (joining the attester set) should only occur at the end of an epoch to ensure consistency and predictability.


68-68: Critical security vulnerability: Vote signature verification is missing

This TODO highlights a critical security vulnerability. Without verifying the vote signature, malicious actors could submit forged attestations, compromising the integrity of the soft confirmation mechanism.

modules/network/keeper/grpc_query.go (2)

114-114: Historic validator set needed for accurate epoch info

The TODO notes that the current active validator count is used instead of the historical validator set that was active during the queried epoch.


126-128: Validator index query needs height/epoch context

The TODO questions the use case for querying a validator's index without specifying a height/epoch, given that the validator set can change.

pkg/adapter/adapter.go (1)

623-623: Stacked events need persistence for crash recovery

The TODO notes that stacked events need to be persisted to recover from restarts. Without persistence, the node could lose events that were stacked but not yet published if it crashes.

modules/network/keeper/keeper.go (4)

225-234: Historical height issue: CalculateVotedPower uses current validator powers.

This method retrieves validator powers from the current state when calculating voted power for historical heights, leading to incorrect calculations.


237-244: Historical height issue: GetTotalPower uses current total staking power.

This method returns the current total staking power rather than the total power at a specific historical height.


258-273: Historical height issue: IsSoftConfirmed relies on current validator state.

This method uses CalculateVotedPower and GetTotalPower, which retrieve current state rather than historical state for the given height.


305-306: Implement signature pruning to prevent unbounded state growth.

The TODO indicates that signatures should be pruned along with bitmaps to prevent unbounded state growth over time.

🧹 Nitpick comments (22)
hack/attester/README.md (1)

1-3: Enhance the README with more detailed usage instructions.

The current README is quite brief. Consider adding:

  • How to build and run the attester tool
  • Required configuration parameters
  • Command-line usage examples
  • Prerequisites and dependencies

Here's a suggested enhancement:

 # Attest everything attester
 
-little helper that pulls new blocks from the rpc node and submits (fake) attestations after each epoch
+A helper tool that pulls new blocks from the RPC node and submits (fake) attestations after each epoch.
+
+## Usage
+
+```bash
+go run main.go [flags]
+```
+
+## Configuration
+
+[Add configuration details here]
+
+## Prerequisites
+
+[Add prerequisites here]
hack/README.md (1)

16-16: Consider using absolute path or documenting directory assumption.

The attester command assumes the current directory structure. Consider either using an absolute path or documenting that this command should be run from a specific directory.

hack/download.sh (1)

52-58: Enhance error handling with descriptive messages.

The download function should provide more specific error information to help with debugging.

 download_file() {
   local url=$1
   local output_path=$2
+  local filename=$(basename "$output_path")

-  echo "Downloading: $url"
+  echo "Downloading $filename from: $url"
   curl -L -o "$output_path" "$url"
   if [ $? -ne 0 ]; then
-    echo "Failed to download $url"
+    echo "Error: Failed to download $filename from $url"
+    echo "Please check your internet connection and verify the URL is accessible"
     exit 1
   fi
+  echo "Successfully downloaded $filename"
 }
audit.md (3)

6-6: Fix hyphenation in "TODOs".

The term should be hyphenated as "TO-DOs" when used as a plural noun.

-## TODOs and Incomplete Features
+## TO-DOs and Incomplete Features

14-14: Add missing comma for clarity.

The sentence would be clearer with a comma before "but."

-   - The `ejectLowParticipants` function is a stub that only logs a message but doesn't actually implement the ejection logic.
+   - The `ejectLowParticipants` function is a stub that only logs a message, but doesn't actually implement the ejection logic.

57-57: Add missing preposition.

The sentence needs "to" before "complete" for proper grammar.

-   - Complete all TODO items, particularly the signature verification and validator ejection logic.
+   - Complete all TO-DO items, particularly the signature verification and validator ejection logic.
hack/ibc-connection-hermes.sh (1)

14-15: Remove unused variables or document their purpose.

The GAIA_DENOM and WORDLED_DENOM variables are defined but not used in the script. Consider removing them or adding a comment explaining if they're reserved for future use.

-GAIA_DENOM="stake"
-WORDLED_DENOM="stake"
hack/init-gaia.sh (1)

82-82: Consider backgrounding and process management best practices.

The current approach of starting the process in background and waiting for it could be improved with better process management. Consider using a process manager or at least capturing the exit status properly.

-"$GAIAD_BIN" start --home "$GAIA_HOME" --minimum-gas-prices "0stake" --rpc.laddr tcp://0.0.0.0:26654 --rpc.pprof_laddr localhost:6061 --p2p.laddr tcp://0.0.0.0:26653 --grpc.address 0.0.0.0:9091  | tee "$GAIA_HOME/gaia.log" &
+"$GAIAD_BIN" start --home "$GAIA_HOME" --minimum-gas-prices "0stake" --rpc.laddr tcp://0.0.0.0:26654 --rpc.pprof_laddr localhost:6061 --p2p.laddr tcp://0.0.0.0:26653 --grpc.address 0.0.0.0:9091 2>&1 | tee "$GAIA_HOME/gaia.log" &
modules/network/client/cli/query.go (3)

76-79: Improve error message consistency.

The error formatting could be more consistent with other commands. Consider using a consistent error message format across all commands.

-			return fmt.Errorf("invalid height: %w", err)
+			return fmt.Errorf("invalid height %q: %w", args[0], err)

111-114: Improve error message consistency.

Similar to the height parsing, the epoch parsing error message could include the invalid value for better debugging.

-			return fmt.Errorf("invalid epoch: %w", err)
+			return fmt.Errorf("invalid epoch %q: %w", args[0], err)

176-179: Improve error message consistency.

Consistent with other commands, include the invalid value in the error message.

-			return fmt.Errorf("invalid height: %w", err)
+			return fmt.Errorf("invalid height %q: %w", args[0], err)
modules/network/types/keys.go (1)

24-34: Consider addressing the TODO comment about key optimization.

The TODO comment suggests using numbers instead of verbose keys. This could improve storage efficiency and performance.

// todo (Alex): use numbers instaed of verbose keyse?

The typo "instaed" should be "instead" and "keyse" should be "keys". Would you like me to propose a refactored version using numeric prefixes?

modules/network/keeper/bitmap.go (1)

89-99: Consider optimizing CountInRange for better performance.

The current implementation iterates bit by bit, which could be inefficient for large ranges. Consider implementing byte-level operations for better performance.

func (bh *BitmapHelper) CountInRange(bitmap []byte, start, end int) int {
+	if start >= end || start < 0 {
+		return 0
+	}
+	
+	maxBits := len(bitmap) * 8
+	if end > maxBits {
+		end = maxBits
+	}
+	
	count := 0
-	for i := start; i < end && i < len(bitmap)*8; i++ {
+	for i := start; i < end; i++ {
		if bh.IsSet(bitmap, i) {
			count++
		}
	}
	return count
}
hack/run_gmd.sh (1)

117-118: Make DA port configurable.

The DA port is hardcoded to 7980, which could cause conflicts in different environments.

-DA_PORT=7980
+DA_PORT="${DA_PORT:-7980}"
modules/network/types/msgs.go (1)

64-66: Consider adding size validation for vote field.

The vote field is validated for emptiness but not for maximum size, which could lead to DoS attacks with extremely large votes.

 if len(msg.Vote) == 0 {
 	return errors.Wrap(sdkerrors.ErrInvalidRequest, "vote cannot be empty")
 }
+
+const maxVoteSize = 1024 // Adjust based on your requirements
+if len(msg.Vote) > maxVoteSize {
+	return errors.Wrapf(sdkerrors.ErrInvalidRequest, "vote size exceeds maximum of %d bytes", maxVoteSize)
+}
modules/network/keeper/msg_server_test.go (1)

86-104: Remove or fix the commented test case.

This commented test case should either be removed or properly implemented. If error injection is needed for testing, consider using a proper mocking approach.

Either remove the commented code or implement it properly:

-//{
-//	name: "failed to set attester set member",
-//	setup: func(t *testing.T, ctx sdk.Context, keeper *Keeper, sk *MockStakingKeeper) {
-//		validatorAddr := sdk.ValAddress([]byte("validator5"))
-//		validator := stakingtypes.Validator{
-//			OperatorAddress: validatorAddr.String(),
-//			Status:          stakingtypes.Bonded,
-//		}
-//		err := sk.SetValidator(ctx, validator)
-//		require.NoError(t, err, "failed to set validator")
-//		keeper.forceError = true
-//	},
-//	msg: &types.MsgJoinAttesterSet{
-//		Validator: "validator5",
-//	},
-//	expErr:  sdkerrors.ErrInternal,
-//	expectResponse: false,
-//},
modules/network/types/params.go (2)

21-21: Consider documenting the rationale for default epoch length.

The TODO asks about a good default epoch length. Consider factors like:

  • Expected block time
  • Desired checkpoint frequency
  • Network latency for attestations
-DefaultEpochLength      = uint64(10)                        // todo (Alex): what is a good default?
+// DefaultEpochLength of 10 blocks provides checkpoints every ~10-60 seconds
+// depending on block time, balancing finality speed with attestation overhead
+DefaultEpochLength      = uint64(10)

172-178: Improve SignMode validation robustness.

The current validation assumes enum values are sequential, which is fragile.

 if v == SignMode_SIGN_MODE_UNSPECIFIED {
     return fmt.Errorf("sign mode cannot be unspecified")
 }

-if v < SignMode_SIGN_MODE_CHECKPOINT || v > SignMode_SIGN_MODE_IBC_ONLY {
-    return fmt.Errorf("invalid sign mode: %d", v)
+switch v {
+case SignMode_SIGN_MODE_CHECKPOINT, SignMode_SIGN_MODE_IBC_ONLY:
+    return nil
+default:
+    return fmt.Errorf("invalid sign mode: %d", v)
 }
-
-return nil
modules/proto/rollkitsdk/network/v1/query.proto (4)

9-9: Remove unused pagination import
cosmos/base/query/v1beta1/pagination.proto is imported but no RPC methods utilize pagination. Drop this import unless you plan to add paginated queries.


40-47: Confirm Params response structure
QueryParamsResponse returns a Params message. Ensure Params is well-documented in types.proto and won't grow unexpectedly—consider pagination or selective fields if it does.


49-56: Annotate required fields
Consider adding gRPC field behavior annotations (e.g., (google.api.field_behavior) = REQUIRED) to clarify that height in QueryAttestationBitmapRequest must be set.


90-95: Normalize quorum fraction representation
quorum_fraction is a string. For consistency with other modules, consider using a uint32 or sdk.Dec codec rather than arbitrary strings, unless formatting requirements dictate otherwise.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cc83106 and 0587cbe.

⛔ Files ignored due to path filters (7)
  • modules/network/module/v1/module.pb.go is excluded by !**/*.pb.go
  • modules/network/types/genesis.pb.go is excluded by !**/*.pb.go
  • modules/network/types/query.pb.go is excluded by !**/*.pb.go
  • modules/network/types/query.pb.gw.go is excluded by !**/*.pb.gw.go
  • modules/network/types/tx.pb.go is excluded by !**/*.pb.go
  • modules/network/types/types.pb.go is excluded by !**/*.pb.go
  • modules/proto/buf.lock is excluded by !**/*.lock
📒 Files selected for processing (41)
  • Makefile (1 hunks)
  • README.md (5 hunks)
  • audit.md (1 hunks)
  • go.mod (1 hunks)
  • hack/.gitignore (1 hunks)
  • hack/README.md (1 hunks)
  • hack/attester/README.md (1 hunks)
  • hack/attester/main.go (1 hunks)
  • hack/download.sh (1 hunks)
  • hack/ibc-connection-hermes.sh (1 hunks)
  • hack/ics20-token-transfer.sh (1 hunks)
  • hack/init-gaia.sh (1 hunks)
  • hack/run_gmd.sh (1 hunks)
  • modules/network/autocli.go (1 hunks)
  • modules/network/client/cli/query.go (1 hunks)
  • modules/network/client/cli/tx.go (1 hunks)
  • modules/network/depinject.go (1 hunks)
  • modules/network/genesis.go (1 hunks)
  • modules/network/keeper/abci.go (1 hunks)
  • modules/network/keeper/bitmap.go (1 hunks)
  • modules/network/keeper/grpc_query.go (1 hunks)
  • modules/network/keeper/keeper.go (1 hunks)
  • modules/network/keeper/msg_server.go (1 hunks)
  • modules/network/keeper/msg_server_test.go (1 hunks)
  • modules/network/module.go (1 hunks)
  • modules/network/types/codec.go (1 hunks)
  • modules/network/types/expected_keepers.go (1 hunks)
  • modules/network/types/genesis.go (1 hunks)
  • modules/network/types/keys.go (1 hunks)
  • modules/network/types/msgs.go (1 hunks)
  • modules/network/types/params.go (1 hunks)
  • modules/proto/rollkitsdk/network/module/v1/module.proto (1 hunks)
  • modules/proto/rollkitsdk/network/v1/genesis.proto (1 hunks)
  • modules/proto/rollkitsdk/network/v1/query.proto (1 hunks)
  • modules/proto/rollkitsdk/network/v1/tx.proto (1 hunks)
  • modules/proto/rollkitsdk/network/v1/types.proto (1 hunks)
  • pkg/adapter/adapter.go (17 hunks)
  • pkg/adapter/adapter_test.go (1 hunks)
  • pkg/adapter/options.go (1 hunks)
  • server/flags.go (1 hunks)
  • server/start.go (2 hunks)
🧰 Additional context used
🪛 LanguageTool
audit.md

[grammar] ~6-~6: It appears that a hyphen is missing in the plural noun “to-dos”?
Context: ...nd consensus-related functionality. ## TODOs and Incomplete Features 1. **Missing I...

(TO_DO_HYPHEN)


[uncategorized] ~14-~14: Possible missing comma found.
Context: ...ction is a stub that only logs a message but doesn't actually implement the ejection...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~57-~57: Possible missing preposition found.
Context: ... 1. Implement Missing Features - Complete all TODO items, particularly the signat...

(AI_HYDRA_LEO_MISSING_TO)

🪛 Buf (1.54.0)
modules/proto/rollkitsdk/network/v1/tx.proto

7-7: import "cosmos/msg/v1/msg.proto": file does not exist

(COMPILE)

modules/proto/rollkitsdk/network/module/v1/module.proto

5-5: import "cosmos/app/v1alpha1/module.proto": file does not exist

(COMPILE)

modules/proto/rollkitsdk/network/v1/genesis.proto

7-7: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

modules/proto/rollkitsdk/network/v1/types.proto

7-7: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

modules/proto/rollkitsdk/network/v1/query.proto

7-7: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

🪛 checkmake (0.2.2)
Makefile

[warning] 79-79: Missing required phony target "all"

(minphony)

🪛 Shellcheck (0.10.0)
hack/ics20-token-transfer.sh

[warning] 151-151: i appears unused. Verify use (or export if used externally).

(SC2034)


[warning] 151-151: Bash doesn't support variables in brace range expansions.

(SC2051)

hack/ibc-connection-hermes.sh

[warning] 14-14: GAIA_DENOM appears unused. Verify use (or export if used externally).

(SC2034)


[warning] 15-15: WORDLED_DENOM appears unused. Verify use (or export if used externally).

(SC2034)

🔇 Additional comments (51)
hack/.gitignore (1)

1-3: LGTM! Standard gitignore patterns for development scripts.

The excluded directories (downloads/, testnet/, config/) are appropriate for keeping generated files and test artifacts out of version control.

go.mod (1)

42-42: Verify the protobuf version for security and currency.

The change from indirect to direct dependency is appropriate given the new network module's protobuf definitions. However, please verify that version v1.36.6 is current and has no known security vulnerabilities.

What is the latest version of google.golang.org/protobuf and are there any security advisories for version v1.36.6?
pkg/adapter/adapter_test.go (1)

84-84: Verify test coverage after constructor signature change.

The constructor call update looks correct for the new options-based initialization. However, ensure that the test still covers all necessary functionality, particularly any metrics or monitoring features that were previously tested.

#!/bin/bash
# Description: Verify the NewABCIExecutor function signature and usage
# Look for the function definition and other usage examples

ast-grep --pattern 'func NewABCIExecutor($$$) $$$'
server/flags.go (2)

9-9: LGTM! Well-named constant following established conventions.

The constant name FlagNetworkSoftConfirmation is clear and follows the existing naming pattern in the codebase.


18-20: LGTM! Proper flag implementation with appropriate defaults.

The flag implementation follows established patterns:

  • Clear descriptive help text
  • Appropriate default value (false) for a new feature
  • Proper placement in the network flags section
Makefile (2)

74-76: LGTM! Protobuf file movement follows the established pattern.

The addition of network module protobuf file movement commands correctly mirrors the existing pattern for the rollkitmngr module, ensuring generated files are properly relocated to their expected source directories.


79-79: Good practice: Adding .PHONY target declaration.

The addition of the .PHONY declaration for the proto-gen target is correct and follows Makefile best practices.

README.md (1)

90-92: LGTM! Documentation updated to reflect new adapter constructor signature.

The addition of the explicit nil parameter and explanatory comment properly documents the new variadic options available in NewABCIExecutor, aligning with the adapter refactoring for metrics and block filters.

modules/proto/rollkitsdk/network/module/v1/module.proto (2)

10-17: LGTM! Module configuration follows Cosmos SDK patterns.

The Module message structure with authority field and proper Cosmos SDK module options is well-designed and follows established patterns for SDK modules.


5-5: Verify the cosmos/app/v1alpha1/module.proto import path.

Static analysis indicates this import file does not exist. Please verify that the import path is correct and that the dependency is properly configured in the build system.

#!/bin/bash
# Description: Check if the cosmos/app/v1alpha1/module.proto import is available in the build environment

# Check if the file exists in the modules/proto directory or dependencies
fd -t f "module.proto" modules/proto/ | grep -E "(app|v1alpha1)"

# Check if it's available in go.mod dependencies
grep -r "cosmos/app" go.mod go.sum 2>/dev/null || echo "No cosmos/app references found in go.mod/go.sum"

# Check if buf.yaml or buf.gen.yaml has the necessary dependencies configured
find . -name "buf.yaml" -o -name "buf.gen.yaml" | xargs cat 2>/dev/null | grep -A5 -B5 "cosmos"
modules/network/types/genesis.go (2)

8-14: LGTM! Well-structured default genesis state.

The default genesis state properly initializes with default parameters and empty collections, providing a clean starting point for the network module.


17-48: Excellent validation logic with comprehensive error checking.

The validation method demonstrates good practices:

  • Parameter validation is delegated to the params' own validation method
  • Duplicate detection prevents invalid state configuration
  • Attestation bitmap validation ensures data consistency
  • Error messages are descriptive and include context

The implementation is thorough and follows defensive programming principles.

modules/network/genesis.go (1)

84-101: LGTM: Helper function is well-implemented.

The setSoftConfirmed helper function correctly handles the soft confirmation update with proper error handling and state management.

audit.md (1)

26-28: Reconsider the struck-through security issue.

The panic condition for no quorum is marked as resolved, but this could still be a legitimate concern for network resilience. Consider if this should remain as an active issue.

Could you clarify why this security issue is struck through? The panic condition could still pose a risk to network stability during edge cases.

modules/network/autocli.go (1)

9-79: LGTM: Well-structured AutoCLI configuration.

The AutoCLI configuration is comprehensive and well-organized. The command mappings are logical, usage strings are clear, and positional arguments are properly defined. The structure follows Cosmos SDK conventions.

modules/proto/rollkitsdk/network/v1/genesis.proto (2)

10-20: LGTM: Well-defined genesis state structure.

The GenesisState message is properly structured with clear field definitions and appropriate protobuf annotations. The nullable=false annotations ensure required fields are properly validated.


7-7: Verify gogoproto import path.

The static analysis indicates that the gogoproto import may not exist. This could cause compilation issues.

Please verify that the gogoproto import is available in your build environment:

#!/bin/bash
# Check if gogoproto is available in the proto path
find . -name "gogo.proto" -type f

If the import is missing, you may need to:

  1. Install the gogoproto dependency
  2. Update the import path to match your setup
  3. Or remove the gogoproto annotations if not needed
server/start.go (1)

358-366: LGTM! Clean refactoring to support multiple adapter options.

The refactoring from a single adapterMetrics variable to a slice of adapter.Option is well-structured and allows for extensible configuration. The conditional addition of metrics and network soft confirmation block filter options follows a clear pattern.

Also applies to: 376-376

modules/network/types/codec.go (1)

1-39: LGTM! Standard Cosmos SDK codec implementation.

The codec registration follows proper Cosmos SDK patterns with support for both legacy Amino and modern protobuf serialization. All message types are correctly registered and the Amino codec is properly sealed in the init function.

modules/network/types/expected_keepers.go (1)

11-27: LGTM! Well-defined keeper interfaces following Cosmos SDK patterns.

The keeper interfaces properly abstract dependencies on staking, account, and bank modules. The use of context.Context and proper error handling in method signatures aligns with modern Cosmos SDK practices and supports clean dependency injection.

hack/ibc-connection-hermes.sh (1)

103-115: LGTM! Secure temporary file handling for mnemonic.

The use of mktemp to create a temporary file for the mnemonic and proper cleanup afterward demonstrates good security practices for handling sensitive data in scripts.

modules/network/client/cli/tx.go (3)

16-33: LGTM! Well-structured CLI command setup.

The transaction command setup follows Cosmos SDK conventions properly with appropriate subcommands and configuration.


73-98: LGTM! Standard validator command pattern.

The join attester command implementation follows the correct pattern for validator operations.


100-126: LGTM! Consistent with join attester command.

The leave attester command implementation is well-structured and consistent.

modules/proto/rollkitsdk/network/v1/types.proto (5)

12-30: Well-designed module parameters.

The Params message includes comprehensive configuration options for attestation windows, quorum requirements, participation thresholds, pruning, emergency mode, and signing behavior. The use of cosmos.Dec scalars for fractions is appropriate.


32-45: Clear and comprehensive SignMode enum.

The SignMode enum provides good flexibility for different validator signing requirements with clear semantics for each mode.


47-63: Well-structured AttestationBitmap message.

The AttestationBitmap captures all necessary checkpoint metadata including voting power tracking and soft confirmation status.


65-75: Efficient ValidatorIndex design.

The ValidatorIndex provides an efficient mapping for bitmap operations with cached voting power for performance.


7-7: Verify gogoproto import necessity.

The static analysis tool reports that gogoproto/gogo.proto doesn't exist, but it's not currently used in this file. Consider removing this import if it's not needed.

#!/bin/bash
# Check if gogoproto annotations are used in this file
grep -n "gogoproto\." modules/proto/rollkitsdk/network/v1/types.proto || echo "No gogoproto annotations found"
modules/network/depinject.go (3)

17-21: Proper interface assertions.

The AppModule type properly asserts required interfaces for Cosmos SDK integration.


29-38: Comprehensive ModuleInputs structure.

The ModuleInputs includes all necessary dependencies for the network module including keepers and configuration.


47-68: Well-implemented ProvideModule function.

The function properly handles authority configuration with appropriate fallback to governance module and constructs the keeper and module correctly.

modules/network/module.go (4)

20-27: Comprehensive interface assertions.

The module properly implements all required Cosmos SDK interfaces for full functionality.


86-96: Standard genesis handling pattern.

The genesis initialization and export methods follow the standard Cosmos SDK pattern with appropriate error handling.


101-105: Proper service registration.

The RegisterServices method correctly registers both message and query servers for the module.


107-113: Correct lifecycle hook implementation.

The BeginBlock and EndBlock methods properly delegate to keeper methods with correct context unwrapping.

modules/network/client/cli/query.go (1)

1-34: Well-structured CLI query module with comprehensive command coverage.

The implementation follows Cosmos SDK conventions and provides a complete set of query commands for the network module. The command structure is consistent and includes proper error handling.

modules/network/types/keys.go (1)

36-72: Key construction functions are well-implemented.

The key construction functions properly use big-endian encoding for numeric values and handle string addresses correctly. The implementation ensures consistent key formatting across the module.

modules/proto/rollkitsdk/network/v1/tx.proto (2)

29-88: Message definitions follow Cosmos SDK conventions correctly.

The message definitions are well-structured with proper:

  • Signer annotations for message validation
  • Scalar type annotations for address fields
  • Consistent gogoproto options
  • Appropriate field naming and types

7-7: Address the missing import issue.

The static analysis tool indicates that the import cosmos/msg/v1/msg.proto does not exist. This could cause compilation issues.

#!/bin/bash
# Verify if the cosmos/msg/v1/msg.proto import exists in the dependency
fd -t f "msg.proto" | grep -E "cosmos/msg/v1/msg\.proto|msg\.proto"

If the import path is incorrect, it may need to be updated to match the actual path in the Cosmos SDK dependencies.

pkg/adapter/options.go (2)

13-38: Functional options pattern implemented correctly.

The functional options pattern is well-implemented with clear separation of concerns. The WithNetworkSoftConfirmationBlockFilter properly initializes the filter with required dependencies.


47-84: Robust implementation with proper error handling.

The IsPublishable method includes comprehensive error handling and logging. The height validation (minimum of 2) and ABCI query integration are properly implemented.

modules/network/keeper/bitmap.go (5)

7-19: Bitmap creation and initialization are well-implemented.

The bitmap size calculation correctly handles the byte alignment for any number of validators, and the initialization pattern is standard.


22-29: Proper bounds checking and bit manipulation.

The SetBit method includes appropriate bounds checking and uses correct bit manipulation operations. The implementation is safe and efficient.


31-39: Consistent bounds checking in IsSet.

The bounds checking logic matches the SetBit method, ensuring consistency across the API.


41-48: Efficient population count implementation.

Using bits.OnesCount8 is the optimal approach for counting set bits, providing better performance than manual bit counting.


50-70: Bitwise operations properly handle different bitmap sizes.

Both OR and AND operations correctly handle bitmaps of different sizes by using the minimum length, preventing buffer overruns.

modules/network/types/msgs.go (1)

40-44: The initial pattern didn’t yield any results—let’s broaden our search to list every GetSigners implementation and inspect their error handling and address‐conversion logic:

#!/bin/bash
# 1. List all GetSigners definitions with context
rg -C3 "func .*GetSigners" --type go

# 2. Extract full bodies of all GetSigners methods
ast-grep --pattern $'func ($_) GetSigners() []sdk.AccAddress { $$$ }'

# 3. Highlight any panic calls across the repo
rg -n "panic(" --type go

# 4. Show all sdk.ValAddressFromBech32 usage
rg -C3 "ValAddressFromBech32" --type go

# 5. Show all sdk.AccAddressFromBech32 usage
rg -C3 "AccAddressFromBech32" --type go
modules/proto/rollkitsdk/network/v1/query.proto (3)

12-38: Validate HTTP REST endpoint paths
The HTTP bindings use /rollkit/network/v1/.... Confirm that the prefix (rollkit) and path segments align with your module route and API conventions (e.g., not rollkitsdk). Also verify path parameters ({height}, {epoch}, {address}) match the request message fields.


65-72: Review participation_bitmap type
participation_bitmap is declared as bytes. If it represents a bitset or repeated boolean, evaluate using a custom repeated field or a typed message for clearer semantics.


80-82: Verify ValidatorIndex import
The ValidatorIndex type is referenced here. Confirm it’s defined in types.proto and the import path is correct so code generators can locate it.

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

♻️ Duplicate comments (12)
hack/init-gaia.sh (2)

13-15: Security risk with hardcoded mnemonics.

Hardcoding mnemonics in plaintext files within the repository is a security risk. Even for test setups, this exposes sensitive information.


26-26: Avoid forceful process termination.

Using kill -9 forcefully terminates processes, which can prevent them from cleaning up resources properly.

hack/ibc-connection-hermes.sh (1)

20-20: Security risk: Remove hardcoded mnemonic.

Hardcoding mnemonics in plaintext files within the repository is a security risk, even for test setups.

Consider using environment variables or generating temporary mnemonics during script execution:

-RELAYER_MNEMONIC="reject camp lock magic dragon degree loop ignore quantum verify invest primary object afraid crane unveil parrot jelly rubber risk mirror globe torch category"
+RELAYER_MNEMONIC="${RELAYER_MNEMONIC:-$(generate_test_mnemonic)}"
hack/run_gmd.sh (1)

1-1: Consider excluding this script from the current PR.

A previous reviewer suggested this file should be excluded as it's more useful in another branch.

modules/network/keeper/grpc_query.go (2)

114-114: TODO already flagged in previous review

This TODO about needing historical validator set data has been previously identified and discussed.


126-128: TODO already flagged in previous review

This TODO about the use case for querying validator index without height/epoch specification has been previously identified.

modules/network/keeper/abci.go (2)

22-22: IBC_ONLY mode TODO already flagged

This unimplemented IBC_ONLY mode has been previously identified in past reviews.


154-155: Validator ejection TODO already flagged

This unimplemented validator ejection logic has been previously identified in past reviews.

modules/network/keeper/keeper.go (4)

225-234: CalculateVotedPower uses current validator powers for historical heights.

This function retrieves power from the current validator set when calculating voted power for any height, which will produce incorrect results for historical blocks.


237-244: GetTotalPower returns current total power instead of historical.

This function always returns the current total staking power, which is incorrect when checking quorum for historical heights.


258-273: IsSoftConfirmed incorrectly uses current validator set for historical blocks.

This function relies on CalculateVotedPower and GetTotalPower which use the current validator set, leading to incorrect soft confirmation status for historical heights.


305-306: Complete the TODO: Prune signatures for pruned heights.

Failing to prune signatures will lead to unbounded state growth over time.

Do you want me to generate the implementation for pruning signatures or open a new issue to track this task?

🧹 Nitpick comments (26)
audit.md (2)

6-6: Nit: Hyphenate To-dos. For consistency and readability, consider changing “TODOs” to “To-dos” in the section header.

-## TODOs and Incomplete Features
+## To-dos and Incomplete Features

14-14: Nit: Add missing comma. Improve clarity by inserting a comma after “message”.

- that only logs a message but doesn't actually implement the ejection logic.
+ that only logs a message, but doesn't actually implement the ejection logic.
hack/attester/README.md (2)

1-1: Nit: Improve title capitalization and clarity. Consider renaming the title to use title case and clearer naming, e.g.:

-# Attest everything attester
+# Attest-Everything Attester

3-3: Nit: Capitalize and punctuation. Start the sentence with a capital letter and end with a period.

-little helper that pulls new blocks from the rpc node and submits (fake) attestations after each epoch
+Little helper that pulls new blocks from the RPC node and submits (fake) attestations after each epoch.
Makefile (1)

79-79: Add an 'all' phony target.

checkmake warns about a missing all target. It’s conventional to define:

all: test
.PHONY: all

to provide a sensible default build step.

README.md (1)

90-91: Illustrate soft confirmation block filter usage.

The example adds nil for metrics but doesn’t show how to enable the network soft-confirmation filter. Consider updating this snippet to pass adapter.WithNetworkSoftConfirmationBlockFilter() (or similar) so users see how it hooks into the new --rollkit.network.soft-confirmation flag.

hack/README.md (2)

7-10: Add download step for required binaries.

Prerequisites mention download.sh, but no instruction invokes it. Insert:

./hack/download.sh

before ./init-gaia.sh to fetch gaiad, hermes, and other tools.


13-19: Clarify script execution context.

The run_node.sh, attester, and IBC scripts assume specific working directories and binary locations. Note whether these commands should be run from the repo root and update paths or flags accordingly to avoid confusion.

modules/network/genesis.go (1)

35-38: Redundant storage operation.

The attestation bitmap is being stored twice - once via SetAttestationBitmap and once via StoredAttestationInfo.Set. This could lead to inconsistency if one operation fails.

Consider consolidating the storage operations or ensuring atomicity:

-		if err := k.SetAttestationBitmap(ctx, ab.Height, ab.Bitmap); err != nil {
-			return err
-		}
-		// Store full attestation info using collections API
-		if err := k.StoredAttestationInfo.Set(ctx, ab.Height, ab); err != nil {
-			return err
-		}
+		// Store full attestation info using collections API (this should handle bitmap storage internally)
+		if err := k.StoredAttestationInfo.Set(ctx, ab.Height, ab); err != nil {
+			return err
+		}
hack/init-gaia.sh (1)

87-89: Improve connection check with timeout.

The current connection check could hang indefinitely if the service never becomes available.

-while ! nc -z localhost 26654; do
-  sleep 1
-done
+timeout=60
+counter=0
+while ! nc -z localhost 26654; do
+  if [ $counter -ge $timeout ]; then
+    log "31" "❌" "Timeout waiting for Gaia to start"
+    exit 1
+  fi
+  sleep 1
+  ((counter++))
+done
hack/ibc-connection-hermes.sh (1)

14-15: Remove unused variables.

The variables GAIA_DENOM and WORDLED_DENOM are defined but never used in the script.

-GAIA_DENOM="stake"
-WORDLED_DENOM="stake"
modules/network/keeper/bitmap.go (3)

50-59: Consider documenting the behavior when bitmaps have different sizes.

The OR operation uses the minimum length of the two bitmaps, which means bits beyond minLen in the destination bitmap remain unchanged. This behavior should be documented to clarify expectations.

-// OR performs bitwise OR of two bitmaps
+// OR performs bitwise OR of two bitmaps
+// Only processes up to the minimum length of the two bitmaps
 func (bh *BitmapHelper) OR(dst, src []byte) {

61-70: Consider documenting the behavior when bitmaps have different sizes.

Similar to the OR method, the AND operation should document that it only processes up to the minimum length, and bits beyond that remain unchanged in the destination.

-// AND performs bitwise AND of two bitmaps
+// AND performs bitwise AND of two bitmaps
+// Only processes up to the minimum length of the two bitmaps
 func (bh *BitmapHelper) AND(dst, src []byte) {

89-98: Optimize the CountInRange method for better performance.

The current implementation calls IsSet for each bit, which repeats the boundary check and bit extraction logic. This could be optimized by working directly with bytes when possible.

 func (bh *BitmapHelper) CountInRange(bitmap []byte, start, end int) int {
+	if start >= end || start < 0 {
+		return 0
+	}
+	maxBits := len(bitmap) * 8
+	if end > maxBits {
+		end = maxBits
+	}
+	
 	count := 0
-	for i := start; i < end && i < len(bitmap)*8; i++ {
-		if bh.IsSet(bitmap, i) {
-			count++
-		}
+	for i := start; i < end; i++ {
+		byteIndex := i / 8
+		bitIndex := uint(i % 8)
+		if (bitmap[byteIndex] & (1 << bitIndex)) != 0 {
+			count++
+		}
 	}
 	return count
 }
modules/network/keeper/msg_server_test.go (3)

86-104: Remove or complete the commented test case.

The commented test case suggests there was an attempt to test error injection but was left incomplete. Either complete this test case or remove it to keep the code clean.

-		//{
-		//	name: "failed to set attester set member",
-		//	setup: func(t *testing.T, ctx sdk.Context, keeper *Keeper, sk *MockStakingKeeper) {
-		//		validatorAddr := sdk.ValAddress([]byte("validator5"))
-		//		validator := stakingtypes.Validator{
-		//			OperatorAddress: validatorAddr.String(),
-		//			Status:          stakingtypes.Bonded,
-		//		}
-		//		err := sk.SetValidator(ctx, validator)
-		//		require.NoError(t, err, "failed to set validator")
-		//		keeper.forceError = true
-		//	},
-		//	msg: &types.MsgJoinAttesterSet{
-		//		Validator: "validator5",
-		//	},
-		//	expErr:  sdkerrors.ErrInternal,
-		//	expectResponse: false,
-		//},

156-160: Add error handling for the SetValidator method.

The SetValidator method in the mock should probably never return an error in this implementation, but it's good practice to at least document this or add a comment explaining why errors are not expected.

 func (m *MockStakingKeeper) SetValidator(ctx context.Context, validator stakingtypes.Validator) error {
 	m.activeSet[validator.GetOperator()] = validator
+	// Mock implementation - errors not expected in test scenarios
 	return nil
-
 }

175-182: Improve the GetLastValidators mock implementation.

The current implementation only returns bonded validators, but the logic could be more explicit about what "last validators" means in this context. Consider adding a comment or making the logic more explicit.

 func (m MockStakingKeeper) GetLastValidators(ctx context.Context) (validators []stakingtypes.Validator, err error) {
+	// Return all bonded validators as "last validators"
 	for _, validator := range m.activeSet {
-		if validator.IsBonded() { // Assuming IsBonded() identifies if a validator is in the last validators
+		if validator.IsBonded() {
 			validators = append(validators, validator)
 		}
 	}
 	return
 }
pkg/adapter/options.go (2)

47-51: Clarify the minimum height requirement.

The code checks height < 2 but doesn't document why blocks below height 2 are not publishable. Consider adding a comment explaining this business logic.

 func (f *NetworkSoftConfirmationBlockFilter) IsPublishable(ctx context.Context, height int64) bool {
-	// First check if height is valid
+	// Genesis block (height 1) and earlier are not publishable
 	if height < 2 {
 		return false
 	}

56-59: Handle marshaling errors more explicitly.

The current error handling silently returns false on marshaling errors. Consider logging the error for debugging purposes.

 	reqData, err := req.Marshal()
 	if err != nil {
+		f.logger.Error("marshal soft confirmation request", "height", height, "error", err)
 		return false
 	}
modules/network/types/params.go (1)

21-21: Address TODO: Determine appropriate default epoch length

The TODO comment indicates uncertainty about the default epoch length value. Consider factors such as block time, network latency, and desired checkpoint frequency when determining this value.

Would you like me to help analyze appropriate epoch length values based on your network requirements, or open an issue to track this decision?

modules/network/types/keys.go (1)

25-25: Consider the trade-offs of numeric vs verbose keys

Using numeric prefixes would save storage space but reduce debuggability. Consider keeping verbose keys for better maintainability unless storage optimization is critical.

modules/network/keeper/abci.go (1)

135-137: Decide on epoch quorum failure handling

The TODO questions whether to fail when no checkpoints achieve quorum. This is a critical consensus decision that affects network liveness.

Consider the trade-offs:

  • Failing could halt the network if validators are offline
  • Logging only could allow the network to continue but without proper attestation

Based on your network's security requirements, you should either return an error or emit a critical event that monitoring systems can alert on.

modules/network/keeper/msg_server.go (1)

27-111: Consider adding metrics for attestation processing.

While the implementation handles attestation logic correctly, adding metrics for successful/failed attestations would help with monitoring and debugging in production.

hack/attester/main.go (2)

256-256: Consider making the block hash configurable or properly computed.

Using a hardcoded "0x00" block hash in attestations, even for testing, could lead to confusion or issues if this utility is used in more realistic test scenarios.

Consider adding a flag to specify the block hash or computing it from actual block data.


259-261: Remove commented-out code.

The commented-out error handling code should be either removed or properly implemented.

-				//time.Sleep(time.Second / 10)
-				//continue
-				return err
+				return err
modules/network/keeper/keeper.go (1)

65-71: Remove commented schema building code.

The commented code for explicit schema building appears to be unnecessary. Consider removing it to improve code clarity.

Apply this diff:

-	// The schema is built implicitly when the first collection is created or can be explicitly built.
-	// schema, err := sb.Build()
-	// if err != nil {
-	// 	panic(err)
-	// }
-	// keeper.schema = schema
-
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cc83106 and 0587cbe.

⛔ Files ignored due to path filters (7)
  • modules/network/module/v1/module.pb.go is excluded by !**/*.pb.go
  • modules/network/types/genesis.pb.go is excluded by !**/*.pb.go
  • modules/network/types/query.pb.go is excluded by !**/*.pb.go
  • modules/network/types/query.pb.gw.go is excluded by !**/*.pb.gw.go
  • modules/network/types/tx.pb.go is excluded by !**/*.pb.go
  • modules/network/types/types.pb.go is excluded by !**/*.pb.go
  • modules/proto/buf.lock is excluded by !**/*.lock
📒 Files selected for processing (41)
  • Makefile (1 hunks)
  • README.md (5 hunks)
  • audit.md (1 hunks)
  • go.mod (1 hunks)
  • hack/.gitignore (1 hunks)
  • hack/README.md (1 hunks)
  • hack/attester/README.md (1 hunks)
  • hack/attester/main.go (1 hunks)
  • hack/download.sh (1 hunks)
  • hack/ibc-connection-hermes.sh (1 hunks)
  • hack/ics20-token-transfer.sh (1 hunks)
  • hack/init-gaia.sh (1 hunks)
  • hack/run_gmd.sh (1 hunks)
  • modules/network/autocli.go (1 hunks)
  • modules/network/client/cli/query.go (1 hunks)
  • modules/network/client/cli/tx.go (1 hunks)
  • modules/network/depinject.go (1 hunks)
  • modules/network/genesis.go (1 hunks)
  • modules/network/keeper/abci.go (1 hunks)
  • modules/network/keeper/bitmap.go (1 hunks)
  • modules/network/keeper/grpc_query.go (1 hunks)
  • modules/network/keeper/keeper.go (1 hunks)
  • modules/network/keeper/msg_server.go (1 hunks)
  • modules/network/keeper/msg_server_test.go (1 hunks)
  • modules/network/module.go (1 hunks)
  • modules/network/types/codec.go (1 hunks)
  • modules/network/types/expected_keepers.go (1 hunks)
  • modules/network/types/genesis.go (1 hunks)
  • modules/network/types/keys.go (1 hunks)
  • modules/network/types/msgs.go (1 hunks)
  • modules/network/types/params.go (1 hunks)
  • modules/proto/rollkitsdk/network/module/v1/module.proto (1 hunks)
  • modules/proto/rollkitsdk/network/v1/genesis.proto (1 hunks)
  • modules/proto/rollkitsdk/network/v1/query.proto (1 hunks)
  • modules/proto/rollkitsdk/network/v1/tx.proto (1 hunks)
  • modules/proto/rollkitsdk/network/v1/types.proto (1 hunks)
  • pkg/adapter/adapter.go (17 hunks)
  • pkg/adapter/adapter_test.go (1 hunks)
  • pkg/adapter/options.go (1 hunks)
  • server/flags.go (1 hunks)
  • server/start.go (2 hunks)
🧰 Additional context used
🪛 Shellcheck (0.10.0)
hack/ibc-connection-hermes.sh

[warning] 14-14: GAIA_DENOM appears unused. Verify use (or export if used externally).

(SC2034)


[warning] 15-15: WORDLED_DENOM appears unused. Verify use (or export if used externally).

(SC2034)

hack/ics20-token-transfer.sh

[warning] 151-151: i appears unused. Verify use (or export if used externally).

(SC2034)


[warning] 151-151: Bash doesn't support variables in brace range expansions.

(SC2051)

🪛 Buf (1.54.0)
modules/proto/rollkitsdk/network/v1/query.proto

7-7: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

modules/proto/rollkitsdk/network/module/v1/module.proto

5-5: import "cosmos/app/v1alpha1/module.proto": file does not exist

(COMPILE)

modules/proto/rollkitsdk/network/v1/genesis.proto

7-7: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

modules/proto/rollkitsdk/network/v1/types.proto

7-7: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

modules/proto/rollkitsdk/network/v1/tx.proto

7-7: import "cosmos/msg/v1/msg.proto": file does not exist

(COMPILE)

🪛 LanguageTool
audit.md

[grammar] ~6-~6: It appears that a hyphen is missing in the plural noun “to-dos”?
Context: ...nd consensus-related functionality. ## TODOs and Incomplete Features 1. **Missing I...

(TO_DO_HYPHEN)


[uncategorized] ~14-~14: Possible missing comma found.
Context: ...ction is a stub that only logs a message but doesn't actually implement the ejection...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~57-~57: Possible missing preposition found.
Context: ... 1. Implement Missing Features - Complete all TODO items, particularly the signat...

(AI_HYDRA_LEO_MISSING_TO)

🪛 checkmake (0.2.2)
Makefile

[warning] 79-79: Missing required phony target "all"

(minphony)

🔇 Additional comments (54)
hack/.gitignore (1)

1-3: Add .gitignore entries for hack directory. The patterns correctly exclude generated artifacts from downloads/, testnet/, and config/.

go.mod (1)

42-42: Verify direct protobuf dependency. Moving google.golang.org/protobuf from indirect to direct is appropriate given new protobuf-generated code in the network module. Ensure the version v1.36.6 is compatible with other indirect dependencies (e.g., genproto and gocosmos).

pkg/adapter/adapter_test.go (1)

84-84: Adapter constructor updated correctly. The test now matches the new variadic options signature for NewABCIExecutor, removing the NopMetrics() argument. All required dependencies are passed.

server/flags.go (2)

9-9: Add new CLI flag constant: good.

The constant FlagNetworkSoftConfirmation is clearly defined and follows the existing naming convention.


19-19: Verify flag binding and config support.

The flag is added via cmd.Flags().Bool, but there’s no pointer binding to config.DefaultConfig. Please confirm that a corresponding NetworkSoftConfirmation field exists in your config struct and that the flag’s value is properly loaded (e.g., via Viper or a BoolVar) so the block filter option can use it.

Makefile (1)

75-76: Add proto-gen moves for network module: good.

The new mv commands correctly relocate the generated network protobuf files. Make sure the source directories exist post-buf generate to avoid silent failures.

README.md (1)

25-25: Clean up Mermaid diagram whitespace: good.

Minor whitespace adjustments improve readability without affecting functionality.

modules/network/types/genesis.go (2)

7-14: LGTM! Genesis state initialization follows best practices.

The DefaultGenesisState function correctly initializes the genesis state with default parameters and empty slices for validator indices and attestation bitmaps, which is appropriate for a clean module start.


16-48: Comprehensive validation logic with good error handling.

The validation method thoroughly checks:

  1. Parameter validation through delegation
  2. Duplicate validator addresses and indices detection using maps
  3. Attestation bitmap integrity (positive heights and power constraints)

The error messages are descriptive and will help with debugging genesis state issues.

server/start.go (2)

358-366: Good refactoring to options pattern for extensibility.

The change from passing individual parameters to building a slice of options makes the executor configuration more flexible and follows good design patterns. The conditional Prometheus metrics setup is correct.


364-366: Verify flag definition and adapter option implementation.

The code references FlagNetworkSoftConfirmation and adapter.WithNetworkSoftConfirmationBlockFilter(), but these aren't defined in this file. Ensure these are properly defined in their respective locations.

#!/bin/bash
# Description: Verify the flag definition and adapter option implementation
# Expected: Find definitions of FlagNetworkSoftConfirmation and WithNetworkSoftConfirmationBlockFilter

echo "Searching for FlagNetworkSoftConfirmation definition:"
rg -A 2 "FlagNetworkSoftConfirmation.*=" 

echo -e "\nSearching for WithNetworkSoftConfirmationBlockFilter implementation:"
rg -A 5 "func.*WithNetworkSoftConfirmationBlockFilter"
modules/proto/rollkitsdk/network/v1/genesis.proto (2)

10-20: Standard genesis state proto definition with proper field annotations.

The GenesisState message definition follows Cosmos SDK conventions with appropriate gogoproto annotations for nullable fields. The field structure aligns with the Go implementation in genesis.go.


7-7: Verify gogoproto import path and availability.

Static analysis indicates the gogoproto import may not be found. This could be a build environment issue or incorrect import path.

#!/bin/bash
# Description: Check if gogoproto is available and verify import paths
# Expected: Find gogoproto dependencies and verify correct import path

echo "Checking for gogoproto in go.mod:"
if [ -f "go.mod" ]; then
    grep -i gogo go.mod || echo "gogoproto not found in go.mod"
fi

echo -e "\nSearching for other gogoproto imports in proto files:"
fd -e proto -x grep -l "gogoproto/gogo.proto" {} \;

echo -e "\nChecking if proto generation works:"
if command -v buf &> /dev/null; then
    buf lint modules/proto/ || echo "Buf lint found issues"
fi
hack/download.sh (1)

10-21: Architecture detection logic is correct but could be more robust.

The architecture mapping from uname -m output to expected labels is handled well with appropriate error handling for unsupported architectures.

modules/network/types/codec.go (3)

10-16: Standard amino codec registration following Cosmos SDK patterns.

The legacy amino codec registration correctly registers all message types with appropriate type URLs. The naming convention follows the module/MessageType pattern.


18-28: Proper protobuf interface registration with gRPC service integration.

The interface registry correctly registers all message types as sdk.Msg implementations and includes the gRPC service descriptor registration, which is essential for proper message routing.


35-38: Appropriate codec initialization and sealing.

The init function properly registers types with the amino codec and seals it to prevent further modifications, which is the recommended pattern for Cosmos SDK modules.

modules/proto/rollkitsdk/network/v1/types.proto (2)

7-7: Static analysis false positive - gogoproto import is valid.

The static analysis tool is flagging the gogoproto import as missing, but this is a false positive. The gogoproto/gogo.proto import is a standard protobuf extension used extensively in Cosmos SDK projects for Go-specific annotations.


12-75: Well-structured protobuf schema with appropriate field design.

The message definitions follow protobuf best practices with:

  • Sequential field numbering
  • Appropriate scalar types for cosmos addresses and decimals
  • Clear field names and documentation
  • Proper enum value assignment starting from 0
modules/network/autocli.go (1)

10-79: Comprehensive and well-structured AutoCLI configuration.

The AutoCLI configuration properly maps all query and transaction commands to their respective protobuf services with:

  • Clear usage strings and descriptions
  • Appropriate positional arguments matching protobuf fields
  • Complete coverage of the network module's RPC methods
modules/network/types/expected_keepers.go (1)

11-27: Clean and minimal keeper interfaces following good design principles.

The expected keeper interfaces are well-designed with:

  • Minimal surface area exposing only required methods
  • Proper use of context.Context for cancellation
  • Appropriate SDK types for parameters and return values
  • Good abstraction for dependency injection
modules/network/client/cli/tx.go (3)

17-33: LGTM: Well-structured root command.

The root transaction command follows Cosmos SDK conventions properly with appropriate subcommands and validation.


74-98: LGTM: Join attester command is well implemented.

The command correctly derives the validator address and follows proper validation patterns.


101-126: LGTM: Leave attester command is well implemented.

The command structure is consistent with the join command and properly implemented.

hack/ibc-connection-hermes.sh (1)

122-127: LGTM: IBC channel creation is properly configured.

The channel creation command correctly sets up the transfer port with automatic client and connection creation.

hack/ics20-token-transfer.sh (2)

80-106: LGTM: Transaction verification logic is robust.

The script properly handles transaction confirmation with retry logic and error checking.


149-164: Good balance verification with timeout handling.

The balance verification logic with retry mechanism ensures IBC tokens are properly received.

hack/run_gmd.sh (1)

84-96: Complex genesis manipulation logic is well-implemented.

The validator setup and genesis file modification using jq is correctly implemented for the test environment.

modules/network/client/cli/query.go (6)

16-34: LGTM: Well-structured query command hierarchy.

The root query command properly organizes all subcommands with standard Cosmos SDK patterns.


37-62: LGTM: Parameters query command is correctly implemented.

The command follows standard patterns with proper error handling and client context usage.


65-97: LGTM: Attestation bitmap query with proper validation.

The command correctly parses the height parameter and handles errors appropriately.


100-132: LGTM: Epoch info query is well-implemented.

The command properly handles epoch number parsing and follows consistent patterns.


135-162: LGTM: Validator index query is straightforward and correct.

The command correctly passes the validator address without additional parsing, which is appropriate.


165-197: LGTM: Soft confirmation status query is properly implemented.

The command follows the same pattern as other height-based queries with appropriate validation.

modules/network/keeper/bitmap.go (3)

15-19: LGTM: Efficient bitmap allocation using ceiling division.

The bitmap size calculation (n + 7) / 8 correctly computes the minimum number of bytes needed to represent n bits, ensuring proper allocation even when n is not divisible by 8.


21-29: LGTM: Proper boundary checks and bit manipulation.

The SetBit method correctly handles out-of-bounds indices by silently returning, which is appropriate for a utility function. The bit manipulation logic using bitwise OR is correct.


31-39: LGTM: Consistent boundary handling with SetBit.

The IsSet method follows the same boundary check pattern as SetBit, returning false for out-of-bounds indices, which is reasonable default behavior.

modules/proto/rollkitsdk/network/v1/tx.proto (4)

29-43: LGTM: Well-structured MsgAttest definition.

The message properly defines validator attestation with appropriate field types and Cosmos SDK annotations. The use of bytes for the vote field allows for flexible vote encoding.


48-56: LGTM: Clean and consistent message structure.

The MsgJoinAttesterSet follows the same pattern as other messages with proper signer annotation and validator address field.


74-85: LGTM: Proper authority-based parameter updates.

The MsgUpdateParams correctly uses authority-based authorization for parameter updates, following Cosmos SDK governance patterns.


7-7: Verify the cosmos/msg/v1/msg.proto import availability.

Static analysis indicates this import file doesn't exist. Please verify that the Cosmos SDK version being used includes this proto file, or update the import path if it has changed.

#!/bin/bash
# Description: Check if the cosmos/msg/v1/msg.proto import exists in the dependency tree
# Expected: Find the proto file in the cosmos-sdk dependency

# Search for the proto file in go.mod dependencies
fd -t f -e proto . | xargs grep -l "cosmos\.msg\.v1\.service" || echo "Proto service definition not found"

# Check if there are any cosmos/msg proto files
fd -t f -e proto . | xargs grep -l "package cosmos.msg" || echo "No cosmos.msg proto files found"
pkg/adapter/options.go (2)

67-75: LGTM: Comprehensive error handling for ABCI queries.

The error handling properly checks both the error and the response code, with appropriate logging that includes both error details and response logs when available.


77-84: LGTM: Proper response unmarshaling with debug logging.

The response handling correctly unmarshals the protobuf response and includes helpful debug logging to track soft confirmation decisions.

modules/network/depinject.go (4)

17-20: LGTM: Proper depinject interface implementation.

The IsOnePerModuleType method correctly implements the marker interface to ensure only one instance of this module type exists per application.


22-27: LGTM: Standard depinject registration pattern.

The module registration follows the standard Cosmos SDK depinject pattern with proper configuration type and provider function registration.


47-53: LGTM: Robust authority configuration with fallback.

The authority configuration properly handles both explicit configuration and defaults to governance module authority when not specified, which is the expected behavior for most Cosmos SDK modules.


54-67: LGTM: Clean keeper and module construction.

The keeper and app module construction properly wire all dependencies and return the expected outputs for the depinject framework.

modules/network/types/params.go (1)

95-181: Well-implemented parameter validation

The validation functions properly enforce type and value constraints:

  • Positive values for epoch length and prune duration
  • Decimal fractions between 0 and 1 for quorum and participation
  • Enum validation for sign mode with unspecified check
modules/network/keeper/grpc_query.go (1)

1-169: Well-structured gRPC query implementation

The query server properly wraps the keeper, validates all requests, handles errors with appropriate gRPC status codes, and returns comprehensive responses.

modules/network/types/keys.go (1)

36-72: Consistent and correct key construction

All key construction functions properly use BigEndian encoding for numeric values and append prefixes correctly.

modules/network/module.go (1)

1-113: Proper Cosmos SDK module implementation

The module correctly implements all required interfaces, registers services, and handles genesis state properly.

pkg/adapter/adapter.go (1)

49-61: Well-designed BlockFilter interface.

The BlockFilter interface provides a clean abstraction for controlling block publishing behavior, with a sensible functional implementation pattern.

modules/network/types/msgs.go (1)

1-196: Message type implementations follow Cosmos SDK conventions correctly.

All four message types are properly implemented with correct validation, routing, and signing logic following standard Cosmos SDK patterns.

modules/proto/rollkitsdk/network/v1/query.proto (1)

1-95: Well-structured query service definition.

The Query service and message definitions are properly structured with appropriate HTTP bindings for REST access. The static analysis warning about gogoproto can be safely ignored as it's likely a false positive in the analysis environment.

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

♻️ Duplicate comments (3)
modules/network/keeper/keeper.go (3)

86-89: Handle error from Params.Get.

The error is silently ignored which could hide configuration issues.


162-194: BuildValidatorIndexMap affects historical attestation validation.

The function rebuilds validator indices from the current bonded set, causing historical attestation checks to use incorrect validator data.


302-303: Implement signature pruning to prevent unbounded state growth.

Signatures should be pruned along with their associated attestation data.

🧹 Nitpick comments (3)
modules/network/keeper/msg_server.go (1)

149-149: Use standard logging format.

The logging statement uses a debug-style prefix "+++". Use standard info-level logging without special prefixes.

-    k.Logger(ctx).Info("+++ joined attester set", "validator", msg.Validator)
+    k.Logger(ctx).Info("validator joined attester set", "validator", msg.Validator)
modules/network/keeper/keeper.go (2)

65-71: Remove or implement the commented schema building code.

The commented code for explicit schema building should either be removed if not needed or properly implemented if required for schema validation.

Either remove the commented code:

-    // The schema is built implicitly when the first collection is created or can be explicitly built.
-    // schema, err := sb.Build()
-    // if err != nil {
-    // 	panic(err)
-    // }
-    // keeper.schema = schema

Or implement it properly if schema validation is needed:

-    // The schema is built implicitly when the first collection is created or can be explicitly built.
-    // schema, err := sb.Build()
-    // if err != nil {
-    // 	panic(err)
-    // }
-    // keeper.schema = schema
+    schema, err := sb.Build()
+    if err != nil {
+        panic(fmt.Errorf("failed to build schema: %w", err))
+    }
+    _ = schema // Schema is built for validation

239-248: Log error details when quorum fraction parsing fails.

Silent failure when parsing quorum fraction could hide configuration issues.

     quorumFrac, err := math.LegacyNewDecFromStr(params.QuorumFraction)
     if err != nil {
+        k.Logger(ctx).Error("failed to parse quorum fraction", 
+            "fraction", params.QuorumFraction, 
+            "error", err)
         return false, fmt.Errorf("invalid quorum fraction: %w", err)
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b44531d and 2ebf6b1.

📒 Files selected for processing (5)
  • modules/network/genesis.go (1 hunks)
  • modules/network/keeper/abci.go (1 hunks)
  • modules/network/keeper/grpc_query.go (1 hunks)
  • modules/network/keeper/keeper.go (1 hunks)
  • modules/network/keeper/msg_server.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • modules/network/genesis.go
  • modules/network/keeper/grpc_query.go
  • modules/network/keeper/abci.go
⏰ 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

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

mostly lgtm!

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

♻️ Duplicate comments (2)
pkg/adapter/adapter.go (2)

626-626: TODO persistence issue remains unaddressed.


703-709: Context cancellation handling still problematic.

🧹 Nitpick comments (2)
modules/network/keeper/abci.go (2)

53-56: Document the expected nil bitmap behavior.

When GetAttestationBitmap returns nil, the function silently returns. Consider adding a comment or debug log to clarify this is expected behavior when no attestations have been submitted yet.

 bitmapBytes, _ := k.GetAttestationBitmap(ctx, height)
 if bitmapBytes == nil {
+    // No attestations submitted for this checkpoint yet
     return nil
 }

165-171: Simplify boolean to string conversion.

Use strconv.FormatBool for cleaner code.

-var softConfirmedSt string
-
-if softConfirmed {
-    softConfirmedSt = "true"
-} else {
-    softConfirmedSt = "false"
-}
+import "strconv"
+
+softConfirmedSt := strconv.FormatBool(softConfirmed)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 541c00e and 7113c13.

⛔ Files ignored due to path filters (1)
  • modules/network/types/types.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (5)
  • modules/network/keeper/abci.go (1 hunks)
  • modules/network/keeper/msg_server.go (1 hunks)
  • modules/network/types/params.go (1 hunks)
  • modules/proto/rollkitsdk/network/v1/types.proto (1 hunks)
  • pkg/adapter/adapter.go (24 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • modules/network/keeper/msg_server.go
  • modules/network/types/params.go
🧰 Additional context used
🧠 Learnings (1)
modules/proto/rollkitsdk/network/v1/types.proto (1)
Learnt from: julienrbrt
PR: rollkit/go-execution-abci#81
File: .github/workflows/integration_test.yml:28-30
Timestamp: 2025-05-07T12:20:24.290Z
Learning: For the rollkit/go-execution-abci repository, the maintainer prefers using the latest version of Ignite CLI rather than pinning to a specific version during the current development phase. Version tags will be added later when Rollkit has a tag.
🪛 Buf (1.54.0)
modules/proto/rollkitsdk/network/v1/types.proto

7-7: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

⏰ 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
🔇 Additional comments (8)
pkg/adapter/adapter.go (7)

49-60: Well-designed BlockFilter interface.

The BlockFilter interface provides a clean abstraction for controlling block commit event publishing. The functional implementation with BlockFilterFn follows good Go patterns for simple function-based implementations.


88-91: Good encapsulation improvements.

Changing Metrics to an unexported metrics field improves encapsulation. The addition of blockFilter and stackedEvents fields properly supports the new event stacking functionality.


104-105: Options pattern implementation looks good.

The constructor now uses functional options, which is a clean and extensible design pattern. The default values are appropriately set with NopMetrics() and a pass-through BlockFilterFn.

Also applies to: 123-129


369-372: Useful transaction hash logging for debugging.

Adding SHA256 hash logging for processed transactions will be valuable for debugging and tracing transaction execution.


478-486: Block filtering logic correctly implemented.

The implementation properly checks blockFilter.IsPublishable() to decide whether to fire events immediately or stack them. Clearing fbResp.Events when stacking prevents premature storage, which is the correct behavior.


67-67: Excellent error wrapping improvements.

The consistent addition of error wrapping with fmt.Errorf and %w verb provides better error context throughout the adapter, which will significantly improve debugging and error tracing.

Also applies to: 262-262, 275-275, 293-293, 317-317, 327-327, 332-332, 420-420, 488-488, 507-507, 513-513, 521-521, 530-530, 542-542, 549-549, 560-560, 645-645, 714-714, 718-718, 722-722


687-729: ```shell
#!/bin/bash

Search for all declarations and references of stackedEvents to understand its lifecycle

rg -n "stackedEvents"


</details>
<details>
<summary>modules/proto/rollkitsdk/network/v1/types.proto (1)</summary>

`1-69`: **Well-structured protobuf definitions for the network module.**

The proto file properly defines the core data structures with clear documentation and appropriate Cosmos SDK scalar types. The message definitions follow proto3 best practices.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

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

♻️ Duplicate comments (3)
modules/network/keeper/abci.go (3)

69-69: Replace placeholder commit hash with actual implementation.

This has been identified in previous reviews - the commit hash should use actual block/commit data instead of a placeholder.


122-125: Implement bitmap pruning strategy.

The commented-out pruning logic has been flagged in previous reviews and needs implementation to prevent unbounded storage growth.


134-137: Implement validator ejection logic.

This TODO has been identified in previous reviews - the ejection logic for low-participation validators needs to be implemented as part of the module's incentive mechanism.

🧹 Nitpick comments (2)
modules/proto/rollkitsdk/network/v1/types.proto (1)

41-43: Height should be unsigned to match Tendermint/Cosmos conventions

Block heights are never negative; using uint64 (as used elsewhere in the file) keeps the type consistent and prevents accidental sign issues.

-  // height is the checkpoint height
-  int64 height = 1;
+  // height is the checkpoint height
+  uint64 height = 1;
modules/network/keeper/abci.go (1)

141-147: Simplify boolean to string conversion.

The manual boolean to string conversion can be simplified for better readability.

-	var softConfirmedSt string
-
-	if softConfirmed {
-		softConfirmedSt = "true"
-	} else {
-		softConfirmedSt = "false"
-	}
+	softConfirmedSt := fmt.Sprintf("%t", softConfirmed)

Or using strconv:

+	import "strconv"
+
-	var softConfirmedSt string
-
-	if softConfirmed {
-		softConfirmedSt = "true"
-	} else {
-		softConfirmedSt = "false"
-	}
+	softConfirmedSt := strconv.FormatBool(softConfirmed)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7113c13 and fffaa00.

⛔ Files ignored due to path filters (1)
  • modules/network/types/types.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (3)
  • modules/network/keeper/abci.go (1 hunks)
  • modules/network/types/params.go (1 hunks)
  • modules/proto/rollkitsdk/network/v1/types.proto (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • modules/network/types/params.go
🧰 Additional context used
🧠 Learnings (1)
modules/proto/rollkitsdk/network/v1/types.proto (1)
Learnt from: julienrbrt
PR: rollkit/go-execution-abci#81
File: .github/workflows/integration_test.yml:28-30
Timestamp: 2025-05-07T12:20:24.290Z
Learning: For the rollkit/go-execution-abci repository, the maintainer prefers using the latest version of Ignite CLI rather than pinning to a specific version during the current development phase. Version tags will be added later when Rollkit has a tag.
🪛 Buf (1.54.0)
modules/proto/rollkitsdk/network/v1/types.proto

7-7: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test with Rollkit Chain
  • GitHub Check: lint / golangci-lint
  • GitHub Check: test / Run Unit Tests
🔇 Additional comments (3)
modules/network/keeper/abci.go (3)

16-24: LGTM! Clean validation logic.

The BeginBlocker correctly enforces the checkpoint-only sign mode constraint with appropriate error handling.


26-49: LGTM! Well-structured end block logic.

The EndBlocker properly handles both checkpoint and epoch processing with clear separation of concerns and good error handling.


67-67: Verify the validator hash calculation approach.

The validator hash is computed from the attestation bitmap bytes, but this may not represent the actual validator set. Consider whether this should hash the validator set data instead of the bitmap.

Could you clarify if hashing the bitmap bytes is the intended approach for the validator hash, or should this be computed from the actual validator set?

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

♻️ Duplicate comments (2)
pkg/adapter/adapter.go (2)

617-637: Address event persistence for restart recovery.

The stacked events are stored in memory and will be lost on node restart, potentially causing missed event publications. This aligns with the existing TODO comment.

The StackedEvent struct design is appropriate for holding all necessary event data for deferred publishing.


707-713: Fix incomplete context cancellation handling.

The context cancellation check modifies maxPosReleased but continues processing, which could lead to partial event publishing and inconsistent state.

Apply this fix to return early on context cancellation:

-		// todo (Alex): exit loop when ctx cancelled
-		select {
-		case <-ctx.Done():
-			maxPosReleased = i
-			break outerLoop
-		default:
-		}
+		select {
+		case <-ctx.Done():
+			// Store remaining events for later processing
+			a.stackedEvents = a.stackedEvents[i:]
+			return ctx.Err()
+		default:
+		}
🧹 Nitpick comments (2)
pkg/adapter/adapter.go (2)

369-373: Consider making transaction hash logging configurable.

The SHA256 hash logging for each transaction could be very verbose in production environments with high transaction throughput. Consider using a configurable log level or feature flag.

-	for i, tx := range txs {
-		sum256 := sha256.Sum256(tx)
-		a.Logger.Debug("Processed TX", "hash", strings.ToUpper(hex.EncodeToString(sum256[:])), "result", fbResp.TxResults[i].Code, "log", fbResp.TxResults[i].Log, "height", blockHeight)
-	}
+	if a.Logger.Core().Enabled(log.LevelDebug) {
+		for i, tx := range txs {
+			sum256 := sha256.Sum256(tx)
+			a.Logger.Debug("Processed TX", "hash", strings.ToUpper(hex.EncodeToString(sum256[:])), "result", fbResp.TxResults[i].Code, "log", fbResp.TxResults[i].Log, "height", blockHeight)
+		}
+	}

691-733: Well-designed soft confirmation mechanism with room for improvement.

The publishQueuedBlockEvents method implements a sophisticated soft confirmation system that correctly processes stacked events. The approach of updating stored block responses before firing events maintains consistency with CometBFT behavior.

However, consider these improvements:

  1. Add comprehensive logging for debugging complex event processing scenarios
  2. Implement metrics to track stacked event counts and processing times
  3. Consider adding configurable timeouts for event processing
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fffaa00 and e2de6ec.

📒 Files selected for processing (1)
  • pkg/adapter/adapter.go (24 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: test / Run Unit Tests
  • GitHub Check: lint / golangci-lint
  • GitHub Check: Test with Rollkit Chain
🔇 Additional comments (4)
pkg/adapter/adapter.go (4)

49-61: LGTM! Clean interface design with functional implementation.

The BlockFilter interface provides a clean abstraction for controlling block event publishing, and the functional type implementation follows Go best practices.


94-132: LGTM! Well-designed options pattern implementation.

The constructor maintains backward compatibility while enabling flexible configuration through the options pattern. The default block filter ensures existing behavior is preserved.


155-212: LGTM! Improved encapsulation with unexported metrics field.

The change from exported Metrics to unexported metrics field improves encapsulation while maintaining all existing functionality.


478-493: LGTM! Well-implemented conditional event publishing logic.

The block filter logic correctly handles both immediate publishing and event stacking scenarios. Clearing events from the response when stacking prevents premature storage, which is the correct approach.

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

♻️ Duplicate comments (1)
modules/proto/rollkitsdk/network/v1/types.proto (1)

7-10: Fix proto compile errors: import resolution & unused dependency

gogoproto/gogo.proto is still unresolved in the module path and will break buf generate; google/protobuf/duration.proto is imported but never referenced, triggering the unused-import linter.
Either vendor gogo.proto or declare it in buf.yaml, and drop the unused duration.proto line.

-import "gogoproto/gogo.proto";
-import "cosmos_proto/cosmos.proto";
-import "google/protobuf/duration.proto";
+import "gogoproto/gogo.proto";           // ← ensure vendored or declared in buf.yaml
+import "cosmos_proto/cosmos.proto";
+// import "google/protobuf/duration.proto";  // ← remove until a field actually needs it
🧹 Nitpick comments (1)
modules/proto/rollkitsdk/network/v1/types.proto (1)

40-41: Use unsigned height to stay consistent with Cosmos SDK conventions

Block heights cannot be negative; switching to uint64 matches other SDK protos and avoids a needless sign bit.

-  int64 height = 1;
+  uint64 height = 1;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e2de6ec and 110096d.

⛔ Files ignored due to path filters (1)
  • modules/network/types/types.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (2)
  • modules/network/keeper/abci.go (1 hunks)
  • modules/proto/rollkitsdk/network/v1/types.proto (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • modules/network/keeper/abci.go
🧰 Additional context used
🧠 Learnings (1)
modules/proto/rollkitsdk/network/v1/types.proto (1)
Learnt from: julienrbrt
PR: rollkit/go-execution-abci#81
File: .github/workflows/integration_test.yml:28-30
Timestamp: 2025-05-07T12:20:24.290Z
Learning: For the rollkit/go-execution-abci repository, the maintainer prefers using the latest version of Ignite CLI rather than pinning to a specific version during the current development phase. Version tags will be added later when Rollkit has a tag.
🪛 Buf (1.54.0)
modules/proto/rollkitsdk/network/v1/types.proto

7-7: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: test / Run Unit Tests
  • GitHub Check: lint / golangci-lint
  • GitHub Check: Test with Rollkit Chain

alpe added 2 commits June 26, 2025 17:43
* main:
  test: add migration integration test + fix migration command (#150)
  build(deps): update to latest rollkit (#159)
  build(deps): bump rollkit to latest (#153)
  feat(server): add migration command (#113)
* main:
  chore: bump rollkit version (#168)
@alpe alpe enabled auto-merge (squash) June 27, 2025 08:13
@alpe alpe merged commit 2d62dd2 into main Jun 27, 2025
12 checks passed
@alpe alpe deleted the alex/val_net_hack branch June 27, 2025 08:37
chatton pushed a commit that referenced this pull request Oct 7, 2025
* add network module

* Mkake compile

* Make proto-gen for network module

* Polish code; add tests

* Compile after merge

* x

* Add start flag to enable the validator network

* Start local dev env

* Do not stop chain when network consensus missed

* Updates

* Remove duplicate code

* Remove wip code

* Fix linter issues

* Run go mod tidy only

* Remove hack/ folder

* Explicit error handling

* Ensure type safety

* Remove ai generated audit file

* Review feedback

* Remove emergency mode

* Store block response before events published

* Review feedback

* Review feedback

---------

Co-authored-by: tac0turtle <marko@baricevic.me>
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.

3 participants