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

Retain environment variable when loading key from config #78

Merged
merged 5 commits into from
Dec 9, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions accounts/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,14 @@ var _ Key = &KMSKey{}

var _ Key = &BIP44Key{}

var _ Key = &EnvKey{}

func keyFromConfig(accountKeyConf config.AccountKey) (Key, error) {
switch accountKeyConf.Type {
case config.KeyTypeHex:
if accountKeyConf.Env != "" {
return envKeyFromConfig(accountKeyConf)
}
return hexKeyFromConfig(accountKeyConf)
case config.KeyTypeBip44:
return bip44KeyFromConfig(accountKeyConf)
Expand Down Expand Up @@ -315,6 +320,59 @@ func NewFileKey(
}
}

// EnvKey represents a key that is saved in an environment variable.
type EnvKey struct {
*baseKey
privateKey crypto.PrivateKey
env string
}

func envKeyFromConfig(accountKey config.AccountKey) (*EnvKey, error) {
return &EnvKey{
baseKey: baseKeyFromConfig(accountKey),
privateKey: accountKey.PrivateKey,
env: accountKey.Env,
}, nil
}

func (f *EnvKey) Signer(ctx context.Context) (crypto.Signer, error) {
key, err := f.PrivateKey()
if err != nil {
return nil, err
}

return crypto.NewInMemorySigner(*key, f.HashAlgo())
}

func (f *EnvKey) PrivateKey() (*crypto.PrivateKey, error) {
pkHex := os.ExpandEnv(f.env)
if pkHex == "" {
return nil, fmt.Errorf("environment variable %s is not set", f.env)
}

pkey, err := crypto.DecodePrivateKeyHex(f.sigAlgo, strings.TrimPrefix(string(pkHex), "0x"))
if err != nil {
return nil, fmt.Errorf("could not decode the key from environment variable %s: %w", f.env, err)
}

return &pkey, nil
}

func (f *EnvKey) ToConfig() config.AccountKey {
pk, err := f.PrivateKey()
if err != nil {
panic(err)
}

return config.AccountKey{
Type: config.KeyTypeHex,
SigAlgo: f.sigAlgo,
HashAlgo: f.hashAlgo,
PrivateKey: *pk,
Env: f.env,
}
}

// FileKey represents a key that is saved in a seperate file and will be lazy-loaded.
//
// The FileKey stores location of the file where private key is stored in hex-encoded format.
Expand Down
Loading