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(rfq-api): check both relayer role and quoter role #3399

Merged
merged 7 commits into from
Nov 22, 2024

Conversation

dwasse
Copy link
Collaborator

@dwasse dwasse commented Nov 18, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced role management for relayers, including the introduction of a new quoterRole.
    • Updated role verification process to allow for more flexible checks based on provided roles.
  • Bug Fixes

    • Improved error messages for role checks to provide more context in case of failures.
  • Documentation

    • Adjusted comments for clarity and consistency regarding role-checking logic.

Copy link
Contributor

coderabbitai bot commented Nov 18, 2024

Walkthrough

The changes made in this pull request primarily focus on the QuoterAPIServer struct and its methods in the services/rfq/api/rest/server.go file, specifically altering the role verification logic to include parameters for QUOTER_ROLE and RELAYER_ROLE. Additionally, the error handling within the checkRole method has been refined. In the services/rfq/e2e/setup_test.go file, the role management in the setupRelayer method has been updated to reflect the new role names and logic, including the introduction of a quoterRole.

Changes

File Change Summary
services/rfq/api/rest/server.go Updated checkRole method to accept a role parameter and refined error handling. Modified checkRoleParallel and AuthMiddleware logic.
services/rfq/e2e/setup_test.go Renamed relayerRole to proverRole in setupRelayer method, introduced quoterRole, and updated error handling and role-granting logic. Added transaction confirmation for granting the quoter role.

Possibly related PRs

Suggested labels

size/s

Suggested reviewers

  • aureliusbtc
  • trajan0x

🐰 In the meadow, roles do play,
Quoters shine in a brand new way.
With checks refined, and errors clear,
The server hops with joyful cheer!
Roles now dance, a merry tune,
In the RFQ sun, we’ll all be in bloom! 🌼

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.61.0)

level=warning msg="[config_reader] The configuration option run.skip-files is deprecated, please use issues.exclude-files."
level=warning msg="[config_reader] The configuration option run.skip-dirs is deprecated, please use issues.exclude-dirs."
level=warning msg="[config_reader] The configuration option run.skip-dirs-use-default is deprecated, please use issues.exclude-dirs-use-default."
level=warning msg="[lintersdb] The linter "maligned" is deprecated (step 2) and deactivated. It should be removed from the list of disabled linters. https://golangci-lint.run/product/roadmap/#linter-deprecation-cycle"
level=warning msg="[lintersdb] The linter "exhaustivestruct" is deprecated (step 2) and deactivated. It should be removed from the list of disabled linters. https://golangci-lint.run/product/roadmap/#linter-deprecation-cycle"
level=warning msg="[lintersdb] The linter "ifshort" is deprecated (step 2) and deactivated. It should be removed from the list of disabled linters. https://golangci-lint.run/product/roadmap/#linter-deprecation-cycle"
level=warning msg="[lintersdb] The linter "interfacer" is deprecated (step 2) and deactivated. It should be removed from the list of disabled linters. https://golangci-lint.run/product/roadmap/#linter-deprecation-cycle"
level=warning msg="[lintersdb] The linter "nosnakecase" is deprecated (step 2) and deactivated. It should be removed from the list of disabled linters. https://golangci-lint.run/product/roadmap/#linter-deprecation-cycle"
level=warning msg="[lintersdb] The name "goerr113" is deprecated. The linter has been renamed to: err113."
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."
level=warning msg="The linter 'execinquery' is deprecated (since v1.58.0) due to: The repository of the linter has been archived by the owner. "


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 67e96e0 and d5b702e.

📒 Files selected for processing (1)
  • services/rfq/api/rest/server.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • services/rfq/api/rest/server.go

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.

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.

@github-actions github-actions bot added go Pull requests that update Go code size/l labels Nov 18, 2024
Copy link

cloudflare-workers-and-pages bot commented Nov 18, 2024

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 67e96e0
Status: ✅  Deploy successful!
Preview URL: https://ac8fffd6.sanguine-fe.pages.dev
Branch Preview URL: https://feat-quoter-role-no-relayer.sanguine-fe.pages.dev

