Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,12 @@ Ref: https://keepachangelog.com/en/1.0.0/
* [\#9011](https://github.com/cosmos/ibc-go/pull/9011) Bump **github.com/cosmos/cosmos-sdk** to **0.55.0**
* [\#9011](https://github.com/cosmos/ibc-go/pull/9011) Bump **github.com/cometbft/cometbft** to **0.40.0**
* [\#9011](https://github.com/cosmos/ibc-go/pull/9011) Bump **Go** to **1.26**
* (light-clients/08-wasm) [\#9175](https://github.com/lfdt-ibc/ibc-go/pull/9175) Replace the GPL-3.0 **github.com/OffchainLabs/prysm/v6** with the Apache-2.0 **github.com/supranational/blst@v0.3.17** in `blsverifier`.

### API Breaking

* (light-clients/08-wasm) [\#9175](https://github.com/lfdt-ibc/ibc-go/pull/9175) Unexport `blsverifier.AggregatePublicKeys`, which returned a prysm `bls.PublicKey`. Use the `Aggregate` query of `blsverifier.CustomQuerier` instead.

### State Machine Breaking

* (apps/rate-limiting) [\#8937](https://github.com/cosmos/ibc-go/pull/8937) imp(ratelimit): use collections for pending markers.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func (s *KeeperTestSuite) TestOnRecvPacket() {
interchainAccountAddr, found := s.chainB.GetSimApp().ICAHostKeeper.GetInterchainAccountAddress(s.chainB.GetContext(), ibctesting.FirstConnectionID, path.EndpointA.ChannelConfig.PortID)
s.Require().True(found)

validatorAddr := (sdk.ValAddress)(s.chainB.Vals.Validators[0].Address)
validatorAddr := sdk.ValAddress(s.chainB.Vals.Validators[0].Address)
msg := &stakingtypes.MsgDelegate{
DelegatorAddress: interchainAccountAddr,
ValidatorAddress: validatorAddr.String(),
Expand Down Expand Up @@ -137,7 +137,7 @@ func (s *KeeperTestSuite) TestOnRecvPacket() {
interchainAccountAddr, found := s.chainB.GetSimApp().ICAHostKeeper.GetInterchainAccountAddress(s.chainB.GetContext(), ibctesting.FirstConnectionID, path.EndpointA.ChannelConfig.PortID)
s.Require().True(found)

validatorAddr := (sdk.ValAddress)(s.chainB.Vals.Validators[0].Address)
validatorAddr := sdk.ValAddress(s.chainB.Vals.Validators[0].Address)
msgDelegate := &stakingtypes.MsgDelegate{
DelegatorAddress: interchainAccountAddr,
ValidatorAddress: validatorAddr.String(),
Expand Down
2 changes: 1 addition & 1 deletion modules/apps/callbacks/ica_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ func (s *CallbacksTestSuite) ExecuteICATimeout(icaAddress, memo string) {
// buildICAMsgDelegatePacketData builds a packetData containing a stakingtypes.MsgDelegate to be executed on chainB
func (s *CallbacksTestSuite) buildICAMsgDelegatePacketData(icaAddress string, memo string) icatypes.InterchainAccountPacketData {
// prepare a simple stakingtypes.MsgDelegate to be used as the interchain account msg executed on chainB
validatorAddr := (sdk.ValAddress)(s.chainB.Vals.Validators[0].Address)
validatorAddr := sdk.ValAddress(s.chainB.Vals.Validators[0].Address)
msgDelegate := &stakingtypes.MsgDelegate{
DelegatorAddress: icaAddress,
ValidatorAddress: validatorAddr.String(),
Expand Down
2 changes: 1 addition & 1 deletion modules/core/04-channel/types/acknowledgement.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func (ack Acknowledgement) ValidateBasic() error {
// considered successful if it is a ResultAcknowledgement. Otherwise it is
// considered a failed acknowledgement.
func (ack Acknowledgement) Success() bool {
return reflect.TypeOf(ack.Response) == reflect.TypeOf(((*Acknowledgement_Result)(nil)))
return reflect.TypeOf(ack.Response) == reflect.TypeOf((*Acknowledgement_Result)(nil))
}

// Acknowledgement implements the Acknowledgement interface. It returns the
Expand Down
95 changes: 90 additions & 5 deletions modules/light-clients/08-wasm/blsverifier/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,104 @@
package blsverifier

import (
"errors"
"fmt"

"github.com/OffchainLabs/prysm/v6/crypto/bls"
lru "github.com/hashicorp/golang-lru/v2"
blst "github.com/supranational/blst/bindings/go"
)

func AggregatePublicKeys(publicKeys [][]byte) (bls.PublicKey, error) {
return bls.AggregatePublicKeys(publicKeys)
// maxCachedPublicKeys bounds publicKeyCache. It holds many sync committees of 512 keys
// in a few megabytes of memory.
const maxCachedPublicKeys = 1 << 16

// dst is the Ethereum consensus proof-of-possession ciphersuite domain separation tag.
var dst = []byte("BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_")

// publicKeyCache maps compressed public keys to their decompressed points. It only holds
// keys that passed validation, so a hit skips decompression and the subgroup check.
// Successive light-client updates commonly reuse the same keys. The cache is safe for
// concurrent use and only affects performance, not results.
var publicKeyCache = mustNewPublicKeyCache()

func mustNewPublicKeyCache() *lru.Cache[[blst.BLST_P1_COMPRESS_BYTES]byte, blst.P1Affine] {
cache, err := lru.New[[blst.BLST_P1_COMPRESS_BYTES]byte, blst.P1Affine](maxCachedPublicKeys)
if err != nil {
panic(err)
}
return cache
}

// aggregatePublicKeys validates the compressed public keys and returns their compressed aggregate.
func aggregatePublicKeys(publicKeys [][]byte) ([]byte, error) {
pk, err := aggregatePublicKeyPoint(publicKeys)
if err != nil {
return nil, err
}
return pk.Compress(), nil
}

// VerifySignature verifies a compressed signature over message against the aggregate of publicKeys.
func VerifySignature(signature []byte, message [32]byte, publicKeys [][]byte) (bool, error) {
aggregatedPublicKey, err := AggregatePublicKeys(publicKeys)
pk, err := aggregatePublicKeyPoint(publicKeys)
if err != nil {
return false, fmt.Errorf("failed to aggregate public keys %w", err)
}
return bls.VerifySignature(signature, message, aggregatedPublicKey)

if len(signature) != blst.BLST_P2_COMPRESS_BYTES {
return false, fmt.Errorf("could not create signature from byte slice: signature must be %d bytes", blst.BLST_P2_COMPRESS_BYTES)
}
sig := new(blst.P2Affine).Uncompress(signature)
if sig == nil {
return false, errors.New("could not create signature from byte slice: could not unmarshal bytes into signature")
}
// Subgroup check only: an aggregate signature may be the point at infinity.
if !sig.SigValidate(false) {
return false, errors.New("signature not in group")
}

// Signature and key are already validated above.
return sig.Verify(false, pk, false, message[:], dst), nil
}

func aggregatePublicKeyPoint(publicKeys [][]byte) (*blst.P1Affine, error) {
if len(publicKeys) == 0 {
return nil, errors.New("nil or empty public keys")
}

agg := new(blst.P1Aggregate)
for _, bz := range publicKeys {
pk, err := publicKeyFromBytes(bz)
if err != nil {
return nil, err
}
agg.Add(&pk, false)
}

return agg.ToAffine(), nil
}

// publicKeyFromBytes decompresses and validates a compressed public key, using publicKeyCache
// for keys that were validated before.
func publicKeyFromBytes(bz []byte) (blst.P1Affine, error) {
if len(bz) != blst.BLST_P1_COMPRESS_BYTES {
return blst.P1Affine{}, fmt.Errorf("public key must be %d bytes", blst.BLST_P1_COMPRESS_BYTES)
}
key := [blst.BLST_P1_COMPRESS_BYTES]byte(bz)
if pk, ok := publicKeyCache.Get(key); ok {
return pk, nil
}

pk := new(blst.P1Affine).Uncompress(bz)
if pk == nil {
return blst.P1Affine{}, errors.New("could not unmarshal bytes into public key")
}
// Rejects the point at infinity and points outside the subgroup.
if !pk.KeyValidate() {
// Same message as prysm, although it also covers the subgroup check.
return blst.P1Affine{}, errors.New("received an infinite public key")
}

publicKeyCache.Add(key, *pk)
return *pk, nil
}
218 changes: 218 additions & 0 deletions modules/light-clients/08-wasm/blsverifier/crypto_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
// SPDX-License-Identifier: Apache-2.0

package blsverifier_test

import (
"encoding/hex"
"encoding/json"
"fmt"
"testing"

"github.com/stretchr/testify/require"
blst "github.com/supranational/blst/bindings/go"

sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/lfdt-ibc/ibc-go/modules/light-clients/08-wasm/v11/blsverifier"
)

// The success vectors were checked against two independent implementations:
// github.com/OffchainLabs/prysm/v6@v6.1.4 crypto/bls, which this package wrapped
// before, and github.com/consensys/gnark-crypto. Both produce aggregatedPublicKey
// from publicKeys and accept aggregatedSignature over message.
//
// The not-in-subgroup vectors are on-curve points outside the prime-order
// subgroup (G1: x = 4, G2: x = 2), generated with gnark-crypto. They decode as
// curve points, so only the subgroup checks reject them.
var (
publicKeys = [][]byte{
mustDecodeHex("84fe268400062ae6255010a421204dad5b0a8bd93522a4abc023037fa7a769f6ef29acc14c7fae8c5c0cd1df21ae1f52"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where do these vectors come from? If prysm or another independent implementation produced them, the success cases prove we match the old behavior; if the new code produced them, they only show it agrees with itself.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// The success vectors were checked against two independent implementations:
// github.com/OffchainLabs/prysm/v6@v6.1.4 crypto/bls, which this package wrapped
// before, and github.com/consensys/gnark-crypto. Both produce aggregatedPublicKey
// from publicKeys and accept aggregatedSignature over message.

mustDecodeHex("8b850e23cf188473e04feaa5d39f40f54b8c0e717f7fccb77d0efb5326802274bda863911efa8775a08674b887e0e766"),
mustDecodeHex("b52684603da6cb2902092310deab2ef3116a0a2b449c0f44d82d1d30bf12f7474492534f518af541ca9da110ee417132"),
}
aggregatedPublicKey = mustDecodeHex("912cf816853d0984e448f065d0bdb34b1e26be1d3c50bbc2f0d39b0ff1c2963a97b5dfd442a496763f3c6e5c54375b1e")
aggregatedSignature = mustDecodeHex("8af25b4a2786b3305f80528520544071a143e80ef4091dfca32e347eeabeef71eeb8673a78e8ff2875883ab5498d8a7b1888a80878bfd82c2d27e93ed74e979014e95d7f2ef55b1d28070a4a2e6ce9df3b8f07c6444c4799c64d654c2810c36d")
message = [32]byte{3, 1, 2, 3}

g1NotInSubgroup = mustDecodeHex("800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004")
g2NotInSubgroup = mustDecodeHex("800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002")
)

func mustDecodeHex(s string) []byte {
bz, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return bz
}

// negate flips the sign bit of a compressed point.
func negate(point []byte) []byte {
bz := append([]byte{}, point...)
bz[0] ^= 0x20
return bz
}

func infinityPoint(size int) []byte {
bz := make([]byte, size)
bz[0] = 0xc0
return bz
}

func TestAggregatePublicKeys(t *testing.T) {
testCases := []struct {
name string
publicKeys [][]byte
expected []byte
expErrorMsg string
}{
{"success: single key", publicKeys[:1], publicKeys[0], ""},
{"success: multiple keys", publicKeys, aggregatedPublicKey, ""},
{"failure: no keys", nil, nil, "nil or empty public keys"},
{"failure: wrong length", [][]byte{publicKeys[0][:47]}, nil, "public key must be 48 bytes"},
{"failure: not a curve point", [][]byte{make([]byte, 48)}, nil, "could not unmarshal bytes into public key"},
{"failure: point at infinity", [][]byte{infinityPoint(48)}, nil, "received an infinite public key"},
{"failure: point not in subgroup", [][]byte{g1NotInSubgroup}, nil, "received an infinite public key"},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
pk, err := blsverifier.AggregatePublicKeys(tc.publicKeys)
if tc.expErrorMsg != "" {
require.ErrorContains(t, err, tc.expErrorMsg)
return
}
require.NoError(t, err)
require.Equal(t, tc.expected, pk)
})
}
}

func TestPublicKeyCache(t *testing.T) {
blsverifier.PurgePublicKeyCache()
t.Cleanup(blsverifier.PurgePublicKeyCache)

// Keys that fail validation are not cached, including after a valid key in the same batch.
invalidKeys := [][]byte{publicKeys[0][:47], make([]byte, 48), infinityPoint(48), g1NotInSubgroup}
for _, key := range invalidKeys {
_, err := blsverifier.AggregatePublicKeys([][]byte{publicKeys[0], key})
require.Error(t, err)
require.Equal(t, 1, blsverifier.PublicKeyCacheLen())
}

// Cached keys produce the same results as freshly validated ones.
for range 2 {
pk, err := blsverifier.AggregatePublicKeys(publicKeys)
require.NoError(t, err)
require.Equal(t, aggregatedPublicKey, pk)
require.Equal(t, len(publicKeys), blsverifier.PublicKeyCacheLen())

valid, err := blsverifier.VerifySignature(aggregatedSignature, message, publicKeys)
require.NoError(t, err)
require.True(t, valid)
}

// A cached key is still rejected when it is not the full input.
_, err := blsverifier.AggregatePublicKeys([][]byte{publicKeys[0][:47]})
require.ErrorContains(t, err, "public key must be 48 bytes")
}

func TestVerifySignature(t *testing.T) {
testCases := []struct {
name string
signature []byte
message [32]byte
publicKeys [][]byte
expValid bool
expErrorMsg string
}{
{"success: valid aggregate signature", aggregatedSignature, message, publicKeys, true, ""},
{"invalid: wrong message", aggregatedSignature, [32]byte{9}, publicKeys, false, ""},
{"invalid: missing signer", aggregatedSignature, message, publicKeys[:2], false, ""},
{"invalid: signature at infinity", infinityPoint(96), message, publicKeys, false, ""},
{"failure: wrong signature length", aggregatedSignature[:95], message, publicKeys, false, "signature must be 96 bytes"},
{"failure: signature not a curve point", make([]byte, 96), message, publicKeys, false, "could not unmarshal bytes into signature"},
{"failure: signature not in subgroup", g2NotInSubgroup, message, publicKeys, false, "signature not in group"},
{"invalid: keys cancel to infinity", infinityPoint(96), message, [][]byte{publicKeys[0], negate(publicKeys[0])}, false, ""},
{"failure: invalid public key", aggregatedSignature, message, [][]byte{infinityPoint(48)}, false, "failed to aggregate public keys"},
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
valid, err := blsverifier.VerifySignature(tc.signature, tc.message, tc.publicKeys)
if tc.expErrorMsg != "" {
require.ErrorContains(t, err, tc.expErrorMsg)
} else {
require.NoError(t, err)
}
require.Equal(t, tc.expValid, valid)
})
}
}

func TestCustomQuerier(t *testing.T) {
querier := blsverifier.CustomQuerier()

request, err := json.Marshal(blsverifier.CustomQuery{
Aggregate: &blsverifier.QueryAggregate{PublicKeys: publicKeys},
})
require.NoError(t, err)
res, err := querier(sdk.Context{}, request)
require.NoError(t, err)
expected, err := json.Marshal(aggregatedPublicKey)
require.NoError(t, err)
require.Equal(t, expected, res)

request, err = json.Marshal(blsverifier.CustomQuery{
AggregateVerify: &blsverifier.QueryAggregateVerify{
PublicKeys: publicKeys,
Signature: aggregatedSignature,
Message: message[:],
},
})
require.NoError(t, err)
res, err = querier(sdk.Context{}, request)
require.NoError(t, err)
require.Equal(t, []byte("true"), res)
}

// generatePublicKeys returns n distinct, valid compressed public keys.
func generatePublicKeys(tb testing.TB, n int) [][]byte {
tb.Helper()
keys := make([][]byte, n)
for i := range keys {
ikm := make([]byte, 32)
ikm[0], ikm[1] = byte(i), byte(i>>8)
sk := blst.KeyGen(ikm)
require.NotNil(tb, sk)
keys[i] = new(blst.P1Affine).From(sk).Compress()
}
return keys
}

// BenchmarkAggregatePublicKeys measures aggregation when the same keys recur across
// queries, as they do across successive light-client updates, against a cold cache.
func BenchmarkAggregatePublicKeys(b *testing.B) {
keys := generatePublicKeys(b, 100)
b.Cleanup(blsverifier.PurgePublicKeyCache)

b.Run(fmt.Sprintf("repeated %d keys", len(keys)), func(b *testing.B) {
blsverifier.PurgePublicKeyCache()
for b.Loop() {
if _, err := blsverifier.AggregatePublicKeys(keys); err != nil {
b.Fatal(err)
}
}
})

b.Run(fmt.Sprintf("uncached %d keys", len(keys)), func(b *testing.B) {
for range b.N {
b.StopTimer()
blsverifier.PurgePublicKeyCache()
b.StartTimer()
if _, err := blsverifier.AggregatePublicKeys(keys); err != nil {
b.Fatal(err)
}
}
})
}
18 changes: 18 additions & 0 deletions modules/light-clients/08-wasm/blsverifier/export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// SPDX-License-Identifier: Apache-2.0

package blsverifier

// AggregatePublicKeys is a wrapper around aggregatePublicKeys to allow the function to be directly called in tests.
func AggregatePublicKeys(publicKeys [][]byte) ([]byte, error) {
return aggregatePublicKeys(publicKeys)
}

// PublicKeyCacheLen returns the number of cached public keys.
func PublicKeyCacheLen() int {
return publicKeyCache.Len()
}

// PurgePublicKeyCache removes all cached public keys.
func PurgePublicKeyCache() {
publicKeyCache.Purge()
}
Loading