Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

DRAFT: IBC Lite Implementation #6299

Draft
wants to merge 20 commits into
base: main
Choose a base branch
from
Draft

DRAFT: IBC Lite Implementation #6299

wants to merge 20 commits into from

Conversation

AdityaSripal
Copy link
Member

@AdityaSripal AdityaSripal commented May 13, 2024

Description

closes: #XXXX


Before we can merge this PR, please make sure that all the following items have been
checked off. If any of the checklist items are not applicable, please leave them but
write a little note why.

  • Targeted PR against the correct branch (see CONTRIBUTING.md).
  • Linked to GitHub issue with discussion and accepted design, OR link to spec that describes this work.
  • Code follows the module structure standards and Go style guide.
  • Wrote unit and integration tests.
  • Updated relevant documentation (docs/).
  • Added relevant godoc comments.
  • Provide a conventional commit message to follow the repository standards.
  • Include a descriptive changelog entry when appropriate. This may be left to the discretion of the PR reviewers. (e.g. chores should be omitted from changelog)
  • Re-reviewed Files changed in the GitHub PR explorer.
  • Review SonarCloud Report in the comment section below once CI passes.

Summary by CodeRabbit

  • New Features

    • Introduced support for sending and receiving packets over IBC channels.
    • Added methods for packet transmission, verification, and application logic.
    • Implemented LiteClientModule interface for counterparty information retrieval and membership verification.
    • Introduced LitePacketHandler interface for handling packet events.
  • Refactor

    • Moved RecvPacket, Acknowledgement, and Timeout methods to a new PacketMsg service in the IBC channel protocol.
  • Enhancements

    • Added function to compute hash for Packet struct properties.

Copy link
Contributor

coderabbitai bot commented May 13, 2024

Important

Review Skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes introduce and enhance functionalities related to Inter-Blockchain Communication (IBC) within the project. Key modifications include the implementation of packet handling methods in the Keeper struct, the introduction of new interfaces and routing mechanisms, and the reorganization of gRPC services for packet operations. These updates aim to streamline packet transmission, verification, and application logic, ensuring efficient and secure inter-chain communication.

Changes

Files Change Summary
modules/core/keeper/msg_server.go Added _ channeltypes.PacketMsgServer = (*Keeper)(nil) to interface declarations.
modules/core/lite/keeper/msg_server.go Introduced Keeper struct with methods for sending and receiving IBC packets.
modules/core/lite/types/client.go Introduced LiteClientModule interface for counterparty information retrieval and membership verification.
modules/core/lite/types/expected_keepers.go Added interfaces for ClientRouter, ChannelKeeper, and AppRouter to manage IBC routing and channel operations.
proto/ibc/core/channel/v1/tx.proto Moved RecvPacket, Acknowledgement, and Timeout methods from Msg service to a new PacketMsg service.
modules/core/04-channel/types/packet.go Added CommitLitePacket function to compute a hash based on Packet properties.
modules/core/05-port/types/module.go Introduced LitePacketHandler interface with methods for packet handling, including SendPacket, WriteAcknowledgement, OnRecvPacket, and more.

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

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

CodeRabbit Commands (invoked as PR comments)

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

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 4f31a3c and ecf8681.
Files ignored due to path filters (1)
  • modules/core/04-channel/types/tx.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
Files selected for processing (5)
  • modules/core/keeper/msg_server.go (1 hunks)
  • modules/core/lite/keeper/msg_server.go (1 hunks)
  • modules/core/lite/types/client.go (1 hunks)
  • modules/core/lite/types/expected_keepers.go (1 hunks)
  • proto/ibc/core/channel/v1/tx.proto (2 hunks)
Files skipped from review due to trivial changes (1)
  • modules/core/keeper/msg_server.go
Additional Context Used
GitHub Check Runs (1)
tests (03) failure (3)

modules/core/lite/types/expected_keepers.go: [failure] 27-27:
undefined: port.AppModule

Path-based Instructions (3)
modules/core/lite/types/client.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

modules/core/lite/types/expected_keepers.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

modules/core/lite/keeper/msg_server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

Additional comments not posted (7)
modules/core/lite/types/client.go (2)

9-10: Method GetCounterparty is well-defined and adheres to good practices in Go.