View logs

Copy link

codecov bot commented Nov 18, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 24.77410%. Comparing base (8edcb7b) to head (d5b702e).
Report is 1 commits behind head on feat/relayer-arb-call.

❗ There is a different number of reports uploaded between BASE (8edcb7b) and HEAD (d5b702e). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (8edcb7b) HEAD (d5b702e)
solidity 1 0
Additional details and impacted files
@@                       Coverage Diff                       @@
##           feat/relayer-arb-call       #3399         +/-   ##
===============================================================
- Coverage               31.14179%   24.77410%   -6.36769%     
===============================================================
  Files                        105         208        +103     
  Lines                       4274       13280       +9006     
  Branches                      82          82                 
===============================================================
+ Hits                        1331        3290       +1959     
- Misses                      2937        9708       +6771     
- Partials                       6         282        +276     
Flag Coverage Δ
opbot 0.18282% <ø> (ø)
packages 90.44834% <ø> (ø)
promexporter 6.81642% <ø> (ø)
solidity ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.


🚨 Try these New Features:

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 (2)
services/rfq/api/rest/server.go (1)

Line range hint 366-368: Improve error message clarity for role verification failure.

The error message "relayer not an on-chain relayer" is misleading as it doesn't reflect that we're checking for either quoter or relayer role.

Consider updating the error message:

-return addressRecovered, fmt.Errorf("relayer not an on-chain relayer")
+return addressRecovered, fmt.Errorf("address %s does not have required roles (quoter or relayer)", addressRecovered.Hex())
services/rfq/e2e/setup_test.go (1)

370-370: Enhance error messages with more context

The error messages could be more descriptive to aid in debugging. Consider including the address of the relayer wallet in the error messages.

-					return fmt.Errorf("could not get prover role: %w", err)
+					return fmt.Errorf("could not get prover role for relayer %s: %w", i.relayerWallet.Address(), err)

-					return fmt.Errorf("could not grant prover role: %w", err)
+					return fmt.Errorf("could not grant prover role to relayer %s: %w", i.relayerWallet.Address(), err)

-					return fmt.Errorf("could not get quoter role: %w", err)
+					return fmt.Errorf("could not get quoter role for relayer %s: %w", i.relayerWallet.Address(), err)

-					return fmt.Errorf("could not grant quoter role: %w", err)
+					return fmt.Errorf("could not grant quoter role to relayer %s: %w", i.relayerWallet.Address(), err)

Also applies to: 375-375, 381-381, 386-386

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 14ed93d and acb1919.

📒 Files selected for processing (2)
  • services/rfq/api/rest/server.go (1 hunks)
  • services/rfq/e2e/setup_test.go (1 hunks)
🔇 Additional comments (2)
services/rfq/api/rest/server.go (2)

347-354: 🛠️ Refactor suggestion

Verify role constant usage and error handling in the role checking logic.

The role checking implementation has the following concerns:

  1. The role constants are hardcoded strings. Consider defining them as package-level constants to ensure consistency and prevent typos.
  2. The error handling could be more specific when the quoter role check fails, as it silently falls back to checking the relayer role.
  3. The error message "unable to check relayer role on-chain" is misleading when checking the quoter role fails.

Consider applying these improvements:

+const (
+    QUOTER_ROLE  = "QUOTER_ROLE"
+    RELAYER_ROLE = "RELAYER_ROLE"
+)

-quoterRole := crypto.Keccak256Hash([]byte("QUOTER_ROLE"))
-hasRole, err = bridge.HasRole(ops, quoterRole, addressRecovered)
-if err != nil {
-    relayerRole := crypto.Keccak256Hash([]byte("RELAYER_ROLE"))
-    hasRole, err = bridge.HasRole(ops, relayerRole, addressRecovered)
-    if err != nil {
-        return addressRecovered, fmt.Errorf("unable to check relayer role on-chain: %w", err)
-    }
-}
+quoterRole := crypto.Keccak256Hash([]byte(QUOTER_ROLE))
+hasRole, err = bridge.HasRole(ops, quoterRole, addressRecovered)
+if err != nil {
+    return addressRecovered, fmt.Errorf("unable to check quoter role on-chain: %w", err)
+}
+if !hasRole {
+    relayerRole := crypto.Keccak256Hash([]byte(RELAYER_ROLE))
+    hasRole, err = bridge.HasRole(ops, relayerRole, addressRecovered)
+    if err != nil {
+        return addressRecovered, fmt.Errorf("unable to check relayer role on-chain: %w", err)
+    }
+}

