Skip to content

Commit

Permalink
[bls] cache BLSPubKey deserialization with LRU
Browse files Browse the repository at this point in the history
Signed-off-by: Leo Chen <[email protected]>
  • Loading branch information
Leo Chen committed Jun 21, 2020
1 parent f84d51a commit c1f6051
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions crypto/bls/bls.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
package bls

import (
"fmt"

"github.com/harmony-one/bls/ffi/go/bls"
lru "github.com/hashicorp/golang-lru"
"github.com/pkg/errors"
)

const (
blsPubKeyCacheSize = 1024
)

var (
// BLSPubKeyCache is the Cache of the Deserialized BLS PubKey
BLSPubKeyCache, _ = lru.New(blsPubKeyCacheSize)
)

func init() {
bls.Init(bls.BLS12_381)
}
Expand All @@ -18,14 +26,32 @@ func RandPrivateKey() *bls.SecretKey {
return &sec
}

var (
errEmptyInput = errors.New("BytesToBLSPublicKey: empty input")
errPubKeyCast = errors.New("BytesToBLSPublicKey: cast error")
)

// BytesToBLSPublicKey converts bytes into bls.PublicKey pointer.
func BytesToBLSPublicKey(bytes []byte) (*bls.PublicKey, error) {
if len(bytes) == 0 {
return nil, fmt.Errorf("[BytesToBLSPublicKey] bytes is empty")
return nil, errEmptyInput
}
kkey := string(bytes)
if k, ok := BLSPubKeyCache.Get(kkey); ok {
if pk, ok := k.(bls.PublicKey); ok {
return &pk, nil
}
return nil, errPubKeyCast
}
pubKey := &bls.PublicKey{}
err := pubKey.Deserialize(bytes)
return pubKey, err

if err == nil {
BLSPubKeyCache.Add(kkey, *pubKey)
return pubKey, nil
}

return nil, err
}

// AggregateSig aggregates all the BLS signature into a single multi-signature.
Expand Down

0 comments on commit c1f6051

Please sign in to comment.