github.com/cosmos/cosmos-sdk@v0.50.10/types/address.go (about) 1 package types 2 3 import ( 4 "bytes" 5 "encoding/hex" 6 "encoding/json" 7 "errors" 8 "fmt" 9 "strings" 10 "sync" 11 "sync/atomic" 12 13 "github.com/hashicorp/golang-lru/simplelru" 14 "sigs.k8s.io/yaml" 15 16 errorsmod "cosmossdk.io/errors" 17 18 cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" 19 "github.com/cosmos/cosmos-sdk/internal/conv" 20 "github.com/cosmos/cosmos-sdk/types/address" 21 "github.com/cosmos/cosmos-sdk/types/bech32" 22 sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 23 ) 24 25 const ( 26 // Constants defined here are the defaults value for address. 27 // You can use the specific values for your project. 28 // Add the follow lines to the `main()` of your server. 29 // 30 // config := sdk.GetConfig() 31 // config.SetBech32PrefixForAccount(yourBech32PrefixAccAddr, yourBech32PrefixAccPub) 32 // config.SetBech32PrefixForValidator(yourBech32PrefixValAddr, yourBech32PrefixValPub) 33 // config.SetBech32PrefixForConsensusNode(yourBech32PrefixConsAddr, yourBech32PrefixConsPub) 34 // config.SetPurpose(yourPurpose) 35 // config.SetCoinType(yourCoinType) 36 // config.Seal() 37 38 // Bech32MainPrefix defines the main SDK Bech32 prefix of an account's address 39 Bech32MainPrefix = "cosmos" 40 41 // Purpose is the ATOM purpose as defined in SLIP44 (https://github.com/satoshilabs/slips/blob/master/slip-0044.md) 42 Purpose = 44 43 44 // CoinType is the ATOM coin type as defined in SLIP44 (https://github.com/satoshilabs/slips/blob/master/slip-0044.md) 45 CoinType = 118 46 47 // FullFundraiserPath is the parts of the BIP44 HD path that are fixed by 48 // what we used during the ATOM fundraiser. 49 FullFundraiserPath = "m/44'/118'/0'/0/0" 50 51 // PrefixAccount is the prefix for account keys 52 PrefixAccount = "acc" 53 // PrefixValidator is the prefix for validator keys 54 PrefixValidator = "val" 55 // PrefixConsensus is the prefix for consensus keys 56 PrefixConsensus = "cons" 57 // PrefixPublic is the prefix for public keys 58 PrefixPublic = "pub" 59 // PrefixOperator is the prefix for operator keys 60 PrefixOperator = "oper" 61 62 // PrefixAddress is the prefix for addresses 63 PrefixAddress = "addr" 64 65 // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address 66 Bech32PrefixAccAddr = Bech32MainPrefix 67 // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key 68 Bech32PrefixAccPub = Bech32MainPrefix + PrefixPublic 69 // Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address 70 Bech32PrefixValAddr = Bech32MainPrefix + PrefixValidator + PrefixOperator 71 // Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key 72 Bech32PrefixValPub = Bech32MainPrefix + PrefixValidator + PrefixOperator + PrefixPublic 73 // Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address 74 Bech32PrefixConsAddr = Bech32MainPrefix + PrefixValidator + PrefixConsensus 75 // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key 76 Bech32PrefixConsPub = Bech32MainPrefix + PrefixValidator + PrefixConsensus + PrefixPublic 77 ) 78 79 // cache variables 80 var ( 81 // AccAddress.String() is expensive and if unoptimized dominantly showed up in profiles, 82 // yet has no mechanisms to trivially cache the result given that AccAddress is a []byte type. 83 accAddrMu sync.Mutex 84 accAddrCache *simplelru.LRU 85 consAddrMu sync.Mutex 86 consAddrCache *simplelru.LRU 87 valAddrMu sync.Mutex 88 valAddrCache *simplelru.LRU 89 90 isCachingEnabled atomic.Bool 91 ) 92 93 // sentinel errors 94 var ( 95 ErrEmptyHexAddress = errors.New("decoding address from hex string failed: empty address") 96 ) 97 98 func init() { 99 var err error 100 SetAddrCacheEnabled(true) 101 102 // in total the cache size is 61k entries. Key is 32 bytes and value is around 50-70 bytes. 103 // That will make around 92 * 61k * 2 (LRU) bytes ~ 11 MB 104 if accAddrCache, err = simplelru.NewLRU(60000, nil); err != nil { 105 panic(err) 106 } 107 if consAddrCache, err = simplelru.NewLRU(500, nil); err != nil { 108 panic(err) 109 } 110 if valAddrCache, err = simplelru.NewLRU(500, nil); err != nil { 111 panic(err) 112 } 113 } 114 115 // SetAddrCacheEnabled enables or disables accAddrCache, consAddrCache, and valAddrCache. By default, caches are enabled. 116 func SetAddrCacheEnabled(enabled bool) { 117 isCachingEnabled.Store(enabled) 118 } 119 120 // IsAddrCacheEnabled returns if the address caches are enabled. 121 func IsAddrCacheEnabled() bool { 122 return isCachingEnabled.Load() 123 } 124 125 // Address is a common interface for different types of addresses used by the SDK 126 type Address interface { 127 Equals(Address) bool 128 Empty() bool 129 Marshal() ([]byte, error) 130 MarshalJSON() ([]byte, error) 131 Bytes() []byte 132 String() string 133 Format(s fmt.State, verb rune) 134 } 135 136 // Ensure that different address types implement the interface 137 var ( 138 _ Address = AccAddress{} 139 _ Address = ValAddress{} 140 _ Address = ConsAddress{} 141 ) 142 143 // ---------------------------------------------------------------------------- 144 // account 145 // ---------------------------------------------------------------------------- 146 147 // AccAddress a wrapper around bytes meant to represent an account address. 148 // When marshaled to a string or JSON, it uses Bech32. 149 type AccAddress []byte 150 151 // AccAddressFromHexUnsafe creates an AccAddress from a HEX-encoded string. 152 // 153 // Note, this function is considered unsafe as it may produce an AccAddress from 154 // otherwise invalid input, such as a transaction hash. Please use 155 // AccAddressFromBech32. 156 func AccAddressFromHexUnsafe(address string) (addr AccAddress, err error) { 157 bz, err := addressBytesFromHexString(address) 158 return AccAddress(bz), err 159 } 160 161 // VerifyAddressFormat verifies that the provided bytes form a valid address 162 // according to the default address rules or a custom address verifier set by 163 // GetConfig().SetAddressVerifier(). 164 // TODO make an issue to get rid of global Config 165 // ref: https://github.com/cosmos/cosmos-sdk/issues/9690 166 func VerifyAddressFormat(bz []byte) error { 167 verifier := GetConfig().GetAddressVerifier() 168 if verifier != nil { 169 return verifier(bz) 170 } 171 172 if len(bz) == 0 { 173 return errorsmod.Wrap(sdkerrors.ErrUnknownAddress, "addresses cannot be empty") 174 } 175 176 if len(bz) > address.MaxAddrLen { 177 return errorsmod.Wrapf(sdkerrors.ErrUnknownAddress, "address max length is %d, got %d", address.MaxAddrLen, len(bz)) 178 } 179 180 return nil 181 } 182 183 // MustAccAddressFromBech32 calls AccAddressFromBech32 and panics on error. 184 func MustAccAddressFromBech32(address string) AccAddress { 185 addr, err := AccAddressFromBech32(address) 186 if err != nil { 187 panic(err) 188 } 189 190 return addr 191 } 192 193 // AccAddressFromBech32 creates an AccAddress from a Bech32 string. 194 func AccAddressFromBech32(address string) (addr AccAddress, err error) { 195 if len(strings.TrimSpace(address)) == 0 { 196 return AccAddress{}, errors.New("empty address string is not allowed") 197 } 198 199 bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix() 200 201 bz, err := GetFromBech32(address, bech32PrefixAccAddr) 202 if err != nil { 203 return nil, err 204 } 205 206 err = VerifyAddressFormat(bz) 207 if err != nil { 208 return nil, err 209 } 210 211 return AccAddress(bz), nil 212 } 213 214 // Returns boolean for whether two AccAddresses are Equal 215 func (aa AccAddress) Equals(aa2 Address) bool { 216 if aa.Empty() && aa2.Empty() { 217 return true 218 } 219 220 return bytes.Equal(aa.Bytes(), aa2.Bytes()) 221 } 222 223 // Returns boolean for whether an AccAddress is empty 224 func (aa AccAddress) Empty() bool { 225 return len(aa) == 0 226 } 227 228 // Marshal returns the raw address bytes. It is needed for protobuf 229 // compatibility. 230 func (aa AccAddress) Marshal() ([]byte, error) { 231 return aa, nil 232 } 233 234 // Unmarshal sets the address to the given data. It is needed for protobuf 235 // compatibility. 236 func (aa *AccAddress) Unmarshal(data []byte) error { 237 *aa = data 238 return nil 239 } 240 241 // MarshalJSON marshals to JSON using Bech32. 242 func (aa AccAddress) MarshalJSON() ([]byte, error) { 243 return json.Marshal(aa.String()) 244 } 245 246 // MarshalYAML marshals to YAML using Bech32. 247 func (aa AccAddress) MarshalYAML() (interface{}, error) { 248 return aa.String(), nil 249 } 250 251 // UnmarshalJSON unmarshals from JSON assuming Bech32 encoding. 252 func (aa *AccAddress) UnmarshalJSON(data []byte) error { 253 var s string 254 err := json.Unmarshal(data, &s) 255 if err != nil { 256 return err 257 } 258 if s == "" { 259 *aa = AccAddress{} 260 return nil 261 } 262 263 aa2, err := AccAddressFromBech32(s) 264 if err != nil { 265 return err 266 } 267 268 *aa = aa2 269 return nil 270 } 271 272 // UnmarshalYAML unmarshals from JSON assuming Bech32 encoding. 273 func (aa *AccAddress) UnmarshalYAML(data []byte) error { 274 var s string 275 err := yaml.Unmarshal(data, &s) 276 if err != nil { 277 return err 278 } 279 if s == "" { 280 *aa = AccAddress{} 281 return nil 282 } 283 284 aa2, err := AccAddressFromBech32(s) 285 if err != nil { 286 return err 287 } 288 289 *aa = aa2 290 return nil 291 } 292 293 // Bytes returns the raw address bytes. 294 func (aa AccAddress) Bytes() []byte { 295 return aa 296 } 297 298 // String implements the Stringer interface. 299 func (aa AccAddress) String() string { 300 if aa.Empty() { 301 return "" 302 } 303 304 key := conv.UnsafeBytesToStr(aa) 305 306 if IsAddrCacheEnabled() { 307 accAddrMu.Lock() 308 defer accAddrMu.Unlock() 309 310 addr, ok := accAddrCache.Get(key) 311 if ok { 312 return addr.(string) 313 } 314 } 315 return cacheBech32Addr(GetConfig().GetBech32AccountAddrPrefix(), aa, accAddrCache, key) 316 } 317 318 // Format implements the fmt.Formatter interface. 319 320 func (aa AccAddress) Format(s fmt.State, verb rune) { 321 switch verb { 322 case 's': 323 s.Write([]byte(aa.String())) 324 case 'p': 325 s.Write([]byte(fmt.Sprintf("%p", aa))) 326 default: 327 s.Write([]byte(fmt.Sprintf("%X", []byte(aa)))) 328 } 329 } 330 331 // ---------------------------------------------------------------------------- 332 // validator operator 333 // ---------------------------------------------------------------------------- 334 335 // ValAddress defines a wrapper around bytes meant to present a validator's 336 // operator. When marshaled to a string or JSON, it uses Bech32. 337 type ValAddress []byte 338 339 // ValAddressFromHex creates a ValAddress from a hex string. 340 func ValAddressFromHex(address string) (addr ValAddress, err error) { 341 bz, err := addressBytesFromHexString(address) 342 return ValAddress(bz), err 343 } 344 345 // ValAddressFromBech32 creates a ValAddress from a Bech32 string. 346 func ValAddressFromBech32(address string) (addr ValAddress, err error) { 347 if len(strings.TrimSpace(address)) == 0 { 348 return ValAddress{}, errors.New("empty address string is not allowed") 349 } 350 351 bech32PrefixValAddr := GetConfig().GetBech32ValidatorAddrPrefix() 352 353 bz, err := GetFromBech32(address, bech32PrefixValAddr) 354 if err != nil { 355 return nil, err 356 } 357 358 err = VerifyAddressFormat(bz) 359 if err != nil { 360 return nil, err 361 } 362 363 return ValAddress(bz), nil 364 } 365 366 // Returns boolean for whether two ValAddresses are Equal 367 func (va ValAddress) Equals(va2 Address) bool { 368 if va.Empty() && va2.Empty() { 369 return true 370 } 371 372 return bytes.Equal(va.Bytes(), va2.Bytes()) 373 } 374 375 // Returns boolean for whether an ValAddress is empty 376 func (va ValAddress) Empty() bool { 377 return len(va) == 0 378 } 379 380 // Marshal returns the raw address bytes. It is needed for protobuf 381 // compatibility. 382 func (va ValAddress) Marshal() ([]byte, error) { 383 return va, nil 384 } 385 386 // Unmarshal sets the address to the given data. It is needed for protobuf 387 // compatibility. 388 func (va *ValAddress) Unmarshal(data []byte) error { 389 *va = data 390 return nil 391 } 392 393 // MarshalJSON marshals to JSON using Bech32. 394 func (va ValAddress) MarshalJSON() ([]byte, error) { 395 return json.Marshal(va.String()) 396 } 397 398 // MarshalYAML marshals to YAML using Bech32. 399 func (va ValAddress) MarshalYAML() (interface{}, error) { 400 return va.String(), nil 401 } 402 403 // UnmarshalJSON unmarshals from JSON assuming Bech32 encoding. 404 func (va *ValAddress) UnmarshalJSON(data []byte) error { 405 var s string 406 407 err := json.Unmarshal(data, &s) 408 if err != nil { 409 return err 410 } 411 if s == "" { 412 *va = ValAddress{} 413 return nil 414 } 415 416 va2, err := ValAddressFromBech32(s) 417 if err != nil { 418 return err 419 } 420 421 *va = va2 422 return nil 423 } 424 425 // UnmarshalYAML unmarshals from YAML assuming Bech32 encoding. 426 func (va *ValAddress) UnmarshalYAML(data []byte) error { 427 var s string 428 429 err := yaml.Unmarshal(data, &s) 430 if err != nil { 431 return err 432 } 433 if s == "" { 434 *va = ValAddress{} 435 return nil 436 } 437 438 va2, err := ValAddressFromBech32(s) 439 if err != nil { 440 return err 441 } 442 443 *va = va2 444 return nil 445 } 446 447 // Bytes returns the raw address bytes. 448 func (va ValAddress) Bytes() []byte { 449 return va 450 } 451 452 // String implements the Stringer interface. 453 func (va ValAddress) String() string { 454 if va.Empty() { 455 return "" 456 } 457 458 key := conv.UnsafeBytesToStr(va) 459 460 if IsAddrCacheEnabled() { 461 valAddrMu.Lock() 462 defer valAddrMu.Unlock() 463 464 addr, ok := valAddrCache.Get(key) 465 if ok { 466 return addr.(string) 467 } 468 } 469 return cacheBech32Addr(GetConfig().GetBech32ValidatorAddrPrefix(), va, valAddrCache, key) 470 } 471 472 // Format implements the fmt.Formatter interface. 473 474 func (va ValAddress) Format(s fmt.State, verb rune) { 475 switch verb { 476 case 's': 477 s.Write([]byte(va.String())) 478 case 'p': 479 s.Write([]byte(fmt.Sprintf("%p", va))) 480 default: 481 s.Write([]byte(fmt.Sprintf("%X", []byte(va)))) 482 } 483 } 484 485 // ---------------------------------------------------------------------------- 486 // consensus node 487 // ---------------------------------------------------------------------------- 488 489 // ConsAddress defines a wrapper around bytes meant to present a consensus node. 490 // When marshaled to a string or JSON, it uses Bech32. 491 type ConsAddress []byte 492 493 // ConsAddressFromHex creates a ConsAddress from a hex string. 494 // Deprecated: use ConsensusAddressCodec from Staking keeper 495 func ConsAddressFromHex(address string) (addr ConsAddress, err error) { 496 bz, err := addressBytesFromHexString(address) 497 return ConsAddress(bz), err 498 } 499 500 // ConsAddressFromBech32 creates a ConsAddress from a Bech32 string. 501 func ConsAddressFromBech32(address string) (addr ConsAddress, err error) { 502 if len(strings.TrimSpace(address)) == 0 { 503 return ConsAddress{}, errors.New("empty address string is not allowed") 504 } 505 506 bech32PrefixConsAddr := GetConfig().GetBech32ConsensusAddrPrefix() 507 508 bz, err := GetFromBech32(address, bech32PrefixConsAddr) 509 if err != nil { 510 return nil, err 511 } 512 513 err = VerifyAddressFormat(bz) 514 if err != nil { 515 return nil, err 516 } 517 518 return ConsAddress(bz), nil 519 } 520 521 // get ConsAddress from pubkey 522 func GetConsAddress(pubkey cryptotypes.PubKey) ConsAddress { 523 return ConsAddress(pubkey.Address()) 524 } 525 526 // Returns boolean for whether two ConsAddress are Equal 527 func (ca ConsAddress) Equals(ca2 Address) bool { 528 if ca.Empty() && ca2.Empty() { 529 return true 530 } 531 532 return bytes.Equal(ca.Bytes(), ca2.Bytes()) 533 } 534 535 // Returns boolean for whether an ConsAddress is empty 536 func (ca ConsAddress) Empty() bool { 537 return len(ca) == 0 538 } 539 540 // Marshal returns the raw address bytes. It is needed for protobuf 541 // compatibility. 542 func (ca ConsAddress) Marshal() ([]byte, error) { 543 return ca, nil 544 } 545 546 // Unmarshal sets the address to the given data. It is needed for protobuf 547 // compatibility. 548 func (ca *ConsAddress) Unmarshal(data []byte) error { 549 *ca = data 550 return nil 551 } 552 553 // MarshalJSON marshals to JSON using Bech32. 554 func (ca ConsAddress) MarshalJSON() ([]byte, error) { 555 return json.Marshal(ca.String()) 556 } 557 558 // MarshalYAML marshals to YAML using Bech32. 559 func (ca ConsAddress) MarshalYAML() (interface{}, error) { 560 return ca.String(), nil 561 } 562 563 // UnmarshalJSON unmarshals from JSON assuming Bech32 encoding. 564 func (ca *ConsAddress) UnmarshalJSON(data []byte) error { 565 var s string 566 567 err := json.Unmarshal(data, &s) 568 if err != nil { 569 return err 570 } 571 if s == "" { 572 *ca = ConsAddress{} 573 return nil 574 } 575 576 ca2, err := ConsAddressFromBech32(s) 577 if err != nil { 578 return err 579 } 580 581 *ca = ca2 582 return nil 583 } 584 585 // UnmarshalYAML unmarshals from YAML assuming Bech32 encoding. 586 func (ca *ConsAddress) UnmarshalYAML(data []byte) error { 587 var s string 588 589 err := yaml.Unmarshal(data, &s) 590 if err != nil { 591 return err 592 } 593 if s == "" { 594 *ca = ConsAddress{} 595 return nil 596 } 597 598 ca2, err := ConsAddressFromBech32(s) 599 if err != nil { 600 return err 601 } 602 603 *ca = ca2 604 return nil 605 } 606 607 // Bytes returns the raw address bytes. 608 func (ca ConsAddress) Bytes() []byte { 609 return ca 610 } 611 612 // String implements the Stringer interface. 613 func (ca ConsAddress) String() string { 614 if ca.Empty() { 615 return "" 616 } 617 618 key := conv.UnsafeBytesToStr(ca) 619 620 if IsAddrCacheEnabled() { 621 consAddrMu.Lock() 622 defer consAddrMu.Unlock() 623 624 addr, ok := consAddrCache.Get(key) 625 if ok { 626 return addr.(string) 627 } 628 } 629 return cacheBech32Addr(GetConfig().GetBech32ConsensusAddrPrefix(), ca, consAddrCache, key) 630 } 631 632 // Bech32ifyAddressBytes returns a bech32 representation of address bytes. 633 // Returns an empty sting if the byte slice is 0-length. Returns an error if the bech32 conversion 634 // fails or the prefix is empty. 635 func Bech32ifyAddressBytes(prefix string, bs []byte) (string, error) { 636 if len(bs) == 0 { 637 return "", nil 638 } 639 if len(prefix) == 0 { 640 return "", errors.New("prefix cannot be empty") 641 } 642 return bech32.ConvertAndEncode(prefix, bs) 643 } 644 645 // MustBech32ifyAddressBytes returns a bech32 representation of address bytes. 646 // Returns an empty sting if the byte slice is 0-length. It panics if the bech32 conversion 647 // fails or the prefix is empty. 648 func MustBech32ifyAddressBytes(prefix string, bs []byte) string { 649 s, err := Bech32ifyAddressBytes(prefix, bs) 650 if err != nil { 651 panic(err) 652 } 653 return s 654 } 655 656 // Format implements the fmt.Formatter interface. 657 658 func (ca ConsAddress) Format(s fmt.State, verb rune) { 659 switch verb { 660 case 's': 661 s.Write([]byte(ca.String())) 662 case 'p': 663 s.Write([]byte(fmt.Sprintf("%p", ca))) 664 default: 665 s.Write([]byte(fmt.Sprintf("%X", []byte(ca)))) 666 } 667 } 668 669 // ---------------------------------------------------------------------------- 670 // auxiliary 671 // ---------------------------------------------------------------------------- 672 673 var errBech32EmptyAddress = errors.New("decoding Bech32 address failed: must provide a non empty address") 674 675 // GetFromBech32 decodes a bytestring from a Bech32 encoded string. 676 func GetFromBech32(bech32str, prefix string) ([]byte, error) { 677 if len(bech32str) == 0 { 678 return nil, errBech32EmptyAddress 679 } 680 681 hrp, bz, err := bech32.DecodeAndConvert(bech32str) 682 if err != nil { 683 return nil, err 684 } 685 686 if hrp != prefix { 687 return nil, fmt.Errorf("invalid Bech32 prefix; expected %s, got %s", prefix, hrp) 688 } 689 690 return bz, nil 691 } 692 693 func addressBytesFromHexString(address string) ([]byte, error) { 694 if len(address) == 0 { 695 return nil, ErrEmptyHexAddress 696 } 697 698 return hex.DecodeString(address) 699 } 700 701 // cacheBech32Addr is not concurrency safe. Concurrent access to cache causes race condition. 702 func cacheBech32Addr(prefix string, addr []byte, cache *simplelru.LRU, cacheKey string) string { 703 bech32Addr, err := bech32.ConvertAndEncode(prefix, addr) 704 if err != nil { 705 panic(err) 706 } 707 if IsAddrCacheEnabled() { 708 cache.Add(cacheKey, bech32Addr) 709 } 710 return bech32Addr 711 }