Skip to content

Commit

Permalink
btcec: add new IsCompressedPubKey function
Browse files Browse the repository at this point in the history
This commit adds a new function to btcec: IsCompressedPubKey. This
function returns true iff the passed serialized public key is encoded
in compressed format.
  • Loading branch information
Roasbeef authored and davecgh committed Aug 14, 2017
1 parent 9054ef8 commit 65feec3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
9 changes: 9 additions & 0 deletions btcec/pubkey.go
Expand Up @@ -54,6 +54,15 @@ const (
pubkeyHybrid byte = 0x6 // y_bit + x coord + y coord
)

// IsCompressedPubKey returns true the the passed serialized public key has
// been encoded in compressed format, and false otherwise.
func IsCompressedPubKey(pubKey []byte) bool {
// The public key is only compressed if it is the correct length and
// the format (first byte) is one of the compressed pubkey values.
return len(pubKey) == PubKeyBytesLenCompressed &&
(pubKey[0]&^byte(0x1) == pubkeyCompressed)
}

// ParsePubKey parses a public key for a koblitz curve from a bytestring into a
// ecdsa.Publickey, verifying that it is valid. It supports compressed,
// uncompressed and hybrid signature formats.
Expand Down
12 changes: 12 additions & 0 deletions btcec/pubkey_test.go
Expand Up @@ -282,3 +282,15 @@ func TestPublicKeyIsEqual(t *testing.T) {
"equal to %v", pubKey1, pubKey2)
}
}

func TestIsCompressed(t *testing.T) {
for _, test := range pubKeyTests {
isCompressed := IsCompressedPubKey(test.key)
wantCompressed := (test.format == pubkeyCompressed)
if isCompressed != wantCompressed {
t.Fatalf("%s (%x) pubkey: unexpected compressed result, "+
"got %v, want %v", test.name, test.key,
isCompressed, wantCompressed)
}
}
}

0 comments on commit 65feec3

Please sign in to comment.