Let's verify the role constant usage across the codebase:


Line range hint 358-364: Refine role caching strategy to handle multiple roles.

The current caching implementation has a potential issue: it doesn't distinguish between quoter and relayer roles in the cache key. This could lead to incorrect role verification when an address has one role but not the other.

Consider using role-specific cache keys:

-r.roleCache[destChainID].Set(addressRecovered.Hex(), hasRole, cacheInterval)
+cacheKey := fmt.Sprintf("%s-%s", addressRecovered.Hex(), "QUOTER_ROLE")
+r.roleCache[destChainID].Set(cacheKey, hasRole, cacheInterval)

Let's verify the cache usage:

Comment on lines +368 to +386
proverRole, err := rfqContract.PROVERROLE(&bind.CallOpts{Context: i.GetTestContext()})
if err != nil {
return fmt.Errorf("could not get relayer role: %w", err)
return fmt.Errorf("could not get prover role: %w", err)
}

tx, err := rfqContract.GrantRole(txContext.TransactOpts, relayerRole, i.relayerWallet.Address())
tx, err := rfqContract.GrantRole(txContext.TransactOpts, proverRole, i.relayerWallet.Address())
if err != nil {
return fmt.Errorf("could not grant role: %w", err)
return fmt.Errorf("could not grant prover role: %w", err)
}
backend.WaitForConfirmation(i.GetTestContext(), tx)

quoterRole, err := rfqContract.QUOTERROLE(&bind.CallOpts{Context: i.GetTestContext()})
if err != nil {
return fmt.Errorf("could not get quoter role: %w", err)
}

