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

Feat/split oracletx #45

Merged
merged 26 commits into from
Nov 19, 2024
Merged

Feat/split oracletx #45

merged 26 commits into from
Nov 19, 2024

Conversation

sh-cha
Copy link
Collaborator

@sh-cha sh-cha commented Nov 18, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced configuration structure for Challenger and Executor components, improving clarity and organization.
    • Introduced sender information in batch message handling and processing across various components.
    • Added new querying capabilities for grants and executors in the BaseChild struct.
    • Implemented new methods for retrieving account addresses and managing oracle accounts in the BaseChild and BaseHost structs.
    • Added a new command for transaction operations, including granting oracle permissions.
  • Bug Fixes

    • Improved error handling in multiple methods, ensuring more informative error messages.
  • Refactor

    • Restructured message queues in both BaseChild and BaseHost to allow for sender-specific message handling.
    • Updated method signatures across various components to include additional return values for improved context.
    • Simplified address retrieval methods and enhanced transaction handling logic in the Broadcaster struct.
    • Removed outdated address retrieval methods from BaseChild and BaseHost for cleaner code.
    • Streamlined the QueryWithdrawal method for better error handling and response structure.
  • Chores

    • Updated dependency versions in go.mod for better stability and performance.

@sh-cha sh-cha self-assigned this Nov 18, 2024
@sh-cha sh-cha requested a review from a team as a code owner November 18, 2024 08:21
Copy link
Contributor

coderabbitai bot commented Nov 18, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request involve significant modifications across multiple files, primarily focusing on the restructuring of configuration settings and message handling within various components. The configuration keys for both the Challenger and Executor components have been updated to a nested structure, enhancing clarity and organization. Additionally, methods across several files have been modified to include new return values, particularly the sender's address, to improve message tracking. These changes reflect an overall enhancement of the system's message processing capabilities and configuration management.

Changes

File Path Change Summary
challenger/README.md Updated configuration structure: replaced listen_address with server object containing address, allow_origins, allow_headers, allow_methods. Changed address from "localhost:3001" to "localhost:3000".
challenger/child/child.go Updated Initialize method signature to include an additional oracleKeyringConfig parameter.
executor/README.md Updated configuration structure: replaced listen_address with server object and added oracle_bridge_executor key.
executor/batch/handler.go Modified CreateBatchMsg method calls to include an additional return value sender.
executor/batch/noop_da.go Updated CreateBatchMsg method signature to return an additional string value.
executor/celestia/celestia.go Removed processedMsgs and msgQueue fields; modified GetAddress to BaseAccountAddress with updated return type. Removed CreateBatchMsg method. Introduced keyringConfigs method.
executor/celestia/msg.go Added new CreateBatchMsg function that returns an sdk.Msg, a string, and an error.
executor/celestia/node.go Modified BuildTxWithMessages method to streamline transaction creation and signing process.
executor/child/child.go Removed GetAddressStr from hostNode interface; added BaseAccountAddressString. Updated GetMsgProposeOutput method signature to include an additional string return value.
executor/child/handler.go Updated endBlockHandler to process messages from multiple queues indexed by sender.
executor/child/withdraw.go Updated handleOutput method signature to include a new sender parameter.
executor/executor.go Updated getKeyringConfigs method to return an additional childOracleKeyringConfig.
executor/host/batch.go Updated recordBatchHandler to use BaseAccountAddressString() for address retrieval.
executor/host/deposit.go Updated initiateDepositHandler to include sender parameter in method call.
executor/host/handler.go Updated endBlockHandler to process multiple message queues. Updated oracleTxHandler method to return an additional sender value.
executor/host/host.go Updated msgQueue field type from slice to map for structured message handling.
executor/host/oracle.go Updated oracleTxHandler to return an additional string value.
executor/types/batch.go Updated CreateBatchMsg method signature to return an additional string value.
executor/types/config.go Added OracleBridgeExecutor field to Config struct.
go.mod Updated github.com/initia-labs/OPinit dependency version from v0.5.2 to v0.5.7.
node/broadcaster/account.go Introduced BroadcasterAccount struct with various methods for transaction handling.
node/broadcaster/account_retriever.go Added methods for querying account information from a blockchain.
node/broadcaster/broadcaster.go Updated Broadcaster struct to handle multiple keyring configurations.
node/broadcaster/db.go Modified methods to handle pending transactions and processed messages using Timestamp instead of Sequence.
node/broadcaster/process.go Added IsTxNotFoundErr function for improved error handling.
node/broadcaster/status.go Introduced methods for retrieving broadcaster status.
node/broadcaster/types/config.go Reorganized function fields from BroadcasterConfig to KeyringConfig.
node/broadcaster/types/db.go Added Sender field to PendingTxInfo and ProcessedMsgs types.
node/broadcaster/types/keys.go Updated PrefixedPendingTx function parameter from sequence to timestamp.
node/broadcaster/types/status.go Added new data structures for broadcaster status.
node/node.go Updated Initialize method to accept a slice of btypes.KeyringConfig. Removed GetStatus method.
node/process.go Enhanced error handling in txChecker method.
node/status.go Introduced new GetStatus method in Node struct.
node/types/status.go Updated Broadcaster field type in Status struct to use *btypes.BroadcasterStatus.
provider/child/child.go Updated msgQueue field type to a map for structured message handling.
provider/child/msgs.go Updated GetMsgFinalizeTokenDeposit and GetMsgUpdateOracle methods to return an additional string value.
provider/child/query.go Removed GetAddress and GetAddressStr methods. Added new methods for querying grants.
provider/host/host.go Updated msgQueue field type to a map for structured message handling.
provider/host/msgs.go Updated GetMsgProposeOutput and CreateBatchMsg methods to return an additional string value.
provider/host/query.go Removed GetAddress and GetAddressStr methods.

