Skip to content

Commit

Permalink
btcec: add new type SerializedKey
Browse files Browse the repository at this point in the history
This commit adds a new type called `SerializedKey`.

A serialized type is useful when using public keys as map keys. This is
because functionally identical public keys can have different internal
representations. These differences would cause the map to treat them as
different keys.
  • Loading branch information
ffranr committed Apr 2, 2024
1 parent 4f839f8 commit 02c8bf7
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions btcec/pubkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,36 @@ type PublicKey = secp.PublicKey
func NewPublicKey(x, y *FieldVal) *PublicKey {
return secp.NewPublicKey(x, y)
}

// SerializedKey is a type for representing a public key in its compressed
// serialized form.
//
// NOTE: This type is useful when using public keys as keys in maps.
type SerializedKey [PubKeyBytesLenCompressed]byte

// ToPubKey returns the public key parsed from the serialized key.
func (s SerializedKey) ToPubKey() (*PublicKey, error) {
return ParsePubKey(s[:])
}

// SchnorrSerialized returns the Schnorr serialized, x-only 32-byte
// representation of the serialized key.
func (s SerializedKey) SchnorrSerialized() []byte {
return s[1:]
}

// CopyBytes returns a copy of the underlying array as a byte slice.
func (s SerializedKey) CopyBytes() []byte {
c := make([]byte, 33)
copy(c, s[:])

return c
}

// ToSerialized serializes a public key in its 33-byte compressed form.
func ToSerialized(pubKey *PublicKey) SerializedKey {
var serialized SerializedKey
copy(serialized[:], pubKey.SerializeCompressed())

return serialized
}

0 comments on commit 02c8bf7

Please sign in to comment.