tx, err = rfqContract.GrantRole(txContext.TransactOpts, quoterRole, i.relayerWallet.Address())
if err != nil {
return fmt.Errorf("could not grant quoter role: %w", err)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor role granting logic to reduce duplication

The role granting logic is duplicated for both prover and quoter roles. Consider extracting this into a helper function to improve maintainability and reduce code duplication.

+func (i *IntegrationSuite) grantRole(backend backends.SimulatedTestBackend, rfqContract *fastbridge.FastBridge, txContext base.TxContext, roleGetter func(*bind.CallOpts) ([32]byte, error), address common.Address) error {
+	role, err := roleGetter(&bind.CallOpts{Context: i.GetTestContext()})
+	if err != nil {
+		return fmt.Errorf("could not get role for address %s: %w", address, err)
+	}
+
+	tx, err := rfqContract.GrantRole(txContext.TransactOpts, role, address)
+	if err != nil {
+		return fmt.Errorf("could not grant role to address %s: %w", address, err)
+	}
+	backend.WaitForConfirmation(i.GetTestContext(), tx)
+	return nil
+}

 func (i *IntegrationSuite) setupRelayer() {
   // ...
-				proverRole, err := rfqContract.PROVERROLE(&bind.CallOpts{Context: i.GetTestContext()})
-				if err != nil {
-					return fmt.Errorf("could not get prover role: %w", err)
-				}
-
-				tx, err := rfqContract.GrantRole(txContext.TransactOpts, proverRole, i.relayerWallet.Address())
-				if err != nil {
-					return fmt.Errorf("could not grant prover role: %w", err)
-				}
-				backend.WaitForConfirmation(i.GetTestContext(), tx)
-
-				quoterRole, err := rfqContract.QUOTERROLE(&bind.CallOpts{Context: i.GetTestContext()})
-				if err != nil {
-					return fmt.Errorf("could not get quoter role: %w", err)
-				}
-
-				tx, err = rfqContract.GrantRole(txContext.TransactOpts, quoterRole, i.relayerWallet.Address())
-				if err != nil {
-					return fmt.Errorf("could not grant quoter role: %w", err)
-				}
-				backend.WaitForConfirmation(i.GetTestContext(), tx)
+				if err := i.grantRole(backend, rfqContract, txContext, rfqContract.PROVERROLE, i.relayerWallet.Address()); err != nil {
+					return err
+				}
+
+				if err := i.grantRole(backend, rfqContract, txContext, rfqContract.QUOTERROLE, i.relayerWallet.Address()); err != nil {
+					return err
+				}
   // ...
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
proverRole, err := rfqContract.PROVERROLE(&bind.CallOpts{Context: i.GetTestContext()})
if err != nil {
return fmt.Errorf("could not get relayer role: %w", err)
return fmt.Errorf("could not get prover role: %w", err)
}
tx, err := rfqContract.GrantRole(txContext.TransactOpts, relayerRole, i.relayerWallet.Address())
tx, err := rfqContract.GrantRole(txContext.TransactOpts, proverRole, i.relayerWallet.Address())
if err != nil {
return fmt.Errorf("could not grant role: %w", err)
return fmt.Errorf("could not grant prover role: %w", err)
}
backend.WaitForConfirmation(i.GetTestContext(), tx)
quoterRole, err := rfqContract.QUOTERROLE(&bind.CallOpts{Context: i.GetTestContext()})
if err != nil {
return fmt.Errorf("could not get quoter role: %w", err)
}
tx, err = rfqContract.GrantRole(txContext.TransactOpts, quoterRole, i.relayerWallet.Address())
if err != nil {
return fmt.Errorf("could not grant quoter role: %w", err)
if err := i.grantRole(backend, rfqContract, txContext, rfqContract.PROVERROLE, i.relayerWallet.Address()); err != nil {
return err
}
if err := i.grantRole(backend, rfqContract, txContext, rfqContract.QUOTERROLE, i.relayerWallet.Address()); err != nil {
return err
}
```
Note: The helper function `grantRole` should be added to the `IntegrationSuite` struct's methods:
```go
func (i *IntegrationSuite) grantRole(backend backends.SimulatedTestBackend, rfqContract *fastbridge.FastBridge, txContext base.TxContext, roleGetter func(*bind.CallOpts) ([32]byte, error), address common.Address) error {
role, err := roleGetter(&bind.CallOpts{Context: i.GetTestContext()})
if err != nil {
return fmt.Errorf("could not get role for address %s: %w", address, err)
}
tx, err := rfqContract.GrantRole(txContext.TransactOpts, role, address)
if err != nil {
return fmt.Errorf("could not grant role to address %s: %w", address, err)
}
backend.WaitForConfirmation(i.GetTestContext(), tx)
return nil
}

Copy link
Collaborator

@ChiTimesChi ChiTimesChi left a comment

Choose a reason for hiding this comment

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

Highlighting a race condition for checking roles

Comment on lines 365 to 372
g.Go(func() error {
v1Addr, v1Err = r.checkRole(c, destChainID, true)
v1Addr, v1Err = r.checkRole(c, destChainID, true, quoterRole)
return v1Err
})
g.Go(func() error {
v1Addr, v1Err = r.checkRole(c, destChainID, true, relayerRole)
return v1Err
})
Copy link
Collaborator

Choose a reason for hiding this comment

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

The cache is contract-specific, but not binded to a role. So what likely to happen here is that we check for two different roles in the same contract, one check will result in the actual RPC call, while the second one will just reuse the cached value. Since we don't really need to check multiple roles in the same contract, I suggest to leave the role cache as is. Instead, let's only check for RELAYER_ROLE in V1 and for QUOTER_ROLE in V2. This also helps with the future cleanup once the V1 is fully deprecated.

Copy link
Collaborator

Choose a reason for hiding this comment

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

This could also lead to race conditions between two go routines

@dwasse dwasse merged commit 884d9ae into feat/relayer-arb-call Nov 22, 2024
42 of 43 checks passed
@dwasse dwasse deleted the feat/quoter-role-no-relayer branch November 22, 2024 17:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants