cosmos-sdk/types/address.go

662 lines
17 KiB
Go
Raw Normal View History

2018-01-07 12:27:56 -08:00
package types
2018-01-06 14:22:21 -08:00
import (
2018-08-04 22:56:48 -07:00
"bytes"
2018-03-17 11:18:04 -07:00
"encoding/hex"
2018-07-09 16:06:05 -07:00
"encoding/json"
2018-03-17 11:18:04 -07:00
"errors"
"fmt"
2019-02-08 15:54:40 -08:00
"strings"
"sync"
2018-03-17 11:18:04 -07:00
yaml "gopkg.in/yaml.v2"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/internal/conv"
"github.com/cosmos/cosmos-sdk/types/address"
"github.com/cosmos/cosmos-sdk/types/bech32"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/hashicorp/golang-lru/simplelru"
2018-01-06 14:22:21 -08:00
)
2018-05-28 16:27:34 -07:00
const (
// Constants defined here are the defaults value for address.
// You can use the specific values for your project.
// Add the follow lines to the `main()` of your server.
//
// config := sdk.GetConfig()
// config.SetBech32PrefixForAccount(yourBech32PrefixAccAddr, yourBech32PrefixAccPub)
// config.SetBech32PrefixForValidator(yourBech32PrefixValAddr, yourBech32PrefixValPub)
// config.SetBech32PrefixForConsensusNode(yourBech32PrefixConsAddr, yourBech32PrefixConsPub)
// config.SetPurpose(yourPurpose)
// config.SetCoinType(yourCoinType)
// config.Seal()
// Bech32MainPrefix defines the main SDK Bech32 prefix of an account's address
Bech32MainPrefix = "cosmos"
// Purpose is the ATOM purpose as defined in SLIP44 (https://github.com/satoshilabs/slips/blob/master/slip-0044.md)
Purpose = 44
// CoinType is the ATOM coin type as defined in SLIP44 (https://github.com/satoshilabs/slips/blob/master/slip-0044.md)
CoinType = 118
// FullFundraiserPath is the parts of the BIP44 HD path that are fixed by
// what we used during the ATOM fundraiser.
FullFundraiserPath = "m/44'/118'/0'/0/0"
// PrefixAccount is the prefix for account keys
PrefixAccount = "acc"
// PrefixValidator is the prefix for validator keys
PrefixValidator = "val"
// PrefixConsensus is the prefix for consensus keys
PrefixConsensus = "cons"
// PrefixPublic is the prefix for public keys
PrefixPublic = "pub"
// PrefixOperator is the prefix for operator keys
PrefixOperator = "oper"
// PrefixAddress is the prefix for addresses
PrefixAddress = "addr"
2018-07-04 14:07:06 -07:00
// Bech32PrefixAccAddr defines the Bech32 prefix of an account's address
Bech32PrefixAccAddr = Bech32MainPrefix
// Bech32PrefixAccPub defines the Bech32 prefix of an account's public key
Bech32PrefixAccPub = Bech32MainPrefix + PrefixPublic
// Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address
Bech32PrefixValAddr = Bech32MainPrefix + PrefixValidator + PrefixOperator
// Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key
Bech32PrefixValPub = Bech32MainPrefix + PrefixValidator + PrefixOperator + PrefixPublic
// Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address
Bech32PrefixConsAddr = Bech32MainPrefix + PrefixValidator + PrefixConsensus
// Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key
Bech32PrefixConsPub = Bech32MainPrefix + PrefixValidator + PrefixConsensus + PrefixPublic
2018-05-28 16:27:34 -07:00
)
// cache variables
var (
// AccAddress.String() is expensive and if unoptimized dominantly showed up in profiles,
// yet has no mechanisms to trivially cache the result given that AccAddress is a []byte type.
accAddrMu sync.Mutex
accAddrCache *simplelru.LRU
consAddrMu sync.Mutex
consAddrCache *simplelru.LRU
valAddrMu sync.Mutex
valAddrCache *simplelru.LRU
)
func init() {
var err error
// in total the cache size is 61k entries. Key is 32 bytes and value is around 50-70 bytes.
// That will make around 92 * 61k * 2 (LRU) bytes ~ 11 MB
if accAddrCache, err = simplelru.NewLRU(60000, nil); err != nil {
panic(err)
}
if consAddrCache, err = simplelru.NewLRU(500, nil); err != nil {
panic(err)
}
if valAddrCache, err = simplelru.NewLRU(500, nil); err != nil {
panic(err)
}
}
// Address is a common interface for different types of addresses used by the SDK
type Address interface {
Equals(Address) bool
Empty() bool
Marshal() ([]byte, error)
MarshalJSON() ([]byte, error)
Bytes() []byte
String() string
Format(s fmt.State, verb rune)
}
// Ensure that different address types implement the interface
var _ Address = AccAddress{}
var _ Address = ValAddress{}
var _ Address = ConsAddress{}
var _ yaml.Marshaler = AccAddress{}
var _ yaml.Marshaler = ValAddress{}
var _ yaml.Marshaler = ConsAddress{}
// ----------------------------------------------------------------------------
// account
// ----------------------------------------------------------------------------
2018-07-06 00:06:53 -07:00
// AccAddress a wrapper around bytes meant to represent an account address.
// When marshaled to a string or JSON, it uses Bech32.
2018-07-06 00:06:53 -07:00
type AccAddress []byte
2018-07-03 21:52:48 -07:00
// AccAddressFromHex creates an AccAddress from a hex string.
2018-07-09 16:06:05 -07:00
func AccAddressFromHex(address string) (addr AccAddress, err error) {
bz, err := addressBytesFromHexString(address)
return AccAddress(bz), err
2018-07-06 00:06:53 -07:00
}
// VerifyAddressFormat verifies that the provided bytes form a valid address
// according to the default address rules or a custom address verifier set by
// GetConfig().SetAddressVerifier()
func VerifyAddressFormat(bz []byte) error {
verifier := GetConfig().GetAddressVerifier()
if verifier != nil {
return verifier(bz)
Merge PR #4159: Module/Genesis Generalization * first commit * gaia cleanup * ... * staking multihooks * missing module function return args * bank module name constant * working, module interface for x/ * got this thing compiling * make test compiles and passes * remove expanded simulation invariants * genesis issue * continued * continued * register crisis routes thought mm * begin blocker to mm * end blocker to mm * empty routes not initialized * move gaia initChainer sanity check to baseapp * remove codecs from module manager * reorging genesis stuff * module manager passed by reference/bugfixes from working last commit int int * move invariant checks from gaia to crisis * typo * basic refactors cmd/gaia/init * working * MultiStakingHooks from types to x/staking/types int * default module manager order of operations from input modules * working * typo * add AppModuleBasic * moduleBasicManager / non-test code compiles * working attempting to get tests passing * make test passes * sim random genesis fix * export bug * ... * genutil module * genutil working * refactored - happy with non-testing code in cmd/ * ... * lint fixes * comment improvement * cli test fix * compile housing * working through compile errors * working gettin' compilin' * non-test code compiles * move testnet to its own module * reworking tests int * bez staging PR 1 comments * concise module function-of names * moved all tests from genesis_test.go to other genutil tests * genaccounts package, add genutil and genaccounts to app.go * docs for genutil genaccounts * genaccounts iterate fn * non-test code with genaccounts/ now compiles * working test compiling * debugging tests * resolved all make test compile errors * test debuggin * resolved all unit tests, introduced param module * cli-test compile fixes * staking initialization bug * code comment improvements, changelog entries * BasicGaiaApp -> ModuleBasics * highlevel explanation in types/module.go * @alexanderbez comment revisions * @fedekunze PR comments * @alexanderbez PR comments (x2) * @cwgoes comments (minor updates) * @fedekunze suggestions * panic on init with multiple validator updates from different modules * initchain panic makes validate genesis fail int * AppModuleGenesis seperation int * test * remove init panic logic in validate genesis replaced with TODO * set maxprocs to match system's GOMAXPROCS * Update circleci * Cap maxprocs in CI to 4 * @alexanderbez recent comments addressed * less blocks in twouble sims int * runsim error output flag * -e on import_export as well * error out int * Try to fix failures * runsim
2019-05-16 08:25:32 -07:00
}
if len(bz) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrUnknownAddress, "addresses cannot be empty")
}
if len(bz) > address.MaxAddrLen {
return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "address max length is %d, got %d", address.MaxAddrLen, len(bz))
}
return nil
}
// AccAddressFromBech32 creates an AccAddress from a Bech32 string.
2018-07-09 16:06:05 -07:00
func AccAddressFromBech32(address string) (addr AccAddress, err error) {
2019-02-08 15:54:40 -08:00
if len(strings.TrimSpace(address)) == 0 {
return AccAddress{}, errors.New("empty address string is not allowed")
2019-02-08 15:54:40 -08:00
}
bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix()
2019-02-08 15:54:40 -08:00
bz, err := GetFromBech32(address, bech32PrefixAccAddr)
2018-07-06 00:06:53 -07:00
if err != nil {
return nil, err
}
err = VerifyAddressFormat(bz)
if err != nil {
return nil, err
2019-02-08 15:54:40 -08:00
}
2018-07-06 00:06:53 -07:00
return AccAddress(bz), nil
2018-07-03 21:52:48 -07:00
}
// Returns boolean for whether two AccAddresses are Equal
func (aa AccAddress) Equals(aa2 Address) bool {
if aa.Empty() && aa2.Empty() {
return true
}
return bytes.Equal(aa.Bytes(), aa2.Bytes())
}
// Returns boolean for whether an AccAddress is empty
func (aa AccAddress) Empty() bool {
return aa == nil || len(aa) == 0
}
// Marshal returns the raw address bytes. It is needed for protobuf
// compatibility.
func (aa AccAddress) Marshal() ([]byte, error) {
return aa, nil
}
// Unmarshal sets the address to the given data. It is needed for protobuf
// compatibility.
func (aa *AccAddress) Unmarshal(data []byte) error {
*aa = data
2018-07-03 21:52:48 -07:00
return nil
}
// MarshalJSON marshals to JSON using Bech32.
func (aa AccAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(aa.String())
2018-07-03 21:52:48 -07:00
}
// MarshalYAML marshals to YAML using Bech32.
func (aa AccAddress) MarshalYAML() (interface{}, error) {
return aa.String(), nil
}
// UnmarshalJSON unmarshals from JSON assuming Bech32 encoding.
func (aa *AccAddress) UnmarshalJSON(data []byte) error {
2018-07-09 16:06:05 -07:00
var s string
err := json.Unmarshal(data, &s)
Change `address` from bytes to bech32 strings (#7242) * init * Fix bank proto messages * missing conversions * remove casttype for addresses * Fix tests * Fix consaddress * more test fixes * Fix tests * fixed tests * migrate missing proto declarations * format * Fix format * Fix alignment * Fix more tests * Fix ibc merge issue * Fix fmt * Fix more tests * Fix missing address declarations * Fix staking tests * Fix more tests * Fix config * fixed tests * Fix more tests * Update staking grpc tests * Fix merge issue * fixed failing tests in x/distr * fixed sim tests * fixed failing tests * Fix bugs * Add logs * fixed slashing issue * Fix staking grpc tests * Fix all bank tests :) * Fix tests in distribution * Fix more tests in distr * Fix slashing tests * Fix statking tests * Fix evidence tests * Fix gov tests * Fix bug in create vesting account * Fix test * remove fmt * fixed gov tests * fixed x/ibc tests * fixed x/ibc-transfer tests * fixed staking tests * fixed staking tests * fixed test * fixed distribution issue * fix pagination test * fmt * lint * fix build * fix format * revert tally tests * revert tally tests * lint * Fix sim test * revert * revert * fixed tally issue * fix tests * revert * fmt * refactor * remove `GetAddress()` * remove fmt * revert fmt.Striger usage * Fix tests * Fix rest test * disable interfacer lint check * make proto-format * add nolint rule * remove stray println Co-authored-by: aleem1314 <aleem.md789@gmail.com> Co-authored-by: atheesh <atheesh@vitwit.com>
2020-09-25 03:25:37 -07:00
2018-07-09 16:06:05 -07:00
if err != nil {
return err
2018-07-03 21:52:48 -07:00
}
if s == "" {
*aa = AccAddress{}
return nil
}
2018-07-03 21:52:48 -07:00
aa2, err := AccAddressFromBech32(s)
2018-07-03 21:52:48 -07:00
if err != nil {
return err
}
*aa = aa2
2018-07-03 21:52:48 -07:00
return nil
}
// UnmarshalYAML unmarshals from JSON assuming Bech32 encoding.
func (aa *AccAddress) UnmarshalYAML(data []byte) error {
var s string
err := yaml.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*aa = AccAddress{}
return nil
}
aa2, err := AccAddressFromBech32(s)
if err != nil {
return err
}
*aa = aa2
return nil
}
// Bytes returns the raw address bytes.
func (aa AccAddress) Bytes() []byte {
return aa
2018-07-03 21:52:48 -07:00
}
// String implements the Stringer interface.
func (aa AccAddress) String() string {
2019-02-08 15:54:40 -08:00
if aa.Empty() {
return ""
}
var key = conv.UnsafeBytesToStr(aa)
accAddrMu.Lock()
defer accAddrMu.Unlock()
addr, ok := accAddrCache.Get(key)
if ok {
return addr.(string)
2018-06-07 15:32:14 -07:00
}
return cacheBech32Addr(GetConfig().GetBech32AccountAddrPrefix(), aa, accAddrCache, key)
2018-07-03 21:52:48 -07:00
}
// Format implements the fmt.Formatter interface.
2018-08-31 15:22:37 -07:00
// nolint: errcheck
func (aa AccAddress) Format(s fmt.State, verb rune) {
2018-07-03 21:52:48 -07:00
switch verb {
case 's':
s.Write([]byte(aa.String()))
2018-07-03 21:52:48 -07:00
case 'p':
s.Write([]byte(fmt.Sprintf("%p", aa)))
2018-07-03 21:52:48 -07:00
default:
s.Write([]byte(fmt.Sprintf("%X", []byte(aa))))
2018-07-03 21:52:48 -07:00
}
2018-06-07 15:32:14 -07:00
}
// ----------------------------------------------------------------------------
// validator operator
// ----------------------------------------------------------------------------
2018-08-04 22:56:48 -07:00
// ValAddress defines a wrapper around bytes meant to present a validator's
// operator. When marshaled to a string or JSON, it uses Bech32.
2018-07-06 00:06:53 -07:00
type ValAddress []byte
// ValAddressFromHex creates a ValAddress from a hex string.
2018-07-09 16:06:05 -07:00
func ValAddressFromHex(address string) (addr ValAddress, err error) {
bz, err := addressBytesFromHexString(address)
return ValAddress(bz), err
}
// ValAddressFromBech32 creates a ValAddress from a Bech32 string.
2018-07-09 16:06:05 -07:00
func ValAddressFromBech32(address string) (addr ValAddress, err error) {
2019-02-08 15:54:40 -08:00
if len(strings.TrimSpace(address)) == 0 {
return ValAddress{}, errors.New("empty address string is not allowed")
2019-02-08 15:54:40 -08:00
}
bech32PrefixValAddr := GetConfig().GetBech32ValidatorAddrPrefix()
2019-02-08 15:54:40 -08:00
bz, err := GetFromBech32(address, bech32PrefixValAddr)
2018-06-07 15:32:14 -07:00
if err != nil {
2018-07-06 00:06:53 -07:00
return nil, err
2018-06-07 15:32:14 -07:00
}
err = VerifyAddressFormat(bz)
if err != nil {
return nil, err
2019-02-08 15:54:40 -08:00
}
2018-07-06 00:06:53 -07:00
return ValAddress(bz), nil
}
// Returns boolean for whether two ValAddresses are Equal
func (va ValAddress) Equals(va2 Address) bool {
if va.Empty() && va2.Empty() {
return true
}
return bytes.Equal(va.Bytes(), va2.Bytes())
}
// Returns boolean for whether an AccAddress is empty
func (va ValAddress) Empty() bool {
return va == nil || len(va) == 0
}
// Marshal returns the raw address bytes. It is needed for protobuf
// compatibility.
func (va ValAddress) Marshal() ([]byte, error) {
return va, nil
2018-06-07 15:32:14 -07:00
}
// Unmarshal sets the address to the given data. It is needed for protobuf
// compatibility.
func (va *ValAddress) Unmarshal(data []byte) error {
*va = data
2018-07-06 00:06:53 -07:00
return nil
}
// MarshalJSON marshals to JSON using Bech32.
func (va ValAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(va.String())
}
// MarshalYAML marshals to YAML using Bech32.
func (va ValAddress) MarshalYAML() (interface{}, error) {
return va.String(), nil
}
// UnmarshalJSON unmarshals from JSON assuming Bech32 encoding.
func (va *ValAddress) UnmarshalJSON(data []byte) error {
2018-07-09 16:06:05 -07:00
var s string
2018-07-09 16:06:05 -07:00
err := json.Unmarshal(data, &s)
if err != nil {
return err
2018-07-06 00:06:53 -07:00
}
if s == "" {
*va = ValAddress{}
return nil
}
2018-07-06 00:06:53 -07:00
va2, err := ValAddressFromBech32(s)
2018-06-07 15:32:14 -07:00
if err != nil {
2018-07-06 00:06:53 -07:00
return err
2018-06-07 15:32:14 -07:00
}
*va = va2
2018-07-06 00:06:53 -07:00
return nil
2018-06-07 15:32:14 -07:00
}
// UnmarshalYAML unmarshals from YAML assuming Bech32 encoding.
func (va *ValAddress) UnmarshalYAML(data []byte) error {
var s string
err := yaml.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*va = ValAddress{}
return nil
}
va2, err := ValAddressFromBech32(s)
if err != nil {
return err
}
*va = va2
return nil
}
// Bytes returns the raw address bytes.
func (va ValAddress) Bytes() []byte {
return va
}
// String implements the Stringer interface.
func (va ValAddress) String() string {
2019-02-08 15:54:40 -08:00
if va.Empty() {
return ""
}
var key = conv.UnsafeBytesToStr(va)
valAddrMu.Lock()
defer valAddrMu.Unlock()
addr, ok := valAddrCache.Get(key)
if ok {
return addr.(string)
2018-06-07 15:32:14 -07:00
}
return cacheBech32Addr(GetConfig().GetBech32ValidatorAddrPrefix(), va, valAddrCache, key)
2018-06-07 15:32:14 -07:00
}
// Format implements the fmt.Formatter interface.
2018-08-31 15:22:37 -07:00
// nolint: errcheck
func (va ValAddress) Format(s fmt.State, verb rune) {
2018-07-06 00:06:53 -07:00
switch verb {
case 's':
s.Write([]byte(va.String()))
2018-07-06 00:06:53 -07:00
case 'p':
s.Write([]byte(fmt.Sprintf("%p", va)))
2018-07-06 00:06:53 -07:00
default:
s.Write([]byte(fmt.Sprintf("%X", []byte(va))))
2018-03-17 11:18:04 -07:00
}
}
// ----------------------------------------------------------------------------
// consensus node
// ----------------------------------------------------------------------------
// ConsAddress defines a wrapper around bytes meant to present a consensus node.
// When marshaled to a string or JSON, it uses Bech32.
type ConsAddress []byte
// ConsAddressFromHex creates a ConsAddress from a hex string.
func ConsAddressFromHex(address string) (addr ConsAddress, err error) {
bz, err := addressBytesFromHexString(address)
return ConsAddress(bz), err
}
// ConsAddressFromBech32 creates a ConsAddress from a Bech32 string.
func ConsAddressFromBech32(address string) (addr ConsAddress, err error) {
2019-02-08 15:54:40 -08:00
if len(strings.TrimSpace(address)) == 0 {
return ConsAddress{}, errors.New("empty address string is not allowed")
2019-02-08 15:54:40 -08:00
}
bech32PrefixConsAddr := GetConfig().GetBech32ConsensusAddrPrefix()
2019-02-08 15:54:40 -08:00
bz, err := GetFromBech32(address, bech32PrefixConsAddr)
if err != nil {
return nil, err
}
err = VerifyAddressFormat(bz)
if err != nil {
return nil, err
2019-02-08 15:54:40 -08:00
}
return ConsAddress(bz), nil
}
// get ConsAddress from pubkey
func GetConsAddress(pubkey cryptotypes.PubKey) ConsAddress {
return ConsAddress(pubkey.Address())
}
// Returns boolean for whether two ConsAddress are Equal
func (ca ConsAddress) Equals(ca2 Address) bool {
if ca.Empty() && ca2.Empty() {
2018-08-16 18:35:17 -07:00
return true
}
return bytes.Equal(ca.Bytes(), ca2.Bytes())
2018-08-04 22:56:48 -07:00
}
// Returns boolean for whether an ConsAddress is empty
func (ca ConsAddress) Empty() bool {
return ca == nil || len(ca) == 0
}
// Marshal returns the raw address bytes. It is needed for protobuf
// compatibility.
func (ca ConsAddress) Marshal() ([]byte, error) {
return ca, nil
}
// Unmarshal sets the address to the given data. It is needed for protobuf
// compatibility.
func (ca *ConsAddress) Unmarshal(data []byte) error {
*ca = data
return nil
}
// MarshalJSON marshals to JSON using Bech32.
func (ca ConsAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(ca.String())
}
// MarshalYAML marshals to YAML using Bech32.
func (ca ConsAddress) MarshalYAML() (interface{}, error) {
return ca.String(), nil
}
// UnmarshalJSON unmarshals from JSON assuming Bech32 encoding.
func (ca *ConsAddress) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*ca = ConsAddress{}
return nil
}
ca2, err := ConsAddressFromBech32(s)
if err != nil {
return err
}
*ca = ca2
return nil
}
// UnmarshalYAML unmarshals from YAML assuming Bech32 encoding.
func (ca *ConsAddress) UnmarshalYAML(data []byte) error {
var s string
err := yaml.Unmarshal(data, &s)
if err != nil {
return err
}
if s == "" {
*ca = ConsAddress{}
return nil
}
ca2, err := ConsAddressFromBech32(s)
if err != nil {
return err
}
*ca = ca2
return nil
}
// Bytes returns the raw address bytes.
func (ca ConsAddress) Bytes() []byte {
return ca
}
// String implements the Stringer interface.
func (ca ConsAddress) String() string {
2019-02-08 15:54:40 -08:00
if ca.Empty() {
return ""
}
var key = conv.UnsafeBytesToStr(ca)
consAddrMu.Lock()
defer consAddrMu.Unlock()
addr, ok := consAddrCache.Get(key)
if ok {
return addr.(string)
}
return cacheBech32Addr(GetConfig().GetBech32ConsensusAddrPrefix(), ca, consAddrCache, key)
}
// Bech32ifyAddressBytes returns a bech32 representation of address bytes.
// Returns an empty sting if the byte slice is 0-length. Returns an error if the bech32 conversion
// fails or the prefix is empty.
func Bech32ifyAddressBytes(prefix string, bs []byte) (string, error) {
if len(bs) == 0 {
return "", nil
}
if len(prefix) == 0 {
return "", errors.New("prefix cannot be empty")
}
return bech32.ConvertAndEncode(prefix, bs)
}
// MustBech32ifyAddressBytes returns a bech32 representation of address bytes.
// Returns an empty sting if the byte slice is 0-length. It panics if the bech32 conversion
// fails or the prefix is empty.
func MustBech32ifyAddressBytes(prefix string, bs []byte) string {
s, err := Bech32ifyAddressBytes(prefix, bs)
if err != nil {
panic(err)
}
return s
}
// Format implements the fmt.Formatter interface.
2018-08-31 15:22:37 -07:00
// nolint: errcheck
func (ca ConsAddress) Format(s fmt.State, verb rune) {
switch verb {
case 's':
s.Write([]byte(ca.String()))
case 'p':
s.Write([]byte(fmt.Sprintf("%p", ca)))
default:
s.Write([]byte(fmt.Sprintf("%X", []byte(ca))))
}
2018-08-04 22:56:48 -07:00
}
// ----------------------------------------------------------------------------
// auxiliary
// ----------------------------------------------------------------------------
Remove bech32 PubKey support (#7477) * Move PubKey bech32 to legacy package and migrate the usage where possible * update /server * wip * move proto json encoding helper functions to internal * update internal/marshal * wip * update sections which needs legacybech32 * update validators output * fix conflicts * slashing update * add more tests and helper function for ANY JSON serialization * update slashing * Update function documentation * Rename code any-marshal helper functions * Update pubkey unpacking test * Update test comments * solve TestDecodeStore * solve legacytx issues * all code compiles * keyring tests * keyring cleanup * remove AssertMsg * fix some tests * fix add_ledger_test.go * update cli tests * debug cli test * rename clashed bech32 names * linter fixes * update tmservice tests * linter: update legacy deprecated checks * fix names * linting * legacybech32 pubkey type rename * fix staking client * fix test compilation * fix TestGetCmdQuerySigningInfo * rename NewIfcJSONAnyMarshaler * keyring: remove duplicated information from multinfo structure * todo cleanups * Update Changelog * remove some legacybech32 from tests * remove todos * remove printlnJSON from /server CLI and amino encoding * remove protocdc.MarshalJSON * client/show remove duplicated function * remove protocdc package * comment update * remove legacybech32.MustMarshalPubKey from a test * add todo * fix TestPublicKeyUnsafe test * review update * fix bech32 UnmarshalPubKey * Use codec.MarshalIfcJSON * fix linter issues * merging conflict: fix codec.Unmarshal calls * cleanups * Update CHANGELOG.md Co-authored-by: Aaron Craelius <aaron@regen.network> * Reword changelog updates * use pubkey.String for comparison in Test_runAddCmdLedgerWithCustomCoinType * Update GetCmdQuerySigningInfo example * cli: update keys add docs * Add errors AsOf and errors.ErrIO type * restore multisigPubKeyInfo structure bring it back to multiInfo struct * Update codec/proto_codec.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * Update crypto/keys/ed25519/ed25519_test.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * Update codec/proto_codec.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * move pubkey any marshaling tests * Apply suggestions from code review Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review updates * adding missing return * errors: use IsOf instead of AsOf * keyring: add a correct check for key not found in keyring.Get * add checkKeyNotFound * fix linter issues * fix: keyring key not found check * fix keyring tests * fix linting issues * cli tests * fix: 'simd keys show <key> -p' * fix: TestVerifyMultisignature * rename keyring Bech32... functions to Mk... * fix RunAddCmd * Update pubkey display * wip * add more tests * udate keyring output tests * remove todo from ledger tests * rename MkKeyOutput * Changelog update * solve liner issues * add link to github issue Co-authored-by: Aaron Craelius <aaron@regen.network> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2021-03-25 07:53:22 -07:00
var errBech32EmptyAddress = errors.New("decoding Bech32 address failed: must provide a non empty address")
// GetFromBech32 decodes a bytestring from a Bech32 encoded string.
func GetFromBech32(bech32str, prefix string) ([]byte, error) {
2018-06-01 07:23:58 -07:00
if len(bech32str) == 0 {
Remove bech32 PubKey support (#7477) * Move PubKey bech32 to legacy package and migrate the usage where possible * update /server * wip * move proto json encoding helper functions to internal * update internal/marshal * wip * update sections which needs legacybech32 * update validators output * fix conflicts * slashing update * add more tests and helper function for ANY JSON serialization * update slashing * Update function documentation * Rename code any-marshal helper functions * Update pubkey unpacking test * Update test comments * solve TestDecodeStore * solve legacytx issues * all code compiles * keyring tests * keyring cleanup * remove AssertMsg * fix some tests * fix add_ledger_test.go * update cli tests * debug cli test * rename clashed bech32 names * linter fixes * update tmservice tests * linter: update legacy deprecated checks * fix names * linting * legacybech32 pubkey type rename * fix staking client * fix test compilation * fix TestGetCmdQuerySigningInfo * rename NewIfcJSONAnyMarshaler * keyring: remove duplicated information from multinfo structure * todo cleanups * Update Changelog * remove some legacybech32 from tests * remove todos * remove printlnJSON from /server CLI and amino encoding * remove protocdc.MarshalJSON * client/show remove duplicated function * remove protocdc package * comment update * remove legacybech32.MustMarshalPubKey from a test * add todo * fix TestPublicKeyUnsafe test * review update * fix bech32 UnmarshalPubKey * Use codec.MarshalIfcJSON * fix linter issues * merging conflict: fix codec.Unmarshal calls * cleanups * Update CHANGELOG.md Co-authored-by: Aaron Craelius <aaron@regen.network> * Reword changelog updates * use pubkey.String for comparison in Test_runAddCmdLedgerWithCustomCoinType * Update GetCmdQuerySigningInfo example * cli: update keys add docs * Add errors AsOf and errors.ErrIO type * restore multisigPubKeyInfo structure bring it back to multiInfo struct * Update codec/proto_codec.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * Update crypto/keys/ed25519/ed25519_test.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * Update codec/proto_codec.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * move pubkey any marshaling tests * Apply suggestions from code review Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review updates * adding missing return * errors: use IsOf instead of AsOf * keyring: add a correct check for key not found in keyring.Get * add checkKeyNotFound * fix linter issues * fix: keyring key not found check * fix keyring tests * fix linting issues * cli tests * fix: 'simd keys show <key> -p' * fix: TestVerifyMultisignature * rename keyring Bech32... functions to Mk... * fix RunAddCmd * Update pubkey display * wip * add more tests * udate keyring output tests * remove todo from ledger tests * rename MkKeyOutput * Changelog update * solve liner issues * add link to github issue Co-authored-by: Aaron Craelius <aaron@regen.network> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2021-03-25 07:53:22 -07:00
return nil, errBech32EmptyAddress
2018-05-28 16:27:34 -07:00
}
2018-06-01 07:23:58 -07:00
hrp, bz, err := bech32.DecodeAndConvert(bech32str)
2018-05-28 16:27:34 -07:00
if err != nil {
return nil, err
}
if hrp != prefix {
return nil, fmt.Errorf("invalid Bech32 prefix; expected %s, got %s", prefix, hrp)
2018-05-28 16:27:34 -07:00
}
return bz, nil
}
func addressBytesFromHexString(address string) ([]byte, error) {
if len(address) == 0 {
return nil, errors.New("decoding Bech32 address failed: must provide an address")
}
return hex.DecodeString(address)
}
// cacheBech32Addr is not concurrency safe. Concurrent access to cache causes race condition.
func cacheBech32Addr(prefix string, addr []byte, cache *simplelru.LRU, cacheKey string) string {
bech32Addr, err := bech32.ConvertAndEncode(prefix, addr)
if err != nil {
panic(err)
}
cache.Add(cacheKey, bech32Addr)
return bech32Addr
}