Skip to content

Commit

Permalink
Caching publick keys for ecdsa
Browse files Browse the repository at this point in the history
  • Loading branch information
aopoltorzhicky committed Sep 10, 2022
1 parent d0a0ae0 commit 20c3874
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions cmd/mempool/endorsement/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package endorsement
import (
"crypto/ecdsa"
"crypto/elliptic"
"encoding/hex"
"math/big"

"golang.org/x/crypto/blake2b"
Expand Down Expand Up @@ -42,24 +43,40 @@ func getWatermark(chainID string) []byte {
return watermark
}

var ecdsaKeysCache map[string]ecdsa.PublicKey

func verifyP256(key, message, signature []byte) bool {
x, y, err := getCoordinates(key)
pubKey, err := ecdsaKeyWithCache(key)
if err != nil {
return false
}

pubKey := ecdsa.PublicKey{
Curve: elliptic.P256(),
X: x,
Y: y,
}

sign1 := new(big.Int).SetBytes(signature[:32])
sign2 := new(big.Int).SetBytes(signature[32:])

return ecdsa.Verify(&pubKey, message, sign1, sign2)
}

func ecdsaKeyWithCache(key []byte) (ecdsa.PublicKey, error) {
if ecdsaKeysCache == nil {
ecdsaKeysCache = make(map[string]ecdsa.PublicKey)
}

keyString := hex.EncodeToString(key)
if result, ok := ecdsaKeysCache[keyString]; ok {
return result, nil
}
x, y, err := getCoordinates(key)
if err != nil {
return ecdsa.PublicKey{}, err
}

return ecdsa.PublicKey{
Curve: elliptic.P256(),
X: x,
Y: y,
}, nil
}

// https://stackoverflow.com/a/46289709
func getCoordinates(data []byte) (*big.Int, *big.Int, error) {
// Split the sign byte from the rest
Expand Down

0 comments on commit 20c3874

Please sign in to comment.