Possibly related PRs

  • Fix/limit max msgs #36: The changes in the endBlockHandler method in both the main PR and this PR involve modifications to how messages are processed, specifically focusing on batching and handling messages in chunks, indicating a related approach to message management.

Suggested reviewers

  • beer-1

🐇 Hopping through the code, what a sight to see,
Changes galore, as bright as can be!
With messages structured, and senders in tow,
Our rabbit team leaps, making features glow!
From configs to handlers, we dance with delight,
In the world of code, everything feels right! 🐾✨

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

level=warning msg="The linter 'exportloopref' is deprecated (since v1.60.2) due to: Since Go1.22 (loopvar) this linter is no longer relevant. Replaced by copyloopvar."


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@sh-cha sh-cha changed the base branch from main to fix/tx-checker November 18, 2024 08:22
@beer-1
Copy link
Member

beer-1 commented Nov 18, 2024

need to set Sender when you append processed message

like

executor/host/handler.go#62

func (h *Host) txHandler(_ context.Context, args nodetypes.TxHandlerArgs) error {
	if args.BlockHeight == args.LatestHeight && args.TxIndex == 0 {
		if msg, err := h.oracleTxHandler(args.BlockHeight, args.Tx); err != nil {
			return err
		} else if msg != nil {
			h.AppendProcessedMsgs(btypes.ProcessedMsgs{
				Msgs:      []sdk.Msg{msg},
				Timestamp: time.Now().UnixNano(),
				Save:      false,
			})
		}
	}
	return nil
}

provider/host/host.go Outdated Show resolved Hide resolved
provider/host/msgs.go Outdated Show resolved Hide resolved
provider/host/msgs.go Outdated Show resolved Hide resolved
Base automatically changed from fix/tx-checker to main November 18, 2024 12:41
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

🧹 Outside diff range and nitpick comments (3)
node/broadcaster/process.go (3)

20-22: Consider using sentinel errors instead of string matching

While the implementation works, string matching for error types can be fragile if error messages change. Consider defining sentinel errors or implementing error types that can be checked using type assertions.

Example approach:

// Define a custom error type
type TxNotFoundError struct {
    TxHash string
}

func (e *TxNotFoundError) Error() string {
    return fmt.Sprintf("tx (%s) not found", e.TxHash)
}

// Update the check function
func IsTxNotFoundErr(err error, txHash string) bool {
    if tnf, ok := err.(*TxNotFoundError); ok {
        return tnf.TxHash == txHash
    }
    return false
}

Line range hint 32-64: Review panic usage in error handling

The error handling logic is well-structured, but there are two panic calls that could be replaced with regular error returns for better error handling:

  1. Line 62: Panic on timeout
  2. Line 67: Panic on transaction failure

Consider returning these as errors instead of panicking to allow the caller to handle these cases gracefully.

Example approach:

- panic(fmt.Errorf("something wrong, pending txs are not processed for a long time; current block time: %s, pending tx processing time: %s", time.Now().UTC().String(), pendingTxTime.UTC().String()))
+ return nil, time.Time{}, fmt.Errorf("pending tx timeout: current block time: %s, pending tx processing time: %s", time.Now().UTC().String(), pendingTxTime.UTC().String())

137-147: Consider adding context support for cancellation

