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

Add Wallet APIs for local development #335

Merged
merged 8 commits into from
Jul 8, 2024
Merged

Add Wallet APIs for local development #335

merged 8 commits into from
Jul 8, 2024

Conversation

devbugging
Copy link
Contributor

@devbugging devbugging commented Jul 3, 2024

Closes: #129

This adds Wallet APIs for local development.

This should not be used in production.

Some tools and clients rely on wallet APIs for local development and testing. This implementation enables the APIs by using a provided wallet key for operations through the config.

Summary by CodeRabbit

  • New Features

    • Introduced Wallet API for enhanced account management, transaction signing, and sending transactions.
    • Added command-line flag wallet-api-key for setting private keys in local or testing environments.
  • Enhancements

    • Updated configuration to include WalletEnabled and WalletKey settings.
    • Improved API support by conditionally including Wallet API based on configuration.

@devbugging devbugging self-assigned this Jul 3, 2024
Copy link
Contributor

coderabbitai bot commented Jul 3, 2024

Warning

Review failed

The pull request is closed.

Walkthrough

The recent changes introduce wallet management functionalities into the system. Specifically, they update configuration options to include a wallet API key, augment the API to handle wallet operations such as managing accounts, signing transactions, and conditionally include these wallet-based functionalities based on configuration flags. They also modify the build script to accommodate these new configurations for local testing purposes.

Changes

File Change Summary
Makefile Enhanced the start-local target to include a --wallet-api-key parameter.
api/api.go Added WalletAPI parameter to SupportedAPIs function, introduced wallet-related conditional handling, and removed certain BlockChainAPI functions.
api/wallet.go Introduced the WalletAPI struct and accompanying methods for account management, signing transactions, and sending transactions.
bootstrap/bootstrap.go Added conditional instantiation and inclusion of walletAPI in the supported API list based on the WalletEnabled configuration flag.
config/config.go Added WalletEnabled and WalletKey fields to the Config struct along with corresponding command-line flag parsing for wallet-api-key.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Config as Config
    participant Makefile as Makefile
    participant Main as Main.go
    participant Bootstrap as Bootstrap
    participant API as API
    participant WalletAPI as WalletAPI

    User->>Config: Set --wallet-api-key flag
    Config->>Makefile: Updated start-local target
    Makefile->>Main: Include wallet-api-key parameter
    Main->>Bootstrap: Initialize components
    Bootstrap->>Config: Check WalletEnabled
    Config-->>Bootstrap: WalletEnabled = true
    Bootstrap->>WalletAPI: Instantiate WalletAPI
    Bootstrap-->>API: Include WalletAPI in SupportedAPIs
    User->>API: Send transaction request
    API->>WalletAPI: Handle transaction
Loading

Poem

On the blockchain path we tread,
Wallets, keys, and code ahead,
Transactions swift and signed with flair,
Configured with a flag, handle with care,
Our system now more robust and grand,
For in our code, wallets stand.


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

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (invoked as PR comments)

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

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

CodeRabbit Configration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a3ad40a and 16c5fae.

Files selected for processing (4)
  • api/api.go (3 hunks)
  • api/wallet.go (1 hunks)
  • bootstrap/bootstrap.go (1 hunks)
  • config/config.go (5 hunks)
Additional comments not posted (4)
api/wallet.go (3)

23-28: Constructor for WalletAPI looks good.

The NewWalletAPI function correctly initializes the WalletAPI struct.


37-51: Sign function correctly indicates unsupported operation.

The Sign function correctly returns ErrNotSupported.


102-114: SendTransaction function looks good.

The SendTransaction function correctly handles the process of signing and sending a transaction.

api/api.go (1)

Line range hint 36-73: SupportedAPIs function looks good.

The SupportedAPIs function correctly handles the inclusion of walletAPI.

