prysm-pulse/shared/bls/herumi/public_key.go
Preston Van Loon fb8be4d555
Refactor BLS (#6395)
* refactor BLS to expose an interface rather than a single implementation
* Split up tests, gofmt, goimports, docs
* godoc for signature.Copy()
* more godocs
* revert gomod / deps changes
* rm newline
* revert proto changes
* rename bls12 to herumi for clarity
2020-06-25 00:47:51 +00:00

66 lines
1.7 KiB
Go

package herumi
import (
"fmt"
"github.com/dgraph-io/ristretto"
bls12 "github.com/herumi/bls-eth-go-binary/bls"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/shared/bls/iface"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/params"
)
var maxKeys = int64(100000)
var pubkeyCache, _ = ristretto.NewCache(&ristretto.Config{
NumCounters: maxKeys,
MaxCost: 1 << 22, // ~4mb is cache max size
BufferItems: 64,
})
// PublicKey used in the BLS signature scheme.
type PublicKey struct {
p *bls12.PublicKey
}
// PublicKeyFromBytes creates a BLS public key from a BigEndian byte slice.
func PublicKeyFromBytes(pubKey []byte) (iface.PublicKey, error) {
if featureconfig.Get().SkipBLSVerify {
return &PublicKey{}, nil
}
if len(pubKey) != params.BeaconConfig().BLSPubkeyLength {
return nil, fmt.Errorf("public key must be %d bytes", params.BeaconConfig().BLSPubkeyLength)
}
if cv, ok := pubkeyCache.Get(string(pubKey)); ok {
return cv.(*PublicKey).Copy(), nil
}
p := &bls12.PublicKey{}
err := p.Deserialize(pubKey)
if err != nil {
return nil, errors.Wrap(err, "could not unmarshal bytes into public key")
}
pubKeyObj := &PublicKey{p: p}
pubkeyCache.Set(string(pubKey), pubKeyObj.Copy(), 48)
return pubKeyObj, nil
}
// Marshal a public key into a LittleEndian byte slice.
func (p *PublicKey) Marshal() []byte {
return p.p.Serialize()
}
// Copy the public key to a new pointer reference.
func (p *PublicKey) Copy() iface.PublicKey {
np := *p.p
return &PublicKey{p: &np}
}
// Aggregate two public keys.
func (p *PublicKey) Aggregate(p2 iface.PublicKey) iface.PublicKey {
if featureconfig.Get().SkipBLSVerify {
return p
}
p.p.Add(p2.(*PublicKey).p)
return p
}