11-29: Methods VerifyMembership and VerifyNonMembership are crucial for blockchain integrity and are implemented with necessary parameters for thorough verification.

modules/core/lite/types/expected_keepers.go (2)

10-12: Method Route in ClientRouter interface is well-defined and adheres to good practices in Go.


15-24: Methods in ChannelKeeper interface are crucial for managing channel states and are implemented correctly.

modules/core/lite/keeper/msg_server.go (2)

13-22: Keeper struct is well-defined and correctly implements the PacketMsgServer interface, ensuring proper handling of IBC operations.


38-103: Method RecvPacket is well-implemented with sophisticated caching strategies. However, please review the caching strategy to ensure it does not lead to state inconsistencies.

Verification successful

The caching strategy in the RecvPacket method appears to be well-implemented, with mechanisms to handle both successful and unsuccessful packet acknowledgements effectively. The use of cacheCtx and writeFn() to manage state changes conditionally based on the success of the acknowledgement process seems to mitigate the risk of state inconsistencies. Therefore, the initial concern about potential state inconsistencies due to the caching strategy does not seem warranted based on the current implementation.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the caching strategy in `RecvPacket` method to ensure it does not lead to state inconsistencies.

# Test: Review the caching implementation and test for potential state inconsistencies.
grep -r "CacheContext" modules/core/lite/keeper/

Length of output: 128



Script:

#!/bin/bash
# Description: Examine the use of cache context and write function in the `RecvPacket` method to understand how state changes are managed.

# Extract the relevant code section around the caching implementation to see how it's used in different scenarios.
rg --context 10 "CacheContext" modules/core/lite/keeper/msg_server.go

Length of output: 979

proto/ibc/core/channel/v1/tx.proto (1)

67-79: Creation of the PacketMsg service enhances modularity and clarity by segregating packet-related operations into a dedicated service.