Comment on lines +30 to +36
// Accounts returns the collection of accounts this node manages.
func (w *WalletAPI) Accounts() ([]common.Address, error) {
return []common.Address{
crypto.PubkeyToAddress(w.config.WalletKey.PublicKey),
}, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for unset WalletKey.

The Accounts function should handle the case where WalletKey is not set to avoid potential runtime errors.

func (w *WalletAPI) Accounts() ([]common.Address, error) {
+  if w.config.WalletKey == nil {
+    return nil, fmt.Errorf("wallet key is not set")
+  }
  return []common.Address{
    crypto.PubkeyToAddress(w.config.WalletKey.PublicKey),
  }, nil
}
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
// Accounts returns the collection of accounts this node manages.
func (w *WalletAPI) Accounts() ([]common.Address, error) {
return []common.Address{
crypto.PubkeyToAddress(w.config.WalletKey.PublicKey),
}, nil
}
func (w *WalletAPI) Accounts() ([]common.Address, error) {
if w.config.WalletKey == nil {
return nil, fmt.Errorf("wallet key is not set")
}
return []common.Address{
crypto.PubkeyToAddress(w.config.WalletKey.PublicKey),
}, nil
}

api/wallet.go Outdated
Comment on lines 53 to 124
// SignTransaction will sign the given transaction with the from account.
// The node needs to have the private key of the account corresponding with
// the given from address and it needs to be unlocked.
func (w *WalletAPI) SignTransaction(
ctx context.Context,
args TransactionArgs,
) (*SignTransactionResult, error) {
nonce := uint64(0)
if args.Nonce != nil {
nonce = uint64(*args.Nonce)
} else {
num := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
n, err := w.net.GetTransactionCount(ctx, *args.From, &num)
if err != nil {
return nil, err
}
nonce = uint64(*n)
}

var data []byte
if args.Data != nil {
data = *args.Data
}

tx := types.NewTx(&types.LegacyTx{
Nonce: nonce,
To: args.To,
Value: args.Value.ToInt(),
Gas: uint64(*args.Gas),
GasPrice: args.GasPrice.ToInt(),
Data: data,
})

signed, err := types.SignTx(tx, evmEmulator.GetDefaultSigner(), w.config.WalletKey)
if err != nil {
return nil, fmt.Errorf("error signing EVM transaction: %w", err)
}

raw, err := signed.MarshalBinary()
if err != nil {
return nil, err
}

return &SignTransactionResult{
Raw: raw,
Tx: tx,
}, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for unset WalletKey.

The SignTransaction function should handle the case where WalletKey is not set to avoid potential runtime errors.

func (w *WalletAPI) SignTransaction(
  ctx context.Context,
  args TransactionArgs,
) (*SignTransactionResult, error) {
+  if w.config.WalletKey == nil {
+    return nil, fmt.Errorf("wallet key is not set")
+  }
  // existing code...
}
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
// SignTransaction will sign the given transaction with the from account.
// The node needs to have the private key of the account corresponding with
// the given from address and it needs to be unlocked.
func (w *WalletAPI) SignTransaction(
ctx context.Context,
args TransactionArgs,
) (*SignTransactionResult, error) {
nonce := uint64(0)
if args.Nonce != nil {
nonce = uint64(*args.Nonce)
} else {
num := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
n, err := w.net.GetTransactionCount(ctx, *args.From, &num)
if err != nil {
return nil, err
}
nonce = uint64(*n)
}
var data []byte
if args.Data != nil {
data = *args.Data
}
tx := types.NewTx(&types.LegacyTx{
Nonce: nonce,
To: args.To,
Value: args.Value.ToInt(),
Gas: uint64(*args.Gas),
GasPrice: args.GasPrice.ToInt(),
Data: data,
})
signed, err := types.SignTx(tx, evmEmulator.GetDefaultSigner(), w.config.WalletKey)
if err != nil {
return nil, fmt.Errorf("error signing EVM transaction: %w", err)
}
raw, err := signed.MarshalBinary()
if err != nil {
return nil, err
}
return &SignTransactionResult{
Raw: raw,
Tx: tx,
}, nil
}
func (w *WalletAPI) SignTransaction(
ctx context.Context,
args TransactionArgs,
) (*SignTransactionResult, error) {
if w.config.WalletKey == nil {
return nil, fmt.Errorf("wallet key is not set")
}
nonce := uint64(0)
if args.Nonce != nil {
nonce = uint64(*args.Nonce)
} else {
num := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
n, err := w.net.GetTransactionCount(ctx, *args.From, &num)
if err != nil {
return nil, err
}
nonce = uint64(*n)
}
var data []byte
if args.Data != nil {
data = *args.Data
}
tx := types.NewTx(&types.LegacyTx{
Nonce: nonce,
To: args.To,
Value: args.Value.ToInt(),
Gas: uint64(*args.Gas),
GasPrice: args.GasPrice.ToInt(),
Data: data,
})
signed, err := types.SignTx(tx, evmEmulator.GetDefaultSigner(), w.config.WalletKey)
if err != nil {
return nil, fmt.Errorf("error signing EVM transaction: %w", err)
}
raw, err := signed.MarshalBinary()
if err != nil {
return nil, err
}
return &SignTransactionResult{
Raw: raw,
Tx: tx,
}, nil
}

Comment on lines +347 to +350
var walletAPI *api.WalletAPI
if cfg.WalletEnabled {
walletAPI = api.NewWalletAPI(cfg, blockchainAPI)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for walletAPI initialization.

The Start function should handle potential errors during walletAPI initialization.

if cfg.WalletEnabled {
  walletAPI = api.NewWalletAPI(cfg, blockchainAPI)
+  if walletAPI == nil {
+    return fmt.Errorf("failed to initialize wallet API")
+  }
}
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
var walletAPI *api.WalletAPI
if cfg.WalletEnabled {
walletAPI = api.NewWalletAPI(cfg, blockchainAPI)
}
var walletAPI *api.WalletAPI
if cfg.WalletEnabled {
walletAPI = api.NewWalletAPI(cfg, blockchainAPI)
if walletAPI == nil {
return fmt.Errorf("failed to initialize wallet API")
}
}

Comment on lines +292 to +300
if walletKey != "" {
var k, err = gethCrypto.HexToECDSA(walletKey)
if err != nil {
return nil, fmt.Errorf("wrong private key for wallet API: %w", err)
}

cfg.WalletKey = k
cfg.WalletEnabled = true
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add validation for WalletKey field.

The FromFlags function should validate the WalletKey field to ensure it is properly set.

if walletKey != "" {
  var k, err = gethCrypto.HexToECDSA(walletKey)
  if err != nil {
    return nil, fmt.Errorf("wrong private key for wallet API: %w", err)
  }
  cfg.WalletKey = k
  cfg.WalletEnabled = true
+} else {
+  cfg.WalletEnabled = false
}
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
if walletKey != "" {
var k, err = gethCrypto.HexToECDSA(walletKey)
if err != nil {
return nil, fmt.Errorf("wrong private key for wallet API: %w", err)
}
cfg.WalletKey = k
cfg.WalletEnabled = true
}
if walletKey != "" {
var k, err = gethCrypto.HexToECDSA(walletKey)
if err != nil {
return nil, fmt.Errorf("wrong private key for wallet API: %w", err)
}
cfg.WalletKey = k
cfg.WalletEnabled = true
} else {
cfg.WalletEnabled = false
}

api/wallet.go Outdated
nonce = uint64(*args.Nonce)
} else {
num := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
n, err := w.net.GetTransactionCount(ctx, *args.From, &num)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Minor: I know that this is only for development, but *args.From might crash, as the From argument is optional.

tx := types.NewTx(&types.LegacyTx{
Nonce: nonce,
To: args.To,
Value: args.Value.ToInt(),
Copy link
Collaborator

Choose a reason for hiding this comment

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

Same here, regarding:

  • args.Value
  • args.Gas
  • args.GasPrice
    We should check whether they are set.

Data: data,
})

signed, err := types.SignTx(tx, evmEmulator.GetDefaultSigner(), w.config.WalletKey)
Copy link
Collaborator

@m-Peter m-Peter Jul 8, 2024

Choose a reason for hiding this comment

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

Technically, I think we should be signing with the address in args.From, but since we have one PrivateKey in the config, this is good enough for development.

api/wallet.go Outdated
addr common.Address,
data hexutil.Bytes,
) (hexutil.Bytes, error) {
return nil, errs.ErrNotSupported
Copy link
Collaborator

Choose a reason for hiding this comment

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

We can add a minimal implementation for this a well, with something like:

// Transform the given message to the following format:
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
hash := accounts.TextHash(data)
// Sign the hash using plain ECDSA operations
signature, err := crypto.Sign(hash, w.config.WalletKey)
if err == nil {
	// Transform V from 0/1 to 27/28 according to the yellow paper
	signature[64] += 27
}

return signature, err

Copy link
Collaborator

@m-Peter m-Peter left a comment

Choose a reason for hiding this comment

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

Added a few comments that might be worthwhile to check out.

@m-Peter m-Peter merged commit 50a7728 into main Jul 8, 2024
2 checks passed
@m-Peter m-Peter deleted the gregor/wallet branch July 8, 2024 15:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

Wallet APIs
2 participants