keystore

package
v0.7.5-beta.r7.5 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2019 License: GPL-3.0 Imports: 53 Imported by: 5

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.

Index

Constants

View Source
const (

	// HardenedKeyStart is the index at which a hardended key starts.  Each
	// extended key has 2^31 normal child keys and 2^31 hardned child keys.
	// Thus the range for normal child keys is [0, 2^31 - 1] and the range
	// for hardened child keys is [2^31, 2^32 - 1].
	HardenedKeyStart = 0x80000000 // 2^31

	// MinSeedBytes is the minimum number of bytes allowed for a seed to
	// a master node.
	MinSeedBytes = 16 // 128 bits

	// MaxSeedBytes is the maximum number of bytes allowed for a seed to
	// a master node.
	MaxSeedBytes = 64 // 512 bits

)
View Source
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
)
View Source
const KeyStoreScheme = "keystore"

KeyStoreScheme is the protocol scheme prefixing account and wallet URLs.

Variables

View Source
var (
	// ErrDeriveHardFromPublic describes an error in which the caller
	// attempted to derive a hardened extended key from a public key.
	ErrDeriveHardFromPublic = errors.New("cannot derive a hardened key " +
		"from a public key")

	// ErrDeriveBeyondMaxDepth describes an error in which the caller
	// has attempted to derive more than 255 keys from a root key.
	ErrDeriveBeyondMaxDepth = errors.New("cannot derive a key with more than " +
		"255 indices in its path")

	// ErrNotPrivExtKey describes an error in which the caller attempted
	// to extract a private key from a public extended key.
	ErrNotPrivExtKey = errors.New("unable to create private keys from a " +
		"public extended key")

	// ErrInvalidChild describes an error in which the child at a specific
	// index is invalid due to the derived key falling outside of the valid
	// range for secp256k1 private keys.  This error indicates the caller
	// should simply ignore the invalid child extended key at this index and
	// increment to the next index.
	ErrInvalidChild = errors.New("the extended key at this index is invalid")

	// ErrUnusableSeed describes an error in which the provided seed is not
	// usable due to the derived key falling outside of the valid range for
	// secp256k1 private keys.  This error indicates the caller must choose
	// another seed.
	ErrUnusableSeed = errors.New("unusable seed")

	// ErrInvalidSeedLen describes an error in which the provided seed or
	// seed length is not in the allowed range.
	ErrInvalidSeedLen = fmt.Errorf("seed length must be between %d and %d "+
		"bits", MinSeedBytes*8, MaxSeedBytes*8)

	// ErrBadChecksum describes an error in which the checksum encoded with
	// a serialized extended key does not match the calculated value.
	ErrBadChecksum = errors.New("bad extended key checksum")

	// ErrInvalidKeyLen describes an error in which the provided serialized
	// key is not the expected length.
	ErrInvalidKeyLen = errors.New("the provided serialized extended key " +
		"length is invalid")
)
View Source
var (
	ErrLocked      = accounts.NewAuthNeededError("password or unlock")
	ErrNoMatch     = errors.New("no key for given address or file")
	ErrDecrypt     = errors.New("could not decrypt key with given passphrase")
	ErrNoStoreType = errors.New("could not support kestore type")
)
View Source
var HDPrivateKeyID = [4]byte{0x04, 0x88, 0xad, 0xe4}
View Source
var HDPublicKeyID = [4]byte{0x04, 0x88, 0xb2, 0x1e} // starts with xpub
View Source
var KeyStoreType = reflect.TypeOf(&KeyStore{})

KeyStoreType is the reflect type of a keystore backend.

Functions

func DoubleHashB

func DoubleHashB(b []byte) []byte

DoubleHashB calculates hash(hash(b)) and returns the resulting bytes.

func EncryptKey

func EncryptKey(key *Key, auth string, scryptN, scryptP int) ([]byte, error)

EncryptKey encrypts a key using the specified scrypt parameters into a json blob that can be decrypted later on.

func GenerateSeed

func GenerateSeed(length uint8) ([]byte, error)

