Skip to content

BLS Components for Simplex #3993

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
Jun 17, 2025
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ require (
github.com/FactomProject/btcutilecc v0.0.0-20130527213604-d3a63a5752ec // indirect
github.com/Microsoft/go-winio v0.6.1 // indirect
github.com/VictoriaMetrics/fastcache v1.12.1 // indirect
github.com/ava-labs/simplex v0.0.0-20250605162940-db8e6d44f53d
github.com/beorn7/perks v1.0.1 // indirect
github.com/bits-and-blooms/bitset v1.10.0 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ github.com/ava-labs/ledger-avalanche/go v0.0.0-20241009183145-e6f90a8a1a60 h1:EL
github.com/ava-labs/ledger-avalanche/go v0.0.0-20241009183145-e6f90a8a1a60/go.mod h1:/7qKobTfbzBu7eSTVaXMTr56yTYk4j2Px6/8G+idxHo=
github.com/ava-labs/libevm v1.13.14-0.2.0.release h1:uKGCc5/ceeBbfAPRVtBUxbQt50WzB2pEDb8Uy93ePgQ=
github.com/ava-labs/libevm v1.13.14-0.2.0.release/go.mod h1:+Iol+sVQ1KyoBsHf3veyrBmHCXr3xXRWq6ZXkgVfNLU=
github.com/ava-labs/simplex v0.0.0-20250605162940-db8e6d44f53d h1:D/BOS3USdAigun2OP/6khvukKnn4BIKviYAdKLHN6zc=
github.com/ava-labs/simplex v0.0.0-20250605162940-db8e6d44f53d/go.mod h1:GVzumIo3zR23/qGRN2AdnVkIPHcKMq/D89EGWZfMGQ0=
github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
Expand Down
134 changes: 134 additions & 0 deletions simplex/bls.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package simplex

import (
"context"
"encoding/asn1"
"errors"
"fmt"

"github.com/ava-labs/simplex"
"go.uber.org/zap"

"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/crypto/bls"
)

var (
errSignatureVerificationFailed = errors.New("signature verification failed")
errSignerNotFound = errors.New("signer not found in the membership set")
simplexLabel = []byte("simplex")
)

var _ simplex.Signer = (*BLSSigner)(nil)

type SignFunc func(msg []byte) (*bls.Signature, error)

// BLSSigner signs messages encoded with the provided ChainID and SubnetID.
// using the SignBLS function.
type BLSSigner struct {
chainID ids.ID
subnetID ids.ID
// signBLS is passed in because we support both software and hardware BLS signing.
signBLS SignFunc
}

type BLSVerifier struct {
nodeID2PK map[ids.NodeID]bls.PublicKey
subnetID ids.ID
chainID ids.ID
}

func NewBLSAuth(config *Config) (BLSSigner, BLSVerifier, error) {
verifier, err := createVerifier(config)

return BLSSigner{
chainID: config.Ctx.ChainID,
subnetID: config.Ctx.SubnetID,
signBLS: config.SignBLS,
}, verifier, err
}

// Sign returns a signature on the given message using BLS signature scheme.
// It encodes the message to sign with the chain ID, and subnet ID,
func (s *BLSSigner) Sign(message []byte) ([]byte, error) {
message2Sign, err := encodeMessageToSign(message, s.chainID, s.subnetID)
if err != nil {
return nil, fmt.Errorf("failed to encode message to sign: %w", err)
}

sig, err := s.signBLS(message2Sign)
if err != nil {
return nil, err
}

sigBytes := bls.SignatureToBytes(sig)
return sigBytes, nil
}

type encodedSimplexSignedPayload struct {
Message []byte
ChainID []byte
SubnetID []byte
Label []byte
}

func encodeMessageToSign(message []byte, chainID ids.ID, subnetID ids.ID) ([]byte, error) {
encodedSimplexMessage := encodedSimplexSignedPayload{
Message: message,
ChainID: chainID[:],
SubnetID: subnetID[:],
Label: simplexLabel,
}
return asn1.Marshal(encodedSimplexMessage)
}

func (v BLSVerifier) Verify(message []byte, signature []byte, signer simplex.NodeID) error {
if len(signer) != ids.NodeIDLen {
return fmt.Errorf("expected signer to be %d bytes but got %d bytes", ids.NodeIDLen, len(signer))
}

key := ids.NodeID(signer)
pk, exists := v.nodeID2PK[key]
if !exists {
return fmt.Errorf("%w: signer %x", errSignerNotFound, key)
}

sig, err := bls.SignatureFromBytes(signature)
if err != nil {
return fmt.Errorf("failed to parse signature: %w", err)
}

message2Verify, err := encodeMessageToSign(message, v.chainID, v.subnetID)
if err != nil {
return fmt.Errorf("failed to encode message to verify: %w", err)
}

if !bls.Verify(&pk, sig, message2Verify) {
return errSignatureVerificationFailed
}

return nil
}

func createVerifier(config *Config) (BLSVerifier, error) {
verifier := BLSVerifier{
nodeID2PK: make(map[ids.NodeID]bls.PublicKey),
subnetID: config.Ctx.SubnetID,
chainID: config.Ctx.ChainID,
}

nodes, err := config.Validators.GetValidatorSet(context.Background(), 0, config.Ctx.SubnetID)
if err != nil {
config.Log.Error("failed to get validator set", zap.Error(err), zap.Stringer("subnetID", config.Ctx.SubnetID))
return BLSVerifier{}, err
}

for _, node := range nodes {
verifier.nodeID2PK[node.NodeID] = *node.PublicKey
}

return verifier, nil
}
62 changes: 62 additions & 0 deletions simplex/bls_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package simplex

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/crypto/bls"
)

