-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
bech32_codec.go
59 lines (45 loc) · 1.22 KB
/
bech32_codec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package address
import (
"errors"
"strings"
"cosmossdk.io/core/address"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/bech32"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
type Bech32Codec struct {
Bech32Prefix string
}
var _ address.Codec = &Bech32Codec{}
func NewBech32Codec(prefix string) address.Codec {
return Bech32Codec{prefix}
}
// StringToBytes encodes text to bytes
func (bc Bech32Codec) StringToBytes(text string) ([]byte, error) {
if len(strings.TrimSpace(text)) == 0 {
return []byte{}, errors.New("empty address string is not allowed")
}
hrp, bz, err := bech32.DecodeAndConvert(text)
if err != nil {
return nil, err
}
if hrp != bc.Bech32Prefix {
return nil, errorsmod.Wrapf(sdkerrors.ErrLogic, "hrp does not match bech32 prefix: expected '%s' got '%s'", bc.Bech32Prefix, hrp)
}
if err := sdk.VerifyAddressFormat(bz); err != nil {
return nil, err
}
return bz, nil
}
// BytesToString decodes bytes to text
func (bc Bech32Codec) BytesToString(bz []byte) (string, error) {
if len(bz) == 0 {
return "", nil
}
text, err := bech32.ConvertAndEncode(bc.Bech32Prefix, bz)
if err != nil {
return "", err
}
return text, nil
}