From ccabdc773a04112c883e26440765b84b01b86bb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tadej=20Jane=C5=BE?= Date: Tue, 26 May 2020 12:54:53 +0200 Subject: [PATCH] go/staking/api: Add Address for representing staking account addresses --- go/staking/api/address.go | 64 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 go/staking/api/address.go diff --git a/go/staking/api/address.go b/go/staking/api/address.go new file mode 100644 index 00000000000..edc85562e64 --- /dev/null +++ b/go/staking/api/address.go @@ -0,0 +1,64 @@ +package api + +import ( + "github.com/oasisprotocol/oasis-core/go/common/crypto/address" + "github.com/oasisprotocol/oasis-core/go/common/crypto/signature" + "github.com/oasisprotocol/oasis-core/go/common/encoding/bech32" +) + +// Human readable part of Bech32 encoded addresses. +const Bech32HRP = "osa" + +var ( + // Context is the unique context for staking account addresses. + Context = address.NewContext("oasis-core/address: staking") + // Version is the unique address version. + Version = address.NewVersion(0) +) + +// Address is the staking account address. +type Address address.Address + +// MarshalBinary encodes an address into binary form. +func (a Address) MarshalBinary() ([]byte, error) { + return (address.Address)(a).MarshalBinary() +} + +// UnMarshalBinary decodes a binary marshaled address. +func (a *Address) UnmarshalBinary(data []byte) error { + return (*address.Address)(a).UnmarshalBinary(data) +} + +// MarshalText encodes an address into text form. +func (a Address) MarshalText() ([]byte, error) { + return (address.Address)(a).MarshalBech32(Bech32HRP) +} + +// UnmarshalText decodes a text marshaled address. +func (a *Address) UnmarshalText(text []byte) error { + return (*address.Address)(a).UnmarshalBech32(Bech32HRP, text) +} + +// Equal compares vs another address for equality. +func (a Address) Equal(cmp Address) bool { + return (address.Address)(a).Equal((address.Address)(cmp)) +} + +// String returns the string representation of an address. +func (a Address) String() string { + bech32Addr, err := bech32.Encode(Bech32HRP, a[:]) + if err != nil { + return "[malformed]" + } + return bech32Addr +} + +func (a Address) IsValid() bool { + return address.Address(a).IsValid() +} + +// NewFromPublicKey creates a new address from an entity's id / public key. +func NewFromPublicKey(pk signature.PublicKey) (a Address) { + pkData, _ := pk.MarshalBinary() + return (Address)(address.NewAddress(Version, Context, pkData)) +}