func TestBLSSignVerify(t *testing.T) {
config, err := newEngineConfig()
require.NoError(t, err)

signer, verifier, err := NewBLSAuth(config)
require.NoError(t, err)

msg := "Begin at the beginning, and go on till you come to the end: then stop"

sig, err := signer.Sign([]byte(msg))
require.NoError(t, err)

err = verifier.Verify([]byte(msg), sig, config.Ctx.NodeID[:])
require.NoError(t, err)
}

func TestSignerNotInMemberSet(t *testing.T) {
config, err := newEngineConfig()
require.NoError(t, err)
signer, verifier, err := NewBLSAuth(config)
require.NoError(t, err)

msg := "Begin at the beginning, and go on till you come to the end: then stop"

sig, err := signer.Sign([]byte(msg))
require.NoError(t, err)

notInMembershipSet := ids.GenerateTestNodeID()
err = verifier.Verify([]byte(msg), sig, notInMembershipSet[:])
require.ErrorIs(t, err, errSignerNotFound)
}

func TestSignerInvalidMessageEncoding(t *testing.T) {
config, err := newEngineConfig()
require.NoError(t, err)

// sign a message with invalid encoding
dummyMsg := []byte("dummy message")
sig, err := config.SignBLS(dummyMsg)
require.NoError(t, err)

sigBytes := bls.SignatureToBytes(sig)

_, verifier, err := NewBLSAuth(config)
require.NoError(t, err)
err = verifier.Verify(dummyMsg, sigBytes, config.Ctx.NodeID[:])
require.ErrorIs(t, err, errSignatureVerificationFailed)
}
41 changes: 41 additions & 0 deletions simplex/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package simplex

import (
"context"

"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow/validators"
"github.com/ava-labs/avalanchego/utils/logging"
)

type ValidatorInfo interface {
// GetValidatorSet returns the validators of the provided subnet at the
// requested P-chain height.
// The returned map should not be modified.
GetValidatorSet(
ctx context.Context,
height uint64,
subnetID ids.ID,
) (map[ids.NodeID]*validators.GetValidatorOutput, error)
}

// Config wraps all the parameters needed for a simplex engine
type Config struct {
Ctx SimplexChainContext
Log logging.Logger
Validators ValidatorInfo
SignBLS SignFunc
}

// Context is information about the current execution.
// [SubnetID] is the ID of the subnet this context exists within.
// [ChainID] is the ID of the chain this context exists within.
// [NodeID] is the ID of this node
type SimplexChainContext struct {
NodeID ids.NodeID
ChainID ids.ID
SubnetID ids.ID
}
69 changes: 69 additions & 0 deletions simplex/test_util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package simplex

import (
"context"

"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow/validators"
"github.com/ava-labs/avalanchego/utils/crypto/bls"
"github.com/ava-labs/avalanchego/utils/crypto/bls/signer/localsigner"
)

var _ ValidatorInfo = (*testValidatorInfo)(nil)

// testValidatorInfo is a mock implementation of ValidatorInfo for testing purposes.
// it assumes all validators are in the same subnet and returns all of them for any subnetID.
type testValidatorInfo struct {
validators map[ids.NodeID]*validators.GetValidatorOutput
}

func (t *testValidatorInfo) GetValidatorSet(
context.Context,
uint64,
ids.ID,
) (map[ids.NodeID]*validators.GetValidatorOutput, error) {
return t.validators, nil
}

func newTestValidatorInfo(nodeIds []ids.NodeID, pks []*bls.PublicKey) *testValidatorInfo {
if len(nodeIds) != len(pks) {
panic("nodeIds and pks must have the same length")
}

vds := make(map[ids.NodeID]*validators.GetValidatorOutput, len(pks))
for i, pk := range pks {
validator := &validators.GetValidatorOutput{
PublicKey: pk,
NodeID: nodeIds[i],
}
vds[nodeIds[i]] = validator
}
// all we need is to generate the public keys for the validators
return &testValidatorInfo{
validators: vds,
}
}

func newEngineConfig() (*Config, error) {
ls, err := localsigner.New()
if err != nil {
return nil, err
}

nodeID := ids.GenerateTestNodeID()

simplexChainContext := SimplexChainContext{
NodeID: nodeID,
ChainID: ids.GenerateTestID(),
SubnetID: ids.GenerateTestID(),
}

return &Config{
Ctx: simplexChainContext,
Validators: newTestValidatorInfo([]ids.NodeID{nodeID}, []*bls.PublicKey{ls.PublicKey()}),
SignBLS: ls.Sign,
}, nil
}