From 31647e46ecbac0dfc4b6432bd3d3cc0136193740 Mon Sep 17 00:00:00 2001 From: ffranr Date: Tue, 2 Apr 2024 19:27:10 +0100 Subject: [PATCH 1/2] btcec: add missing doc comments --- btcec/pubkey.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/btcec/pubkey.go b/btcec/pubkey.go index c4b0680a7a..bff1b24b5f 100644 --- a/btcec/pubkey.go +++ b/btcec/pubkey.go @@ -10,6 +10,8 @@ import ( // These constants define the lengths of serialized public keys. const ( + // PubKeyBytesLenCompressed is the bytes length of a serialized compressed + // public key. PubKeyBytesLenCompressed = 33 ) From 665eeb52b19fce48a025afcde01ffdd781672299 Mon Sep 17 00:00:00 2001 From: ffranr Date: Tue, 2 Apr 2024 19:36:47 +0100 Subject: [PATCH 2/2] btcec: add new type `SerializedKey` 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. --- btcec/pubkey.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/btcec/pubkey.go b/btcec/pubkey.go index bff1b24b5f..2c3a5ccbef 100644 --- a/btcec/pubkey.go +++ b/btcec/pubkey.go @@ -51,3 +51,38 @@ 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() [32]byte { + var serializedSchnorr [32]byte + copy(serializedSchnorr[:], s[1:]) + return serializedSchnorr +} + +// CopyBytes returns a copy of the underlying array as a byte slice. +func (s SerializedKey) CopyBytes() []byte { + c := make([]byte, PubKeyBytesLenCompressed) + copy(c, s[:]) + + return c +} + +// ToSerialized serializes a public key into its compressed form. +func ToSerialized(pubKey *PublicKey) SerializedKey { + var serialized SerializedKey + copy(serialized[:], pubKey.SerializeCompressed()) + + return serialized +}