-
Notifications
You must be signed in to change notification settings - Fork 31
/
address.go
736 lines (609 loc) · 20 KB
/
address.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
package types
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/dgraph-io/ristretto"
yaml "gopkg.in/yaml.v2"
"github.com/line/lbm-sdk/codec/legacy"
cryptotypes "github.com/line/lbm-sdk/crypto/types"
"github.com/line/lbm-sdk/types/address"
"github.com/line/lbm-sdk/types/bech32"
sdkerrors "github.com/line/lbm-sdk/types/errors"
)
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()
BytesAddrLen = 20
// Bech32MainPrefix defines the main SDK Bech32 prefix of an account's address
Bech32MainPrefix = "link"
// Purpose is the LINK purpose as defined in SLIP44 (https://github.com/satoshilabs/slips/blob/master/slip-0044.md)
Purpose = 44
// CoinType is the LINK coin type as defined in SLIP44 (https://github.com/satoshilabs/slips/blob/master/slip-0044.md)
CoinType = 438
// FullFundraiserPath is the parts of the BIP44 HD path that are fixed by
// what we used during the LINK fundraiser.
FullFundraiserPath = "m/44'/438'/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"
// 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
)
const DefaultBech32CacheSize = 1 << 30 // maximum size of cache (1GB)
// 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
// ----------------------------------------------------------------------------
// TODO We should add a layer to choose whether to access the cache or to run actual conversion
// bech32 encoding and decoding takes a lot of time, so memoize it
var bech32Cache Bech32Cache
type Bech32Cache struct {
bech32ToAddrCache *ristretto.Cache
addrToBech32Cache *ristretto.Cache
}
func SetBech32Cache(size int64) {
var err error
config := &ristretto.Config{
NumCounters: 1e7, // number of keys to track frequency of (10M).
MaxCost: size,
BufferItems: 64, // number of keys per Get buffer.
}
bech32Cache.bech32ToAddrCache, err = ristretto.NewCache(config)
if err != nil {
panic(err)
}
bech32Cache.addrToBech32Cache, err = ristretto.NewCache(config)
if err != nil {
panic(err)
}
}
// Used only for test cases
func InvalidateBech32Cache() {
bech32Cache.bech32ToAddrCache = nil
bech32Cache.addrToBech32Cache = nil
}
func (cache *Bech32Cache) GetAddr(bech32Addr string) ([]byte, bool) {
if cache.bech32ToAddrCache != nil {
rawAddr, ok := cache.bech32ToAddrCache.Get(bech32Addr)
if ok {
return rawAddr.([]byte), ok
}
}
return nil, false
}
func (cache *Bech32Cache) GetBech32(rawAddr []byte) (string, bool) {
if cache.addrToBech32Cache != nil {
bech32Addr, ok := cache.addrToBech32Cache.Get(string(rawAddr))
if ok {
return bech32Addr.(string), ok
}
}
return "", false
}
func (cache *Bech32Cache) Set(bech32Addr string, rawAddr []byte) {
if cache.bech32ToAddrCache != nil {
cache.bech32ToAddrCache.Set(bech32Addr, rawAddr, int64(len(rawAddr)))
}
if cache.addrToBech32Cache != nil {
cache.addrToBech32Cache.Set(string(rawAddr), bech32Addr, int64(len(bech32Addr)))
}
}
// AccAddress a wrapper around bytes meant to represent an account address.
// When marshaled to a string or JSON, it uses Bech32.
type AccAddress string
// AccAddressFromHex creates an AccAddress from a hex string.
func AccAddressFromHex(addressBytesHex string) (addr AccAddress, err error) {
bz, err := addressBytesFromHexString(addressBytesHex)
return BytesToAccAddress(bz), err
}
// 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)
}
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
}
// Returns boolean for whether two AccAddresses are Equal
func (aa AccAddress) Equals(aa2 Address) bool {
if aa.Empty() && aa2.Empty() {
return true
}
return strings.EqualFold(aa.String(), aa2.String())
}
// Returns boolean for whether an AccAddress is empty
func (aa AccAddress) Empty() bool {
return len(string(aa)) == 0
}
// Marshal returns the raw address bytes. It is needed for protobuf
// compatibility.
func (aa AccAddress) Marshal() ([]byte, error) {
return []byte(aa.String()), nil
}
// Unmarshal sets the address to the given data. It is needed for protobuf
// compatibility.
func (aa *AccAddress) Unmarshal(data []byte) error {
*aa = AccAddress(data)
return nil
}
// MarshalJSON marshals to JSON using Bech32.
func (aa AccAddress) MarshalJSON() ([]byte, error) {
return json.Marshal(aa.String())
}
// 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 {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
// TODO: address validation?
*aa = AccAddress(s)
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
}
// TODO: address validation?
*aa = AccAddress(s)
return nil
}
// Bytes returns the raw address bytes.
func (aa AccAddress) Bytes() []byte {
return []byte(aa.String())
}
// String implements the Stringer interface.
func (aa AccAddress) String() string {
return string(aa)
}
func (aa AccAddress) ToValAddress() ValAddress {
bytes, _ := AccAddressToBytes(aa.String())
return BytesToValAddress(bytes)
}
func (aa AccAddress) ToConsAddress() ConsAddress {
bytes, _ := AccAddressToBytes(aa.String())
return BytesToConsAddress(bytes)
}
// Format implements the fmt.Formatter interface.
// nolint: errcheck
func (aa AccAddress) Format(s fmt.State, verb rune) {
switch verb {
case 's':
s.Write([]byte(aa.String()))
case 'p':
s.Write([]byte(fmt.Sprintf("%p", aa)))
default:
s.Write([]byte(fmt.Sprintf("%X", []byte(aa))))
}
}
func BytesToAccAddress(addrBytes []byte) AccAddress {
bech32Addr, ok := bech32Cache.GetBech32(addrBytes)
if ok {
return AccAddress(bech32Addr)
}
bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix()
bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixAccAddr, addrBytes)
if err != nil {
panic(err)
}
bech32Cache.Set(bech32Addr, addrBytes)
return AccAddress(bech32Addr)
}
func AccAddressToBytes(bech32Addr string) ([]byte, error) {
bz, ok := bech32Cache.GetAddr(bech32Addr)
if ok {
return bz, nil
}
if len(strings.TrimSpace(bech32Addr)) == 0 {
return nil, errors.New("empty address string is not allowed")
}
bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix()
bz, err := GetFromBech32(bech32Addr, bech32PrefixAccAddr)
if err != nil {
return nil, err
}
err = VerifyAddressFormat(bz)
if err != nil {
return nil, err
}
bech32Cache.Set(bech32Addr, bz)
return bz, nil
}
func ValidateAccAddress(bech32Addr string) error {
_, err := AccAddressToBytes(bech32Addr)
return err
}
// ----------------------------------------------------------------------------
// validator operator
// ----------------------------------------------------------------------------
// ValAddress defines a wrapper around bytes meant to present a validator's
// operator. When marshaled to a string or JSON, it uses Bech32.
type ValAddress string
func BytesToValAddress(addrBytes []byte) ValAddress {
bech32PrefixValAddr := GetConfig().GetBech32ValidatorAddrPrefix()
bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixValAddr, addrBytes)
if err != nil {
panic(err)
}
return ValAddress(bech32Addr)
}
func ValAddressToBytes(bech32Addr string) ([]byte, error) {
if len(strings.TrimSpace(bech32Addr)) == 0 {
return nil, errors.New("empty address string is not allowed")
}
bech32PrefixValAddr := GetConfig().GetBech32ValidatorAddrPrefix()
bz, err := GetFromBech32(bech32Addr, bech32PrefixValAddr)
if err != nil {
return nil, err
}
err = VerifyAddressFormat(bz)
if err != nil {
return nil, err
}
return bz, nil
}
func ValidateValAddress(bech32Addr string) error {
_, err := ValAddressToBytes(bech32Addr)
return err
}
// ValAddressFromHex creates a ValAddress from a hex string.
func ValAddressFromHex(address string) (addr ValAddress, err error) {
bz, err := addressBytesFromHexString(address)
return BytesToValAddress(bz), err
}
// Returns boolean for whether two ValAddresses are Equal
func (va ValAddress) Equals(va2 Address) bool {
if va.Empty() && va2.Empty() {
return true
}
return strings.EqualFold(va.String(), va2.String())
}
// Returns boolean for whether an AccAddress is empty
func (va ValAddress) Empty() bool {
return va == ""
}
// Marshal returns the raw address bytes. It is needed for protobuf
// compatibility.
func (va ValAddress) Marshal() ([]byte, error) {
return []byte(va), nil
}
// Unmarshal sets the address to the given data. It is needed for protobuf
// compatibility.
func (va *ValAddress) Unmarshal(data []byte) error {
*va = ValAddress(data)
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 {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
*va = ValAddress(s)
return nil
}
// 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
}
*va = ValAddress(s)
return nil
}
// Bytes returns the raw address bytes.
func (va ValAddress) Bytes() []byte {
return []byte(va.String())
}
// String implements the Stringer interface.
func (va ValAddress) String() string {
return string(va)
}
// Format implements the fmt.Formatter interface.
// nolint: errcheck
func (va ValAddress) Format(s fmt.State, verb rune) {
switch verb {
case 's':
s.Write([]byte(va.String()))
case 'p':
s.Write([]byte(fmt.Sprintf("%p", va)))
default:
s.Write([]byte(fmt.Sprintf("%X", []byte(va))))
}
}
func (va ValAddress) ToAccAddress() AccAddress {
bytes, _ := ValAddressToBytes(va.String())
return BytesToAccAddress(bytes)
}
func (va ValAddress) ToConsAddress() ConsAddress {
bytes, _ := ValAddressToBytes(va.String())
return BytesToConsAddress(bytes)
}
// ----------------------------------------------------------------------------
// 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 string
func BytesToConsAddress(addrBytes []byte) ConsAddress {
bech32PrefixConsAddr := GetConfig().GetBech32ConsensusAddrPrefix()
bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixConsAddr, addrBytes)
if err != nil {
panic(err)
}
return ConsAddress(bech32Addr)
}
func ConsAddressToBytes(bech32Addr string) ([]byte, error) {
if len(strings.TrimSpace(bech32Addr)) == 0 {
return nil, errors.New("empty address string is not allowed")
}
bech32PrefixConsAddr := GetConfig().GetBech32ConsensusAddrPrefix()
bz, err := GetFromBech32(bech32Addr, bech32PrefixConsAddr)
if err != nil {
return nil, err
}
err = VerifyAddressFormat(bz)
if err != nil {
return nil, err
}
return bz, nil
}
// ConsAddressFromHex creates a ConsAddress from a hex string.
func ConsAddressFromHex(address string) (addr ConsAddress, err error) {
bz, err := addressBytesFromHexString(address)
return BytesToConsAddress(bz), err
}
func ValidateConsAddress(bech32Addr string) error {
_, err := ConsAddressToBytes(bech32Addr)
return err
}
// get ConsAddress from pubkey
func GetConsAddress(pubkey cryptotypes.PubKey) ConsAddress {
return BytesToConsAddress(pubkey.Address())
}
// Returns boolean for whether two ConsAddress are Equal
func (ca ConsAddress) Equals(ca2 Address) bool {
if ca.Empty() && ca2.Empty() {
return true
}
return strings.EqualFold(ca.String(), ca2.String())
}
// Returns boolean for whether an ConsAddress is empty
func (ca ConsAddress) Empty() bool {
return ca == ""
}
// Marshal returns the raw address bytes. It is needed for protobuf
// compatibility.
func (ca ConsAddress) Marshal() ([]byte, error) {
return []byte(ca), nil
}
// Unmarshal sets the address to the given data. It is needed for protobuf
// compatibility.
func (ca *ConsAddress) Unmarshal(data []byte) error {
*ca = ConsAddress(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
}
*ca = ConsAddress(s)
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
}
*ca = ConsAddress(s)
return nil
}
// Bytes returns the raw address bytes.
func (ca ConsAddress) Bytes() []byte {
return []byte(ca)
}
// String implements the Stringer interface.
func (ca ConsAddress) String() string {
return string(ca)
}
// 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.
// 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))))
}
}
// ----------------------------------------------------------------------------
// auxiliary
// ----------------------------------------------------------------------------
var errBech32EmptyAddress = errors.New("decoding Bech32 address failed: must provide a non empty address")
// Bech32PubKeyType defines a string type alias for a Bech32 public key type.
type Bech32PubKeyType string
// Bech32 conversion constants
const (
Bech32PubKeyTypeAccPub Bech32PubKeyType = "accpub"
Bech32PubKeyTypeValPub Bech32PubKeyType = "valpub"
Bech32PubKeyTypeConsPub Bech32PubKeyType = "conspub"
)
// Bech32ifyPubKey returns a Bech32 encoded string containing the appropriate
// prefix based on the key type provided for a given PublicKey.
// TODO: Remove Bech32ifyPubKey and all usages (cosmos/cosmos-sdk/issues/#7357)
func Bech32ifyPubKey(pkt Bech32PubKeyType, pubkey cryptotypes.PubKey) (string, error) {
var bech32Prefix string
switch pkt {
case Bech32PubKeyTypeAccPub:
bech32Prefix = GetConfig().GetBech32AccountPubPrefix()
case Bech32PubKeyTypeValPub:
bech32Prefix = GetConfig().GetBech32ValidatorPubPrefix()
case Bech32PubKeyTypeConsPub:
bech32Prefix = GetConfig().GetBech32ConsensusPubPrefix()
}
return bech32.ConvertAndEncode(bech32Prefix, legacy.Cdc.MustMarshal(pubkey))
}
// MustBech32ifyPubKey calls Bech32ifyPubKey except it panics on error.
func MustBech32ifyPubKey(pkt Bech32PubKeyType, pubkey cryptotypes.PubKey) string {
res, err := Bech32ifyPubKey(pkt, pubkey)
if err != nil {
panic(err)
}
return res
}
// GetPubKeyFromBech32 returns a PublicKey from a bech32-encoded PublicKey with
// a given key type.
func GetPubKeyFromBech32(pkt Bech32PubKeyType, pubkeyStr string) (cryptotypes.PubKey, error) {
var bech32Prefix string
switch pkt {
case Bech32PubKeyTypeAccPub:
bech32Prefix = GetConfig().GetBech32AccountPubPrefix()
case Bech32PubKeyTypeValPub:
bech32Prefix = GetConfig().GetBech32ValidatorPubPrefix()
case Bech32PubKeyTypeConsPub:
bech32Prefix = GetConfig().GetBech32ConsensusPubPrefix()
}
bz, err := GetFromBech32(pubkeyStr, bech32Prefix)
if err != nil {
return nil, err
}
return legacy.PubKeyFromBytes(bz)
}
// MustGetPubKeyFromBech32 calls GetPubKeyFromBech32 except it panics on error.
func MustGetPubKeyFromBech32(pkt Bech32PubKeyType, pubkeyStr string) cryptotypes.PubKey {
res, err := GetPubKeyFromBech32(pkt, pubkeyStr)
if err != nil {
panic(err)
}
return res
}
// GetFromBech32 decodes a bytestring from a Bech32 encoded string.
func GetFromBech32(bech32str, prefix string) ([]byte, error) {
if len(bech32str) == 0 {
return nil, errBech32EmptyAddress
}
hrp, bz, err := bech32.DecodeAndConvert(bech32str)
if err != nil {
return nil, err
}
if hrp != prefix {
return nil, fmt.Errorf("invalid Bech32 prefix; expected %s, got %s", prefix, hrp)
}
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)
}