-
Notifications
You must be signed in to change notification settings - Fork 0
/
bech32_codec.go
46 lines (36 loc) · 1.01 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
package keeper
import (
sdk "github.com/mycodeku/transtionhelper/types"
"github.com/mycodeku/transtionhelper/types/address"
"github.com/mycodeku/transtionhelper/types/bech32"
sdkerrors "github.com/mycodeku/transtionhelper/types/errors"
)
type bech32Codec struct {
bech32Prefix string
}
var _ address.Codec = &bech32Codec{}
func newBech32Codec(prefix string) bech32Codec {
return bech32Codec{prefix}
}
// StringToBytes encodes text to bytes
func (bc bech32Codec) StringToBytes(text string) ([]byte, error) {
hrp, bz, err := bech32.DecodeAndConvert(text)
if err != nil {
return nil, err
}
if hrp != bc.bech32Prefix {
return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "hrp does not match bech32Prefix")
}
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) {
text, err := bech32.ConvertAndEncode(bc.bech32Prefix, bz)
if err != nil {
return "", err
}
return text, nil
}