Comment on lines 26 to 28
type AppRouter interface {
Route(portID string) port.AppModule
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Method Route in AppRouter interface references an undefined AppModule. Please ensure that AppModule is correctly imported or defined.

- Route(portID string) port.AppModule
+ // Ensure AppModule is defined or imported correctly
+ Route(portID string) port.AppModule

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
type AppRouter interface {
Route(portID string) port.AppModule
}
type AppRouter interface {
// Ensure AppModule is defined or imported correctly
Route(portID string) port.AppModule
}

Comment on lines 30 to 36
// SendPacket implements the MsgServer interface. It creates a new packet
// with the given source port and source channel and sends it over the channel
// end with the given destination port and channel identifiers.
func (k Keeper) SendPacket(context.Context, *channeltypes.MsgSendPacket) (*channeltypes.MsgSendPacketResponse, error) {

return nil, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Method SendPacket is currently a stub and does not implement any logic. Please ensure to complete the implementation or provide documentation if this is intentional.

modules/core/lite/keeper/msg_server.go Fixed Show fixed Hide fixed
modules/core/lite/keeper/msg_server.go Fixed Show fixed Hide fixed
modules/core/lite/keeper/msg_server.go Fixed Show fixed Hide fixed
modules/core/lite/keeper/msg_server.go Fixed Show fixed Hide fixed
modules/core/lite/keeper/msg_server.go Fixed Show fixed Hide fixed
modules/core/lite/keeper/msg_server.go Fixed Show fixed Hide fixed
modules/core/lite/keeper/msg_server.go Fixed Show fixed Hide fixed
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

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between ecf8681 and fdf9e25.
Files ignored due to path filters (1)
  • modules/core/04-channel/types/tx.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
Files selected for processing (5)
  • modules/core/04-channel/types/packet.go (1 hunks)
  • modules/core/05-port/types/module.go (1 hunks)
  • modules/core/lite/keeper/msg_server.go (1 hunks)
  • modules/core/lite/types/expected_keepers.go (1 hunks)
  • proto/ibc/core/channel/v1/tx.proto (3 hunks)
Files skipped from review as they are similar to previous changes (2)
  • modules/core/lite/types/expected_keepers.go
  • proto/ibc/core/channel/v1/tx.proto
Additional Context Used
Path-based Instructions (3)
modules/core/04-channel/types/packet.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

modules/core/05-port/types/module.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

modules/core/lite/keeper/msg_server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

Additional comments not posted (2)
modules/core/04-channel/types/packet.go (1)

38-57: The implementation of CommitLitePacket correctly computes the packet commitment by including the destination port and channel, which enhances the specificity of the commitment. This change aligns with the PR's goal to improve packet handling.

modules/core/05-port/types/module.go (1)

200-238: The addition of the LitePacketHandler interface is a significant enhancement for handling IBC Lite specific packet operations. This interface segregates the Lite functionality from the standard IBC operations, which is a good practice in terms of modularity and maintainability.

Comment on lines 37 to 102
// SendPacket implements the MsgServer interface. It creates a new packet
// with the given source port and source channel and sends it over the channel
// end with the given destination port and channel identifiers.
func (k Keeper) SendPacket(goCtx context.Context, msg *channeltypes.MsgSendPacket) (*channeltypes.MsgSendPacketResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)

// Get LightClientModule associated with the destination channel
// Note: This can be implemented by the current clientRouter
lightClientModule := k.clientRouter.Route(msg.SourceChannel)
if lightClientModule == nil {
return nil, errorsmod.Wrapf(channeltypes.ErrInvalidChannel, "source channel %s not associated with a light client module", msg.SourceChannel)
}

// Lookup counterparty associated with our channel and ensure that it was packet was indeed
// sent by our counterparty.
// Note: This can be implemented by the current channelKeeper
// TODO: Use context instead of sdk.Context eventually
_, counterpartyChannelId, found := k.channelKeeper.GetCounterparty(ctx, "", msg.SourceChannel)
if !found {
return nil, channeltypes.ErrChannelNotFound
}

if counterpartyChannelId != msg.DestChannel {
return nil, channeltypes.ErrInvalidChannelIdentifier
}

sequence, found := k.channelKeeper.GetNextSequenceSend(ctx, msg.SourcePort, msg.SourceChannel)
if !found {
sequence = 1
}

// construct packet from given fields and channel state
packet := channeltypes.NewPacket(msg.Data, sequence, msg.SourcePort, msg.SourceChannel,
msg.DestPort, msg.DestChannel, *msg.TimeoutHeight, msg.TimeoutTimestamp)

if err := packet.ValidateBasic(); err != nil {
return nil, errorsmod.Wrap(err, "constructed packet failed basic validation")
}

latestHeight := lightClientModule.LatestHeight(ctx, msg.SourceChannel).(clienttypes.Height)
if latestHeight.IsZero() {
return nil, errorsmod.Wrapf(clienttypes.ErrInvalidHeight, "cannot send packet using client (%s) with zero height", msg.SourceChannel)
}

latestTimestamp, err := lightClientModule.TimestampAtHeight(ctx, msg.SourceChannel, latestHeight)
if err != nil {
return nil, err
}

// check if packet is timed out on the receiving chain
timeout := channeltypes.NewTimeout(packet.GetTimeoutHeight().(clienttypes.Height), packet.GetTimeoutTimestamp())
if timeout.Elapsed(latestHeight, latestTimestamp) {
return nil, errorsmod.Wrap(timeout.ErrTimeoutElapsed(latestHeight, latestTimestamp), "invalid packet timeout")
}

commitment := channeltypes.CommitLitePacket(k.cdc, packet)

k.channelKeeper.SetNextSequenceSend(ctx, msg.SourcePort, msg.SourceChannel, sequence+1)
k.channelKeeper.SetPacketCommitment(ctx, msg.SourcePort, msg.SourceChannel, packet.GetSequence(), commitment)

// IBC Lite routes to the application to do specific sendpacket logic rather than assuming the caller is the application module.
// IMPORTANT: This changes the ordering of core and application execution for SendPacket
// TODO: Add SendPacket callback to IBCModule interface

return &channeltypes.MsgSendPacketResponse{Sequence: packet.GetSequence()}, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The SendPacket method correctly implements the packet sending logic for IBC Lite, including validation and commitment handling. However, there are several TODO comments indicating incomplete features, such as adding a SendPacket callback to the IBCModule interface. It's important to address these TODOs before finalizing the PR.

Would you like me to help implement the missing features or open a GitHub issue to track these tasks?

Comment on lines 104 to 181
// ReceivePacket implements the MsgServer interface. It receives an incoming
// packet, which was sent over a channel end with the given port and channel
// identifiers, performs all necessary application logic, and then
// acknowledges the packet.
func (k Keeper) RecvPacket(goCtx context.Context, msg *channeltypes.MsgRecvPacket) (*channeltypes.MsgRecvPacketResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
packet := msg.Packet

// Lookup counterparty associated with our channel and ensure that it was packet was indeed
// sent by our counterparty.
// Note: This can be implemented by the current channelKeeper
// TODO: Use context instead of sdk.Context eventually
_, counterpartyChannelId, found := k.channelKeeper.GetCounterparty(ctx, "", packet.DestinationChannel)
if !found {
return nil, channeltypes.ErrChannelNotFound
}

if counterpartyChannelId != packet.SourceChannel {
return nil, channeltypes.ErrInvalidChannelIdentifier
}

// create key/value pair for proof verification
key := host.PacketCommitmentPath(packet.SourcePort, packet.SourceChannel, packet.Sequence)
commitment := channeltypes.CommitLitePacket(k.cdc, packet)

// Get LightClientModule associated with the destination channel
// Note: This can be implemented by the current clientRouter
lightClientModule := k.clientRouter.Route(packet.DestinationChannel)

// TODO: Use context instead of sdk.Context eventually
if err := lightClientModule.VerifyMembership(
ctx,
packet.DestinationChannel,
msg.ProofHeight,
0, 0,
msg.ProofCommitment,
commitmenttypes.NewMerklePath(key),
commitment,
); err != nil {
return nil, err
}

// Port should directly correspond to the application module route
// No need for capabilities and mapping from portID to ModuleName
appModule, ok := k.appRouter.GetRoute(packet.DestinationPort)
if !ok {
return nil, porttypes.ErrInvalidPort
}

// TODO: Figure out how to do caching generically without using SDK
// Perform application logic callback
//
// Cache context so that we may discard state changes from callback if the acknowledgement is unsuccessful.
cacheCtx, writeFn := ctx.CacheContext()
// TODO: Use signer as string rather than sdk.AccAddress
relayer, err := sdk.AccAddressFromBech32(msg.Signer)
if err != nil {
ctx.Logger().Error("acknowledgement failed", "error", errorsmod.Wrap(err, "Invalid address for msg Signer"))
return nil, errorsmod.Wrap(err, "Invalid address for msg Signer")
}
ack := appModule.OnRecvPacket(cacheCtx, packet, relayer)
if ack == nil || ack.Success() {
// write application state changes for asynchronous and successful acknowledgements
writeFn()
} else {
// Modify events in cached context to reflect unsuccessful acknowledgement
// TODO: How do we create interface for this that isn't too SDK specific?
// ctx.EventManager().EmitEvents(convertToErrorEvents(cacheCtx.EventManager().Events()))
}

// Write acknowledgement to store
if ack != nil {
// Can be implemented by current channelKeeper with change in sdk.Context to context.Context
k.channelKeeper.WriteAcknowledgement(ctx, packet.DestinationPort, packet.DestinationChannel, ack.Acknowledgement())
}

return &channeltypes.MsgRecvPacketResponse{Result: channeltypes.SUCCESS}, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The RecvPacket method handles the receipt of packets appropriately, including proof verification and application logic execution. The use of caching to manage state changes is a good practice. However, the numerous TODO comments suggest that the implementation is not yet complete, particularly in areas like error handling and event emission.

Should I assist in completing these implementations or would you prefer to track them via a GitHub issue?

Comment on lines 183 to 265
// Acknowledgement implements the MsgServer interface. It processes the acknowledgement
// of a packet previously sent by the calling chain once the packet has been received and acknowledged
// by the counterparty chain.
func (k Keeper) Acknowledgement(goCtx context.Context, msg *channeltypes.MsgAcknowledgement) (*channeltypes.MsgAcknowledgementResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
packet := msg.Packet

// Lookup counterparty associated with our channel and ensure that it was packet was indeed
// sent by our counterparty.
// Note: This can be implemented by the current channelKeeper
// TODO: Use context instead of sdk.Context eventually
_, counterpartyChannelId, found := k.channelKeeper.GetCounterparty(ctx, "", packet.SourceChannel)
if !found {
return nil, channeltypes.ErrChannelNotFound
}

if counterpartyChannelId != packet.DestinationChannel {
return nil, channeltypes.ErrInvalidChannelIdentifier
}

commitment := k.channelKeeper.GetPacketCommitment(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence())
if len(commitment) == 0 {
// TODO: events
// emitAcknowledgePacketEvent(ctx, packet, channel)

// This error indicates that the acknowledgement has already been relayed
// or there is a misconfigured relayer attempting to prove an acknowledgement
// for a packet never sent. Core IBC will treat this error as a no-op in order to
// prevent an entire relay transaction from failing and consuming unnecessary fees.
return nil, channeltypes.ErrNoOpMsg
}

packetCommitment := channeltypes.CommitLitePacket(k.cdc, packet)

// verify we sent the packet and haven't cleared it out yet
if !bytes.Equal(commitment, packetCommitment) {
return nil, errorsmod.Wrapf(channeltypes.ErrInvalidPacket, "commitment bytes are not equal: got (%v), expected (%v)", packetCommitment, commitment)
}

proofPath := commitmenttypes.NewMerklePath(host.PacketAcknowledgementPath(packet.DestinationPort, packet.DestinationChannel, packet.Sequence))

// Get LightClientModule associated with the destination channel
// Note: This can be implemented by the current clientRouter
lightClientModule := k.clientRouter.Route(packet.SourceChannel)
// TODO: Use context instead of sdk.Context eventually
if err := lightClientModule.VerifyMembership(
ctx,
packet.SourceChannel,
msg.ProofHeight,
0, 0,
msg.ProofAcked,
proofPath,
channeltypes.CommitAcknowledgement(msg.Acknowledgement),
); err != nil {
return nil, err
}

k.channelKeeper.DeletePacketCommitment(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence())

// TODO: emit events
// emitAcknowledgePacketEvent(ctx, packet, channel)

// Port should directly correspond to the application module route
// No need for capabilities and mapping from portID to ModuleName
appModule, ok := k.appRouter.GetRoute(packet.SourcePort)
if !ok {
return nil, porttypes.ErrInvalidPort
}

relayer, err := sdk.AccAddressFromBech32(msg.Signer)
if err != nil {
ctx.Logger().Error("acknowledgement failed", "error", errorsmod.Wrap(err, "Invalid address for msg Signer"))
return nil, errorsmod.Wrap(err, "Invalid address for msg Signer")
}
// TODO: Use context instead of sdk.Context eventually
err = appModule.OnAcknowledgementPacket(ctx, packet, msg.Acknowledgement, relayer)
if err != nil {
ctx.Logger().Error("acknowledgement failed", "port-id", packet.SourcePort, "channel-id", packet.SourceChannel, "error", errorsmod.Wrap(err, "acknowledge packet callback failed"))
return nil, errorsmod.Wrap(err, "acknowledge packet callback failed")
}

return &channeltypes.MsgAcknowledgementResponse{Result: channeltypes.SUCCESS}, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The Acknowledgement method processes packet acknowledgements correctly, ensuring that the packet commitment matches before proceeding. The method also handles errors appropriately. However, the presence of TODO comments related to event emission and context usage indicates areas that need further development.

I can help finalize these sections or create a tracking issue if that would be helpful.

Comment on lines 267 to 349
// Timeout implements the MsgServer interface. It processes a timeout
// for a packet previously sent by the calling chain.
func (k Keeper) Timeout(goCtx context.Context, msg *channeltypes.MsgTimeout) (*channeltypes.MsgTimeoutResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
packet := msg.Packet

// Lookup counterparty associated with our channel and ensure that it was packet was indeed
// sent by our counterparty.
// Note: This can be implemented by the current channelKeeper
// TODO: Use context instead of sdk.Context eventually
_, counterpartyChannelId, found := k.channelKeeper.GetCounterparty(ctx, "", packet.SourceChannel)
if !found {
return nil, channeltypes.ErrChannelNotFound
}

if counterpartyChannelId != packet.DestinationChannel {
return nil, channeltypes.ErrInvalidChannelIdentifier
}

// TODO: Use context instead of sdk.Context eventually
commitment := k.channelKeeper.GetPacketCommitment(ctx, packet.SourcePort, packet.SourceChannel, packet.Sequence)
if len(commitment) == 0 {
// TODO: events
// emitTimeoutPacketEvent(ctx, packet, channel)

// This error indicates that the timeout has already been relayed
// or there is a misconfigured relayer attempting to prove a timeout
// for a packet never sent. Core IBC will treat this error as a no-op in order to
// prevent an entire relay transaction from failing and consuming unnecessary fees.
return nil, channeltypes.ErrNoOpMsg
}

packetCommitment := channeltypes.CommitLitePacket(k.cdc, packet)

// verify we sent the packet and haven't cleared it out yet
if !bytes.Equal(commitment, packetCommitment) {
return nil, errorsmod.Wrapf(channeltypes.ErrInvalidPacket, "packet commitment bytes are not equal: got (%v), expected (%v)", commitment, packetCommitment)
}

proofPath := commitmenttypes.NewMerklePath(host.PacketReceiptPath(packet.DestinationPort, packet.DestinationChannel, packet.Sequence))

// Get LightClientModule associated with the destination channel
// Note: This can be implemented by the current clientRouter
lightClientModule := k.clientRouter.Route(packet.SourceChannel)
// TODO: Use context instead of sdk.Context eventually
if err := lightClientModule.VerifyNonMembership(
ctx,
packet.DestinationChannel,
msg.ProofHeight,
0, 0,
msg.ProofUnreceived,
proofPath,
); err != nil {
return nil, err
}

// TODO: Use context instead of sdk.Context eventually
k.channelKeeper.DeletePacketCommitment(ctx, packet.SourcePort, packet.SourceChannel, packet.Sequence)

// TODO: emit an event marking that we have processed the timeout
// emitTimeoutPacketEvent(ctx, packet, channel)

// Port should directly correspond to the application module route
// No need for capabilities and mapping from portID to ModuleName
appModule, ok := k.appRouter.GetRoute(packet.SourcePort)
if !ok {
return nil, porttypes.ErrInvalidPort
}
relayer, err := sdk.AccAddressFromBech32(msg.Signer)
if err != nil {
ctx.Logger().Error("acknowledgement failed", "error", errorsmod.Wrap(err, "Invalid address for msg Signer"))
return nil, errorsmod.Wrap(err, "Invalid address for msg Signer")
}
// Perform application logic callback
// TODO: Use context instead of sdk.Context eventually
err = appModule.OnTimeoutPacket(ctx, packet, relayer)
if err != nil {
ctx.Logger().Error("timeout failed", "port-id", packet.SourcePort, "channel-id", packet.SourceChannel, "error", errorsmod.Wrap(err, "timeout packet callback failed"))
return nil, errorsmod.Wrap(err, "timeout packet callback failed")
}

return &channeltypes.MsgTimeoutResponse{Result: channeltypes.SUCCESS}, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The Timeout method implements the timeout logic for packets, including verification of non-membership. The method's structure is consistent with the other methods in this file, but like the others, it includes several TODO comments that need to be addressed to complete the implementation.

Would you like assistance in addressing these TODOs, or should they be tracked via a GitHub issue?

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

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between fdf9e25 and 98b4b02.
Files selected for processing (1)
  • modules/core/lite/keeper/msg_server.go (1 hunks)
Additional Context Used
GitHub Check Runs (1)
lint failure (9)

modules/core/lite/keeper/msg_server.go: [failure] 174-174:
Error return value of k.channelKeeper.WriteAcknowledgement is not checked (errcheck)


modules/core/lite/keeper/msg_server.go: [failure] 73-73:
unchecked-type-assertion: type cast result is unchecked in lightClientModule.LatestHeight(ctx, msg.SourceChannel).(clienttypes.Height) - type assertion will panic if not matched (revive)


modules/core/lite/keeper/msg_server.go: [failure] 165-165:
empty-block: this block is empty, you can remove it (revive)


modules/core/lite/keeper/msg_server.go: [failure] 51-51:
var-naming: var counterpartyChannelId should be counterpartyChannelID (revive)


modules/core/lite/keeper/msg_server.go: [failure] 113-113:
var-naming: var counterpartyChannelId should be counterpartyChannelID (revive)


modules/core/lite/keeper/msg_server.go: [failure] 191-191:
var-naming: var counterpartyChannelId should be counterpartyChannelID (revive)


modules/core/lite/keeper/msg_server.go: [failure] 274-274:
var-naming: var counterpartyChannelId should be counterpartyChannelID (revive)

Path-based Instructions (1)
modules/core/lite/keeper/msg_server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

return nil, errorsmod.Wrap(err, "constructed packet failed basic validation")
}

latestHeight := lightClientModule.LatestHeight(ctx, msg.SourceChannel).(clienttypes.Height)
Copy link
Contributor

Choose a reason for hiding this comment

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

Unchecked type assertion in lightClientModule.LatestHeight.

- latestHeight := lightClientModule.LatestHeight(ctx, msg.SourceChannel).(clienttypes.Height)
+ latestHeight, ok := lightClientModule.LatestHeight(ctx, msg.SourceChannel).(clienttypes.Height)
+ if !ok {
+     return nil, fmt.Errorf("type assertion to clienttypes.Height failed")
+ }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
latestHeight := lightClientModule.LatestHeight(ctx, msg.SourceChannel).(clienttypes.Height)
latestHeight, ok := lightClientModule.LatestHeight(ctx, msg.SourceChannel).(clienttypes.Height)
if !ok {
return nil, fmt.Errorf("type assertion to clienttypes.Height failed")
}


// IBC Lite routes to the application to do specific sendpacket logic rather than assuming the caller is the application module.
// IMPORTANT: This changes the ordering of core and application execution for SendPacket
// TODO: Add SendPacket callback to IBCModule interface
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: TODO to add SendPacket callback to IBCModule interface.

Would you like me to help implement this feature or should I open a GitHub issue to track this task?

// Write acknowledgement to store
if ack != nil {
// Can be implemented by current channelKeeper with change in sdk.Context to context.Context
k.channelKeeper.WriteAcknowledgement(ctx, packet.DestinationPort, packet.DestinationChannel, ack.Acknowledgement())
Copy link
Contributor

Choose a reason for hiding this comment

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

Error return value of k.channelKeeper.WriteAcknowledgement is not checked.

- k.channelKeeper.WriteAcknowledgement(ctx, packet.DestinationPort, packet.DestinationChannel, ack.Acknowledgement())
+ if err := k.channelKeeper.WriteAcknowledgement(ctx, packet.DestinationPort, packet.DestinationChannel, ack.Acknowledgement()); err != nil {
+     return nil, fmt.Errorf("failed to write acknowledgement: %w", err)
+ }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
k.channelKeeper.WriteAcknowledgement(ctx, packet.DestinationPort, packet.DestinationChannel, ack.Acknowledgement())
if err := k.channelKeeper.WriteAcknowledgement(ctx, packet.DestinationPort, packet.DestinationChannel, ack.Acknowledgement()); err != nil {
return nil, fmt.Errorf("failed to write acknowledgement: %w", err)
}

// Note: This can be implemented by the current clientRouter
lightClientModule := k.clientRouter.Route(packet.DestinationChannel)

// TODO: Use context instead of sdk.Context eventually
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: TODO to use context instead of sdk.Context.

Would you like me to help refactor this to use the standard context.Context?


k.channelKeeper.DeletePacketCommitment(ctx, packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence())

// TODO: emit events
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: TODO to emit events.

Would you like me to help implement event emission or should I open a GitHub issue to track this task?

// TODO: Use context instead of sdk.Context eventually
k.channelKeeper.DeletePacketCommitment(ctx, packet.SourcePort, packet.SourceChannel, packet.Sequence)

// TODO: emit an event marking that we have processed the timeout
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: TODO to emit an event marking that we have processed the timeout.

Would you like me to help implement this event emission or should I open a GitHub issue to track this task?

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

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 98b4b02 and 36a4146.
Files selected for processing (2)
  • modules/core/lite/keeper/msg_server.go (1 hunks)
  • modules/core/lite/types/expected_keepers.go (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • modules/core/lite/keeper/msg_server.go
  • modules/core/lite/types/expected_keepers.go

@colin-axner colin-axner marked this pull request as draft May 14, 2024 09:30
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.

None yet

2 participants