Skip to content
This repository was archived by the owner on Feb 8, 2026. It is now read-only.

refactor: update vault storage implementation and clean up related code#55

Merged
johnnyluo merged 2 commits into
mainfrom
47-issue
May 20, 2025
Merged

refactor: update vault storage implementation and clean up related code#55
johnnyluo merged 2 commits into
mainfrom
47-issue

Conversation

@johnnyluo

@johnnyluo johnnyluo commented May 19, 2025

Copy link
Copy Markdown
Contributor

fixes #47

Summary by CodeRabbit

  • New Features

    • Added support for encrypted vault backups, including retrieval and decryption using a configurable encryption secret.
    • Introduced a new configuration option for specifying the encryption secret.
  • Refactor

    • Replaced previous vault storage logic with a new vault storage interface for improved handling of vault files.
    • Centralized vault retrieval and decryption for signature verification.
    • Updated signature verification to use derived public keys from decrypted vaults.
  • Dependency Updates

    • Updated core dependencies and removed unused indirect dependencies for a leaner installation.
  • Chores

    • Removed unused utility functions and cleaned up related imports.

Copilot AI review requested due to automatic review settings May 19, 2025 23:29
@coderabbitai

coderabbitai Bot commented May 19, 2025

Copy link
Copy Markdown
Contributor

"""

Walkthrough

The changes refactor vault storage handling by introducing a vaultStorage interface for vault operations, removing direct use of blockStorage. A new getVault method centralizes vault retrieval and decryption using an encryption secret from the configuration. Policy signature verification now derives the public key from the decrypted vault, ensuring signatures are validated against vault-derived keys. Several utility functions are removed as part of this refactor.

Changes

File(s) Change Summary
api/plugin.go Added getVault method to Server for vault retrieval/decryption. Updated SignPluginMessages and verifyPolicySignature to use vault-based logic and derived public key for signature verification.
api/server.go Replaced blockStorage with vaultStorage in Server struct and constructor. Updated all vault file operations to use vaultStorage. Removed pluginConfigs.
cmd/vultisigner/main.go Switched initialization from blockStorage to vaultStorage. Updated api.NewServer call accordingly. Removed pluginConfigs argument.
common/util.go Removed IsSubset, GetVaultName, and GetThreshold utility functions. Updated vaultBackupSuffix constant. Cleaned up imports.
config/config.go Added EncryptionSecret field to Config struct with appropriate tags.
go.mod Updated direct dependencies (verifier, vultiserver). Pruned many indirect dependencies.
internal/sigutil/signing.go Renamed and simplified VerifySignature to VerifyPolicySignature, removing vault public key derivation logic. Cleaned up imports.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant VaultStorage

    Client->>Server: Create/Update PluginPolicy (with publicKey, signature)
    Server->>VaultStorage: GetVault(publicKey)
    VaultStorage-->>Server: Encrypted vault data
    Server->>Server: Decrypt vault with EncryptionSecret
    Server->>Server: Derive public key from vault
    Server->>Server: Verify policy signature using derived public key
    Server-->>Client: Respond with verification result
Loading

Assessment against linked issues

Objective Addressed Explanation
Retrieve relevant vault when creating/updating PluginPolicy for signature validation (#47)

Poem

A vault now waits behind a key,
Decrypted with secrets, safe as can be.
Policies checked, signatures true,
With storage refactored, the code feels new!
The rabbit hops with pride and glee—
“Your vaults are safe, just trust in me!”
🐇🔐
"""

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

level=warning msg="[runner] Can't run linter goanalysis_metalinter: buildir: failed to load package session: could not load export data: no export data for "github.com/vultisig/go-wrappers/go-dkls/sessions""
level=error msg="Running error: can't run linter goanalysis_metalinter\nbuildir: failed to load package session: could not load export data: no export data for "github.com/vultisig/go-wrappers/go-dkls/sessions""

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

This PR refactors the vault storage implementation throughout the codebase and cleans up related utilities and dependencies.

  • Replaces BlockStorage usage with a new vault.Storage abstraction in CLI and server layers
  • Introduces EncryptionSecret in configuration and centralizes vault decryption in a shared helper
  • Cleans up unused utilities in common/util.go and trims indirect dependencies in go.mod

