github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/native/validatorpk/pubkey.go (about) 1 package validatorpk 2 3 import ( 4 "github.com/pkg/errors" 5 "github.com/unicornultrafoundation/go-u2u/common" 6 ) 7 8 const ( 9 FakePassword = "fakepassword" 10 ) 11 12 type PubKey struct { 13 Type uint8 14 Raw []byte 15 } 16 17 var Types = struct { 18 Secp256k1 uint8 19 }{ 20 Secp256k1: 0xc0, 21 } 22 23 func (pk PubKey) Empty() bool { 24 return len(pk.Raw) == 0 && pk.Type == 0 25 } 26 27 func (pk PubKey) String() string { 28 return "0x" + common.Bytes2Hex(pk.Bytes()) 29 } 30 31 func (pk PubKey) Bytes() []byte { 32 return append([]byte{pk.Type}, pk.Raw...) 33 } 34 35 func (pk PubKey) Copy() PubKey { 36 return PubKey{ 37 Type: pk.Type, 38 Raw: common.CopyBytes(pk.Raw), 39 } 40 } 41 42 func FromString(str string) (PubKey, error) { 43 return FromBytes(common.FromHex(str)) 44 } 45 46 func FromBytes(b []byte) (PubKey, error) { 47 if len(b) == 0 { 48 return PubKey{}, errors.New("empty pubkey") 49 } 50 return PubKey{b[0], b[1:]}, nil 51 } 52 53 // MarshalText returns the hex representation of a. 54 func (pk *PubKey) MarshalText() ([]byte, error) { 55 return []byte(pk.String()), nil 56 } 57 58 // UnmarshalText parses a hash in hex syntax. 59 func (pk *PubKey) UnmarshalText(input []byte) error { 60 res, err := FromString(string(input)) 61 if err != nil { 62 return err 63 } 64 *pk = res 65 return nil 66 }