Documentation
¶
Overview ¶
Package keystore implements encrypted storage of secp256k1 private keys.
Keys are stored as encrypted JSON files according to the Web3 Secret Storage specification. See https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition for more information.
Concurrency ¶
A KeyStore is safe for concurrent use by multiple goroutines. All exported methods acquire the necessary locks internally. In particular:
- KeyStore.SignHash and KeyStore.SignTx hold a read lock while accessing the unlocked key, so concurrent signing is safe.
- KeyStore.Lock, KeyStore.Unlock, and KeyStore.TimedUnlock hold a write lock while mutating the set of unlocked keys.
- KeyStore.Close may be called from any goroutine and is idempotent.
Callers must not retain or share *Key values returned by KeyStore.GetDecryptedKey; the key material is owned by the caller and must be zeroized (see [zeroKey]) when no longer needed.
Index ¶
- Constants
- Variables
- func CheckSignatureRoom(tx *core.Transaction) error
- func DecryptDataV3(cj CryptoJSON, auth string) ([]byte, error)
- func DecryptPQKeyV3(keyjson []byte, auth string) (scheme, address string, ext, seed []byte, err error)
- func EncryptKey(key *Key, auth string, scryptN, scryptP int) ([]byte, error)
- func EncryptPQKeyV3(scheme, address string, ext, seed, auth []byte, scryptN, scryptP int) ([]byte, error)
- func NewAuthNeededError(needed string) error
- func RecoverPubkey(hash []byte, signature []byte) (address.Address, error)
- func TextAndHash(data []byte, useFixedLength ...bool) ([]byte, string)
- func TextHash(data []byte, useFixedLength ...bool) []byte
- func UnmarshalPublic(pbk []byte) (*ecdsa.PublicKey, error)
- type Account
- type AmbiguousAddrError
- type AuthNeededError
- type CryptoJSON
- type DerivationPath
- type Key
- type KeyStore
- func (ks *KeyStore) Accounts() []Account
- func (ks *KeyStore) Close()
- func (ks *KeyStore) Delete(a Account, passphrase string) error
- func (ks *KeyStore) Export(a Account, passphrase, newPassphrase string) (keyJSON []byte, err error)
- func (ks *KeyStore) Find(a Account) (Account, error)
- func (ks *KeyStore) GetDecryptedKey(a Account, auth string) (Account, *Key, error)
- func (ks *KeyStore) HasAddress(addr address.Address) bool
- func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (Account, error)
- func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (Account, error)
- func (ks *KeyStore) Lock(addr address.Address) error
- func (ks *KeyStore) NewAccount(passphrase string) (Account, error)
- func (ks *KeyStore) SignHash(a Account, hash []byte) ([]byte, error)
- func (ks *KeyStore) SignHashWithPassphrase(a Account, passphrase string, hash []byte) (signature []byte, err error)
- func (ks *KeyStore) SignTx(a Account, tx *core.Transaction) (*core.Transaction, error)
- func (ks *KeyStore) SignTxWithPassphrase(a Account, passphrase string, tx *core.Transaction) (*core.Transaction, error)
- func (ks *KeyStore) Subscribe(sink chan<- WalletEvent) event.Subscription
- func (ks *KeyStore) TimedUnlock(a Account, passphrase string, timeout time.Duration) error
- func (ks *KeyStore) Unlock(a Account, passphrase string) error
- func (ks *KeyStore) Update(a Account, passphrase, newPassphrase string) error
- func (ks *KeyStore) Wallets() []Wallet
- type URL
- type Wallet
- type WalletEvent
- type WalletEventType
Constants ¶
const ( // StandardScryptN is the N parameter of Scrypt encryption algorithm, using 256MB // memory and taking approximately 1s CPU time on a modern processor. StandardScryptN = 1 << 18 // StandardScryptP is the P parameter of Scrypt encryption algorithm, using 256MB // memory and taking approximately 1s CPU time on a modern processor. StandardScryptP = 1 // LightScryptN is the N parameter of Scrypt encryption algorithm, using 4MB // memory and taking approximately 100ms CPU time on a modern processor. LightScryptN = 1 << 12 // LightScryptP is the P parameter of Scrypt encryption algorithm, using 4MB // memory and taking approximately 100ms CPU time on a modern processor. LightScryptP = 6 )
const KeyStoreScheme = "keystore"
KeyStoreScheme is the protocol scheme prefixing account and wallet URLs.
const MaxTotalSignatures = 5
MaxTotalSignatures is the most signatures a TRON transaction may carry: ECDSA signatures plus TIP-899 pq_auth_sig entries together. It mirrors the node's TOTAL_SIGN_NUM, a genesis constant that proposals cannot change. signer.MaxTotalSignatures is the same value.
Variables ¶
var ( // ErrLocked is returned when an operation requires an unlocked account. ErrLocked = NewAuthNeededError("password or unlock") // ErrNoMatch is returned when no key matches the given address or file. ErrNoMatch = errors.New("no key for given address or file") // ErrDecrypt is returned when a key cannot be decrypted with the given passphrase. ErrDecrypt = errors.New("could not decrypt key with given passphrase") // ErrAccountAlreadyExists is returned if an account attempted to import is // already present in the keystore. ErrAccountAlreadyExists = errors.New("account already exists") // ErrTooManySignatures is returned when the transaction already carries // MaxTotalSignatures signatures, so the node would reject another. // signer.ErrTooManySignatures is the same error; the "signer:" prefix is // kept from when it was defined there, so its text did not change. ErrTooManySignatures = errors.New("signer: transaction already has the maximum number of signatures") )
var ErrInvalidPassphrase = errors.New("invalid passphrase")
ErrInvalidPassphrase is returned when a decryption operation receives a bad passphrase.
var ErrNotSupported = errors.New("not supported")
ErrNotSupported is returned when an operation is requested from an account backend that it does not support.
var ErrUnknownAccount = errors.New("unknown account")
ErrUnknownAccount is returned for any requested operation for which no backend provides the specified account.
var ErrUnknownWallet = errors.New("unknown wallet")
ErrUnknownWallet is returned for any requested operation for which no backend provides the specified wallet.
var ErrWalletAlreadyOpen = errors.New("wallet already open")
ErrWalletAlreadyOpen is returned if a wallet is attempted to be opened the second time.
var ErrWalletClosed = errors.New("wallet closed")
ErrWalletClosed is returned if a wallet is attempted to be opened the secodn time.
var KeyStoreType = reflect.TypeOf(&KeyStore{})
KeyStoreType is the reflect type of a keystore backend.
Functions ¶
func CheckSignatureRoom ¶ added in v0.27.0
func CheckSignatureRoom(tx *core.Transaction) error
CheckSignatureRoom returns an error wrapping ErrTooManySignatures when tx already carries MaxTotalSignatures signatures (ECDSA and pq_auth_sig together), so another one would make the node reject it. Signers call it before any key or device use.
func DecryptDataV3 ¶
func DecryptDataV3(cj CryptoJSON, auth string) ([]byte, error)
DecryptDataV3 decrypts Web3 Secret Storage v3 crypto fields.
func DecryptPQKeyV3 ¶ added in v0.27.0
func DecryptPQKeyV3(keyjson []byte, auth string) (scheme, address string, ext, seed []byte, err error)
DecryptPQKeyV3 decrypts a wallet-cli post-quantum keystore and returns its clear scheme and address fields with the decrypted segments; an absent segment is returned as nil. The address is not validated here.
The file must be version 3, aes-128-ctr and scrypt, with a scheme and at least one complete segment; a segment with only some of its fields is rejected, as are two segments sharing an IV. Every present MAC is verified before any segment is decrypted. A MAC mismatch (normally a wrong password) returns ErrDecrypt.
Experimental: this is a byte-level helper for package pqc; use pqc.DecryptKeystore instead. It may change with TIP-899.
func EncryptKey ¶
EncryptKey encrypts a key using the specified scrypt parameters into a json blob that can be decrypted later on.
func EncryptPQKeyV3 ¶ added in v0.27.0
func EncryptPQKeyV3(scheme, address string, ext, seed, auth []byte, scryptN, scryptP int) ([]byte, error)
EncryptPQKeyV3 encrypts post-quantum key material into a wallet-cli compatible keystore. scheme is the TIP-899 scheme name ("FN_DSA_512", "ML_DSA_44") and address the Base58Check address; both are stored in clear and are not validated here. ext is the persisted private key and seed the key-generation seed; at least one must be non-empty, an empty one is left out of the file, and each is limited to 4096 bytes. scryptN and scryptP must be within the limits DecryptPQKeyV3 accepts (for example StandardScryptN/StandardScryptP or LightScryptN/LightScryptP).
Experimental: this is a byte-level helper for package pqc; use pqc.EncryptKeystore instead. It may change with TIP-899.
func NewAuthNeededError ¶
NewAuthNeededError creates a new authentication error with the extra details about the needed fields set.
func RecoverPubkey ¶
RecoverPubkey recovers the TRON address from a message hash and its ECDSA signature. The caller's signature slice is never modified; V-byte normalization (Ethereum-style v >= 27), if needed, is applied to an internal copy.
func TextAndHash ¶
TextAndHash is a helper function that calculates a hash for the given message that can be safely used to calculate a signature from.
The hash is calculated as: keccak256("\x19TRON Signed Message:\n"${message length}${message}).
This gives context to the signed message and prevents signing of transactions.
func TextHash ¶
TextHash is a helper function that calculates a hash for the given message that can be safely used to calculate a signature from.
The hash is calculated as: keccak256("\x19TRON Signed Message:\n"${message length}${message}).
This gives context to the signed message and prevents signing of transactions.
Types ¶
type Account ¶
type Account struct {
Address address.Address `json:"address"` // Ethereum account address derived from the key
URL URL `json:"url"` // Optional resource locator within a backend
}
Account represents an Ethereum account located at a specific location defined by the optional URL field.
type AmbiguousAddrError ¶
AmbiguousAddrError is returned when attempting to unlock an address for which more than one file exists.
func (*AmbiguousAddrError) Error ¶
func (err *AmbiguousAddrError) Error() string
type AuthNeededError ¶
type AuthNeededError struct {
Needed string // Extra authentication the user needs to provide
}
AuthNeededError is returned by backends for signing requests where the user is required to provide further authentication before signing can succeed.
This usually means either that a password needs to be supplied, or perhaps a one time PIN code displayed by some hardware device.
func (*AuthNeededError) Error ¶
func (err *AuthNeededError) Error() string
Error implements the standard error interface.
type CryptoJSON ¶
type CryptoJSON struct {
Cipher string `json:"cipher"`
CipherText string `json:"ciphertext"`
CipherParams cipherparamsJSON `json:"cipherparams"`
KDF string `json:"kdf"`
KDFParams map[string]interface{} `json:"kdfparams"`
MAC string `json:"mac"`
}
CryptoJSON ...
func EncryptDataV3 ¶
func EncryptDataV3(data, auth []byte, scryptN, scryptP int) (CryptoJSON, error)
EncryptDataV3 encrypts the data given as 'data' with the password 'auth'.
Plaintext longer than maxCiphertextLen (1024 bytes) is rejected so the ciphertext stays within the same bound DecryptDataV3 enforces. EncryptKey only encrypts a 32-byte private key and is unaffected.
type DerivationPath ¶
type DerivationPath []uint32
DerivationPath represents an HD wallet derivation path as a sequence of child indices.
type Key ¶
type Key struct {
ID uuid.UUID // Version 4 "random" for unique id not derived from key data
// to simplify lookups we also store the address
Address address.Address
// we only store privkey as pubkey/address can be derived from it
// privkey in this struct is always in plaintext
PrivateKey *ecdsa.PrivateKey
}
Key struct represents the account Key
func DecryptKey ¶
DecryptKey decrypts a key from a json blob, returning the private key itself.
func (*Key) MarshalJSON ¶
MarshalJSON will marshal the Key object
func (*Key) UnmarshalJSON ¶
UnmarshalJSON will unmarshal a byte array to the Key object
type KeyStore ¶
type KeyStore struct {
// contains filtered or unexported fields
}
KeyStore manages a key storage directory on disk.
func ForPath ¶
ForPath returns a KeyStore backed by the directory at p using standard scrypt parameters.
func ForPathLight ¶ added in v0.24.3
ForPathLight returns a keystore using lightweight scrypt parameters. This is significantly faster than ForPath but provides weaker key derivation. It should only be used in tests; production code should use ForPath or NewKeyStore with StandardScryptN/StandardScryptP.
func NewKeyStore ¶
NewKeyStore creates a keystore for the given directory.
func (*KeyStore) Close ¶ added in v0.24.3
func (ks *KeyStore) Close()
Close stops the account cache watcher and releases resources. Any active subscriptions are terminated and unlocked keys are zeroed. It is safe to call Close multiple times.
func (*KeyStore) Delete ¶
Delete deletes the key matched by account if the passphrase is correct. If the account contains no filename, the address must match a unique key.
func (*KeyStore) GetDecryptedKey ¶
GetDecryptedKey decrypt and return the key for the account.
func (*KeyStore) HasAddress ¶
HasAddress reports whether a key with the given address is present.
func (*KeyStore) ImportECDSA ¶
ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
func (*KeyStore) Lock ¶
Lock removes the private key with the given address from memory. The decrypted key material is zeroized before removal.
func (*KeyStore) NewAccount ¶
NewAccount generates a new key and stores it into the key directory, encrypting it with the passphrase.
func (*KeyStore) SignHash ¶
SignHash calculates a ECDSA signature for the given hash. The produced signature is in the [R || S || V] format where V is 0 or 1.
func (*KeyStore) SignHashWithPassphrase ¶
func (ks *KeyStore) SignHashWithPassphrase(a Account, passphrase string, hash []byte) (signature []byte, err error)
SignHashWithPassphrase signs hash if the private key matching the given address can be decrypted with the given passphrase. The produced signature is in the [R || S || V] format where V is 0 or 1.
func (*KeyStore) SignTx ¶
func (ks *KeyStore) SignTx(a Account, tx *core.Transaction) (*core.Transaction, error)
SignTx signs the given transaction with the requested account.
func (*KeyStore) SignTxWithPassphrase ¶
func (ks *KeyStore) SignTxWithPassphrase(a Account, passphrase string, tx *core.Transaction) (*core.Transaction, error)
SignTxWithPassphrase signs the transaction if the private key matching the given address can be decrypted with the given passphrase.
func (*KeyStore) Subscribe ¶
func (ks *KeyStore) Subscribe(sink chan<- WalletEvent) event.Subscription
Subscribe implements account.Backend, creating an async subscription to receive notifications on the addition or removal of keystore wallets.
func (*KeyStore) TimedUnlock ¶
TimedUnlock unlocks the given account with the passphrase. The account stays unlocked for the duration of timeout. A timeout of 0 unlocks the account until the program exits. The account must match a unique key file.
If the account address is already unlocked for a duration, TimedUnlock extends or shortens the active unlock timeout. If the address was previously unlocked indefinitely the timeout is not altered.
type URL ¶
type URL struct {
Scheme string // Protocol scheme to identify a capable account backend
Path string // Path for the backend to identify a unique entity
}
URL represents the canonical identification URL of a wallet or account.
It is a simplified version of url.URL, with the important limitations (which are considered features here) that it contains value-copyable components only, as well as that it doesn't do any URL encoding/decoding of special characters.
The former is important to allow an account to be copied without leaving live references to the original version, whereas the latter is important to ensure one single canonical form opposed to many allowed ones by the RFC 3986 spec.
As such, these URLs should not be used outside of the scope of an Ethereum wallet or account.
func (URL) MarshalJSON ¶
MarshalJSON implements the json.Marshaller interface.
func (URL) TerminalString ¶
TerminalString implements the log.TerminalStringer interface.
func (*URL) UnmarshalJSON ¶
UnmarshalJSON parses url.
type Wallet ¶
type Wallet interface {
// URL retrieves the canonical path under which this wallet is reachable. It is
// user by upper layers to define a sorting order over all wallets from multiple
// backends.
URL() URL
// Status returns a textual status to aid the user in the current state of the
// wallet. It also returns an error indicating any failure the wallet might have
// encountered.
Status() (string, error)
// Open initializes access to a wallet instance. It is not meant to unlock or
// decrypt account keys, rather simply to establish a connection to hardware
// wallets and/or to access derivation seeds.
//
// The passphrase parameter may or may not be used by the implementation of a
// particular wallet instance. The reason there is no passwordless open method
// is to strive towards a uniform wallet handling, oblivious to the different
// backend providers.
//
// Please note, if you open a wallet, you must close it to release any allocated
// resources (especially important when working with hardware wallets).
Open(passphrase string) error
// Close releases any resources held by an open wallet instance.
Close() error
// Accounts retrieves the list of signing accounts the wallet is currently aware
// of. For hierarchical deterministic wallets, the list will not be exhaustive,
// rather only contain the accounts explicitly pinned during account derivation.
Accounts() []Account
// Contains returns whether an account is part of this particular wallet or not.
Contains(account Account) bool
// Derive attempts to explicitly derive a hierarchical deterministic account at
// the specified derivation path. If requested, the derived account will be added
// to the wallet's tracked account list.
Derive(path DerivationPath, pin bool) (Account, error)
// SignData requests the wallet to sign the hash of the given data
// It looks up the account specified either solely via its address contained within,
// or optionally with the aid of any location metadata from the embedded URL field.
//
// If the wallet requires additional authentication to sign the request (e.g.
// a password to decrypt the account, or a PIN code o verify the transaction),
// an AuthNeededError instance will be returned, containing infos for the user
// about which fields or actions are needed. The user may retry by providing
// the needed details via SignDataWithPassphrase, or by other means (e.g. unlock
// the account in a keystore).
SignData(account Account, mimeType string, data []byte) ([]byte, error)
// SignDataWithPassphrase is identical to SignData, but also takes a password
// NOTE: there's an chance that an erroneous call might mistake the two strings, and
// supply password in the mimetype field, or vice versa. Thus, an implementation
// should never echo the mimetype or return the mimetype in the error-response
SignDataWithPassphrase(account Account, passphrase, mimeType string, data []byte) ([]byte, error)
// SignText requests the wallet to sign the hash of a given piece of data, prefixed
// by the Ethereum prefix scheme
// It looks up the account specified either solely via its address contained within,
// or optionally with the aid of any location metadata from the embedded URL field.
//
// If the wallet requires additional authentication to sign the request (e.g.
// a password to decrypt the account, or a PIN code o verify the transaction),
// an AuthNeededError instance will be returned, containing infos for the user
// about which fields or actions are needed. The user may retry by providing
// the needed details via SignHashWithPassphrase, or by other means (e.g. unlock
// the account in a keystore).
SignText(account Account, text []byte, useFixedLength ...bool) ([]byte, error)
// SignTextWithPassphrase is identical to Signtext, but also takes a password
SignTextWithPassphrase(account Account, passphrase string, hash []byte) ([]byte, error)
// SignTx requests the wallet to sign the given transaction.
//
// It looks up the account specified either solely via its address contained within,
// or optionally with the aid of any location metadata from the embedded URL field.
//
// If the wallet requires additional authentication to sign the request (e.g.
// a password to decrypt the account, or a PIN code to verify the transaction),
// an AuthNeededError instance will be returned, containing infos for the user
// about which fields or actions are needed. The user may retry by providing
// the needed details via SignTxWithPassphrase, or by other means (e.g. unlock
// the account in a keystore).
SignTx(account Account, tx *core.Transaction) (*core.Transaction, error)
// SignTxWithPassphrase is identical to SignTx, but also takes a password
SignTxWithPassphrase(account Account, passphrase string, tx *core.Transaction) (*core.Transaction, error)
}
Wallet represents a software or hardware wallet that might contain one or more accounts (derived from the same seed).
type WalletEvent ¶
type WalletEvent struct {
Wallet Wallet // Wallet instance arrived or departed
Kind WalletEventType // Event type that happened in the system
}
WalletEvent is emitted when a wallet arrival or departure is detected.
type WalletEventType ¶
type WalletEventType int
WalletEventType represents the different event types that can be fired by the wallet subscription subsystem.
const ( // WalletArrived is fired when a new wallet is detected either via USB or via // a filesystem event in the keystore. WalletArrived WalletEventType = iota // WalletOpened is fired when a wallet is successfully opened with the purpose // of starting any background processes such as automatic key derivation. WalletOpened // WalletDropped is fired when a wallet is no longer detected. WalletDropped )