Skip to content
New issue

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

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

Already on GitHub? # to your account

chore: update api remove callback #53

Merged
merged 24 commits into from
Oct 21, 2024

Conversation

foxytanuki
Copy link
Member

@foxytanuki foxytanuki commented Oct 17, 2024

related:

I tested with:

go test ./src/go/... ./test/... -count=1

also don't forget to run:

forge test

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced Continuous Integration (CI) workflow to include the dev branch.
    • New shell script for generating Go bindings from Solidity contracts.
    • New build targets added for Solidity and Go bindings in the build process.
  • Improvements

    • Updated API documentation for clarity and consistency regarding signature algorithms.
    • Simplified transaction handling and error management in the smart contract.
    • Streamlined test setup and improved modularity in test cases.
  • Bug Fixes

    • Adjusted account management functions for better error handling and clarity.
  • Chores

    • Updated .gitignore to include new directories for ignored files.

Copy link

coderabbitai bot commented Oct 17, 2024

Walkthrough

The changes in this pull request include updates to the Continuous Integration (CI) workflow to trigger on the dev branch, modifications to the .gitignore file to ignore additional directories, and significant updates to the Makefile, enhancing build targets related to Solidity and Go. The API documentation has been revised to replace the Curve field with SignatureAlgorithm, reflecting changes in the underlying data structures. Additionally, several Solidity contracts and associated tests have been refactored for improved error handling and clarity, with new scripts introduced for generating Go bindings from Solidity contracts.

Changes

File Path Change Summary
.github/workflows/ci.yaml Updated CI triggers to include dev branch alongside main.
.gitignore Added entries for cache/ and out/; removed -go entry.
Makefile Updated Docker Compose references; added targets build-solidity-extra and gen-solidity-go-bindings.
docs/api.md Replaced Curve with SignatureAlgorithm in API documentation; updated Account struct and added new enum values.
scripts/utils/gen-solidity-go-bindings.sh Introduced a new script for generating Go bindings for Solidity contracts.
src/go/server/server.go Enhanced server functionality with new fields and methods for interacting with Ethereum contracts; refactored transaction handling.
src/go/server/server_test.go Restructured test setup; introduced new helper functions and updated test cases for account management.
src/proto/api/v1/transferable_account.proto Updated Account struct to replace curve with signature_algorithm and removed Curve enum; added SignatureAlgorithm enum.
src/solidity/TransferableAccountStore.sol Removed onlyUnlocked modifier; updated functions to improve error handling and simplified control flow.
src/solidity/interfaces/ITransferableAccountStore.sol Replaced Curve enum with SignatureAlgorithm; updated function signatures to remove return types.
test/TransferableAccountStore.t.sol Simplified test cases by removing callbacks; updated to reflect changes in function signatures and parameters.
test/integration/auth_test.go Updated signature type in TestAuth function to reflect new structure.

Possibly related issues

🐰 In a meadow where the code does flow,
Changes bloom like flowers that grow.
From Curve to SignatureAlgorithm, we leap,
In the world of contracts, our promises we keep.
With tests refined and CI in tune,
Let's hop along, under the bright moon! 🌙


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 243e354 and 78a5e49.

⛔ Files ignored due to path filters (3)
  • src/go/pb/api/v1/transferable_account.pb.go is excluded by !**/*.pb.go
  • src/go/pb/google/api/annotations.pb.go is excluded by !**/*.pb.go
  • src/go/pb/google/api/http.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (12)
  • .github/workflows/ci.yaml (1 hunks)
  • .gitignore (0 hunks)
  • Makefile (2 hunks)
  • docs/api.md (3 hunks)
  • scripts/utils/gen-solidity-go-bindings.sh (1 hunks)
  • src/go/server/server.go (9 hunks)
  • src/go/server/server_test.go (17 hunks)
  • src/proto/api/v1/transferable_account.proto (1 hunks)
  • src/solidity/TransferableAccountStore.sol (7 hunks)
  • src/solidity/interfaces/ITransferableAccountStore.sol (2 hunks)
  • test/TransferableAccountStore.t.sol (11 hunks)
  • test/integration/auth_test.go (2 hunks)
💤 Files with no reviewable changes (1)
  • .gitignore
✅ Files skipped from review due to trivial changes (1)
  • scripts/utils/gen-solidity-go-bindings.sh
🧰 Additional context used
🪛 Markdownlint
docs/api.md

34-34: Expected: 2; Actual: 4
Unordered list indentation

(MD007, ul-indent)

🔇 Additional comments (33)
.github/workflows/ci.yaml (2)

Line range hint 63-64: Consider enabling tests in CI

The test step is currently commented out in the CI workflow. Running tests as part of CI is crucial for maintaining code quality and catching regressions early.

Could you clarify why the tests are currently disabled? If there are no blocking issues, I recommend uncommenting and enabling the test step:

-      # - name: Test
-      #   run: make test
+      - name: Test
+        run: make test

