cosmos-sdk: Index | Examples | Files

package keyring

import ""

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.


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.


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.


The New constructor returns an implementation backed by a keyring library (, 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
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:
pass	This backend uses the pass command line utility to store and retrieve keys:
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.



Package Files

codec.go doc.go errors.go info.go keyring.go legacy.go output.go signing_algorithms.go types.go


const (
    BackendFile    = "file"
    BackendOS      = "os"
    BackendKWallet = "kwallet"
    BackendPass    = "pass"
    BackendTest    = "test"
    BackendMemory  = "memory"

Backend options for Keyring

const (
    // DefaultBIP39Passphrase used for deriving seed from mnemonic
    DefaultBIP39Passphrase = ""


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")
var CryptoCdc *codec.Codec

CryptoCdc defines the codec required for keys and info

func RegisterCodec Uses

func RegisterCodec(cdc *codec.Codec)

RegisterCodec registers concrete types and interfaces on the given codec.

func SignWithLedger Uses

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.

type DeriveKeyFunc Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

NewMultiInfo creates a new multiInfo instance

type InfoImporter Uses

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 Uses

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

type KeyOutput Uses

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 Uses

func Bech32ConsKeyOutput(keyInfo Info) (KeyOutput, error)

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

func Bech32KeyOutput Uses

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 Uses

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 Uses

func Bech32ValKeyOutput(keyInfo Info) (KeyOutput, error)

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

func NewKeyOutput Uses

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

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

type KeyType Uses

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 Uses

func (kt KeyType) String() string

String implements the stringer interface for KeyType.

type KeybaseOption Uses

type KeybaseOption func(*kbOptions)

KeybaseOption overrides options for the db.

type Keyring Uses

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

    // Supported signing algorithms for Keyring and Ledger respectively.
    SupportedAlgorithms() (SigningAlgoList, SigningAlgoList)

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



Keyring exposes operations over a backend supported by

func New Uses

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

New 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".


// 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
} else {
    // return info here just like in List
_, _, _ = cstore.NewMnemonic("Alice", English, sdk.FullFundraiserPath, sec)
_, _, _ = cstore.NewMnemonic("Carl", English, sdk.FullFundraiserPath, sec)
info, _ := cstore.List()
for _, i := range info {

// 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")


signed by Bob

func NewInMemory Uses

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 Uses

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.
    // Korean is currently not supported.
    // Spanish is currently not supported.
    // ChineseSimplified is currently not supported.
    // ChineseTraditional is currently not supported.
    // French is currently not supported.
    // Italian is currently not supported.

type LegacyKeybase Uses

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 Uses

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

NewLegacy creates a new instance of a legacy keybase.

type Option Uses

type Option func(options *Options)

Option overrides keyring configuration options.

type Options Uses

type Options struct {
    // supported signing algorithms for keyring
    SupportedAlgos SigningAlgoList
    // supported signing algorithms for Ledger
    SupportedAlgosLedger SigningAlgoList

Options define the options of the Keyring.

type PrivKeyGenFunc Uses

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 Uses

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

SignatureAlgo defines the interface for a keyring supported algorithm.

func NewSigningAlgoFromString Uses

func NewSigningAlgoFromString(str string, algoList SigningAlgoList) (SignatureAlgo, error)

NewSigningAlgoFromString creates a supported SignatureAlgo.

type Signer Uses

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 Uses

type SigningAlgoList []SignatureAlgo

SigningAlgoList is a slice of signature algorithms

func (SigningAlgoList) Contains Uses

func (sal SigningAlgoList) Contains(algo SignatureAlgo) bool

Contains returns true if the SigningAlgoList the given SignatureAlgo.

func (SigningAlgoList) String Uses

func (sal SigningAlgoList) String() string

String returns a comma separated string of the signature algorithm names in the list.

Package keyring imports 26 packages (graph) and is imported by 10 packages. Updated 2020-07-29. Refresh now. Tools for package owners.