keystore

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrHDWalletAlreadyExists  = fmt.Errorf("HD wallet already exists")
	ErrHDWalletNotFound       = fmt.Errorf("HD wallet file not found")
	ErrHDWalletDecryptFailed  = fmt.Errorf("HD wallet decryption failed")
	ErrHDWalletInvalidVersion = fmt.Errorf("unsupported HD wallet version")
	ErrMnemonicInvalid        = fmt.Errorf("invalid BIP-39 mnemonic")
	ErrHDWalletClosed         = fmt.Errorf("HD wallet is closed")
	ErrHDDerivationFailed     = fmt.Errorf("HD key derivation failed")
	ErrInvalidDerivationRange = fmt.Errorf("invalid derivation range: start must be less than end")
)
View Source
var (
	// ErrNotTerminal is returned when stdin is not a terminal
	ErrNotTerminal = errors.New("stdin is not a terminal, cannot read password securely")

	// ErrPasswordMismatch is returned when password confirmation does not match
	ErrPasswordMismatch = errors.New("passwords do not match")

	// ErrEmptyPassword is returned when password is empty
	ErrEmptyPassword = errors.New("password cannot be empty")

	// ErrContextCanceled is returned when context is canceled during password reading
	ErrContextCanceled = errors.New("password reading canceled by context")
)

Functions

func ChangeEnhancedKeyPassword added in v0.5.0

func ChangeEnhancedKeyPassword(keystorePath string, currentPassword, newPassword []byte) error

ChangeEnhancedKeyPassword changes the password of an enhanced key file.

func ChangePassword

func ChangePassword(keystorePath string, currentPassword, newPassword []byte) error

ChangePassword changes the password of an existing keystore file.

Parameters:

  • keystorePath: Path to the keystore file
  • currentPassword: Current password
  • newPassword: New password

Returns:

  • error: Any error that occurred

func CreateEnhancedKey added in v0.5.0

func CreateEnhancedKey(dir string, keyType KeyType, password []byte, label string) (identifier, path string, err error)

CreateEnhancedKey creates a new enhanced key of the given type.

func CreateHDWallet added in v0.4.0

func CreateHDWallet(dir string, password []byte, entropyBits int) (address, walletPath string, err error)

CreateHDWallet generates a random BIP-39 mnemonic, encrypts its entropy, derives the primary address (index 0), and writes an hdwallet--<address>.json file into dir.

func CreateKeystore

func CreateKeystore(dir string, password []byte) (string, string, error)

CreateKeystore creates a new keystore with a randomly generated key.

Parameters:

  • dir: Directory to store the keystore file (will be created if not exists)
  • password: Password to encrypt the keystore

Returns:

  • address: The Ethereum address of the new key (0x prefixed)
  • path: Full path to the created keystore file
  • error: Any error that occurred

func ExportEnhancedKey added in v0.5.0

func ExportEnhancedKey(keystorePath string, password []byte, format KeyFormat) ([]byte, error)

ExportEnhancedKey decrypts and exports a key in the given format.

func ExportMnemonic added in v0.4.0

func ExportMnemonic(walletPath string, password []byte) ([]byte, error)

ExportMnemonic decrypts the HD wallet and returns the mnemonic words. The caller is responsible for securely zeroizing the returned bytes.

func ExportNativeKey added in v0.5.0

func ExportNativeKey(keystorePath string, password []byte) ([]byte, error)

ExportNativeKey decrypts a native go-ethereum keystore and returns the raw private key bytes.

func FormatKeyOutput added in v0.5.0

func FormatKeyOutput(keyBytes []byte, format KeyFormat, keyType KeyType) ([]byte, error)

FormatKeyOutput formats raw key bytes into the given format.

func GetKeystoreAddress

func GetKeystoreAddress(keystorePath string) (string, error)

GetKeystoreAddress reads a keystore file and returns the address without decrypting.

Parameters:

  • keystorePath: Path to the keystore file

Returns:

  • address: The Ethereum address (0x prefixed, checksummed)
  • error: Any error that occurred

func ImportEnhancedKey added in v0.5.0

func ImportEnhancedKey(dir string, input []byte, keyType KeyType, format KeyFormat, password []byte, label string) (identifier, path string, err error)

ImportEnhancedKey imports a key from the given input and format.