If there are specific reasons for disabling tests, consider adding a TODO comment explaining why and when they should be re-enabled.


Line range hint 1-80: Verify compatibility with related PRs

The PR description mentions related pull requests #44 and #47. It's important to ensure that the changes in this PR are compatible with those previous updates.

To verify compatibility, you can run the following script:

This script will help identify any potential conflicts or areas that might need attention due to the changes in the related PRs. Please review the output and ensure that all necessary adjustments have been made to maintain compatibility.

Makefile (4)

11-11: LGTM: Consistent change with devnet-up target.

The docker compose file name change is consistent with the change made in the devnet-up target. This ensures that both up and down operations use the same file.


94-94: Verify the local docker compose file renaming.

The change from local.compose.yaml to compose.local.yaml is consistent with the naming convention used in other targets. This improves overall consistency in the project.

Please run the following script to ensure the file has been renamed correctly and there are no lingering references to the old filename:

#!/bin/bash
# Description: Verify local docker compose file renaming and check for any remaining references.

# Test 1: Check if the new file exists
if [ -f "compose.local.yaml" ]; then
    echo "New file 'compose.local.yaml' exists."
else
    echo "Error: 'compose.local.yaml' not found."
fi

# Test 2: Check if the old file still exists (it shouldn't)
if [ -f "local.compose.yaml" ]; then
    echo "Warning: Old file 'local.compose.yaml' still exists."
else
    echo "Old file 'local.compose.yaml' has been removed."
fi

# Test 3: Search for any remaining references to the old filename
echo "Searching for any remaining references to 'local.compose.yaml':"
rg "local\.compose\.yaml"

20-21: Verify the Go bindings generation script.

The new gen-solidity-go-bindings target is a good addition, likely using the ABI files generated by build-solidity-extra to create Go bindings for the Solidity contracts.

Please run the following script to verify the existence and permissions of the Go bindings generation script:

#!/bin/bash
# Description: Verify the existence and permissions of the Go bindings generation script.

SCRIPT_PATH="./scripts/utils/gen-solidity-go-bindings.sh"

# Test 1: Check if the script exists
if [ -f "$SCRIPT_PATH" ]; then
    echo "Script '$SCRIPT_PATH' exists."
else
    echo "Error: Script '$SCRIPT_PATH' not found."
    exit 1
fi

# Test 2: Check if the script is executable
if [ -x "$SCRIPT_PATH" ]; then
    echo "Script '$SCRIPT_PATH' is executable."
else
    echo "Warning: Script '$SCRIPT_PATH' is not executable. Consider running: chmod +x $SCRIPT_PATH"
fi

# Test 3: Display the first few lines of the script for a quick content check
echo "First few lines of the script:"
head -n 5 "$SCRIPT_PATH"

Additionally, consider adding a comment in the Makefile explaining the purpose of this target and its relationship to build-solidity-extra.


7-7: Verify the docker compose file renaming.

The docker compose file for the devnet has been renamed from suave-geth.compose.yaml to compose.geth.yaml. This change appears to be for consistency or clarity.

Please run the following script to ensure the file has been renamed correctly and there are no lingering references to the old filename:

✅ Verification successful

Docker compose file renaming verified.

The docker compose file has been successfully renamed from suave-geth.compose.yaml to compose.geth.yaml. The old file has been removed, and no remaining references to suave-geth.compose.yaml were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify docker compose file renaming and check for any remaining references.

# Test 1: Check if the new file exists
if [ -f "compose.geth.yaml" ]; then
    echo "New file 'compose.geth.yaml' exists."
else
    echo "Error: 'compose.geth.yaml' not found."
fi

# Test 2: Check if the old file still exists (it shouldn't)
if [ -f "suave-geth.compose.yaml" ]; then
    echo "Warning: Old file 'suave-geth.compose.yaml' still exists."
else
    echo "Old file 'suave-geth.compose.yaml' has been removed."
fi

# Test 3: Search for any remaining references to the old filename
echo "Searching for any remaining references to 'suave-geth.compose.yaml':"
rg "suave-geth\.compose\.yaml"

Length of output: 531


Script:

#!/bin/bash
# Description: Verify docker compose file renaming and check for any remaining references.

# Test 1: Check if the new file exists
if [ -f "compose.geth.yaml" ]; then
    echo "New file 'compose.geth.yaml' exists."
else
    echo "Error: 'compose.geth.yaml' not found."
fi

# Test 2: Check if the old file still exists (it shouldn't)
if [ -f "suave-geth.compose.yaml" ]; then
    echo "Warning: Old file 'suave-geth.compose.yaml' still exists."
else
    echo "Old file 'suave-geth.compose.yaml' has been removed."
fi

# Test 3: Search for any remaining references to the old filename
echo "Searching for any remaining references to 'suave-geth.compose.yaml':"
rg "suave-geth\.compose\.yaml"

Length of output: 463

test/integration/auth_test.go (2)

