github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/crypto/bech32.go (about) 1 package crypto 2 3 import ( 4 "errors" 5 "fmt" 6 7 "github.com/gnolang/gno/tm2/pkg/amino" 8 "github.com/gnolang/gno/tm2/pkg/bech32" 9 ) 10 11 func AddressToBech32(addr Address) string { 12 bech32Addr, err := bech32.Encode(Bech32AddrPrefix, addr[:]) 13 if err != nil { 14 panic(err) 15 } 16 return bech32Addr 17 } 18 19 func AddressFromBech32(bech32str string) (Address, error) { 20 bz, err := GetFromBech32(bech32str, Bech32AddrPrefix) 21 if err != nil { 22 return Address{}, err 23 } else { 24 return AddressFromBytes(bz), nil 25 } 26 } 27 28 func PubKeyToBech32(pub PubKey) string { 29 bech32PubKey, err := bech32.Encode(Bech32PubKeyPrefix, pub.Bytes()) 30 if err != nil { 31 panic(err) 32 } 33 return bech32PubKey 34 } 35 36 func PubKeyFromBech32(bech32str string) (pubKey PubKey, err error) { 37 bz, err := GetFromBech32(bech32str, Bech32PubKeyPrefix) 38 if err != nil { 39 return PubKey(nil), err 40 } else { 41 err = amino.Unmarshal(bz, &pubKey) 42 return 43 } 44 } 45 46 // GetFromBech32 decodes a bytestring from a Bech32 encoded string. 47 func GetFromBech32(bech32str, prefix string) ([]byte, error) { 48 if len(bech32str) == 0 { 49 return nil, errors.New("decoding Bech32 failed: must provide a valid bech32 string") 50 } 51 52 hrp, bz, err := bech32.DecodeAndConvert(bech32str) 53 if err != nil { 54 return nil, err 55 } 56 57 if hrp != prefix { 58 return nil, fmt.Errorf("invalid Bech32 prefix; expected %s, got %s", prefix, hrp) 59 } 60 61 return bz, nil 62 }