func ImportHDWallet added in v0.4.0

func ImportHDWallet(dir string, mnemonic []byte, password []byte) (address, walletPath string, err error)

ImportHDWallet validates the provided mnemonic, encrypts its entropy, and writes an hdwallet--<address>.json file into dir.

func ImportPrivateKey

func ImportPrivateKey(dir string, privateKeyHex []byte, password []byte) (string, string, error)

ImportPrivateKey imports a hex-encoded private key into a new keystore.

Parameters:

  • dir: Directory to store the keystore file (will be created if not exists)
  • privateKeyHex: Hex-encoded private key (with or without 0x prefix)
  • password: Password to encrypt the keystore

Returns:

  • address: The Ethereum address derived from the private key (0x prefixed)
  • path: Full path to the created keystore file
  • error: Any error that occurred

func IsEnhancedKeyFile added in v0.5.0

func IsEnhancedKeyFile(filePath string) bool

IsEnhancedKeyFile checks if the given file is an enhanced key file by reading its JSON.

func IsTerminal

func IsTerminal() bool

IsTerminal checks if stdin is a terminal.

func ParseKeyInput added in v0.5.0

func ParseKeyInput(input []byte, format KeyFormat, keyType KeyType) ([]byte, error)

ParseKeyInput parses raw key bytes from the given format.

func ReadPasswordWithConfirm

func ReadPasswordWithConfirm(ctx context.Context, prompt string) ([]byte, error)

ReadPasswordWithConfirm reads a password twice for confirmation. Returns error if passwords don't match or if stdin is not a terminal.

func ReadSecret

func ReadSecret(ctx context.Context) ([]byte, error)

ReadSecret reads a secret from stdin without echoing, with context support. Returns error if stdin is not a terminal to prevent insecure piping. If context is canceled, it restores terminal state, unblocks the internal ReadPassword goroutine, and waits for it to exit before returning.

func SecureZeroize

func SecureZeroize(data []byte)

SecureZeroize securely erases sensitive data from memory. This function should be called with defer after reading a password.

func ValidateKeyBytes added in v0.5.0

func ValidateKeyBytes(keyBytes []byte, keyType KeyType) error

ValidateKeyBytes checks if the raw key bytes are valid for the given key type. It also validates compatibility with secp256k1 curve order since we use go-ethereum's EncryptDataV3 which stores arbitrary bytes, but we proactively check so that the key could also be loaded via the native ECDSA path if needed.

func VerifyEnhancedKeyPassword added in v0.5.0

func VerifyEnhancedKeyPassword(keystorePath string, password []byte) error

VerifyEnhancedKeyPassword verifies password can decrypt the enhanced key.

func VerifyHDWalletPassword added in v0.4.0

func VerifyHDWalletPassword(walletPath string, password []byte) error

VerifyHDWalletPassword verifies that the password can decrypt the HD wallet without returning any secret material.

func VerifyPassword

func VerifyPassword(keystorePath string, password []byte) error

VerifyPassword verifies that the password can decrypt the keystore.

Parameters:

  • keystorePath: Path to the keystore file
  • password: Password to verify

Returns:

  • error: nil if password is correct, error otherwise

Types

type EnhancedKeyFile added in v0.5.0

type EnhancedKeyFile struct {
	Version    int                    `json:"version"`
	KeyType    KeyType                `json:"key_type"`
	Identifier string                 `json:"identifier"`
	Crypto     ethkeystore.CryptoJSON `json:"crypto"`
	Label      string                 `json:"label,omitempty"`
}

EnhancedKeyFile represents the encrypted enhanced key file on disk.

type EnhancedKeyInfo added in v0.5.0

type EnhancedKeyInfo struct {
	KeyType    KeyType
	Identifier string
	Label      string
	Path       string
}

EnhancedKeyInfo contains metadata readable without decryption.

func GetEnhancedKeyInfo added in v0.5.0

func GetEnhancedKeyInfo(keystorePath string) (*EnhancedKeyInfo, error)

GetEnhancedKeyInfo reads enhanced key metadata without decryption.

func ListEnhancedKeys added in v0.5.0

func ListEnhancedKeys(dir string) ([]EnhancedKeyInfo, error)

ListEnhancedKeys lists all enhanced key files in a directory.

type HDConfig added in v0.4.0