9-9: LGTM: New import added correctly.

The addition of the transferable_account_store package import, aliased as tas, is appropriate and aligns with the changes made in the rest of the file.


Line range hint 1-108: Overall impact: Minor refactoring with potential wider implications.

The changes in this file appear to be part of a larger refactoring effort, specifically updating the API to remove a callback as mentioned in the PR objectives. While the changes here are minimal and the test logic remains intact, it's important to ensure that these updates are consistent across the entire codebase.

To maintain consistency and prevent potential issues:

  1. Review the results of the verification script for TimedSignature usage.
  2. Ensure that all related files (especially those mentioned in PR Reduce callback function #44 and Update timed signature #47) have been updated to use the new tas.SignatureVerifierTimedSignature type where appropriate.
  3. Verify that the verifyTimedSignature function in the taStoreContract is compatible with the new signature type.
  4. Consider adding a test case that specifically checks for any behavioral changes introduced by this refactoring.

To help with this verification, please run the following script to check for usage of the verifyTimedSignature function:

Review the results to ensure that all calls to verifyTimedSignature are updated if necessary.

✅ Verification successful

Verification Successful: No Removed or Replaced Code Detected

The executed shell script confirmed that verifyTimedSignature is consistently used across relevant test files and within the transferable_account_store.go contract. There are no instances of removed or replaced code in the specified lines of test/integration/auth_test.go.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for verifyTimedSignature usage in the codebase

echo "Searching for verifyTimedSignature usage:"
rg --type go "verifyTimedSignature"

Length of output: 30126

src/solidity/interfaces/ITransferableAccountStore.sol (4)

Line range hint 1-63: Overall LGTM. Verify impact on implementations and update documentation.

The changes to ITransferableAccountStore.sol are consistent and improve the interface's clarity. The main modifications include:

  1. Replacing Curve with SignatureAlgorithm in the Account struct.
  2. Adding a new SignatureAlgorithm enum.
  3. Removing returns (bytes memory) from several function signatures.

These changes appear to be part of a larger refactoring effort to improve the handling of signature algorithms.

To ensure a smooth transition:

  1. Verify that all implementations of this interface have been updated to reflect these changes.
  2. Update any documentation or comments related to the modified functions and struct.
  3. Review and update any code that depends on the return values of the modified functions.

Run the following script to find potential implementations that need updating:

#!/bin/bash
# Description: Find potential implementations of ITransferableAccountStore

# Test: Look for contract definitions that might implement ITransferableAccountStore
rg --type solidity -e "contract.*ITransferableAccountStore" -A 10

43-44: LGTM. Verify impact on dependent code.

The removal of the returns (bytes memory) clause from both deleteAccount and unlockAccount function signatures is consistent with the changes made to transferAccount. This modification simplifies the function interfaces.

Please ensure that any code depending on the previously returned values has been updated accordingly. Run the following script to check for potential issues:

✅ Verification successful

Please run the following script to verify the impact on dependent code:


Verified: No dependent code relies on the removed return values.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for uses of deleteAccount and unlockAccount that expect a return value

# Test: Look for assignments from deleteAccount and unlockAccount calls
rg --type solidity -e "=.*deleteAccount\s*\(" -e "=.*unlockAccount\s*\(" -e "deleteAccount.*returns" -e "unlockAccount.*returns" -A 5

Length of output: 168


Script:

# 
#!/bin/bash
# Description: Search for uses of deleteAccount and unlockAccount that expect a return value

# Test: Look for assignments from deleteAccount and unlockAccount calls in .sol files
rg -g "*.sol" -e "=.*deleteAccount\s*\(" -e "=.*unlockAccount\s*\(" -e "deleteAccount.*returns" -e "unlockAccount.*returns" -A 5

Length of output: 130


49-49: LGTM. Verify impact on dependent code.

The removal of the returns (bytes memory) clause from both approveAddress and revokeApproval function signatures is consistent with the changes made to other functions in this interface. This modification simplifies the function interfaces.

Please ensure that any code depending on the previously returned values has been updated accordingly. Run the following script to check for potential issues:

Also applies to: 54-54

✅ Verification successful

Verified: No dependent code relies on the removed returns (bytes memory) clause.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for uses of approveAddress and revokeApproval that expect a return value

# Test: Look for assignments from approveAddress and revokeApproval calls
rg --type solidity -e "=.*approveAddress\s*\(" -e "=.*revokeApproval\s*\(" -e "approveAddress.*returns" -e "revokeApproval.*returns" -A 5

Length of output: 194


Script:

#!/bin/bash
# Description: Search for usages of approveAddress and revokeApproval that expect a return value in Solidity files

# Test: Look for assignments from approveAddress and revokeApproval calls in .sol files
rg -g '*.sol' -e '=.*approveAddress\s*\(' -e '=.*revokeApproval\s*\(' -A 5

Length of output: 76


42-42: LGTM. Verify impact on dependent code.

The removal of the returns (bytes memory) clause from the transferAccount function signature is consistent with the described changes. This modification simplifies the function interface.

Please ensure that any code depending on the previously returned value has been updated accordingly. Run the following script to check for potential issues:

✅ Verification successful

Change Verified.

The removal of the returns (bytes memory) clause from the transferAccount function signature has been verified, and no dependent code relies on the returned value.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for uses of transferAccount that expect a return value

# Test: Look for assignments from transferAccount calls
rg --type solidity -e "=.*transferAccount\s*\(" -e "=.*transferAccount\s*\(" -e "transferAccount.*returns" -A 5

Length of output: 146


Script:

#!/bin/bash
# Description: Define solidity type and search for uses of transferAccount that expect a return value.

# Define 'solidity' type to include '.sol' files
rg --type-add 'solidity:*.sol' --type solidity -e "=.*transferAccount\s*\(" -e "transferAccount.*returns" -A 5

Length of output: 112


Script:

#!/bin/bash
# Description: Search for assignments of transferAccount's return value in Solidity files.

# Find all .sol files and search for lines where transferAccount is assigned to a variable
fd -e sol . | xargs grep -E '=\s*transferAccount\s*\(' -n

Length of output: 59

src/proto/api/v1/transferable_account.proto (1)

15-15: ⚠️ Potential issue

API Change: curve field replaced with signature_algorithm

The curve field in the Account message has been replaced with signature_algorithm. This change aligns with the PR objective of updating the API, providing a more general approach to specifying the signature method.

However, be aware that this change may break backwards compatibility:

  1. Existing clients expecting a curve field will need to be updated.
  2. The serialized format of the Account message will change.

Ensure that:

  1. All client code is updated to use signature_algorithm instead of curve.
  2. Any stored data using the old format is migrated or handled appropriately.
  3. API documentation is updated to reflect this change.

To verify the impact of this change, run the following script:

This will help identify any code that might need updating due to this change.

✅ Verification successful

Verification Successful: No usages of the old curve field found.

The replacement of the curve field with signature_algorithm does not affect existing clients, as there are no references to the curve field in the codebase outside of the protobuf definitions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of the old 'curve' field in the codebase
rg --type go --type rust --type python --type typescript 'curve.*=.*5' -g '!*.proto'

Length of output: 117


Script:

#!/bin/bash
# Search for usages of the old 'curve' field in the codebase
rg --type go --type rust --type py --type ts 'curve.*=.*5' -g '!*.proto'

Length of output: 74

docs/api.md (2)

61-61: Approve field name change

The change from 'curve' to 'signature_algorithm' in the Account struct is appropriate and consistent with the API updates. This new field name is more descriptive and accurately represents its purpose.


458-467: Approve addition of SignatureAlgorithm enumeration

The addition of the SignatureAlgorithm enumeration is well-structured and consistent with the API changes. It provides a clear set of options for signature algorithms, including an UNSPECIFIED value, which is a good practice. The order of the enumeration values is logical.

test/TransferableAccountStore.t.sol (6)

137-140: LGTM! Simplified approval process.

The removal of the callback mechanism and the direct call to approveAddress simplifies the code while maintaining the test's functionality. The assertion now directly checks the contract's state, which is a more accurate test of the approval process.


153-160: LGTM! Consistent simplification of account operations.

The changes in this segment follow the same pattern of removing callback functions and using direct calls. This simplification improves code readability and maintains consistency across the test suite.


176-181: LGTM! Consistent simplification of approval and revocation processes.

The changes in this segment continue the pattern of replacing callback functions with direct calls. This simplification improves code readability and maintains consistency across the test suite for approval and revocation operations.


235-240: LGTM! Consistent simplification of approval and revocation processes.

The changes in this segment continue the pattern of replacing callback functions with direct calls for approval and revocation operations. This simplification improves code readability and maintains consistency across the test suite.


Line range hint 246-261: LGTM! Simplified account deletion test.

The changes in this segment follow the consistent pattern of removing callback functions and using direct calls. The function name change and the direct call to deleteAccount improve code readability and maintain consistency with the other simplified tests.


Line range hint 265-335: LGTM! Improved test coverage with new locked account signing test.

The changes in the testUnlockAccount function follow the consistent pattern of removing callback functions and using direct calls, improving code readability.

The addition of the testSignWhenAccountIsLocked function is a valuable improvement to the test suite. It covers an important edge case, ensuring that signing operations are correctly restricted when an account is locked. This enhances the overall robustness of the test coverage.

src/solidity/TransferableAccountStore.sol (5)

133-138: Ensure Consistency in Access Control Checks

In revokeApproval, the function checks for ownership using isOwner. Verify that this is consistent with the expected behavior and that only the owner can revoke approvals. Additionally, consider using the same modifiers or patterns established elsewhere for access control.


185-187: Unused Variable Warning

In the createAccount function, after verifying the signature, ensure that all variables, especially keyData, are used appropriately and securely. Unused variables may lead to warnings or security issues.


255-264: Review the Use of onlyLocked Modifier

The unlockAccount function uses the onlyLocked(accountId) modifier. Since this function's purpose is to unlock an account, verify that this logic aligns with the intended behavior and that unauthorized access is prevented.


289-291: Access Control Verification

Ensure that the access control checks in the sign function are sufficient and that only authorized and approved users can perform the sign operation on unlocked accounts. This is critical for maintaining the security of the signing process.


111-120: Verify the Existence of onlyLocked Modifier

The function approveAddress is using the onlyLocked(accountId) modifier. Ensure that this modifier is properly defined in the contract since the onlyUnlocked modifier was removed. This is important to maintain the intended access control logic.

Run the following script to check for the definition of onlyLocked:

✅ Verification successful

Modifier onlyLocked Verified

The onlyLocked modifier is properly defined in src/solidity/TransferableAccountStore.sol at line 34. The access control logic remains intact as intended.

  • File: src/solidity/TransferableAccountStore.sol
  • Line: 34
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the `onlyLocked` modifier is defined.

# Test: Search for the definition of `onlyLocked`. Expect: Modifier definition exists.
rg --type solidity --no-heading --line-number '^.*modifier\s+onlyLocked\(.*\)' src/

Length of output: 118


Script:

#!/bin/bash
# Description: Re-verify the `onlyLocked` modifier definition by searching in all Solidity files.

rg --no-heading --line-number '^.*modifier\s+onlyLocked\(.*\)' --glob '*.sol' src/

Length of output: 180

src/go/server/server.go (7)

14-18: Necessary imports from Ethereum Go library are appropriately added.

The added imports are required for Ethereum client functionality and smart contract interactions introduced in the code.


26-26: Project-specific imports added correctly.

The imports for transferable_account_store, framework, and the updated protobuf package are necessary for the new functionalities.


33-37: New fields in server struct are well-integrated.

The addition of fr, taStoreContract, taStoreContractBind, auth, and client fields in the server struct are appropriate and necessary for Ethereum interactions.


47-48: Retrieving environment variables for contract address and private key.

The code correctly retrieves TA_STORE_CONTRACT_ADDRESS and PRIVATE_KEY from environment variables.


117-119: Avoid logging sensitive information in error messages.

When logging errors from NewServer, ensure that the error messages do not contain sensitive information such as private keys or other secrets. Verify that any errors that may include sensitive data are sanitized before logging.


199-201: Ensure consistent error handling and logging across transaction methods.

Similar to the TransferAccount method, other transaction methods should log errors with sufficient context to aid in debugging.


Line range hint 446-462: Updated populateTimedSignature function handles new types correctly.

The function now returns *tas.SignatureVerifierTimedSignature, aligning with changes in the underlying contract structure.


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.

@foxytanuki foxytanuki changed the base branch from main to dev October 17, 2024 15:24
Copy link

@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.

Caution

Inline review comments failed to post

Actionable comments posted: 9

🧹 Outside diff range and nitpick comments (17)
.github/workflows/ci.yaml (1)

5-5: LGTM: CI workflow now includes the dev branch

The addition of the dev branch to both push and pull_request events is a good practice. This change ensures that the CI pipeline runs for changes in both the main and dev branches, which can help catch issues earlier in the development process.

Consider the following suggestions to further improve your CI workflow:

  1. If you have a staging environment, you might want to add automatic deployments for the dev branch.
  2. Implement branch protection rules for both main and dev branches to ensure CI passes before merging.
  3. If not already in place, consider adding a step to your CI that creates and uploads build artifacts for easy testing and deployment.

Also applies to: 7-7

Makefile (1)

17-18: LGTM: New target for additional Solidity build outputs.

The new build-solidity-extra target is a valuable addition, generating ABI and binary files alongside the standard build. This is likely useful for other parts of the project, such as generating Go bindings.

Consider adding a comment explaining the purpose and use cases for this new target to improve maintainability.

test/integration/auth_test.go (1)

Further Action Required: Inconsistent TimedSignature Usage Detected

While the change in test/integration/auth_test.go correctly updates the sig variable type from *server.TimedSignature to *tas.SignatureVerifierTimedSignature, the search results indicate that server.TimedSignature is still used in multiple other files throughout the codebase.

  • scripts/e2e/main.go
  • src/go/server/server_test.go
  • src/go/contract/transferable_account_store/transferable_account_store.go

Please ensure that all instances of server.TimedSignature are reviewed and updated as necessary to maintain consistency and prevent potential compatibility issues.

🔗 Analysis chain

Line range hint 85-90: LGTM: Variable type updated correctly.

The change from *server.TimedSignature to *tas.SignatureVerifierTimedSignature aligns with the new import and likely reflects updates in the underlying implementation.

To ensure consistency across the codebase, please run the following script to check for any other occurrences of TimedSignature that might need updating:

Please review the results to determine if any other files need to be updated to use the new tas.SignatureVerifierTimedSignature type.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for other occurrences of TimedSignature in the codebase

# Test: Search for TimedSignature usage
echo "Searching for TimedSignature usage:"
rg --type go "TimedSignature"

# Test: Search for server.TimedSignature usage specifically
echo "Searching for server.TimedSignature usage:"
rg --type go "server\.TimedSignature"

Length of output: 30126

src/solidity/interfaces/ITransferableAccountStore.sol (2)

13-13: LGTM. Consider updating documentation.

The change from Curve curve to SignatureAlgorithm signatureAlgorithm in the Account struct is consistent with the overall refactoring. This modification improves clarity by explicitly stating that it's a signature algorithm rather than a generic curve.

Consider updating any relevant documentation or comments to reflect this change in terminology from "curve" to "signature algorithm".


17-20: LGTM. Consider adding a comment for UNSPECIFIED.

The addition of the SignatureAlgorithm enum is well-structured and aligns with the changes in the Account struct. The naming convention is clear and consistent.

Consider adding a brief comment explaining the purpose of the SignatureAlgorithm_UNSPECIFIED value. For example:

enum SignatureAlgorithm {
    SignatureAlgorithm_UNSPECIFIED, // Default value, indicates no algorithm set
    SignatureAlgorithm_ECDSA,
    SignatureAlgorithm_EDDSA
}
src/proto/api/v1/transferable_account.proto (2)

19-22: Approval: New SignatureAlgorithm enum added

The addition of the SignatureAlgorithm enum is a good improvement. It provides a clear and extensible way to specify signature algorithms, which aligns well with the change in the Account message.

Positive aspects:

  1. Follows Protocol Buffers naming conventions.
  2. Includes an UNSPECIFIED (0) value, which is a good practice.
  3. Covers common signature algorithms (ECDSA and EDDSA).

Suggestion for improvement:
Consider adding a comment to describe each enum value, especially explaining the difference between ECDSA and EDDSA for clarity. For example:

enum SignatureAlgorithm {
    SignatureAlgorithm_UNSPECIFIED = 0; // Default value when not set
    SignatureAlgorithm_ECDSA = 1;       // Elliptic Curve Digital Signature Algorithm
    SignatureAlgorithm_EDDSA = 2;       // Edwards-curve Digital Signature Algorithm
}

Line range hint 1-190: Summary: API updated to use SignatureAlgorithm

The changes in this file successfully update the API to use a more flexible SignatureAlgorithm instead of the previous Curve. This aligns well with the PR objective of updating the API and removing the callback.

Key points:

  1. The Account message now uses SignatureAlgorithm instead of Curve.
  2. A new SignatureAlgorithm enum has been added with appropriate values.

Recommendations:

  1. Ensure all client code is updated to use the new signature_algorithm field.
  2. Update any data storage or serialization code to handle the new format.
  3. Revise API documentation to reflect these changes.
  4. Consider adding comments to the SignatureAlgorithm enum for clarity.
  5. Implement and test a migration strategy for existing data.

Overall, these changes improve the API's flexibility and clarity. However, careful attention must be paid to maintaining backwards compatibility or providing a clear upgrade path for existing users of the API.

docs/api.md (1)

34-34: Approve change and fix indentation

The addition of 'SignatureAlgorithm' to the table of contents is correct and consistent with the API changes. However, the indentation needs to be adjusted.

Please fix the indentation of this line to match the other entries in the list. The expected indentation is 2 spaces, but the actual indentation is 4 spaces. Update the line as follows:

-    - [SignatureAlgorithm](#api-v1-SignatureAlgorithm)
+  - [SignatureAlgorithm](#api-v1-SignatureAlgorithm)
🧰 Tools
🪛 Markdownlint

34-34: Expected: 2; Actual: 4
Unordered list indentation

(MD007, ul-indent)

test/TransferableAccountStore.t.sol (2)

Line range hint 111-123: LGTM! Consider clarifying the assertion message.

The change from Curve to SignatureAlgorithm is consistent and aligns with the updated data structure. This modification improves the clarity of the account's signature verification method.

Consider updating the assertion message to be more specific:

-        assertEq(
-            uint256(signatureAlgorithm), uint256(decodedAccount.signatureAlgorithm), "Stored account curve should match"
-        );
+        assertEq(
+            uint256(signatureAlgorithm), uint256(decodedAccount.signatureAlgorithm), "Stored account signature algorithm should match"
+        );

220-222: LGTM! Consider updating the assertion message.

The change from Curve to SignatureAlgorithm in the assertion is consistent with the earlier modifications and reflects the updated data structure.

Consider updating the assertion message to be more specific:

        assertEq(
-           uint256(retrievedAccount.signatureAlgorithm), uint256(account.signatureAlgorithm), "Curve should match"
+           uint256(retrievedAccount.signatureAlgorithm), uint256(account.signatureAlgorithm), "Signature algorithm should match"
        );
src/solidity/TransferableAccountStore.sol (3)

116-118: Access Control Enhancement

The access control check uses isOwner to verify if the signer is the owner. Ensure that this function reliably determines ownership and consider emitting an event or logging when access is denied for better traceability.


119-120: Potential Optimization in Account ID Conversion

The use of Utils.iToHex(abi.encodePacked(accountId)) may introduce unnecessary overhead. If accountId is already in the desired format, consider removing redundant conversions to optimize gas usage.

Apply this diff if appropriate:

-emit AddressApproved(Utils.iToHex(abi.encodePacked(accountId)), _address);
+emit AddressApproved(accountId, _address);

244-246: Consistent Error Messages

For clarity and consistency, ensure that all error messages and event emissions use the same format and provide sufficient information for debugging. This might involve standardizing the message content or structure.

src/go/server/server.go (4)

70-105: Ensure secure handling of private keys.

In NewServer, the privateKey is passed as a string and used to create the Ethereum transactor. Storing and passing private keys as plain strings can pose security risks. Consider using secure methods for managing private keys, such as a secrets manager or integrating with a secure key storage service. Ensure that the private key is not logged or exposed in error messages.


123-132: Variable name gprcs may be a typo; consider renaming for clarity.

The variable gprcs seems to be a typo or may cause confusion. Consider renaming it to grpcServer or server to improve readability.

Apply this diff to rename the variable:

-	gprcs := grpc.NewServer()
+	grpcServer := grpc.NewServer()

And update all references accordingly:

-	pb.RegisterAccountServiceServer(gprcs, s)
+	pb.RegisterAccountServiceServer(grpcServer, s)

...

-	if err := gprcs.Serve(lis); err != nil {
+	if err := grpcServer.Serve(lis); err != nil {

195-195: Improve error logging for better context.

The error is logged as err: %v, which lacks context. Consider adding more descriptive messages to aid in debugging. Include the function name and a brief description of the operation.

Apply this diff:

-log.Printf("err: %v", err)
+log.Printf("TransferAccount: failed to populate timed signature: %v", err)

421-435: Include transaction hash in error message for failed transactions.

When a transaction fails, including the transaction hash in the error message can help with debugging and tracking issues.

Apply this diff:

if receipt.Status != types.ReceiptStatusSuccessful {
-	return nil, fmt.Errorf("transaction failed")
+	return nil, fmt.Errorf("transaction %s failed", tx.Hash().Hex())
}
🛑 Comments failed to post (9)
src/solidity/TransferableAccountStore.sol (6)

167-169: 🛠️ Refactor suggestion

Duplicate Signature Verification Logic

The signature verification logic is duplicated here. Refer to the earlier suggestion about creating a modifier to handle this check uniformly across all functions.


259-264: 🛠️ Refactor suggestion

Eliminate Redundant Signature Verification

As previously suggested, refactor the signature verification into a modifier to streamline the code and enhance readability.


283-291: ⚠️ Potential issue

Correct Error Name for Locked Account

In the sign function, the error OnlyUnlockAccount is raised when isAccountLocked(accountId) returns true. This might be confusing due to the naming. Consider renaming the error to AccountLocked or AccountIsLocked for better clarity.

Apply this diff to rename the error and update its usage:

 error OnlyApprovedAccount();
-error OnlyUnlockAccount();
+error AccountLocked();

 ...

 if (isAccountLocked(accountId)) {
-    revert OnlyUnlockAccount();
+    revert AccountLocked();
 }
📝 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.

        if (!verifyTimedSignature(timedSignature)) {
            revert InvalidTimedSignature();
        }
        if (!isApproved(accountId, timedSignature.signer)) {
            revert OnlyApprovedAccount();
        }
        if (isAccountLocked(accountId)) {
            revert AccountLocked();
        }

42-48: 🛠️ Refactor suggestion

Consistent Error Naming for Clarity

Consider renaming the OnlyUnlockAccount error to OnlyUnlockedAccount for consistency with the naming convention used in other error definitions like OnlyOwnerCanApproveAddresses and OnlyOwnerCanUnlockAccount. This enhances readability and consistency throughout the contract.

Apply this diff to rename the error:

 error InvalidTimedSignature();
 error OnlyOwnerCanApproveAddresses();
 error OnlyOwnerCanRevokeApproval();
 error OnlyOwnerCanDeleteAccount();
 error OnlyOwnerCanUnlockAccount();
 error OnlyApprovedAccount();
-error OnlyUnlockAccount();
+error OnlyUnlockedAccount();
📝 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.

    error InvalidTimedSignature();
    error OnlyOwnerCanApproveAddresses();
    error OnlyOwnerCanRevokeApproval();
    error OnlyOwnerCanDeleteAccount();
    error OnlyOwnerCanUnlockAccount();
    error OnlyApprovedAccount();
    error OnlyUnlockedAccount();

112-114: 🛠️ Refactor suggestion

Consolidate Repeated Signature Verification

The check for !verifyTimedSignature(timedSignature) and subsequent revert is repeated across multiple functions. Consider creating a modifier or a private function to handle this verification to reduce code duplication and improve maintainability.

Apply this diff to create a modifier for signature verification:

+modifier verifySignature(SignatureVerifier.TimedSignature calldata timedSignature) {
+    if (!verifyTimedSignature(timedSignature)) {
+        revert InvalidTimedSignature();
+    }
+    _;
+}

 function approveAddress(
     SignatureVerifier.TimedSignature calldata timedSignature,
     string memory accountId,
     address _address
-) external onlyLocked(accountId) {
-    if (!verifyTimedSignature(timedSignature)) {
-        revert InvalidTimedSignature();
-    }
+)
+    external
+    onlyLocked(accountId)
+    verifySignature(timedSignature)
+{
     Account storage account = accountsStore[accountId];
     if (!isOwner(accountId, timedSignature.signer)) {
         revert OnlyOwnerCanApproveAddresses();
     }
     accountApprovals[account.accountId] = _address;
     emit AddressApproved(Utils.iToHex(abi.encodePacked(accountId)), _address);
 }

Repeat this pattern for other functions where signature verification is performed.

Committable suggestion was skipped due to low confidence.


217-227: 🛠️ Refactor suggestion

Refactor Access Checks and Error Handling

The transferAccount function includes repeated access checks and error handling similar to other functions. Implement the suggested signature verification modifier and consider adding an access control modifier for approved accounts to reduce redundancy.

Apply this diff to create an onlyApproved modifier:

+modifier onlyApproved(string memory accountId, address signer) {
+    if (!isApproved(accountId, signer)) {
+        revert OnlyApprovedAccount();
+    }
+    _;
+}

 function transferAccount(
     SignatureVerifier.TimedSignature calldata timedSignature,
     string memory accountId,
     address to
-) public onlyLocked(accountId) {
-    if (!verifyTimedSignature(timedSignature)) {
-        revert InvalidTimedSignature();
-    }
-    if (!isApproved(accountId, timedSignature.signer)) {
-        revert OnlyApprovedAccount();
-    }
+)
+    public
+    onlyLocked(accountId)
+    verifySignature(timedSignature)
+    onlyApproved(accountId, timedSignature.signer)
+{
     Account storage account = accountsStore[accountId];
     account.owner = to;
     delete accountApprovals[account.accountId];
     emit AccountTransferred(accountId, account);
 }

Committable suggestion was skipped due to low confidence.

src/go/server/server_test.go (3)

24-27: ⚠️ Potential issue

Avoid using global variables in tests to ensure test isolation and prevent potential data races

Declaring s as a global variable can lead to concurrency issues when tests are run in parallel. Each test should have its own instance of server to maintain isolation and prevent shared state.


25-25: ⚠️ Potential issue

Avoid using global variables to store state in tests

Using accountId as a global variable can cause tests to interfere with each other, especially if tests are executed concurrently. Consider returning accountId from newAccount and passing it explicitly to test functions.


604-645: 🛠️ Refactor suggestion

Refactor helper functions to return errors instead of calling t.Fatalf

Calling t.Fatalf within helper functions can obscure the source of errors and halt the entire test suite. Instead, have helper functions return errors and handle them appropriately in the test functions.

Apply this diff to modify the helper functions:

-func newAccount(t *testing.T, privateKey *ecdsa.PrivateKey) *pb.Account {
+func newAccount(privateKey *ecdsa.PrivateKey) (*pb.Account, error) {
    sig := newTimedSignature(privateKey)
    receipt, err := s.taStoreContract.SendConfidentialRequest("createAccount", []interface{}{sig}, nil)
    if err != nil {
+       return nil, fmt.Errorf("failed to send confidential request: %v", err)
    }
    ev, err := s.taStoreContract.Abi.Events["AccountCreated"].ParseLog(receipt.Logs[0])
    if err != nil {
+       return nil, fmt.Errorf("failed to parse log: %v", err)
    }
    accountId := ev["accountId"].(string)

    return &pb.Account{
        AccountId: accountId,
        Owner:     crypto.PubkeyToAddress(privateKey.PublicKey).Hex(),
    }, nil
}

Update the calls to newAccount in your tests to handle the returned error:

-account := newAccount(t, privateKey)
+account, err := newAccount(privateKey)
+if err != nil {
+    t.Fatalf("failed to create new account: %v", err)
+}

Committable suggestion was skipped due to low confidence.

Copy link
Contributor

@peaceandwhisky peaceandwhisky left a comment

Choose a reason for hiding this comment

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

LGTM🍄

@peaceandwhisky peaceandwhisky merged commit 46a55ae into dev Oct 21, 2024
1 check passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 7, 2024
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Simplify Account Management by Removing Callback Functions
2 participants