GenerateSeed returns a cryptographically secure random seed that can be used as the input for the NewMaster function to generate a new master node.

The length is in bytes and it must be between 16 and 64 (128 to 512 bits). The recommended length is 32 (256 bits) as defined by the RecommendedSeedLen constant.

func GetAddress

func GetAddress(keyjson []byte) (string, error)

func Hash160

func Hash160(buf []byte) []byte

Hash160 calculates the hash ripemd160(sha256(b)).

func StoreKey

func StoreKey(dir, auth string, scryptN, scryptP int) (address.AccountAddress, error)

StoreKey generates a key, encrypts with 'auth' and stores in the given directory

Types

type AmbiguousAddrError

type AmbiguousAddrError struct {
	Addr    address.AccountAddress
	Matches []accounts.Account
}

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 HDKey

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

HDKey houses all the information needed to support a hierarchical deterministic extended key. See the package overview documentation for more details on how to use extended keys.

func CreateBip39HDKey

func CreateBip39HDKey() (string, *HDKey, error)

func CreateBip39HDKeyWithPassword

func CreateBip39HDKeyWithPassword(password string) (string, *HDKey, error)

func NewFromMnemonic

func NewFromMnemonic(mnemonic string) (*HDKey, error)

func NewFromMnemonicWithPassword

func NewFromMnemonicWithPassword(mnemonic, password string) (*HDKey, error)

func NewHDKey

func NewHDKey(version, key, chainCode, parentFP []byte, depth uint8,
	childNum uint32, isPrivate bool) *HDKey

NewHDKey returns a new instance of an extended key with the given fields. No error checking is performed here as it's only intended to be a convenience method used to create a populated struct. This function should only by used by applications that need to create custom HDKeys. All other applications should just use NewMaster, Child, or Neuter.

func NewKeyFromString

func NewKeyFromString(key string) (*HDKey, error)

NewKeyFromString returns a new extended key instance from a base58-encoded extended key.

func NewMaster

func NewMaster(seed []byte) (*HDKey, error)

NewMaster creates a new master node for use in creating a hierarchical deterministic key chain. The seed must be between 128 and 512 bits and should be generated by a cryptographically secure random generation source.

NOTE: There is an extremely small chance (< 1 in 2^127) the provided seed will derive to an unusable secret key. The ErrUnusable error will be returned if this should occur, so the caller must check for it and generate a new seed accordingly.

func (*HDKey) Child

func (k *HDKey) Child(i uint32) (*HDKey, error)

Child returns a derived child extended key at the given index. When this extended key is a private extended key (as determined by the IsPrivate function), a private extended key will be derived. Otherwise, the derived extended key will be also be a public extended key.

When the index is greater to or equal than the HardenedKeyStart constant, the derived extended key will be a hardened extended key. It is only possible to derive a hardended extended key from a private extended key. Consequently, this function will return ErrDeriveHardFromPublic if a hardened child extended key is requested from a public extended key.

A hardened extended key is useful since, as previously mentioned, it requires a parent private extended key to derive. In other words, normal child extended public keys can be derived from a parent public extended key (no knowledge of the parent private key) whereas hardened extended keys may not be.

NOTE: There is an extremely small chance (< 1 in 2^127) the specific child index does not derive to a usable child. The ErrInvalidChild error will be returned if this should occur, and the caller is expected to ignore the invalid child and simply increment to the next index.

func (*HDKey) Depth

func (k *HDKey) Depth() uint8

Depth returns the current derivation level with respect to the root.

The root key has depth zero, and the field has a maximum of 255 due to how depth is serialized.

func (*HDKey) DriverChild

func (k *HDKey) DriverChild(index uint32) (*HDKey, error)

func (*HDKey) DriverChildKey

func (k *HDKey) DriverChildKey(index uint32) (*Key, error)

func (*HDKey) DriverPath

func (k *HDKey) DriverPath(path string) (*HDKey, error)

func (*HDKey) DriverPathKey

func (k *HDKey) DriverPathKey(path string) (*Key, error)

func (*HDKey) IsPrivate

