From 39500ed5ed1904c5b1a6182b98913bbedee0b412 Mon Sep 17 00:00:00 2001 From: Conner Fromknecht Date: Tue, 14 May 2019 22:46:54 -0700 Subject: [PATCH] btcec/pubkey: remove redundant checks from compressed pubkey parsing As of https://github.com/btcsuite/btcd/pull/1193, decompressPoint now validates that the point is on the curve. The x and y cooordinates are also implicitly <= P, since the modular reduction is applied to both before the method returns. The checks are moved so that they are still applied when parsing an uncompressed pubkey, as the checks are not redundant in that path. --- btcec/pubkey.go | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/btcec/pubkey.go b/btcec/pubkey.go index cf498075..a6a492e7 100644 --- a/btcec/pubkey.go +++ b/btcec/pubkey.go @@ -102,6 +102,17 @@ func ParsePubKey(pubKeyStr []byte, curve *KoblitzCurve) (key *PublicKey, err err if format == pubkeyHybrid && ybit != isOdd(pubkey.Y) { return nil, fmt.Errorf("ybit doesn't match oddness") } + + if pubkey.X.Cmp(pubkey.Curve.Params().P) >= 0 { + return nil, fmt.Errorf("pubkey X parameter is >= to P") + } + if pubkey.Y.Cmp(pubkey.Curve.Params().P) >= 0 { + return nil, fmt.Errorf("pubkey Y parameter is >= to P") + } + if !pubkey.Curve.IsOnCurve(pubkey.X, pubkey.Y) { + return nil, fmt.Errorf("pubkey isn't on secp256k1 curve") + } + case PubKeyBytesLenCompressed: // format is 0x2 | solution, // solution determines which solution of the curve we use. @@ -115,20 +126,12 @@ func ParsePubKey(pubKeyStr []byte, curve *KoblitzCurve) (key *PublicKey, err err if err != nil { return nil, err } + default: // wrong! return nil, fmt.Errorf("invalid pub key length %d", len(pubKeyStr)) } - if pubkey.X.Cmp(pubkey.Curve.Params().P) >= 0 { - return nil, fmt.Errorf("pubkey X parameter is >= to P") - } - if pubkey.Y.Cmp(pubkey.Curve.Params().P) >= 0 { - return nil, fmt.Errorf("pubkey Y parameter is >= to P") - } - if !pubkey.Curve.IsOnCurve(pubkey.X, pubkey.Y) { - return nil, fmt.Errorf("pubkey isn't on secp256k1 curve") - } return &pubkey, nil }