Reviewed Changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
internal/sigutil/signing.go Renamed signature verifier to VerifyPolicySignature and removed unused imports
go.mod Updated verifier/vultiserver versions and pruned indirect deps
config/config.go Added EncryptionSecret field to top-level Config
common/util.go Removed unused helpers and updated vaultBackupSuffix
cmd/vultisigner/main.go Switched from storage.NewBlockStorage to vault.NewBlockStorageImp
api/server.go Replaced blockStorage with vaultStorage and updated variable naming
api/plugin.go Added getVault helper, updated policy signature flow
Comments suppressed due to low confidence (3)

api/server.go:295

  • [nitpick] The variable name v is too short; consider renaming it to vaultData or similar for better readability.
v, err := common.DecryptVaultFromBackup(passwd, content)

internal/sigutil/signing.go:71

  • [nitpick] The parameter name messageHex suggests a hex-encoded string, but it takes raw bytes; consider renaming it to messageBytes or message.
func VerifyPolicySignature(publicKeyHex string, messageHex []byte, signature []byte) (bool, error) {

cmd/vultisigner/main.go:54

  • [nitpick] The suffix Imp in NewBlockStorageImp is unclear; consider renaming to NewBlockStorage or NewDefaultBlockStorage for consistency.
vaultStorage, err := vault.NewBlockStorageImp(cfg.BlockStorage)

Comment thread config/config.go
Comment thread common/util.go
Comment thread api/plugin.go Outdated
Comment thread api/plugin.go Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 comments (2)
api/plugin.go (1)

96-105: 🛠️ Refactor suggestion

Guard against empty / nil vault bytes returned from storage

vaultStorage.GetVault may legitimately return nil/[]byte{} together with err == nil (e.g. zero-sized object, mis-configured bucket ACL, etc.).
Passing this straight to DecryptVaultFromBackup will bubble up an opaque base-64 decode error.

-content, err := s.vaultStorage.GetVault(filePathName)
-if err != nil {
+content, err := s.vaultStorage.GetVault(filePathName)
+if err != nil {
     ...
 }
+
+if len(content) == 0 {
+    return fmt.Errorf("vault file %s is empty", filePathName)
+}

Repeating this check here and in server.go’s handlers will save a trip down the call-stack and deliver clearer diagnostics.

api/server.go (1)

331-341: 🛠️ Refactor suggestion

Nil vault bytes check (SignMessages)

Please replicate the same empty-content guard here to keep behaviour consistent across endpoints.

🧹 Nitpick comments (4)
api/plugin.go (2)

380-389: Verification path assumes ECDSA – will fail for EdDSA vaults

verifyPolicySignature derives the public key with:

derivedPublicKey, _ := tss.GetDerivedPubKey(vault.PublicKeyEcdsa, ...)

If the vault happens to be an EdDSA one (vault.PublicKeyEddsa), PublicKeyEcdsa is empty and GetDerivedPubKey returns an error, causing the whole signature check to fail.

Suggested defensive logic:

-var derivedPublicKey, err = tss.GetDerivedPubKey(vault.PublicKeyEcdsa, vault.HexChainCode, vcommon.Ethereum.GetDerivePath(), false)
+pk := vault.PublicKeyEcdsa
+isEdDSA := false
+if pk == "" {
+    pk = vault.PublicKeyEddsa
+    isEdDSA = true
+}
+derivedPublicKey, err := tss.GetDerivedPubKey(pk, vault.HexChainCode, vcommon.Ethereum.GetDerivePath(), isEdDSA)

Also, pass the same isEdDSA flag down to sigutil.VerifyPolicySignature if it supports EdDSA.


399-419: Improve error propagation & nil-content handling in getVault

  1. The wrapped error from storage is discarded:
return nil, fmt.Errorf("failed to get vault")

This loses the original cause, making troubleshooting harder.

  1. Empty content is only logged, but DecryptVaultFromBackup will panic on it.
-vaultContent, err := s.vaultStorage.GetVault(fileName)
-if err != nil {
-    ...
-    return nil, fmt.Errorf("failed to get vault")
-}
-if vaultContent == nil {
-    s.logger.Error("vault not found")
-    return nil, fmt.Errorf("vault not found")
-}
+vaultContent, err := s.vaultStorage.GetVault(fileName)
+if err != nil {
+    return nil, fmt.Errorf("failed to get vault: %w", err)
+}
+if len(vaultContent) == 0 {
+    return nil, fmt.Errorf("vault %s is empty", fileName)
+}

This keeps the original stack-trace and prevents obscure base-64 errors later on.

api/server.go (2)

40-42: Cross-module coupling introduced via verifier/vault

The plugin server now depends on github.com/vultisig/verifier/vault.
While technically fine, this increases compile-time coupling between the plugin and verifier repos and can result in circular-dependency headaches if both evolve independently.

Consider extracting the minimal storage interface into a tiny, version-stable shared module (e.g. github.com/vultisig/common/vaultiface) to decouple the two services.


398-401: HTTP semantics: return 404 instead of 400 when vault is absent

ExistVault currently maps “file does not exist” to 400 Bad Request:

exist, err := s.vaultStorage.Exist(filePathName)
if err != nil || !exist {
    return c.NoContent(http.StatusBadRequest)
}

For a well-formed request where the resource simply isn’t found, 404 Not Found is semantically more accurate:

-if err != nil || !exist {
-    return c.NoContent(http.StatusBadRequest)
+if err != nil {
+    s.logger.WithError(err).Error("failed to query vault storage")
+    return c.NoContent(http.StatusInternalServerError)
+}
+if !exist {
+    return c.NoContent(http.StatusNotFound)
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 8f6328d and b75e4cb.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (7)
  • api/plugin.go (3 hunks)
  • api/server.go (7 hunks)
  • cmd/vultisigner/main.go (3 hunks)
  • common/util.go (1 hunks)
  • config/config.go (1 hunks)
  • go.mod (1 hunks)
  • internal/sigutil/signing.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
api/server.go (1)
common/util.go (1)
  • DecryptVaultFromBackup (137-166)
🔇 Additional comments (8)
go.mod (2)

22-23: Dependency updates look good.

The updates to verifier and vultiserver dependencies support the vault storage refactoring. Removing indirect dependencies also helps clean up the codebase.


52-52: Addition of CORS dependency.

The addition of github.com/rs/cors v1.8.3 as an indirect dependency suggests API changes. Ensure this is intentional and properly configured if the API needs to handle cross-origin requests.

cmd/vultisigner/main.go (3)

9-9: LGTM: Added import for vault package.

This import supports the refactoring of vault storage implementation.


54-54: Refactored block storage to vault storage.

The change from blockStorage to vaultStorage using vault.NewBlockStorageImp() aligns with the PR objectives of refactoring vault storage implementation.


65-77:

Details

✅ Verification successful

Removed pluginConfigs parameter from NewServer.

The call to api.NewServer no longer includes cfg.Plugin.PluginConfigs as an argument, which indicates changes to server initialization. Ensure that this was an intentional removal and that the server can function correctly without this parameter.

Run the following script to verify this change:


🏁 Script executed:

#!/bin/bash
# Check how NewServer is defined in the api package
rg -A 5 "func NewServer" api/

Length of output: 275


I’ll check the full NewServer signature and search for any PluginConfigs references to confirm its removal.


🏁 Script executed:

#!/bin/bash
# Show full NewServer signature
rg -A20 "func NewServer" api/server.go

# Search for any PluginConfigs usage in the api package
rg -n "PluginConfigs" api/

Length of output: 598


pluginConfigs Parameter Removal Confirmed
The NewServer signature in api/server.go no longer accepts a pluginConfigs argument, and all call sites—including in cmd/vultisigner/main.go—have been updated to match. No further action is required.

  • api/server.go shows the new signature without pluginConfigs.
  • A search for PluginConfigs in the api package yields no results.
  • The invocation in cmd/vultisigner/main.go aligns with the updated parameters.
internal/sigutil/signing.go (2)

71-71: Simplified signature verification function.

Renaming VerifySignature to VerifyPolicySignature and simplifying the parameters is a good refactor. The function now directly accepts the public key hex string instead of deriving it, which improves code clarity and separation of concerns.


71-92:

Details

✅ Verification successful

Verify key derivation logic is implemented elsewhere.

The removal of key derivation from this function suggests that this logic has been moved elsewhere. Ensure that the public key derivation is properly implemented in the vault decryption process to maintain security.

Let's check where the public key derivation is now implemented:


🏁 Script executed:

#!/bin/bash
# Look for public key derivation in the codebase
rg -A 5 "GetAddress|Derive" --include "*.go"

# Check how VerifyPolicySignature is called
rg -A 5 "VerifyPolicySignature" --include "*.go"

Length of output: 979


🏁 Script executed:

#!/bin/bash
# Search for public key derivation logic in Go files
rg -g '*.go' -A 5 "Derive"
rg -g '*.go' -A 5 "GetAddress"

# Locate all calls to VerifyPolicySignature
rg -g '*.go' -A 5 "VerifyPolicySignature"

Length of output: 5243


Derivation logic verified elsewhere
The public‐key derivation has been moved out of VerifyPolicySignature into:

  • common/util.go’s DeriveAddress (which wraps tss.GetDerivedPubKey)
  • The TSS layer calls in api/server.go (GetDerivedPublicKey) and api/plugin.go before invoking sigutil.VerifyPolicySignature

Since key derivation occurs correctly in those components and VerifyPolicySignature now solely handles ECDSA verification, no further changes are needed.

common/util.go (1)

30-32: Potential breaking change after renaming backup suffix

vaultBackupSuffix is now ".bak" (was previously ".bak.vult" according to commit message).
Any existing backups on disk that still carry the old extension will no longer be discoverable by GetVaultBackupFilename, which could lead to failed migrations or data-loss if operators upgrade without renaming the files.

Consider one of the following:

-const (
-    vaultBackupSuffix = ".bak"
-)
+// keep the new suffix but transparently fall back to the legacy one
+const (
+    vaultBackupSuffix      = ".bak"
+    legacyBackupSuffix     = ".bak.vult"
+)
+
+func GetVaultBackupFilename(pubKey string) string {
+    return fmt.Sprintf("%s%s", pubKey, vaultBackupSuffix)
+}
+
+// helper for readers – tries new first, then legacy
+func ResolveBackupFilenames(pubKey string) []string {
+    return []string{
+        fmt.Sprintf("%s%s", pubKey, vaultBackupSuffix),
+        fmt.Sprintf("%s%s", pubKey, legacyBackupSuffix),
+    }
+}

…and update callers (vaultStorage.GetVault, Exist, etc.) to iterate through both names until one succeeds, then optionally migrate the file to the new name.

Please verify whether backward compatibility is required in production before merging.

Comment thread config/config.go
Comment thread api/server.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 comments (1)
api/plugin.go (1)

96-105: 💡 Verification agent

🧩 Analysis chain

Use the new getVault helper to avoid duplicated logic and secret / password drift

SignPluginMessages re-implements vault-retrieval + decryption even though you just introduced getVault.
Besides duplication, it now decrypts with req.VaultPassword whereas verifyPolicySignature decrypts with cfg.EncryptionSecret. If those secrets can diverge (e.g., operator rotates the server‐side secret but a stale client keeps an old password) you risk hard-to-debug signing failures.

Consider replacing lines 96-105 with:

- filePathName := common.GetVaultBackupFilename(req.PublicKey)
- content, err := s.vaultStorage.GetVault(filePathName)
- if err != nil {
-   wrappedErr := fmt.Errorf("fail to read file, err: %w", err)
-   ...
- }
-
- _, err = common.DecryptVaultFromBackup(req.VaultPassword, content)
+ _, err := s.getVault(req.PublicKey)   // re-uses centralised logic & cfg.EncryptionSecret

and decide on one authoritative secret (probably the server-side EncryptionSecret).
This keeps a single code-path, reduces I/O, and prevents inconsistencies between password sources.


🏁 Script executed:

#!/bin/bash
# Locate the definition of getVault and inspect its implementation
rg -n "func .*getVault" -C3 .

# Locate verifyPolicySignature to confirm which secret it uses for decryption
rg -n "verifyPolicySignature" -C3 .

Length of output: 1974


🏁 Script executed:

#!/bin/bash
# Display full getVault implementation for context
rg -n "func (s \\*Server) getVault" -C30 api/plugin.go

Length of output: 55


🏁 Script executed:

#!/bin/bash
# Display full implementation of getVault in api/plugin.go
sed -n '380,430p' api/plugin.go

# Locate usages of DecryptVaultFromBackup to see how getVault handles decryption
rg -n "DecryptVaultFromBackup" -C5 api/plugin.go

Length of output: 2467


Simplify vault loading in SignPluginMessages
Use the shared getVault helper (which uses s.cfg.EncryptionSecret) instead of re-implementing file I/O and decryption with req.VaultPassword. This ensures a single decryption secret and removes duplicate code.

—in api/plugin.go around lines 96–105—
Replace:

filePathName := common.GetVaultBackupFilename(req.PublicKey)
content, err := s.vaultStorage.GetVault(filePathName)
if err != nil {
    wrappedErr := fmt.Errorf("fail to read file, err: %w", err)
    s.logger.Infof("fail to read file in SignPluginMessages, err: %v", err)
    s.logger.Error(wrappedErr)
    return wrappedErr
}

_, err = common.DecryptVaultFromBackup(req.VaultPassword, content)
if err != nil {
    return fmt.Errorf("fail to decrypt vault from the backup, err: %w", err)
}

With:

vault, err := s.getVault(req.PublicKey)
if err != nil {
    return fmt.Errorf("fail to load vault: %w", err)
}
// …use vault for signing…

• Drops req.VaultPassword in favor of the single server‐side EncryptionSecret
• Removes duplicated I/O and error handling
• Keeps one source of truth for vault decryption

🧹 Nitpick comments (1)
api/plugin.go (1)

399-415: Graceful handling when vaults are not encrypted & minor clean-ups

  1. getVault currently aborts if EncryptionSecret is empty, even when the vault itself is stored unencrypted (IsEncrypted == false).
    Users running in plain-text mode will be blocked. Suggest checking the IsEncrypted flag after reading the backup and only requiring the secret when needed.

  2. Double-logging the same error (WithError(err).Error("fail to get vault") then wrapping and returning) clutters logs. Prefer either:

    return nil, fmt.Errorf("failed to get vault: %w", err)   // let caller log

    or keep the log line but wrap with %w once – not both.

  3. Nit: the wrapping message has a punctuation typo ("failed to decrypt vault,err: %w"). Add a space after the comma.

- return nil, fmt.Errorf("failed to decrypt vault,err: %w", err)
+ return nil, fmt.Errorf("failed to decrypt vault: %w", err)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between b75e4cb and 05f8860.

📒 Files selected for processing (1)
  • api/plugin.go (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
api/plugin.go (3)
internal/sigutil/signing.go (1)
  • VerifyPolicySignature (71-92)
api/server.go (1)
  • Server (36-50)
common/util.go (2)
  • GetVaultBackupFilename (265-267)
  • DecryptVaultFromBackup (137-166)

Comment thread api/plugin.go
Comment on lines +380 to 390
vault, err := s.getVault(policy.PublicKey)
if err != nil {
s.logger.WithError(err).Error("fail to get vault")
return false
}
derivedPublicKey, err := tss.GetDerivedPubKey(vault.PublicKeyEcdsa, vault.HexChainCode, vcommon.Ethereum.GetDerivePath(), false)
if err != nil {
s.logger.WithError(err).Error("failed to get derived public key")
return false
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prefix handling & potential verification mismatch

derivedPublicKey may contain a 0x prefix while sigutil.VerifyPolicySignature expects a pure hex string (it later runs hex.DecodeString).
If the prefix is present, verification will always fail with “invalid byte” errors.

Add an explicit trim before calling the verifier:

-derivedPublicKey, err := tss.GetDerivedPubKey(...)
+derivedPublicKey, err := tss.GetDerivedPubKey(...)
+derivedPublicKey = strings.TrimPrefix(derivedPublicKey, "0x")

Also, reuse strings.TrimPrefix consistently across the file for clarity.

📝 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
vault, err := s.getVault(policy.PublicKey)
if err != nil {
s.logger.WithError(err).Error("fail to get vault")
return false
}
derivedPublicKey, err := tss.GetDerivedPubKey(vault.PublicKeyEcdsa, vault.HexChainCode, vcommon.Ethereum.GetDerivePath(), false)
if err != nil {
s.logger.WithError(err).Error("failed to get derived public key")
return false
}
vault, err := s.getVault(policy.PublicKey)
if err != nil {
s.logger.WithError(err).Error("fail to get vault")
return false
}
derivedPublicKey, err := tss.GetDerivedPubKey(vault.PublicKeyEcdsa, vault.HexChainCode, vcommon.Ethereum.GetDerivePath(), false)
derivedPublicKey = strings.TrimPrefix(derivedPublicKey, "0x")
if err != nil {
s.logger.WithError(err).Error("failed to get derived public key")
return false
}
🤖 Prompt for AI Agents
In api/plugin.go around lines 380 to 390, the derivedPublicKey may include a
"0x" prefix which causes sigutil.VerifyPolicySignature to fail due to invalid
hex decoding. Fix this by explicitly trimming the "0x" prefix from
derivedPublicKey using strings.TrimPrefix before passing it to the verifier.
Also, ensure that strings.TrimPrefix is used consistently throughout the file
for handling hex string prefixes.

@RaghavSood RaghavSood left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PluginPolicy - When create/update PluginPolicy , retrieve relevant vault

3 participants