func (k *HDKey) IsPrivate() bool

IsPrivate returns whether or not the extended key is a private extended key.

A private extended key can be used to derive both hardened and non-hardened child private and public extended keys. A public extended key can only be used to derive non-hardened child public extended keys.

func (*HDKey) ParentFingerprint

func (k *HDKey) ParentFingerprint() uint32

ParentFingerprint returns a fingerprint of the parent extended key from which this one was derived.

func (*HDKey) PrivateHDkey

func (k *HDKey) PrivateHDkey() string

func (*HDKey) PublicHDkey

func (k *HDKey) PublicHDkey() string

func (*HDKey) Zero

func (k *HDKey) Zero()

Zero manually clears all fields and bytes in the extended key. This can be used to explicitly clear key material from memory for enhanced security against memory scraping. This function only clears this particular key and not any children that have already been derived.

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.AccountAddress

	Tk address.AccountAddress
	// we only store privkey as pubkey/address can be derived from it
	// privkey in this struct is always in plaintext
	PrivateKey *ecdsa.PrivateKey

	At uint64
}

func DecryptKey

func DecryptKey(keyjson []byte, auth string) (*Key, error)

DecryptKey decrypts a key from a json blob, returning the private key itself.

type KeyStore

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

KeyStore manages a key storage directory on disk.

func NewKeyStore

func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore

NewKeyStore creates a keystore for the given directory.

func (*KeyStore) Accounts

func (ks *KeyStore) Accounts() []accounts.Account

Accounts returns all key files present in the directory.

func (*KeyStore) Delete

func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error

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) Export

func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error)

Export exports as a JSON key, encrypted with newPassphrase.

func (*KeyStore) ExportMnemonic

func (ks *KeyStore) ExportMnemonic(a accounts.Account, passphrase string) (string, error)

func (*KeyStore) Find

func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error)

Find resolves the given account into a unique entry in the keystore.

func (*KeyStore) GetSeed

func (ks *KeyStore) GetSeed(a accounts.Account) (*address.Seed, error)

func (*KeyStore) GetSeedWithPassphrase

func (ks *KeyStore) GetSeedWithPassphrase(account accounts.Account, passphrase string) (*address.Seed, error)

func (*KeyStore) HasAddress

func (ks *KeyStore) HasAddress(addr address.AccountAddress) bool

HasAddress reports whether a key with the given address is present.

func (*KeyStore) Import

func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error)

Import stores the given encrypted JSON key into the key directory.

func (*KeyStore) ImportECDSA

func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error)

ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.

func (*KeyStore) ImportPreSaleKey

func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error)

ImportPreSaleKey decrypts the given Sero presale wallet and stores a key file in the key directory. The key file is encrypted with the same passphrase.

func (*KeyStore) ImportTk

func (ks *KeyStore) ImportTk(tk address.AccountAddress) (accounts.Account, error)

func (*KeyStore) Lock

func (ks *KeyStore) Lock(addr address.AccountAddress) error

Lock removes the private key with the given address from memory.

func (*KeyStore) NewAccount

func (ks *KeyStore) NewAccount(passphrase string, at uint64) (accounts.Account, error)

NewAccount generates a new key and stores it into the key directory, encrypting it with the passphrase.

func (*KeyStore) NewAccountWithMnemonic

func (ks *KeyStore) NewAccountWithMnemonic(passphrase string, at uint64) (string, accounts.Account, error)

func (*KeyStore) Subscribe

func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription

Subscribe implements accounts.Backend, creating an async subscription to receive notifications on the addition or removal of keystore wallets.

func (*KeyStore) TimedUnlock

func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error

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.

func (*KeyStore) Unlock

func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error

Unlock unlocks the given account indefinitely.

func (*KeyStore) Update

func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error

Update changes the passphrase of an existing account.

func (*KeyStore) Wallets

func (ks *KeyStore) Wallets() []accounts.Wallet

Wallets implements accounts.Backend, returning all single-key wallets from the keystore directory.

Jump to

Keyboard shortcuts

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