The channel operations are well-implemented, but the method could benefit from context support to allow for cancellation and timeout handling.

Example approach:

- func (b Broadcaster) BroadcastMsgs(msgs btypes.ProcessedMsgs) {
+ func (b Broadcaster) BroadcastMsgs(ctx context.Context, msgs btypes.ProcessedMsgs) {
    if b.txChannel == nil {
        return
    }

    select {
    case <-b.txChannelStopped:
    case b.txChannel <- msgs:
+   case <-ctx.Done():
+       return
    }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8b1daff and bded342.

📒 Files selected for processing (1)
  • node/broadcaster/process.go (7 hunks)
🔇 Additional comments (3)
node/broadcaster/process.go (3)

8-8: LGTM: Import required for string operations

The addition of the "strings" package is necessary for the new error checking functionality.


Line range hint 78-86: LGTM: Improved method signature

The change from accepting a sequence number to accepting the full PendingTxInfo provides better context and aligns with the PR objectives.


98-111: LGTM: Enhanced error handling with proper sender management

The changes properly implement the sender management mentioned in the PR objectives. The error handling is comprehensive with proper cleanup and retry logic.

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

🧹 Outside diff range and nitpick comments (6)
provider/child/msgs.go (1)

77-78: Consider splitting authorization logic

The function is handling multiple concerns: oracle message creation and authorization wrapping. Consider splitting these responsibilities for better maintainability.

Consider creating a separate helper method for wrapping messages with authorization, something like:

func (b BaseChild) wrapWithOracleAuth(msg sdk.Msg) (sdk.Msg, string, error) {
    oracleAddress, err := b.OracleAccountAddress()
    if err != nil {
        return nil, "", err
    }
    oracleAddressString, err := b.OracleAccountAddressString()
    if err != nil {
        return nil, "", err
    }
    authzMsgExec := authz.NewMsgExec(oracleAddress, []sdk.Msg{msg})
    return &authzMsgExec, oracleAddressString, nil
}
node/broadcaster/tx.go (5)

Line range hint 28-40: Consider wrapping errors for better context.

The error handling could be improved by wrapping errors with additional context when returning them.

Consider applying this change:

- return err
+ return errors.Wrap(err, "account sequence mismatch")

Line range hint 28-74: Consider splitting error handling into smaller, focused functions.

The handleMsgError function handles multiple types of errors (sequence mismatch, output index, ignorable errors). Consider splitting these into separate handler functions for better maintainability and testability.

Example structure:

func (b *Broadcaster) handleMsgError(err error, broadcasterAccount *BroadcasterAccount) error {
    if err := b.handleSequenceMismatch(err, broadcasterAccount); err != nil {
        return err
    }
    if err := b.handleOutputIndexError(err); err != nil {
        return err
    }
    return b.handleIgnorableErrors(err)
}

79-81: Improve error handling specificity.

The error wrapping could be more specific about which part of the simulation failed.

Consider this change:

- return errors.Wrapf(err, "simulation failed")
+ return errors.Wrapf(err, "failed to build transaction with messages: %v", data.GetMsgTypes())

Line range hint 84-89: Address TODO comment regarding error handling.

The TODO comment indicates that error handling for broadcast failures needs to be implemented.

Would you like me to help design a retry mechanism for handling broadcast failures? This could include:

  • Exponential backoff
  • Maximum retry attempts
  • Different handling strategies based on error types

Line range hint 76-122: Consider breaking down the handleProcessedMsgs function.

The function is handling multiple responsibilities including:

  • Transaction building
  • Broadcasting
  • Database operations
  • Pending transaction management

This could make it harder to maintain and test.

Consider splitting into smaller functions:

func (b *Broadcaster) handleProcessedMsgs(ctx context.Context, data btypes.ProcessedMsgs, broadcasterAccount *BroadcasterAccount) error {
    if err := b.buildAndBroadcastTx(ctx, data, broadcasterAccount); err != nil {
        return err
    }
    if err := b.cleanupProcessedMsgs(data.Timestamp); err != nil {
        return err
    }
    return b.handlePendingTx(data, broadcasterAccount)
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bded342 and d22889e.

📒 Files selected for processing (3)
  • node/broadcaster/process.go (7 hunks)
  • node/broadcaster/tx.go (5 hunks)
  • provider/child/msgs.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • node/broadcaster/process.go
🔇 Additional comments (3)
provider/child/msgs.go (2)

10-10: LGTM: Required import for authz functionality

The added import is necessary for the new authorization message handling.


Line range hint 21-44: LGTM: Improved sender tracking in GetMsgFinalizeTokenDeposit

The changes enhance message tracking by explicitly returning the sender's address. Error handling is comprehensive and maintains proper validation.

Let's verify the BaseAccountAddressString implementation:

✅ Verification successful

The verification shows that BaseAccountAddressString() is consistently implemented in both host and child providers, and it's used uniformly across the codebase for sender address retrieval. The implementation properly handles the ErrKeyNotSet error case, which aligns with the error handling in the reviewed code. Let's verify one final aspect - the error type being checked:


BaseAccountAddressString implementation and usage verified successfully

The implementation is consistent across the codebase:

  • Error type ErrKeyNotSet is properly defined in types/errors.go
  • Error handling pattern is uniform in all usages, returning empty values when key is not set
  • The method is correctly implemented in both host and child providers with proper error propagation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify BaseAccountAddressString implementation and its usage
# Expected: Find the implementation and any other usages for consistency

ast-grep --pattern 'func $_ BaseAccountAddressString() $_ {
  $$$
}'

# Also check for any other usages of this method
rg "BaseAccountAddressString()" -A 3

Length of output: 2417


Script:

#!/bin/bash
# Verify the ErrKeyNotSet error type definition and usage
rg "ErrKeyNotSet" -A 2

Length of output: 1656

node/broadcaster/tx.go (1)

Line range hint 101-108: Verify consistent sender handling across the codebase.

The sender is properly set in PendingTxInfo, but let's verify it's consistently handled in related components.

✅ Verification successful

Sender field handling is consistent across the codebase

The verification shows that the sender field is consistently handled throughout the broadcaster package:

  • Properly structured in both ProcessedMsgs and PendingTxInfo types
  • Correctly propagated from ProcessedMsgs to PendingTxInfo during transaction handling
  • Consistently used for account lookups and transaction processing
  • Properly included in string representations for logging
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent sender handling in related files

# Search for ProcessedMsgs struct usage and Sender field access
rg -A 5 "ProcessedMsgs.*Sender"

# Search for PendingTxInfo struct usage and Sender field access
rg -A 5 "PendingTxInfo.*Sender"

Length of output: 67


Script:

#!/bin/bash
# Let's try a different approach to verify sender handling

# Search for struct definitions and usages
rg -A 10 "type ProcessedMsgs struct"
rg -A 10 "type PendingTxInfo struct"

# Search for any sender-related field assignments
rg -l "Sender.*=" 

# Search for any methods that handle these types
ast-grep --pattern 'func $$$($_: $$$ProcessedMsgs$$$) { $$$ }'
ast-grep --pattern 'func $$$($_: $$$PendingTxInfo$$$) { $$$ }'

Length of output: 1722


Script:

#!/bin/bash
# Let's check how the Sender field is used in the codebase

# Check for Sender field usage in the broadcaster package
rg -B 3 -A 3 "\.Sender" node/broadcaster/

# Check for any methods that process these structs
rg -B 3 -A 3 "ProcessedMsgs|PendingTxInfo" node/broadcaster/tx.go

# Look for any validation or processing of sender
rg -B 3 -A 3 "sender" node/broadcaster/tx.go

Length of output: 5083

provider/child/msgs.go Show resolved Hide resolved
provider/child/msgs.go Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (1)
merkle/merkle.go (1)

313-316: Consider clarifying the error message for out-of-range indices.

The split conditions improve error handling clarity. However, the second error message "tree containing the leaf has not been finalized yet" might be misleading when the leaf index is simply beyond the tree's range.

Consider this alternative error message:

-		return nil, 0, nil, nil, fmt.Errorf("the tree containing the leaf (`%d`) has not been finalized yet", leafIndex)
+		return nil, 0, nil, nil, fmt.Errorf("leaf index (`%d`) exceeds the tree's range (start: %d, count: %d)", leafIndex, treeInfo.StartLeafIndex, treeInfo.LeafCount)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d22889e and 3ec9bfd.

📒 Files selected for processing (1)
  • merkle/merkle.go (1 hunks)

merkle/merkle.go Show resolved Hide resolved
Copy link
Member

@beer-1 beer-1 left a comment

Choose a reason for hiding this comment

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

LGTM with minor comments

* introduce authz tx msg command

* update readme

* format

* update evm version

* can disable to relay oracle data by emptying oracle-bridge-executor
@sh-cha sh-cha merged commit 88491e9 into main Nov 19, 2024
5 of 6 checks passed
@sh-cha sh-cha deleted the feat/split-oracletx branch November 19, 2024 05:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants