keyring

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2021 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package keys provides common key management API.

The Keybase interface

The Keybase interface defines the methods that a type needs to implement to be used as key storage backend. This package provides few implementations out-of-the-box.

NewLegacy

The NewLegacy constructor returns an on-disk implementation backed by LevelDB storage that has been the default implementation used by the SDK until v0.38.0. Due to security concerns, it is recommended to drop it in favor of the NewKeyring constructor as it will be removed in future releases.

NewInMemory

The NewInMemory constructor returns an implementation backed by an in-memory, goroutine-safe map that has historically been used for testing purposes or on-the-fly key generation as the generated keys are discarded when the process terminates or the type instance is garbage collected.

New

The New constructor returns an implementation backed by a keyring library (https://github.com/99designs/keyring), whose aim is to provide a common abstraction and uniform interface between secret stores available for Windows, macOS, and most GNU/Linux distributions as well as operating system-agnostic encrypted file-based backends.

The backends:

os		The instance returned by this constructor uses the operating system's default
		credentials store to handle keys storage operations securely. It should be noted
		that the keyring keyring may be kept unlocked for the whole duration of the user
		session.
file	This backend more closely resembles the previous keyring storage used prior to
		v0.38.1. It stores the keyring encrypted within the apps configuration directory.
		This keyring will request a password each time it is accessed, which may occur
		multiple times in a single command resulting in repeated password prompts.
kwallet	This backend uses KDE Wallet Manager as a credentials management application:
		https://github.com/KDE/kwallet
pass	This backend uses the pass command line utility to store and retrieve keys:
		https://www.passwordstore.org/
test	This backend stores keys insecurely to disk. It does not prompt for a password to
		be unlocked and it should be use only for testing purposes.
memory	Same instance as returned by NewInMemory. This backend uses a transient storage. Keys
		are discarded when the process terminates or the type instance is garbage collected.

Index

Examples

Constants

View Source
const (
	BackendFile    = "file"
	BackendOS      = "os"
	BackendKWallet = "kwallet"
	BackendPass    = "pass"
	BackendTest    = "test"
	BackendMemory  = "memory"
)
View Source
const (
	// DefaultBIP39Passphrase used for deriving seed from mnemonic
	DefaultBIP39Passphrase = ""
)

Variables

View Source
var (
	// ErrUnsupportedSigningAlgo is raised when the caller tries to use a
	// different signing scheme than secp256k1.
	ErrUnsupportedSigningAlgo = errors.New("unsupported signing algo")

	// ErrUnsupportedLanguage is raised when the caller tries to use a
	// different language than english for creating a mnemonic sentence.
	ErrUnsupportedLanguage = errors.New("unsupported language: only english is supported")
)
View Source
var CryptoCdc *codec.Codec

CryptoCdc defines the codec required for keys and info

Functions

func RegisterCodec

func RegisterCodec(cdc *codec.Codec)

RegisterCodec registers concrete types and interfaces on the given codec.

func SignWithLedger

func SignWithLedger(info Info, msg []byte) (sig []byte, pub tmcrypto.PubKey, err error)

SignWithLedger signs a binary message with the ledger device referenced by an Info object and returns the signed bytes and the public key. It returns an error if the device could not be queried or it returned an error.

Types

type DeriveKeyFunc

type DeriveKeyFunc func(mnemonic string, bip39Passphrase, hdPath string, algo hd.PubKeyType) ([]byte, error)

DeriveKeyFunc defines the function to derive a new key from a seed and hd path

type Exporter

type Exporter interface {
	// Export public key
	ExportPubKeyArmor(uid string) (string, error)
	ExportPubKeyArmorByAddress(address sdk.Address) (string, error)
	// ExportPrivKey returns a private key in ASCII armored format.
	// It returns an error if the key does not exist or a wrong encryption passphrase is supplied.
	ExportPrivKeyArmor(uid, encryptPassphrase string) (armor string, err error)
	ExportPrivKeyArmorByAddress(address sdk.Address, encryptPassphrase string) (armor string, err error)
}

Exporter is implemented by key stores that support export of public and private keys.

type Importer

type Importer interface {
	// ImportPrivKey imports ASCII armored passphrase-encrypted private keys.
	ImportPrivKey(uid, armor, passphrase string) error
	// ImportPubKey imports ASCII armored public keys.
	ImportPubKey(uid string, armor string) error
}

Importer is implemented by key stores that support import of public and private keys.

type Info

type Info interface {
	// Human-readable type for key listing
	GetType() KeyType
	// Name of the key
	GetName() string
	// Public key
	GetPubKey() crypto.PubKey
	// Address
	GetAddress() types.AccAddress
	// Bip44 Path
	GetPath() (*hd.BIP44Params, error)
	// Algo
	GetAlgo() hd.PubKeyType
}

Info is the publicly exposed information about a keypair

func NewMultiInfo

func NewMultiInfo(name string, pub crypto.PubKey) Info

NewMultiInfo creates a new multiInfo instance

type InfoImporter

type InfoImporter interface {
	// Import imports ASCII-armored private keys.
	Import(uid string, armor string) error
}

InfoImporter is implemented by those types that want to provide functions necessary to migrate keys from LegacyKeybase types to Keyring types.

func NewInfoImporter

func NewInfoImporter(
	appName, backend, rootDir string, userInput io.Reader, opts ...Option,
) (InfoImporter, error)

type KeyOutput

type KeyOutput struct {
	Name      string                 `json:"name" yaml:"name"`
	Type      string                 `json:"type" yaml:"type"`
	Address   string                 `json:"address" yaml:"address"`
	PubKey    string                 `json:"pubkey" yaml:"pubkey"`
	Mnemonic  string                 `json:"mnemonic,omitempty" yaml:"mnemonic"`
	Threshold uint                   `json:"threshold,omitempty" yaml:"threshold"`
	PubKeys   []multisigPubKeyOutput `json:"pubkeys,omitempty" yaml:"pubkeys"`
}

KeyOutput defines a structure wrapping around an Info object used for output functionality.

func Bech32ConsKeyOutput

func Bech32ConsKeyOutput(keyInfo Info) (KeyOutput, error)

Bech32ConsKeyOutput create a KeyOutput in with "cons" Bech32 prefixes.

func Bech32KeyOutput

func Bech32KeyOutput(keyInfo Info) (KeyOutput, error)

Bech32KeyOutput create a KeyOutput in with "acc" Bech32 prefixes. If the public key is a multisig public key, then the threshold and constituent public keys will be added.

func Bech32KeysOutput

func Bech32KeysOutput(infos []Info) ([]KeyOutput, error)

Bech32KeysOutput returns a slice of KeyOutput objects, each with the "acc" Bech32 prefixes, given a slice of Info objects. It returns an error if any call to Bech32KeyOutput fails.

func Bech32ValKeyOutput

func Bech32ValKeyOutput(keyInfo Info) (KeyOutput, error)

Bech32ValKeyOutput create a KeyOutput in with "val" Bech32 prefixes.

func NewKeyOutput

func NewKeyOutput(name, keyType, address, pubkey string) KeyOutput

NewKeyOutput creates a default KeyOutput instance without Mnemonic, Threshold and PubKeys

type KeyType

type KeyType uint

KeyType reflects a human-readable type for key listing.

const (
	TypeLocal   KeyType = 0
	TypeLedger  KeyType = 1
	TypeOffline KeyType = 2
	TypeMulti   KeyType = 3
)

Info KeyTypes

func (KeyType) String

func (kt KeyType) String() string

String implements the stringer interface for KeyType.

type KeybaseOption

type KeybaseOption func(*kbOptions)

KeybaseOption overrides options for the db.

type Keyring

type Keyring interface {
	// List all keys.
	List() ([]Info, error)

	// Key and KeyByAddress return keys by uid and address respectively.
	Key(uid string) (Info, error)
	KeyByAddress(address sdk.Address) (Info, error)

	// Delete and DeleteByAddress remove keys from the keyring.
	Delete(uid string) error
	DeleteByAddress(address sdk.Address) error

	// NewMnemonic generates a new mnemonic, derives a hierarchical deterministic
	// key from that, and persists it to the storage. Returns the generated mnemonic and the key
	// Info. It returns an error if it fails to generate a key for the given algo type, or if
	// another key is already stored under the same name.
	NewMnemonic(uid string, language Language, hdPath string, algo SignatureAlgo) (Info, string, error)

	// NewAccount converts a mnemonic to a private key and BIP-39 HD Path and persists it.
	NewAccount(uid, mnemonic, bip39Passwd, hdPath string, algo SignatureAlgo) (Info, error)

	// SaveLedgerKey retrieves a public key reference from a Ledger device and persists it.
	SaveLedgerKey(uid string, algo SignatureAlgo, hrp string, coinType, account, index uint32) (Info, error)

	// SavePubKey stores a public key and returns the persisted Info structure.
	SavePubKey(uid string, pubkey tmcrypto.PubKey, algo hd.PubKeyType) (Info, error)

	// SaveMultisig stores and returns a new multsig (offline) key reference.
	SaveMultisig(uid string, pubkey tmcrypto.PubKey) (Info, error)

	Signer

	Importer
	Exporter
}

Keyring exposes operations over a backend supported by github.com/99designs/keyring.

func New

func New(
	appName, backend, rootDir string, userInput io.Reader, opts ...Option,
) (Keyring, error)

NewKeyring creates a new instance of a keyring. Keyring ptions can be applied when generating the new instance. Available backends are "os", "file", "kwallet", "memory", "pass", "test".

Example
// Select the encryption and storage for your cryptostore
cstore := NewInMemory()

sec := hd.Secp256k1

// Add keys and see they return in alphabetical order
bob, _, err := cstore.NewMnemonic("Bob", English, sdk.FullFundraiserPath, sec)
if err != nil {
	// this should never happen
	fmt.Println(err)
} else {
	// return info here just like in List
	fmt.Println(bob.GetName())
}
_, _, _ = cstore.NewMnemonic("Alice", English, sdk.FullFundraiserPath, sec)
_, _, _ = cstore.NewMnemonic("Carl", English, sdk.FullFundraiserPath, sec)
info, _ := cstore.List()
for _, i := range info {
	fmt.Println(i.GetName())
}

// We need to use passphrase to generate a signature
tx := []byte("deadbeef")
sig, pub, err := cstore.Sign("Bob", tx)
if err != nil {
	fmt.Println("don't accept real passphrase")
}

// and we can validate the signature with publicly available info
binfo, _ := cstore.Key("Bob")
if !binfo.GetPubKey().Equals(bob.GetPubKey()) {
	fmt.Println("Get and Create return different keys")
}

if pub.Equals(binfo.GetPubKey()) {
	fmt.Println("signed by Bob")
}
if !pub.VerifyBytes(tx, sig) {
	fmt.Println("invalid signature")
}
Output:

Bob
Alice
Bob
Carl
signed by Bob

func NewInMemory

func NewInMemory(opts ...Option) Keyring

NewInMemory creates a transient keyring useful for testing purposes and on-the-fly key generation. Keybase options can be applied when generating this new Keybase.

type Language

type Language int

Language is a language to create the BIP 39 mnemonic in. Currently, only english is supported though. Find a list of all supported languages in the BIP 39 spec (word lists).

const (
	// English is the default language to create a mnemonic.
	// It is the only supported language by this package.
	English Language = iota + 1
	// Japanese is currently not supported.
	Japanese
	// Korean is currently not supported.
	Korean
	// Spanish is currently not supported.
	Spanish
	// ChineseSimplified is currently not supported.
	ChineseSimplified
	// ChineseTraditional is currently not supported.
	ChineseTraditional
	// French is currently not supported.
	French
	// Italian is currently not supported.
	Italian
)

type LegacyKeybase

type LegacyKeybase interface {
	List() ([]Info, error)
	Export(name string) (armor string, err error)
	ExportPrivKey(name, decryptPassphrase, encryptPassphrase string) (armor string, err error)
	ExportPubKey(name string) (armor string, err error)
	Close() error
}

LegacyKeybase is implemented by the legacy keybase implementation.

func NewLegacy

func NewLegacy(name, dir string, opts ...KeybaseOption) (LegacyKeybase, error)

NewLegacy creates a new instance of a legacy keybase.

type Option

type Option func(options *Options)

Option overrides keyring configuration options.

type Options

type Options struct {
	SupportedAlgos       SigningAlgoList
	SupportedAlgosLedger SigningAlgoList
}

Options define the options of the Keyring

type PrivKeyGenFunc

type PrivKeyGenFunc func(bz []byte, algo hd.PubKeyType) (crypto.PrivKey, error)

PrivKeyGenFunc defines the function to convert derived key bytes to a tendermint private key

type SignatureAlgo

type SignatureAlgo interface {
	Name() hd.PubKeyType
	Derive() hd.DeriveFn
	Generate() hd.GenerateFn
}

func NewSigningAlgoFromString

func NewSigningAlgoFromString(str string) (SignatureAlgo, error)

type Signer

type Signer interface {
	// Sign sign byte messages with a user key.
	Sign(uid string, msg []byte) ([]byte, tmcrypto.PubKey, error)

	// SignByAddress sign byte messages with a user key providing the address.
	SignByAddress(address sdk.Address, msg []byte) ([]byte, tmcrypto.PubKey, error)
}

Signer is implemented by key stores that want to provide signing capabilities.

type SigningAlgoList

type SigningAlgoList []SignatureAlgo

func (SigningAlgoList) Contains

func (l SigningAlgoList) Contains(algo SignatureAlgo) bool

Jump to

Keyboard shortcuts

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