type HDConfig struct {
	BasePath string `json:"base_path"`
	Locale   string `json:"locale"`
}

HDConfig stores the HD derivation configuration.

type HDWallet added in v0.4.0

type HDWallet struct {
	// contains filtered or unexported fields
}

HDWallet derives Ethereum keys from a BIP-39 seed held in memory.

func NewHDWallet added in v0.4.0

func NewHDWallet(seed []byte, basePath accounts.DerivationPath) (*HDWallet, error)

NewHDWallet constructs an HDWallet from a raw BIP-39 seed and base derivation path.

func OpenHDWallet added in v0.4.0

func OpenHDWallet(walletPath string, password []byte) (*HDWallet, error)

OpenHDWallet decrypts an HD wallet file and returns an HDWallet ready for key derivation.

func (*HDWallet) Close added in v0.4.0

func (w *HDWallet) Close() error

Close zeroizes the seed, rendering the wallet unusable.

func (*HDWallet) DeriveAddress added in v0.4.0

func (w *HDWallet) DeriveAddress(index uint32) (common.Address, error)

DeriveAddress derives the Ethereum address at basePath/index.

func (*HDWallet) DeriveAddresses added in v0.4.0

func (w *HDWallet) DeriveAddresses(start, end uint32) ([]common.Address, error)

DeriveAddresses batch-derives addresses for indices [start, end).

func (*HDWallet) DeriveKey added in v0.4.0

func (w *HDWallet) DeriveKey(index uint32) (*ecdsa.PrivateKey, error)

DeriveKey derives the private key at basePath/index. The caller must zeroize the returned key when done.

type HDWalletFile added in v0.4.0

type HDWalletFile struct {
	Version        int                 `json:"version"`
	PrimaryAddress string              `json:"primary_address"`
	Mnemonic       keystore.CryptoJSON `json:"mnemonic"`
	HDConfig       HDConfig            `json:"hd_config"`
}

HDWalletFile represents the encrypted HD wallet file on disk.

type HDWalletInfo added in v0.4.0

type HDWalletInfo struct {
	PrimaryAddress string
	BasePath       string
	Path           string
}

HDWalletInfo contains non-secret HD wallet metadata readable without decryption.

func GetHDWalletInfo added in v0.4.0

func GetHDWalletInfo(walletPath string) (*HDWalletInfo, error)

GetHDWalletInfo reads HD wallet metadata without requiring a password.

func ListHDWallets added in v0.4.0

func ListHDWallets(dir string) ([]HDWalletInfo, error)

ListHDWallets scans dir for HD wallet files and returns their metadata.

type KeyFormat added in v0.5.0

type KeyFormat string

KeyFormat represents the input/output format for private keys.

const (
	KeyFormatHex    KeyFormat = "hex"
	KeyFormatBase64 KeyFormat = "base64"
	KeyFormatPEM    KeyFormat = "pem"
)

type KeyType added in v0.5.0

type KeyType string

KeyType represents the type of cryptographic key.

const (
	KeyTypeEd25519   KeyType = "ed25519"
	KeyTypeSecp256k1 KeyType = "secp256k1"
	KeyTypeP256      KeyType = "p256"
)

type KeystoreInfo

type KeystoreInfo struct {
	Address string `json:"address"`
	Path    string `json:"path"`
}

KeystoreInfo contains information about a keystore file.

func ListKeystores

func ListKeystores(dir string) ([]KeystoreInfo, error)

ListKeystores lists all keystore files in a directory.

Parameters:

  • dir: Directory to scan for keystore files

Returns:

  • []KeystoreInfo: List of keystores found
  • error: Any error that occurred

type SecureBytes added in v0.4.0

type SecureBytes struct {
	// contains filtered or unexported fields
}

SecureBytes wraps sensitive byte data with zeroization support.

func NewSecureBytes added in v0.4.0

func NewSecureBytes(data []byte) *SecureBytes

NewSecureBytes creates a SecureBytes from a copy of data.

func (*SecureBytes) Bytes added in v0.4.0

func (sb *SecureBytes) Bytes() []byte

Bytes returns a copy of the underlying data.

func (*SecureBytes) Zeroize added in v0.4.0

func (sb *SecureBytes) Zeroize()

Zeroize overwrites the data with zeros.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL