From 8fee6226af2f6807b613d0e643f036e99c6c4efd Mon Sep 17 00:00:00 2001 From: kitty Date: Wed, 14 Jul 2021 15:54:13 +0100 Subject: [PATCH 01/10] bls signature for basic account --- crypto/codec/amino.go | 5 + crypto/codec/proto.go | 2 + crypto/hd/algo.go | 45 +++ crypto/keyring/keyring.go | 2 +- crypto/keys/bls12381/bls12381.go | 233 +++++++++++ crypto/keys/bls12381/bls12381_test.go | 22 ++ crypto/keys/bls12381/keys.pb.go | 496 ++++++++++++++++++++++++ go.mod | 1 + go.sum | 2 + proto/cosmos/crypto/bls12381/keys.proto | 22 ++ x/auth/ante/sigverify.go | 15 + 11 files changed, 844 insertions(+), 1 deletion(-) create mode 100644 crypto/keys/bls12381/bls12381.go create mode 100644 crypto/keys/bls12381/bls12381_test.go create mode 100644 crypto/keys/bls12381/keys.pb.go create mode 100644 proto/cosmos/crypto/bls12381/keys.proto diff --git a/crypto/codec/amino.go b/crypto/codec/amino.go index d50a08864c..0043c6855c 100644 --- a/crypto/codec/amino.go +++ b/crypto/codec/amino.go @@ -1,6 +1,7 @@ package codec import ( + "github.com/cosmos/cosmos-sdk/crypto/keys/bls12381" "github.com/tendermint/tendermint/crypto/sr25519" "github.com/cosmos/cosmos-sdk/codec" @@ -22,6 +23,8 @@ func RegisterCrypto(cdc *codec.LegacyAmino) { secp256k1.PubKeyName, nil) cdc.RegisterConcrete(&kmultisig.LegacyAminoPubKey{}, kmultisig.PubKeyAminoRoute, nil) + cdc.RegisterConcrete(&bls12381.PubKey{}, + bls12381.PubKeyName, nil) cdc.RegisterInterface((*cryptotypes.PrivKey)(nil), nil) cdc.RegisterConcrete(sr25519.PrivKey{}, @@ -30,4 +33,6 @@ func RegisterCrypto(cdc *codec.LegacyAmino) { ed25519.PrivKeyName, nil) cdc.RegisterConcrete(&secp256k1.PrivKey{}, secp256k1.PrivKeyName, nil) + cdc.RegisterConcrete(&bls12381.PrivKey{}, + bls12381.PrivKeyName, nil) } diff --git a/crypto/codec/proto.go b/crypto/codec/proto.go index 9c07ca1105..6bdac15ab6 100644 --- a/crypto/codec/proto.go +++ b/crypto/codec/proto.go @@ -2,6 +2,7 @@ package codec import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/keys/bls12381" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" @@ -14,4 +15,5 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &ed25519.PubKey{}) registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &secp256k1.PubKey{}) registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &multisig.LegacyAminoPubKey{}) + registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &bls12381.PubKey{}) } diff --git a/crypto/hd/algo.go b/crypto/hd/algo.go index f934ad08ae..3606a8bce1 100644 --- a/crypto/hd/algo.go +++ b/crypto/hd/algo.go @@ -1,6 +1,7 @@ package hd import ( + "github.com/cosmos/cosmos-sdk/crypto/keys/bls12381" bip39 "github.com/cosmos/go-bip39" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" @@ -20,11 +21,15 @@ const ( Ed25519Type = PubKeyType("ed25519") // Sr25519Type represents the Sr25519Type signature system. Sr25519Type = PubKeyType("sr25519") + // Bls12381Type represents the Bls12381Type signature system. + Bls12381Type = PubKeyType("bls12381") ) var ( // Secp256k1 uses the Bitcoin secp256k1 ECDSA parameters. Secp256k1 = secp256k1Algo{} + // Bls12381 uses blst implememtation of bls signatures + Bls12381 = bls12381Algo{} ) type DeriveFn func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) @@ -69,3 +74,43 @@ func (s secp256k1Algo) Generate() GenerateFn { return &secp256k1.PrivKey{Key: bzArr} } } + + + + +type bls12381Algo struct { +} + +func (s bls12381Algo) Name() PubKeyType { + return Bls12381Type +} + +// todo: replace bitcoin private key generation +// Derive derives and returns the bls12381 private key for the given seed and HD path. +func (s bls12381Algo) Derive() DeriveFn { + return func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) { + seed, err := bip39.NewSeedWithErrorChecking(mnemonic, bip39Passphrase) + if err != nil { + return nil, err + } + + masterPriv, ch := ComputeMastersFromSeed(seed) + if len(hdPath) == 0 { + return masterPriv[:], nil + } + derivedKey, err := DerivePrivateKeyForPath(masterPriv, ch, hdPath) + + return derivedKey, err + } +} + +// Generate generates a bls12381 private key from the given bytes. +func (s bls12381Algo) Generate() GenerateFn { + return func(bz []byte) types.PrivKey { + var bzArr = make([]byte, bls12381.SeedSize) + copy(bzArr, bz) + sk := bls12381.GenPrivKeyFromSecret(bzArr) + + return sk + } +} \ No newline at end of file diff --git a/crypto/keyring/keyring.go b/crypto/keyring/keyring.go index febad555df..25a0a7dcb2 100644 --- a/crypto/keyring/keyring.go +++ b/crypto/keyring/keyring.go @@ -200,7 +200,7 @@ type keystore struct { func newKeystore(kr keyring.Keyring, opts ...Option) keystore { // Default options for keybase options := Options{ - SupportedAlgos: SigningAlgoList{hd.Secp256k1}, + SupportedAlgos: SigningAlgoList{hd.Secp256k1, hd.Bls12381}, SupportedAlgosLedger: SigningAlgoList{hd.Secp256k1}, } diff --git a/crypto/keys/bls12381/bls12381.go b/crypto/keys/bls12381/bls12381.go new file mode 100644 index 0000000000..c9df90bab8 --- /dev/null +++ b/crypto/keys/bls12381/bls12381.go @@ -0,0 +1,233 @@ +package bls12381 + +import ( + "crypto/subtle" + "fmt" + "github.com/cosmos/cosmos-sdk/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/types/errors" + blst "github.com/supranational/blst/bindings/go" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/tmhash" + "io" + +) + +const ( + PrivKeyName = "tendermint/PrivKeyBls12381" + PubKeyName = "tendermint/PubKeyBls12381" + // PubKeySize is is the size, in bytes, of public keys as used in this package. + PubKeySize = 96 + // PrivKeySize is the size, in bytes, of private keys as used in this package. + // Uncompressed public key + PrivKeySize = 32 + // Compressed signature + SignatureSize = 96 + keyType = "bls12381" + SeedSize = 32 +) + +var _ cryptotypes.PrivKey = &PrivKey{} +var _ codec.AminoMarshaler = &PrivKey{} + + +// Bytes returns the byte representation of the Private Key. +func (privKey *PrivKey) Bytes() []byte { + return privKey.Key +} + + +// PubKey performs the point-scalar multiplication from the privKey on the +// generator point to get the pubkey. +func (privKey *PrivKey) PubKey() cryptotypes.PubKey { + sk := new(blst.SecretKey).Deserialize(privKey.Key) + if sk == nil { + panic("Failed to deserialize secret key!") + } + pk := new(blst.P1Affine).From(sk) + pk_bytes := pk.Serialize() + + return &PubKey{Key: pk_bytes} +} + + +// Sign produces a signature on the provided message. +// This assumes the privkey is wellformed in the golang format. + +func (privKey *PrivKey) Sign(msg []byte) ([]byte, error) { + dst := []byte("BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_") + sk := new(blst.SecretKey).Deserialize(privKey.Key) + if sk == nil { + panic("Failed to deserialize secret key!") + } + + sig := new(blst.P2Affine).Sign(sk, msg, dst) + if sig == nil { + panic("Failed to sign message!") + } + + sig_bytes := sig.Compress() + + return sig_bytes, nil +} + +// Equals - you probably don't need to use this. +// Runs in constant time based on length of the +func (privKey *PrivKey) Equals(other cryptotypes.LedgerPrivKey) bool { + return privKey.Type() == other.Type() && subtle.ConstantTimeCompare(privKey.Bytes(), other.Bytes()) == 1 +} + +func (privKey *PrivKey) Type() string { + return keyType +} + + +// MarshalAmino overrides Amino binary marshalling. +func (privKey PrivKey) MarshalAmino() ([]byte, error) { + return privKey.Key, nil +} + +// UnmarshalAmino overrides Amino binary marshalling. +func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { + if len(bz) != PrivKeySize { + return fmt.Errorf("invalid privkey size") + } + privKey.Key = bz + + return nil +} + + +// MarshalAminoJSON overrides Amino JSON marshalling. +func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) { + // When we marshal to Amino JSON, we don't marshal the "key" field itself, + // just its contents (i.e. the key bytes). + return privKey.MarshalAmino() +} + +// UnmarshalAminoJSON overrides Amino JSON marshalling. +func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error { + return privKey.UnmarshalAmino(bz) +} + + + +// GenPrivKey generates a new BLS private key on curve bls12-381 private key. +// It uses OS randomness to generate the private key. +func GenPrivKey() *PrivKey { + return &PrivKey{Key: genPrivKey(crypto.CReader())} +} + +// genPrivKey generates a new secp256k1 private key using the provided reader. +func genPrivKey(rand io.Reader) []byte { + var ikm [SeedSize]byte + _, err := io.ReadFull(rand, ikm[:]) + if err != nil { + panic(err) + } + + sk := blst.KeyGen(ikm[:]) + if sk == nil { + panic("Failed to generate secret key!") + } + + sk_bytes := sk.Serialize() + + return sk_bytes +} + +// GenPrivKeyFromSecret hashes the secret with SHA2, and uses +// that 32 byte output to create the private key. +// NOTE: secret should be the output of a KDF like bcrypt, +// if it's derived from user input. +func GenPrivKeyFromSecret(secret []byte) *PrivKey { + ikm := crypto.Sha256(secret) // Not Ripemd160 because we want 32 bytes. + sk_bytes := blst.KeyGen(ikm[:]).Serialize() + + return &PrivKey{Key: sk_bytes} +} + + +var _ cryptotypes.PubKey = &PubKey{} +var _ codec.AminoMarshaler = &PubKey{} + +// Validate public key, infinity and subgroup checking +func (pubKey *PubKey) Validate() bool { + pk := new(blst.P1Affine).Deserialize(pubKey.Key) + return pk.KeyValidate() +} + + +// Address is the SHA256-20 of the raw pubkey bytes. +func (pubKey *PubKey) Address() crypto.Address { + if len(pubKey.Key) != PubKeySize { + panic("pubkey is incorrect size") + } + return crypto.Address(tmhash.SumTruncated(pubKey.Key)) +} + +// Bytes returns the PubKey byte format. +func (pubKey *PubKey) Bytes() []byte { + return pubKey.Key +} + +// Assume public key is validated +func (pubKey *PubKey) VerifySignature(msg []byte, sig []byte) bool { + // make sure we use the same algorithm to sign + pk := new(blst.P1Affine).Deserialize(pubKey.Key) + if pk == nil { + panic("Failed to deserialize public key") + } + + sigma := new(blst.P2Affine).Uncompress(sig) + if sigma == nil { + panic("Failed to deserialize signature") + } + + dst := []byte("BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_") + + return sigma.Verify(true, pk, false, msg, dst) +} + +func (pubKey *PubKey) String() string { + return fmt.Sprintf("PubKeyBls12381{%X}", pubKey.Key) +} + +func (pubKey *PubKey) Type() string { + return keyType +} + +func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool { + if pubKey.Type() != other.Type() { + return false + } + + return subtle.ConstantTimeCompare(pubKey.Bytes(), other.Bytes()) == 1 +} + +// MarshalAmino overrides Amino binary marshalling. +func (pubKey PubKey) MarshalAmino() ([]byte, error) { + return pubKey.Key, nil +} + +// UnmarshalAmino overrides Amino binary marshalling. +func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { + if len(bz) != PubKeySize { + return errors.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size") + } + pubKey.Key = bz + + return nil +} + +// MarshalAminoJSON overrides Amino JSON marshalling. +func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) { + // When we marshal to Amino JSON, we don't marshal the "key" field itself, + // just its contents (i.e. the key bytes). + return pubKey.MarshalAmino() +} + +// UnmarshalAminoJSON overrides Amino JSON marshalling. +func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error { + return pubKey.UnmarshalAmino(bz) +} diff --git a/crypto/keys/bls12381/bls12381_test.go b/crypto/keys/bls12381/bls12381_test.go new file mode 100644 index 0000000000..7e6cd13a30 --- /dev/null +++ b/crypto/keys/bls12381/bls12381_test.go @@ -0,0 +1,22 @@ +package bls12381_test + +import ( + "github.com/cosmos/cosmos-sdk/crypto/keys/bls12381" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/crypto" + "testing" +) + +func TestSignAndValidateBls12381(t *testing.T) { + privKey := bls12381.GenPrivKey() + pubKey := privKey.PubKey() + + msg := crypto.CRandBytes(1000) + sig, err := privKey.Sign(msg) + require.Nil(t, err) + + // Test the signature + assert.True(t, pubKey.VerifySignature(msg, sig)) + +} \ No newline at end of file diff --git a/crypto/keys/bls12381/keys.pb.go b/crypto/keys/bls12381/keys.pb.go new file mode 100644 index 0000000000..9a7569ca71 --- /dev/null +++ b/crypto/keys/bls12381/keys.pb.go @@ -0,0 +1,496 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/crypto/bls12381/keys.proto + +package bls12381 + +import ( + fmt "fmt" + _ "github.com/gogo/protobuf/gogoproto" + proto "github.com/gogo/protobuf/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// PubKey defines a bls public key +// Key is the uncompressed form of the pubkey. The first byte depends is a 0x02 byte +// if the y-coordinate is the lexicographically largest of the two associated with +// the x-coordinate. Otherwise the first byte is a 0x03. +// This prefix is followed with the x-coordinate. +type PubKey struct { + Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` +} + +func (m *PubKey) Reset() { *m = PubKey{} } +func (*PubKey) ProtoMessage() {} +func (*PubKey) Descriptor() ([]byte, []int) { + return fileDescriptor_295d2962e809fcdb, []int{0} +} +func (m *PubKey) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PubKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PubKey.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PubKey) XXX_Merge(src proto.Message) { + xxx_messageInfo_PubKey.Merge(m, src) +} +func (m *PubKey) XXX_Size() int { + return m.Size() +} +func (m *PubKey) XXX_DiscardUnknown() { + xxx_messageInfo_PubKey.DiscardUnknown(m) +} + +var xxx_messageInfo_PubKey proto.InternalMessageInfo + +func (m *PubKey) GetKey() []byte { + if m != nil { + return m.Key + } + return nil +} + +// PrivKey defines a bls private key. +type PrivKey struct { + Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` +} + +func (m *PrivKey) Reset() { *m = PrivKey{} } +func (m *PrivKey) String() string { return proto.CompactTextString(m) } +func (*PrivKey) ProtoMessage() {} +func (*PrivKey) Descriptor() ([]byte, []int) { + return fileDescriptor_295d2962e809fcdb, []int{1} +} +func (m *PrivKey) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PrivKey) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PrivKey.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PrivKey) XXX_Merge(src proto.Message) { + xxx_messageInfo_PrivKey.Merge(m, src) +} +func (m *PrivKey) XXX_Size() int { + return m.Size() +} +func (m *PrivKey) XXX_DiscardUnknown() { + xxx_messageInfo_PrivKey.DiscardUnknown(m) +} + +var xxx_messageInfo_PrivKey proto.InternalMessageInfo + +func (m *PrivKey) GetKey() []byte { + if m != nil { + return m.Key + } + return nil +} + +func init() { + proto.RegisterType((*PubKey)(nil), "cosmos.crypto.bls12381.PubKey") + proto.RegisterType((*PrivKey)(nil), "cosmos.crypto.bls12381.PrivKey") +} + +func init() { proto.RegisterFile("cosmos/crypto/bls12381/keys.proto", fileDescriptor_295d2962e809fcdb) } + +var fileDescriptor_295d2962e809fcdb = []byte{ + // 184 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4c, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x4f, 0x2e, 0xaa, 0x2c, 0x28, 0xc9, 0xd7, 0x4f, 0xca, 0x29, 0x36, 0x34, 0x32, + 0xb6, 0x30, 0xd4, 0xcf, 0x4e, 0xad, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x83, + 0x28, 0xd1, 0x83, 0x28, 0xd1, 0x83, 0x29, 0x91, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x2b, 0xd1, + 0x07, 0xb1, 0x20, 0xaa, 0x95, 0x14, 0xb8, 0xd8, 0x02, 0x4a, 0x93, 0xbc, 0x53, 0x2b, 0x85, 0x04, + 0xb8, 0x98, 0xb3, 0x53, 0x2b, 0x25, 0x18, 0x15, 0x18, 0x35, 0x78, 0x82, 0x40, 0x4c, 0x2b, 0x96, + 0x19, 0x0b, 0xe4, 0x19, 0x94, 0xa4, 0xb9, 0xd8, 0x03, 0x8a, 0x32, 0xcb, 0xb0, 0x2a, 0x71, 0xf2, + 0x3e, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, + 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xc3, 0xf4, 0xcc, 0x92, 0x8c, + 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x98, 0xa3, 0xc1, 0x94, 0x6e, 0x71, 0x4a, 0x36, 0xcc, + 0xfd, 0x20, 0x67, 0xc3, 0x3d, 0x91, 0xc4, 0x06, 0x76, 0x92, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, + 0x0e, 0x2e, 0xb6, 0x08, 0xe5, 0x00, 0x00, 0x00, +} + +func (m *PubKey) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PubKey) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PubKey) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintKeys(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *PrivKey) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PrivKey) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PrivKey) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintKeys(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintKeys(dAtA []byte, offset int, v uint64) int { + offset -= sovKeys(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *PubKey) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func (m *PrivKey) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + if l > 0 { + n += 1 + l + sovKeys(uint64(l)) + } + return n +} + +func sovKeys(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozKeys(x uint64) (n int) { + return sovKeys(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *PubKey) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PubKey: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PubKey: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthKeys + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) + if m.Key == nil { + m.Key = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PrivKey) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PrivKey: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PrivKey: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowKeys + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthKeys + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthKeys + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) + if m.Key == nil { + m.Key = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipKeys(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthKeys + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipKeys(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowKeys + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowKeys + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowKeys + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthKeys + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupKeys + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthKeys + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthKeys = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowKeys = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupKeys = fmt.Errorf("proto: unexpected end of group") +) diff --git a/go.mod b/go.mod index 4f83be4fc3..ee4bb40e80 100644 --- a/go.mod +++ b/go.mod @@ -45,6 +45,7 @@ require ( github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.7.1 github.com/stretchr/testify v1.7.0 + github.com/supranational/blst v0.3.4 github.com/tendermint/btcd v0.1.1 github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 github.com/tendermint/go-amino v0.16.0 diff --git a/go.sum b/go.sum index 0274c8cf10..b382b59e32 100644 --- a/go.sum +++ b/go.sum @@ -543,6 +543,8 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= +github.com/supranational/blst v0.3.4 h1:iZE9lBMoywK2uy2U/5hDOvobQk9FnOQ2wNlu9GmRCoA= +github.com/supranational/blst v0.3.4/go.mod h1:jZJtfjgudtNl4en1tzwPIV3KjUnQUvG3/j+w+fVonLw= github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca h1:Ld/zXl5t4+D69SiV4JoN7kkfvJdOWlPpfxrzxpLMoUk= github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca/go.mod h1:u2MKkTVTVJWe5D1rCvame8WqhBd88EuIwODJZ1VHCPM= github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c h1:g+WoO5jjkqGAzHWCjJB1zZfXPIAaDpzXIEJ0eS6B5Ok= diff --git a/proto/cosmos/crypto/bls12381/keys.proto b/proto/cosmos/crypto/bls12381/keys.proto new file mode 100644 index 0000000000..54740c32c9 --- /dev/null +++ b/proto/cosmos/crypto/bls12381/keys.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; +package cosmos.crypto.bls12381; + +import "gogoproto/gogo.proto"; + +option go_package = "github.com/cosmos/cosmos-sdk/crypto/keys/bls12381"; + +// PubKey defines a bls public key +// Key is the uncompressed form of the pubkey. The first byte depends is a 0x02 byte +// if the y-coordinate is the lexicographically largest of the two associated with +// the x-coordinate. Otherwise the first byte is a 0x03. +// This prefix is followed with the x-coordinate. +message PubKey { + option (gogoproto.goproto_stringer) = false; + + bytes key = 1; +} + +// PrivKey defines a bls private key. +message PrivKey { + bytes key = 1; +} \ No newline at end of file diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index 79fbbcdc67..84ea7a0ae7 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/hex" "fmt" + "github.com/cosmos/cosmos-sdk/crypto/keys/bls12381" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" @@ -83,6 +84,15 @@ func (spkd SetPubKeyDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b if acc.GetPubKey() != nil { continue } + + //Validate public key for bls12381 so that the public key only needs to be checked once + switch pubkey := pk.(type) { + case *bls12381.PubKey: + if !pubkey.Validate() { + return ctx, sdkerrors.Wrap(sdkerrors.ErrInvalidPubKey, "Invalid public key: either infinity or not subgroup element") + } + } + err = acc.SetPubKey(pk) if err != nil { return ctx, sdkerrors.Wrap(sdkerrors.ErrInvalidPubKey, err.Error()) @@ -379,6 +389,11 @@ func DefaultSigVerificationGasConsumer( } return nil + // todo: add gas option to params and genesis.json + case *bls12381.PubKey: + meter.ConsumeGas(6213, "ante verify: bls12381") + return nil + default: return sdkerrors.Wrapf(sdkerrors.ErrInvalidPubKey, "unrecognized public key type: %T", pubkey) } From e47c7f88b9d23b5c2f493cf3c969991928f9bb25 Mon Sep 17 00:00:00 2001 From: kitty Date: Thu, 15 Jul 2021 11:01:21 +0100 Subject: [PATCH 02/10] benchmark for bls and ed25519 --- crypto/keys/bls12381/bls12381_test.go | 16 ++++++++++++++++ crypto/keys/ed25519/ed25519_test.go | 17 +++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/crypto/keys/bls12381/bls12381_test.go b/crypto/keys/bls12381/bls12381_test.go index 7e6cd13a30..c7a9c993aa 100644 --- a/crypto/keys/bls12381/bls12381_test.go +++ b/crypto/keys/bls12381/bls12381_test.go @@ -2,6 +2,7 @@ package bls12381_test import ( "github.com/cosmos/cosmos-sdk/crypto/keys/bls12381" + bench "github.com/cosmos/cosmos-sdk/crypto/keys/internal/benchmarking" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" @@ -19,4 +20,19 @@ func TestSignAndValidateBls12381(t *testing.T) { // Test the signature assert.True(t, pubKey.VerifySignature(msg, sig)) +} + + +func BenchmarkSignBls(b *testing.B) { + privKey := bls12381.GenPrivKey() + + bench.BenchmarkSigning(b, privKey) + +} + + +func BenchmarkVerifyBls(b *testing.B) { + privKey := bls12381.GenPrivKey() + + bench.BenchmarkVerification(b, privKey) } \ No newline at end of file diff --git a/crypto/keys/ed25519/ed25519_test.go b/crypto/keys/ed25519/ed25519_test.go index 59cce4066a..4e455c47ad 100644 --- a/crypto/keys/ed25519/ed25519_test.go +++ b/crypto/keys/ed25519/ed25519_test.go @@ -3,6 +3,7 @@ package ed25519_test import ( stded25519 "crypto/ed25519" "encoding/base64" + bench "github.com/cosmos/cosmos-sdk/crypto/keys/internal/benchmarking" "testing" "github.com/stretchr/testify/assert" @@ -228,3 +229,19 @@ func TestMarshalAmino_BackwardsCompatibility(t *testing.T) { }) } } + + + +func BenchmarkSignEd25519(b *testing.B) { + privKey := ed25519.GenPrivKey() + + bench.BenchmarkSigning(b, privKey) + +} + + +func BenchmarkVerifyEd25519(b *testing.B) { + privKey := ed25519.GenPrivKey() + + bench.BenchmarkVerification(b, privKey) +} \ No newline at end of file From 082e0710e3dd2f96733e76f8e2f928c2d7e4ab29 Mon Sep 17 00:00:00 2001 From: kitty Date: Thu, 15 Jul 2021 15:16:23 +0100 Subject: [PATCH 03/10] added bls sig verify cost to genesis --- proto/cosmos/auth/v1beta1/auth.proto | 3 + x/auth/ante/sigverify.go | 4 +- x/auth/simulation/genesis.go | 14 ++- x/auth/types/auth.pb.go | 128 ++++++++++++++++++--------- x/auth/types/params.go | 24 ++++- 5 files changed, 124 insertions(+), 49 deletions(-) diff --git a/proto/cosmos/auth/v1beta1/auth.proto b/proto/cosmos/auth/v1beta1/auth.proto index 72e1d9ec28..799568c186 100644 --- a/proto/cosmos/auth/v1beta1/auth.proto +++ b/proto/cosmos/auth/v1beta1/auth.proto @@ -2,6 +2,7 @@ syntax = "proto3"; package cosmos.auth.v1beta1; import "cosmos_proto/cosmos.proto"; +//import "cosmos.proto"; import "gogoproto/gogo.proto"; import "google/protobuf/any.proto"; @@ -47,4 +48,6 @@ message Params { [(gogoproto.customname) = "SigVerifyCostED25519", (gogoproto.moretags) = "yaml:\"sig_verify_cost_ed25519\""]; uint64 sig_verify_cost_secp256k1 = 5 [(gogoproto.customname) = "SigVerifyCostSecp256k1", (gogoproto.moretags) = "yaml:\"sig_verify_cost_secp256k1\""]; + uint64 sig_verify_cost_bls12381 = 6 + [(gogoproto.customname) = "SigVerifyCostBls12381", (gogoproto.moretags) = "yaml:\"sig_verify_cost_bls12381\""]; } diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index 84ea7a0ae7..223d81b296 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -5,7 +5,6 @@ import ( "encoding/hex" "fmt" "github.com/cosmos/cosmos-sdk/crypto/keys/bls12381" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" @@ -389,9 +388,8 @@ func DefaultSigVerificationGasConsumer( } return nil - // todo: add gas option to params and genesis.json case *bls12381.PubKey: - meter.ConsumeGas(6213, "ante verify: bls12381") + meter.ConsumeGas(params.SigVerifyCostBls12381, "ante verify: bls12381") return nil default: diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 2da36b54fa..5bb2297f29 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -19,6 +19,7 @@ const ( TxSizeCostPerByte = "tx_size_cost_per_byte" SigVerifyCostED25519 = "sig_verify_cost_ed25519" SigVerifyCostSECP256K1 = "sig_verify_cost_secp256k1" + SigVerifyCostBLS12381 = "sig_verify_cost_bls12381" ) // RandomGenesisAccounts defines the default RandomGenesisAccountsFn used on the SDK. @@ -87,6 +88,11 @@ func GenSigVerifyCostSECP256K1(r *rand.Rand) uint64 { return uint64(simulation.RandIntBetween(r, 500, 1000)) } +// GenSigVerifyCostBLS12381 randomized SigVerifyCostBLS12381 +func GenSigVerifyCostBLS12381(r *rand.Rand) uint64 { + return uint64(simulation.RandIntBetween(r, 6000, 12000)) +} + // RandomizedGenState generates a random GenesisState for auth func RandomizedGenState(simState *module.SimulationState, randGenAccountsFn types.RandomGenesisAccountsFn) { var maxMemoChars uint64 @@ -119,8 +125,14 @@ func RandomizedGenState(simState *module.SimulationState, randGenAccountsFn type func(r *rand.Rand) { sigVerifyCostSECP256K1 = GenSigVerifyCostSECP256K1(r) }, ) + var sigVerifyCostBLS12381 uint64 + simState.AppParams.GetOrGenerate( + simState.Cdc, SigVerifyCostBLS12381, &sigVerifyCostBLS12381, simState.Rand, + func(r *rand.Rand) { sigVerifyCostBLS12381 = GenSigVerifyCostBLS12381(r) }, + ) + params := types.NewParams(maxMemoChars, txSigLimit, txSizeCostPerByte, - sigVerifyCostED25519, sigVerifyCostSECP256K1) + sigVerifyCostED25519, sigVerifyCostSECP256K1, sigVerifyCostBLS12381) genesisAccs := randGenAccountsFn(simState) authGenesis := types.NewGenesisState(params, genesisAccs) diff --git a/x/auth/types/auth.pb.go b/x/auth/types/auth.pb.go index fa52ac5a8b..ad2283b816 100644 --- a/x/auth/types/auth.pb.go +++ b/x/auth/types/auth.pb.go @@ -113,6 +113,7 @@ type Params struct { TxSizeCostPerByte uint64 `protobuf:"varint,3,opt,name=tx_size_cost_per_byte,json=txSizeCostPerByte,proto3" json:"tx_size_cost_per_byte,omitempty" yaml:"tx_size_cost_per_byte"` SigVerifyCostED25519 uint64 `protobuf:"varint,4,opt,name=sig_verify_cost_ed25519,json=sigVerifyCostEd25519,proto3" json:"sig_verify_cost_ed25519,omitempty" yaml:"sig_verify_cost_ed25519"` SigVerifyCostSecp256k1 uint64 `protobuf:"varint,5,opt,name=sig_verify_cost_secp256k1,json=sigVerifyCostSecp256k1,proto3" json:"sig_verify_cost_secp256k1,omitempty" yaml:"sig_verify_cost_secp256k1"` + SigVerifyCostBls12381 uint64 `protobuf:"varint,6,opt,name=sig_verify_cost_bls12381,json=sigVerifyCostBls12381,proto3" json:"sig_verify_cost_bls12381,omitempty" yaml:"sig_verify_cost_bls12381"` } func (m *Params) Reset() { *m = Params{} } @@ -182,6 +183,13 @@ func (m *Params) GetSigVerifyCostSecp256k1() uint64 { return 0 } +func (m *Params) GetSigVerifyCostBls12381() uint64 { + if m != nil { + return m.SigVerifyCostBls12381 + } + return 0 +} + func init() { proto.RegisterType((*BaseAccount)(nil), "cosmos.auth.v1beta1.BaseAccount") proto.RegisterType((*ModuleAccount)(nil), "cosmos.auth.v1beta1.ModuleAccount") @@ -191,50 +199,52 @@ func init() { func init() { proto.RegisterFile("cosmos/auth/v1beta1/auth.proto", fileDescriptor_7e1f7e915d020d2d) } var fileDescriptor_7e1f7e915d020d2d = []byte{ - // 674 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x54, 0x4d, 0x4f, 0xdb, 0x4a, - 0x14, 0x8d, 0x5f, 0xf2, 0xf8, 0x98, 0x00, 0x12, 0x26, 0x80, 0x93, 0xf7, 0x64, 0x5b, 0x5e, 0xe5, - 0x49, 0x2f, 0x8e, 0x92, 0x8a, 0x4a, 0x64, 0x51, 0x15, 0xd3, 0x2e, 0x50, 0x0b, 0x42, 0x46, 0xea, - 0xa2, 0xaa, 0xe4, 0x8e, 0x9d, 0xc1, 0x58, 0x64, 0x32, 0xc6, 0x33, 0x46, 0x31, 0xbf, 0xa0, 0xcb, - 0x2e, 0xbb, 0xe4, 0x47, 0xf0, 0x0f, 0xba, 0xe9, 0x12, 0xb1, 0xea, 0xca, 0xad, 0xc2, 0xa6, 0xea, - 0x32, 0xfb, 0x4a, 0x95, 0x67, 0x9c, 0x90, 0xa0, 0x74, 0x95, 0xb9, 0xe7, 0x9c, 0x7b, 0xee, 0x9d, - 0x7b, 0xe3, 0x01, 0xaa, 0x47, 0x28, 0x26, 0xb4, 0x09, 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c, 0x88, 0xa7, 0x85, 0x25, 0x21, 0xa2, 0xee, - 0x02, 0xff, 0x52, 0x9f, 0xfc, 0x0e, 0x00, 0x00, 0xff, 0xff, 0x49, 0x90, 0x16, 0xd9, 0x76, 0x04, - 0x00, 0x00, + // 707 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x54, 0x4f, 0x4f, 0xdb, 0x48, + 0x14, 0x8f, 0x97, 0x6c, 0x80, 0x09, 0x20, 0x61, 0x12, 0x30, 0xd9, 0x95, 0xc7, 0xf2, 0x29, 0x2b, + 0x6d, 0x1c, 0x25, 0x88, 0xd5, 0x12, 0xad, 0x56, 0x8b, 0xd9, 0x1e, 0x50, 0x0b, 0x42, 0x46, 0xea, + 0xa1, 0xaa, 0xe4, 0x8e, 0x9d, 0xc1, 0x58, 0x64, 0x32, 0xc6, 0x33, 0x46, 0x31, 0x9f, 0xa0, 0xc7, + 0x1e, 0x7b, 0xe4, 0x43, 0xf0, 0x0d, 0x7a, 0xe9, 0x11, 0x71, 0xa8, 0x7a, 0xb2, 0xaa, 0x70, 0xa9, + 0x7a, 0xf4, 0xbd, 0x52, 0x95, 0xb1, 0x13, 0x12, 0x94, 0x9e, 0xe2, 0xf7, 0x7e, 0xff, 0xde, 0xbc, + 0x51, 0x06, 0xa8, 0x2e, 0x65, 0x84, 0xb2, 0x26, 0x8a, 0xf8, 0x79, 0xf3, 0xaa, 0xe5, 0x60, 0x8e, + 0x5a, 0xa2, 0x30, 0x82, 0x90, 0x72, 0x2a, 0x6f, 0x64, 0xb8, 0x21, 0x5a, 0x39, 0x5e, 0x5b, 0xc9, + 0x9b, 0x82, 0x52, 0xab, 0x78, 0xd4, 0xa3, 0xe2, 0xb3, 0x39, 0xfa, 0xca, 0xbb, 0xdb, 0x1e, 0xa5, + 0x5e, 0x0f, 0x37, 0x45, 0xe5, 0x44, 0x67, 0x4d, 0xd4, 0x8f, 0x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0x87, 0xfe, 0x59, 0x9c, 0xf1, 0x71, 0xb7, 0xbd, 0xbb, 0xdb, + 0xda, 0xcb, 0x2e, 0xdd, 0xec, 0x0c, 0x13, 0x58, 0x39, 0xf5, 0xbd, 0x97, 0x82, 0x31, 0x92, 0x3e, + 0xfb, 0x5f, 0xe0, 0x69, 0x02, 0xd5, 0x2c, 0xed, 0x27, 0x06, 0xba, 0x55, 0x61, 0x33, 0xba, 0xac, + 0x2d, 0xc7, 0x60, 0xfb, 0xa9, 0x82, 0x61, 0x37, 0x68, 0xef, 0xfe, 0x75, 0xd1, 0x52, 0x7e, 0x15, + 0xa1, 0xff, 0x0e, 0x13, 0xb8, 0x39, 0x13, 0x7a, 0x3a, 0x66, 0xa4, 0x09, 0xd4, 0xe6, 0xc7, 0x4e, + 0x4c, 0x74, 0x6b, 0x93, 0xcd, 0xd5, 0xca, 0x11, 0x50, 0x9e, 0xaa, 0x9c, 0x1e, 0x6b, 0xb5, 0x77, + 0xfe, 0x6e, 0x29, 0x25, 0x91, 0xfc, 0xcf, 0x30, 0x81, 0xd5, 0x99, 0x64, 0x33, 0x27, 0xa4, 0x09, + 0x84, 0xf3, 0x83, 0xc7, 0x16, 0xba, 0x55, 0x65, 0xf3, 0x94, 0x9d, 0xa5, 0xfc, 0xaf, 0x22, 0x99, + 0x07, 0x1f, 0x87, 0xaa, 0x74, 0x37, 0x54, 0xa5, 0x2f, 0x43, 0x55, 0x7a, 0xf7, 0xa0, 0x16, 0xee, + 0x1e, 0xd4, 0xc2, 0xe7, 0x07, 0xb5, 0xf0, 0xea, 0x0f, 0xcf, 0xe7, 0xe7, 0x91, 0x63, 0xb8, 0x94, + 0x34, 0xf3, 0x77, 0x2b, 0xfb, 0x69, 0xb0, 0xee, 0x45, 0x73, 0x90, 0x3d, 0x62, 0x3c, 0x0e, 0x30, + 0x73, 0x4a, 0xe2, 0x81, 0xd8, 0xf9, 0x11, 0x00, 0x00, 0xff, 0xff, 0xd3, 0xe6, 0x37, 0xa1, 0xe0, + 0x04, 0x00, 0x00, } func (this *Params) Equal(that interface{}) bool { @@ -271,6 +281,9 @@ func (this *Params) Equal(that interface{}) bool { if this.SigVerifyCostSecp256k1 != that1.SigVerifyCostSecp256k1 { return false } + if this.SigVerifyCostBls12381 != that1.SigVerifyCostBls12381 { + return false + } return true } func (m *BaseAccount) Marshal() (dAtA []byte, err error) { @@ -396,6 +409,11 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.SigVerifyCostBls12381 != 0 { + i = encodeVarintAuth(dAtA, i, uint64(m.SigVerifyCostBls12381)) + i-- + dAtA[i] = 0x30 + } if m.SigVerifyCostSecp256k1 != 0 { i = encodeVarintAuth(dAtA, i, uint64(m.SigVerifyCostSecp256k1)) i-- @@ -502,6 +520,9 @@ func (m *Params) Size() (n int) { if m.SigVerifyCostSecp256k1 != 0 { n += 1 + sovAuth(uint64(m.SigVerifyCostSecp256k1)) } + if m.SigVerifyCostBls12381 != 0 { + n += 1 + sovAuth(uint64(m.SigVerifyCostBls12381)) + } return n } @@ -941,6 +962,25 @@ func (m *Params) Unmarshal(dAtA []byte) error { break } } + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field SigVerifyCostBls12381", wireType) + } + m.SigVerifyCostBls12381 = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAuth + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.SigVerifyCostBls12381 |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } default: iNdEx = preIndex skippy, err := skipAuth(dAtA[iNdEx:]) diff --git a/x/auth/types/params.go b/x/auth/types/params.go index 13db369d23..fb2a47ec50 100644 --- a/x/auth/types/params.go +++ b/x/auth/types/params.go @@ -15,6 +15,7 @@ const ( DefaultTxSizeCostPerByte uint64 = 10 DefaultSigVerifyCostED25519 uint64 = 590 DefaultSigVerifyCostSecp256k1 uint64 = 1000 + DefaultSigVerifyCostBls12381 uint64 = 6300 ) // Parameter keys @@ -24,13 +25,14 @@ var ( KeyTxSizeCostPerByte = []byte("TxSizeCostPerByte") KeySigVerifyCostED25519 = []byte("SigVerifyCostED25519") KeySigVerifyCostSecp256k1 = []byte("SigVerifyCostSecp256k1") + KeySigVerifyCostBls12381 = []byte("SigVerifyCostBls12381") ) var _ paramtypes.ParamSet = &Params{} // NewParams creates a new Params object func NewParams( - maxMemoCharacters, txSigLimit, txSizeCostPerByte, sigVerifyCostED25519, sigVerifyCostSecp256k1 uint64, + maxMemoCharacters, txSigLimit, txSizeCostPerByte, sigVerifyCostED25519, sigVerifyCostSecp256k1 uint64, sigVerifyCostBls12381 uint64, ) Params { return Params{ MaxMemoCharacters: maxMemoCharacters, @@ -38,6 +40,7 @@ func NewParams( TxSizeCostPerByte: txSizeCostPerByte, SigVerifyCostED25519: sigVerifyCostED25519, SigVerifyCostSecp256k1: sigVerifyCostSecp256k1, + SigVerifyCostBls12381: sigVerifyCostBls12381, } } @@ -55,6 +58,7 @@ func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { paramtypes.NewParamSetPair(KeyTxSizeCostPerByte, &p.TxSizeCostPerByte, validateTxSizeCostPerByte), paramtypes.NewParamSetPair(KeySigVerifyCostED25519, &p.SigVerifyCostED25519, validateSigVerifyCostED25519), paramtypes.NewParamSetPair(KeySigVerifyCostSecp256k1, &p.SigVerifyCostSecp256k1, validateSigVerifyCostSecp256k1), + paramtypes.NewParamSetPair(KeySigVerifyCostBls12381, &p.SigVerifyCostBls12381, validateSigVerifyCostBls12381), } } @@ -66,6 +70,7 @@ func DefaultParams() Params { TxSizeCostPerByte: DefaultTxSizeCostPerByte, SigVerifyCostED25519: DefaultSigVerifyCostED25519, SigVerifyCostSecp256k1: DefaultSigVerifyCostSecp256k1, + SigVerifyCostBls12381: DefaultSigVerifyCostBls12381, } } @@ -114,6 +119,20 @@ func validateSigVerifyCostSecp256k1(i interface{}) error { return nil } + +func validateSigVerifyCostBls12381(i interface{}) error { + v, ok := i.(uint64) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v == 0 { + return fmt.Errorf("invalid BLS12381 signature verification cost: %d", v) + } + + return nil +} + func validateMaxMemoCharacters(i interface{}) error { v, ok := i.(uint64) if !ok { @@ -151,6 +170,9 @@ func (p Params) Validate() error { if err := validateSigVerifyCostSecp256k1(p.SigVerifyCostSecp256k1); err != nil { return err } + if err := validateSigVerifyCostBls12381(p.SigVerifyCostBls12381); err != nil { + return err + } if err := validateMaxMemoCharacters(p.MaxMemoCharacters); err != nil { return err } From 78a09e55d29c6a0c0b28fc6b54bce22fe35fd6ea Mon Sep 17 00:00:00 2001 From: kitty Date: Thu, 15 Jul 2021 15:43:27 +0100 Subject: [PATCH 04/10] Revert "Merge branch 'fetchai:master' into bls" This reverts commit a5dd8ea9c1597c285e9375f168dd7af51e76f6b3, reversing changes made to 082e0710e3dd2f96733e76f8e2f928c2d7e4ab29. --- x/airdrop/keeper/keeper_test.go | 84 +-------------------------------- x/airdrop/keeper/params.go | 2 +- x/airdrop/types/genesis_test.go | 63 ------------------------- 3 files changed, 2 insertions(+), 147 deletions(-) delete mode 100644 x/airdrop/types/genesis_test.go diff --git a/x/airdrop/keeper/keeper_test.go b/x/airdrop/keeper/keeper_test.go index 37e9f51a5c..94aa2b7d79 100644 --- a/x/airdrop/keeper/keeper_test.go +++ b/x/airdrop/keeper/keeper_test.go @@ -17,8 +17,6 @@ var ( feeCollectorAddress = authtypes.NewModuleAddress(authtypes.FeeCollectorName) addr1 = sdk.AccAddress([]byte("addr1_______________")) addr2 = sdk.AccAddress([]byte("addr2_______________")) - addr3 = sdk.AccAddress([]byte("addr3_______________")) - addr4 = sdk.AccAddress([]byte("addr4_______________")) ) type KeeperTestSuite struct { @@ -36,10 +34,9 @@ func (s *KeeperTestSuite) SetupTest() { Height: 10, }) - s.app.AirdropKeeper.SetParams(s.ctx, types.NewParams(addr1.String(), addr2.String(), addr3.String(), addr4.String())) + s.app.AirdropKeeper.SetParams(s.ctx, types.NewParams(addr1.String(), addr2.String())) } - func (s *KeeperTestSuite) TestAddNewFund() { amount := sdk.NewInt64Coin(sdk.DefaultBondDenom, 4000) s.Require().NoError(s.app.BankKeeper.SetBalance(s.ctx, addr1, amount)) // ensure the account is funded @@ -167,85 +164,6 @@ func (s *KeeperTestSuite) TestFeeDrip() { s.Require().Equal(feeCollectorBalance, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(4040))) } -func (s *KeeperTestSuite) TestAddNewFundWithDiffDenom() { - amount := sdk.NewInt64Coin("denom", 4000) - s.Require().NoError(s.app.BankKeeper.SetBalance(s.ctx, addr1, amount)) // ensure the account is funded - - addrBalance := s.app.BankKeeper.GetBalance(s.ctx, addr1, "denom") - moduleBalance := s.app.BankKeeper.GetBalance(s.ctx, moduleAddress, "denom") - - // sanity check - s.Require().Equal(addrBalance, sdk.NewCoin("denom", sdk.NewInt(4000))) - s.Require().Equal(moduleBalance, sdk.NewCoin("denom", sdk.NewInt(0))) - - fund := types.Fund{ - Amount: &amount, - DripAmount: sdk.NewInt(40), - } - s.Require().NoError(s.app.AirdropKeeper.AddFund(s.ctx, addr1, fund)) - - addrBalance = s.app.BankKeeper.GetBalance(s.ctx, addr1, "denom") - moduleBalance = s.app.BankKeeper.GetBalance(s.ctx, moduleAddress, "denom") - - s.Require().Equal(addrBalance, sdk.NewCoin("denom", sdk.NewInt(0))) - s.Require().Equal(moduleBalance, sdk.NewCoin("denom", sdk.NewInt(4000))) -} - -func (s *KeeperTestSuite) TestMultiDenomFeeDrip() { - amountStake := sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000) - amountDenom := sdk.NewInt64Coin("denom", 1000) - fund1 := types.Fund{ - Amount: &amountStake, - DripAmount: sdk.NewInt(500)} - - fund2 := types.Fund{ - Amount: &amountStake, - DripAmount: sdk.NewInt(800), - } - - fund3 := types.Fund{ - Amount: &amountDenom, - DripAmount: sdk.NewInt(100)} - - fund4 := types.Fund{ - Amount: &amountDenom, - DripAmount: sdk.NewInt(300), - } - s.Require().NoError(s.app.BankKeeper.SetBalance(s.ctx, addr1, amountStake)) - s.Require().NoError(s.app.BankKeeper.SetBalance(s.ctx, addr2, amountStake)) - s.Require().NoError(s.app.BankKeeper.SetBalance(s.ctx, addr3, amountDenom)) - s.Require().NoError(s.app.BankKeeper.SetBalance(s.ctx, addr4, amountDenom)) - - s.Require().NoError(s.app.AirdropKeeper.AddFund(s.ctx, addr1, fund1)) - s.Require().NoError(s.app.AirdropKeeper.AddFund(s.ctx, addr2, fund2)) - s.Require().NoError(s.app.AirdropKeeper.AddFund(s.ctx, addr3, fund3)) - s.Require().NoError(s.app.AirdropKeeper.AddFund(s.ctx, addr4, fund4)) // check the balances - - moduleBalanceStake := s.app.BankKeeper.GetBalance(s.ctx, moduleAddress, sdk.DefaultBondDenom) - moduleBalanceDenom := s.app.BankKeeper.GetBalance(s.ctx, moduleAddress, "denom") - feeCollectorBalanceStake := s.app.BankKeeper.GetBalance(s.ctx, feeCollectorAddress, sdk.DefaultBondDenom) - feeCollectorBalanceDenom := s.app.BankKeeper.GetBalance(s.ctx, feeCollectorAddress, "denom") - - s.Require().Equal(moduleBalanceStake, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2000))) - s.Require().Equal(moduleBalanceDenom, sdk.NewCoin("denom", sdk.NewInt(2000))) - s.Require().Equal(feeCollectorBalanceStake, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(0))) - s.Require().Equal(feeCollectorBalanceDenom, sdk.NewCoin("denom", sdk.NewInt(0))) - - _, err := s.app.AirdropKeeper.DripAllFunds(s.ctx) // test case - drip the funds - s.Require().NoError(err) // check that the fees have been transferred - - moduleBalanceStake = s.app.BankKeeper.GetBalance(s.ctx, moduleAddress, sdk.DefaultBondDenom) - moduleBalanceDenom = s.app.BankKeeper.GetBalance(s.ctx, moduleAddress, "denom") - feeCollectorBalanceStake = s.app.BankKeeper.GetBalance(s.ctx, feeCollectorAddress, sdk.DefaultBondDenom) - feeCollectorBalanceDenom = s.app.BankKeeper.GetBalance(s.ctx, feeCollectorAddress, "denom") - - s.Require().Equal(feeCollectorBalanceStake, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1300))) // 800 drip fund 1, 500 drip fund 2 - s.Require().Equal(feeCollectorBalanceDenom, sdk.NewCoin("denom", sdk.NewInt(400))) // 100 drip fund 3, 300 drip fund 4 - s.Require().Equal(moduleBalanceStake, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(700))) // remainder 500 from fund 1, remainder 200 from fund 2 - s.Require().Equal(moduleBalanceDenom, sdk.NewCoin("denom", sdk.NewInt(1600))) // remainder 900 from fund 3, remainder 700 from fund 4 - -} - func TestKeeperTestSuite(t *testing.T) { suite.Run(t, new(KeeperTestSuite)) } diff --git a/x/airdrop/keeper/params.go b/x/airdrop/keeper/params.go index 0ccf156afd..c748d41074 100644 --- a/x/airdrop/keeper/params.go +++ b/x/airdrop/keeper/params.go @@ -7,7 +7,7 @@ import ( func (k Keeper) GetWhiteListClients(ctx sdk.Context) []string { var res []string - k.paramSpace.GetIfExists(ctx, types.KeyWhiteList, &res) + k.paramSpace.Get(ctx, types.KeyWhiteList, &res) return res } diff --git a/x/airdrop/types/genesis_test.go b/x/airdrop/types/genesis_test.go deleted file mode 100644 index 901770b719..0000000000 --- a/x/airdrop/types/genesis_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/x/airdrop/types" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - addr = sdk.AccAddress([]byte("addr________________")) - invalidAddr = sdk.AccAddress([]byte("\n\n\n\n\taddr________________\t\n\n\n\n\n")) -) - -func TestNewGenesisState(t *testing.T) { - p := types.NewParams() - expectedFunds := []types.ActiveFund{ - { - Sender: addr.String(), - Fund: &types.Fund{ - Amount: &sdk.Coin{Denom: "test", Amount: sdk.NewInt(10)}, - DripAmount: sdk.NewInt(1), - }, - }, - } - expectedState := &types.GenesisState{ - Params: p, - Funds: expectedFunds, - } - require.Equal(t, expectedState.GetFunds(), expectedFunds) - require.Equal(t, expectedState.Params, p) -} - -func TestValidateGenesisState(t *testing.T) { - p1 := types.Params{ - AllowList: []string{ - addr.String(), // valid address - }, - } - p2 := types.Params{ - AllowList: []string{ - invalidAddr.String(), // invalid address - }, - } - funds := []types.ActiveFund{ - { - Sender: addr.String(), - Fund: &types.Fund{ - Amount: &sdk.Coin{ - Denom: "test", - Amount: sdk.NewInt(10), - }, - DripAmount: sdk.NewInt(1), - }, - }, - } - gen1 := types.NewGenesisState(p1, funds) - gen2 := types.NewGenesisState(p2, funds) - require.NoError(t, gen1.Validate()) - require.Error(t, gen2.Validate()) -} \ No newline at end of file From 535777db1176899025fcc5c02633ace5208168c1 Mon Sep 17 00:00:00 2001 From: kitty Date: Tue, 20 Jul 2021 11:05:35 +0100 Subject: [PATCH 05/10] format using go tools --- crypto/hd/algo.go | 5 +---- crypto/keys/bls12381/bls12381.go | 16 +++------------- crypto/keys/bls12381/bls12381_test.go | 4 +--- crypto/keys/ed25519/ed25519_test.go | 5 +---- x/auth/simulation/genesis.go | 2 +- x/auth/types/params.go | 7 +++---- 6 files changed, 10 insertions(+), 29 deletions(-) diff --git a/crypto/hd/algo.go b/crypto/hd/algo.go index 3606a8bce1..fcd4851996 100644 --- a/crypto/hd/algo.go +++ b/crypto/hd/algo.go @@ -75,9 +75,6 @@ func (s secp256k1Algo) Generate() GenerateFn { } } - - - type bls12381Algo struct { } @@ -113,4 +110,4 @@ func (s bls12381Algo) Generate() GenerateFn { return sk } -} \ No newline at end of file +} diff --git a/crypto/keys/bls12381/bls12381.go b/crypto/keys/bls12381/bls12381.go index c9df90bab8..ea13409782 100644 --- a/crypto/keys/bls12381/bls12381.go +++ b/crypto/keys/bls12381/bls12381.go @@ -10,7 +10,6 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/tmhash" "io" - ) const ( @@ -23,24 +22,22 @@ const ( PrivKeySize = 32 // Compressed signature SignatureSize = 96 - keyType = "bls12381" - SeedSize = 32 + keyType = "bls12381" + SeedSize = 32 ) var _ cryptotypes.PrivKey = &PrivKey{} var _ codec.AminoMarshaler = &PrivKey{} - // Bytes returns the byte representation of the Private Key. func (privKey *PrivKey) Bytes() []byte { return privKey.Key } - // PubKey performs the point-scalar multiplication from the privKey on the // generator point to get the pubkey. func (privKey *PrivKey) PubKey() cryptotypes.PubKey { - sk := new(blst.SecretKey).Deserialize(privKey.Key) + sk := new(blst.SecretKey).Deserialize(privKey.Key) if sk == nil { panic("Failed to deserialize secret key!") } @@ -50,7 +47,6 @@ func (privKey *PrivKey) PubKey() cryptotypes.PubKey { return &PubKey{Key: pk_bytes} } - // Sign produces a signature on the provided message. // This assumes the privkey is wellformed in the golang format. @@ -81,7 +77,6 @@ func (privKey *PrivKey) Type() string { return keyType } - // MarshalAmino overrides Amino binary marshalling. func (privKey PrivKey) MarshalAmino() ([]byte, error) { return privKey.Key, nil @@ -97,7 +92,6 @@ func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { return nil } - // MarshalAminoJSON overrides Amino JSON marshalling. func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, @@ -110,8 +104,6 @@ func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error { return privKey.UnmarshalAmino(bz) } - - // GenPrivKey generates a new BLS private key on curve bls12-381 private key. // It uses OS randomness to generate the private key. func GenPrivKey() *PrivKey { @@ -147,7 +139,6 @@ func GenPrivKeyFromSecret(secret []byte) *PrivKey { return &PrivKey{Key: sk_bytes} } - var _ cryptotypes.PubKey = &PubKey{} var _ codec.AminoMarshaler = &PubKey{} @@ -157,7 +148,6 @@ func (pubKey *PubKey) Validate() bool { return pk.KeyValidate() } - // Address is the SHA256-20 of the raw pubkey bytes. func (pubKey *PubKey) Address() crypto.Address { if len(pubKey.Key) != PubKeySize { diff --git a/crypto/keys/bls12381/bls12381_test.go b/crypto/keys/bls12381/bls12381_test.go index c7a9c993aa..48fbd02faf 100644 --- a/crypto/keys/bls12381/bls12381_test.go +++ b/crypto/keys/bls12381/bls12381_test.go @@ -22,7 +22,6 @@ func TestSignAndValidateBls12381(t *testing.T) { } - func BenchmarkSignBls(b *testing.B) { privKey := bls12381.GenPrivKey() @@ -30,9 +29,8 @@ func BenchmarkSignBls(b *testing.B) { } - func BenchmarkVerifyBls(b *testing.B) { privKey := bls12381.GenPrivKey() bench.BenchmarkVerification(b, privKey) -} \ No newline at end of file +} diff --git a/crypto/keys/ed25519/ed25519_test.go b/crypto/keys/ed25519/ed25519_test.go index 4e455c47ad..2291a01de8 100644 --- a/crypto/keys/ed25519/ed25519_test.go +++ b/crypto/keys/ed25519/ed25519_test.go @@ -230,8 +230,6 @@ func TestMarshalAmino_BackwardsCompatibility(t *testing.T) { } } - - func BenchmarkSignEd25519(b *testing.B) { privKey := ed25519.GenPrivKey() @@ -239,9 +237,8 @@ func BenchmarkSignEd25519(b *testing.B) { } - func BenchmarkVerifyEd25519(b *testing.B) { privKey := ed25519.GenPrivKey() bench.BenchmarkVerification(b, privKey) -} \ No newline at end of file +} diff --git a/x/auth/simulation/genesis.go b/x/auth/simulation/genesis.go index 5bb2297f29..c0311e66a2 100644 --- a/x/auth/simulation/genesis.go +++ b/x/auth/simulation/genesis.go @@ -19,7 +19,7 @@ const ( TxSizeCostPerByte = "tx_size_cost_per_byte" SigVerifyCostED25519 = "sig_verify_cost_ed25519" SigVerifyCostSECP256K1 = "sig_verify_cost_secp256k1" - SigVerifyCostBLS12381 = "sig_verify_cost_bls12381" + SigVerifyCostBLS12381 = "sig_verify_cost_bls12381" ) // RandomGenesisAccounts defines the default RandomGenesisAccountsFn used on the SDK. diff --git a/x/auth/types/params.go b/x/auth/types/params.go index fb2a47ec50..632de20cae 100644 --- a/x/auth/types/params.go +++ b/x/auth/types/params.go @@ -15,7 +15,7 @@ const ( DefaultTxSizeCostPerByte uint64 = 10 DefaultSigVerifyCostED25519 uint64 = 590 DefaultSigVerifyCostSecp256k1 uint64 = 1000 - DefaultSigVerifyCostBls12381 uint64 = 6300 + DefaultSigVerifyCostBls12381 uint64 = 6300 ) // Parameter keys @@ -25,7 +25,7 @@ var ( KeyTxSizeCostPerByte = []byte("TxSizeCostPerByte") KeySigVerifyCostED25519 = []byte("SigVerifyCostED25519") KeySigVerifyCostSecp256k1 = []byte("SigVerifyCostSecp256k1") - KeySigVerifyCostBls12381 = []byte("SigVerifyCostBls12381") + KeySigVerifyCostBls12381 = []byte("SigVerifyCostBls12381") ) var _ paramtypes.ParamSet = &Params{} @@ -70,7 +70,7 @@ func DefaultParams() Params { TxSizeCostPerByte: DefaultTxSizeCostPerByte, SigVerifyCostED25519: DefaultSigVerifyCostED25519, SigVerifyCostSecp256k1: DefaultSigVerifyCostSecp256k1, - SigVerifyCostBls12381: DefaultSigVerifyCostBls12381, + SigVerifyCostBls12381: DefaultSigVerifyCostBls12381, } } @@ -119,7 +119,6 @@ func validateSigVerifyCostSecp256k1(i interface{}) error { return nil } - func validateSigVerifyCostBls12381(i interface{}) error { v, ok := i.(uint64) if !ok { From a785d231ed314fbcb5eda2af1db7604dec784fc2 Mon Sep 17 00:00:00 2001 From: kitty Date: Tue, 20 Jul 2021 12:22:29 +0100 Subject: [PATCH 06/10] nuisance golangci-lint errors --- crypto/keys/bls12381/bls12381.go | 24 +++++++++++++----------- x/auth/ante/sigverify.go | 7 ++++--- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/crypto/keys/bls12381/bls12381.go b/crypto/keys/bls12381/bls12381.go index ea13409782..4806b26685 100644 --- a/crypto/keys/bls12381/bls12381.go +++ b/crypto/keys/bls12381/bls12381.go @@ -3,13 +3,14 @@ package bls12381 import ( "crypto/subtle" "fmt" + "io" + "github.com/cosmos/cosmos-sdk/codec" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/types/errors" blst "github.com/supranational/blst/bindings/go" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/tmhash" - "io" ) const ( @@ -20,7 +21,8 @@ const ( // PrivKeySize is the size, in bytes, of private keys as used in this package. // Uncompressed public key PrivKeySize = 32 - // Compressed signature + // SignatureSize is the size of a bls signature. Namely the size of a compressed + // G2 point. SignatureSize = 96 keyType = "bls12381" SeedSize = 32 @@ -42,9 +44,9 @@ func (privKey *PrivKey) PubKey() cryptotypes.PubKey { panic("Failed to deserialize secret key!") } pk := new(blst.P1Affine).From(sk) - pk_bytes := pk.Serialize() + pkBytes := pk.Serialize() - return &PubKey{Key: pk_bytes} + return &PubKey{Key: pkBytes} } // Sign produces a signature on the provided message. @@ -62,9 +64,9 @@ func (privKey *PrivKey) Sign(msg []byte) ([]byte, error) { panic("Failed to sign message!") } - sig_bytes := sig.Compress() + sigBytes := sig.Compress() - return sig_bytes, nil + return sigBytes, nil } // Equals - you probably don't need to use this. @@ -123,9 +125,9 @@ func genPrivKey(rand io.Reader) []byte { panic("Failed to generate secret key!") } - sk_bytes := sk.Serialize() + skBytes := sk.Serialize() - return sk_bytes + return skBytes } // GenPrivKeyFromSecret hashes the secret with SHA2, and uses @@ -134,9 +136,9 @@ func genPrivKey(rand io.Reader) []byte { // if it's derived from user input. func GenPrivKeyFromSecret(secret []byte) *PrivKey { ikm := crypto.Sha256(secret) // Not Ripemd160 because we want 32 bytes. - sk_bytes := blst.KeyGen(ikm[:]).Serialize() + skBytes := blst.KeyGen(ikm).Serialize() - return &PrivKey{Key: sk_bytes} + return &PrivKey{Key: skBytes} } var _ cryptotypes.PubKey = &PubKey{} @@ -161,7 +163,7 @@ func (pubKey *PubKey) Bytes() []byte { return pubKey.Key } -// Assume public key is validated +// VerifySignature assumes public key is already validated func (pubKey *PubKey) VerifySignature(msg []byte, sig []byte) bool { // make sure we use the same algorithm to sign pk := new(blst.P1Affine).Deserialize(pubKey.Key) diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index 223d81b296..428b9f97bb 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/hex" "fmt" + "github.com/cosmos/cosmos-sdk/crypto/keys/bls12381" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" @@ -84,9 +85,9 @@ func (spkd SetPubKeyDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b continue } - //Validate public key for bls12381 so that the public key only needs to be checked once - switch pubkey := pk.(type) { - case *bls12381.PubKey: + // Validate public key for bls12381 so that the public key only needs to be checked once + pubkey, ok := pk.(*bls12381.PubKey) + if ok { if !pubkey.Validate() { return ctx, sdkerrors.Wrap(sdkerrors.ErrInvalidPubKey, "Invalid public key: either infinity or not subgroup element") } From ea62aa9bddfb1481b676eb08c556c8df5322056f Mon Sep 17 00:00:00 2001 From: kitty Date: Thu, 22 Jul 2021 13:17:13 +0100 Subject: [PATCH 07/10] POP interfaces in accounts and authentication --- proto/cosmos/auth/v1beta1/auth.proto | 1 + x/auth/ante/ante.go | 1 + x/auth/ante/sigverify.go | 34 +++++++ x/auth/types/account.go | 23 +++++ x/auth/types/auth.pb.go | 127 +++++++++++++++++---------- 5 files changed, 140 insertions(+), 46 deletions(-) diff --git a/proto/cosmos/auth/v1beta1/auth.proto b/proto/cosmos/auth/v1beta1/auth.proto index 799568c186..5b98820258 100644 --- a/proto/cosmos/auth/v1beta1/auth.proto +++ b/proto/cosmos/auth/v1beta1/auth.proto @@ -23,6 +23,7 @@ message BaseAccount { [(gogoproto.jsontag) = "public_key,omitempty", (gogoproto.moretags) = "yaml:\"public_key\""]; uint64 account_number = 3 [(gogoproto.moretags) = "yaml:\"account_number\""]; uint64 sequence = 4; + bool pop_is_valid = 5; } // ModuleAccount defines an account for modules that holds coins on a pool. diff --git a/x/auth/ante/ante.go b/x/auth/ante/ante.go index 8cc025bad2..ee474b8fbc 100644 --- a/x/auth/ante/ante.go +++ b/x/auth/ante/ante.go @@ -28,6 +28,7 @@ func NewAnteHandler( NewDeductFeeDecorator(ak, bankKeeper), NewSigGasConsumeDecorator(ak, sigGasConsumer), NewSigVerificationDecorator(ak, signModeHandler), + NewSetPopValidDecorator(ak), NewIncrementSequenceDecorator(ak), ) } diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index 428b9f97bb..c5a0d925dd 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -289,6 +289,40 @@ func (svd SigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simul return next(ctx, tx, simulate) } +// SetPopValidDecorator handles the validation status of the proof-of-possession (POP) of an individual public key. +// A valid transaction and signature can be viewed as a POP for the signer's public key. +// POP is required when forming a compact multisig group in order to prevent rogue public key attacks. +type SetPopValidDecorator struct { + ak AccountKeeper +} + +func NewSetPopValidDecorator(ak AccountKeeper) SetPopValidDecorator { + return SetPopValidDecorator{ + ak: ak, + } +} + +func (spvd SetPopValidDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { + sigTx, ok := tx.(authsigning.SigVerifiableTx) + if !ok { + return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type") + } + + for _, addr := range sigTx.GetSigners() { + acc := spvd.ak.GetAccount(ctx, addr) + pk := acc.GetPubKey() + + switch pk.(type) { + case *bls12381.PubKey, *secp256k1.PubKey, *ed25519.PubKey: + if err := acc.SetPopValid(true); err != nil { + panic(err) + } + } + } + + return next(ctx, tx, simulate) +} + // IncrementSequenceDecorator handles incrementing sequences of all signers. // Use the IncrementSequenceDecorator decorator to prevent replay attacks. Note, // there is no need to execute IncrementSequenceDecorator on RecheckTX since diff --git a/x/auth/types/account.go b/x/auth/types/account.go index eb9939ffce..9b1b89ec6c 100644 --- a/x/auth/types/account.go +++ b/x/auth/types/account.go @@ -32,6 +32,7 @@ func NewBaseAccount(address sdk.AccAddress, pubKey cryptotypes.PubKey, accountNu Address: address.String(), AccountNumber: accountNumber, Sequence: sequence, + PopIsValid: false, } err := acc.SetPubKey(pubKey) @@ -117,6 +118,20 @@ func (acc *BaseAccount) SetSequence(seq uint64) error { return nil } +// SetPopValid - Implements sdk.AccountI. +func (acc *BaseAccount) SetPopValid(isValid bool) error { + if acc.PubKey == nil { + return errors.New("public key is not set yet") + } + acc.PopIsValid = isValid + return nil +} + +// GetPopValid - Implements sdk.AccountI. +func (acc *BaseAccount) GetPopValid() bool { + return acc.PopIsValid +} + // Validate checks for errors on the account fields func (acc BaseAccount) Validate() error { if acc.Address == "" || acc.PubKey == nil { @@ -222,6 +237,11 @@ func (ma ModuleAccount) SetSequence(seq uint64) error { return fmt.Errorf("not supported for module accounts") } +// SetPopValid - Implements AccountI +func (ma ModuleAccount) SetPopValid(isValid bool) error { + return fmt.Errorf("not supported for module accounts") +} + // Validate checks for errors on the account fields func (ma ModuleAccount) Validate() error { if strings.TrimSpace(ma.Name) == "" { @@ -324,6 +344,9 @@ type AccountI interface { GetSequence() uint64 SetSequence(uint64) error + GetPopValid() bool + SetPopValid(bool) error + // Ensure that account implements stringer String() string } diff --git a/x/auth/types/auth.pb.go b/x/auth/types/auth.pb.go index ad2283b816..dff9c39fc2 100644 --- a/x/auth/types/auth.pb.go +++ b/x/auth/types/auth.pb.go @@ -33,6 +33,7 @@ type BaseAccount struct { PubKey *types.Any `protobuf:"bytes,2,opt,name=pub_key,json=pubKey,proto3" json:"public_key,omitempty" yaml:"public_key"` AccountNumber uint64 `protobuf:"varint,3,opt,name=account_number,json=accountNumber,proto3" json:"account_number,omitempty" yaml:"account_number"` Sequence uint64 `protobuf:"varint,4,opt,name=sequence,proto3" json:"sequence,omitempty"` + PopIsValid bool `protobuf:"varint,5,opt,name=pop_is_valid,json=popIsValid,proto3" json:"pop_is_valid,omitempty"` } func (m *BaseAccount) Reset() { *m = BaseAccount{} } @@ -199,52 +200,53 @@ func init() { func init() { proto.RegisterFile("cosmos/auth/v1beta1/auth.proto", fileDescriptor_7e1f7e915d020d2d) } var fileDescriptor_7e1f7e915d020d2d = []byte{ - // 707 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x54, 0x4f, 0x4f, 0xdb, 0x48, - 0x14, 0x8f, 0x97, 0x6c, 0x80, 0x09, 0x20, 0x61, 0x12, 0x30, 0xd9, 0x95, 0xc7, 0xf2, 0x29, 0x2b, - 0x6d, 0x1c, 0x25, 0x88, 0xd5, 0x12, 0xad, 0x56, 0x8b, 0xd9, 0x1e, 0x50, 0x0b, 0x42, 0x46, 0xea, - 0xa1, 0xaa, 0xe4, 0x8e, 0x9d, 0xc1, 0x58, 0x64, 0x32, 0xc6, 0x33, 0x46, 0x31, 0x9f, 0xa0, 0xc7, - 0x1e, 0x7b, 0xe4, 0x43, 0xf0, 0x0d, 0x7a, 0xe9, 0x11, 0x71, 0xa8, 0x7a, 0xb2, 0xaa, 0x70, 0xa9, - 0x7a, 0xf4, 0xbd, 0x52, 0x95, 0xb1, 0x13, 0x12, 0x94, 0x9e, 0xe2, 0xf7, 0x7e, 0xff, 0xde, 0xbc, - 0x51, 0x06, 0xa8, 0x2e, 0x65, 0x84, 0xb2, 0x26, 0x8a, 0xf8, 0x79, 0xf3, 0xaa, 0xe5, 0x60, 0x8e, - 0x5a, 0xa2, 0x30, 0x82, 0x90, 0x72, 0x2a, 0x6f, 0x64, 0xb8, 0x21, 0x5a, 0x39, 0x5e, 0x5b, 0xc9, - 0x9b, 0x82, 0x52, 0xab, 0x78, 0xd4, 0xa3, 0xe2, 0xb3, 0x39, 0xfa, 0xca, 0xbb, 0xdb, 0x1e, 0xa5, - 0x5e, 0x0f, 0x37, 0x45, 0xe5, 0x44, 0x67, 0x4d, 0xd4, 0x8f, 0x33, 0x48, 0xff, 0x2e, 0x81, 0xb2, - 0x89, 0x18,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xbd, 0xbb, 0xdb, - 0xda, 0xcb, 0x2e, 0xdd, 0xec, 0x0c, 0x13, 0x58, 0x39, 0xf5, 0xbd, 0x97, 0x82, 0x31, 0x92, 0x3e, - 0xfb, 0x5f, 0xe0, 0x69, 0x02, 0xd5, 0x2c, 0xed, 0x27, 0x06, 0xba, 0x55, 0x61, 0x33, 0xba, 0xac, - 0x2d, 0xc7, 0x60, 0xfb, 0xa9, 0x82, 0x61, 0x37, 0x68, 0xef, 0xfe, 0x75, 0xd1, 0x52, 0x7e, 0x15, - 0xa1, 0xff, 0x0e, 0x13, 0xb8, 0x39, 0x13, 0x7a, 0x3a, 0x66, 0xa4, 0x09, 0xd4, 0xe6, 0xc7, 0x4e, - 0x4c, 0x74, 0x6b, 0x93, 0xcd, 0xd5, 0xca, 0x11, 0x50, 0x9e, 0xaa, 0x9c, 0x1e, 0x6b, 0xb5, 0x77, - 0xfe, 0x6e, 0x29, 0x25, 0x91, 0xfc, 0xcf, 0x30, 0x81, 0xd5, 0x99, 0x64, 0x33, 0x27, 0xa4, 0x09, - 0x84, 0xf3, 0x83, 0xc7, 0x16, 0xba, 0x55, 0x65, 0xf3, 0x94, 0x9d, 0xa5, 0xfc, 0xaf, 0x22, 0x99, - 0x07, 0x1f, 0x87, 0xaa, 0x74, 0x37, 0x54, 0xa5, 0x2f, 0x43, 0x55, 0x7a, 0xf7, 0xa0, 0x16, 0xee, - 0x1e, 0xd4, 0xc2, 0xe7, 0x07, 0xb5, 0xf0, 0xea, 0x0f, 0xcf, 0xe7, 0xe7, 0x91, 0x63, 0xb8, 0x94, - 0x34, 0xf3, 0x77, 0x2b, 0xfb, 0x69, 0xb0, 0xee, 0x45, 0x73, 0x90, 0x3d, 0x62, 0x3c, 0x0e, 0x30, - 0x73, 0x4a, 0xe2, 0x81, 0xd8, 0xf9, 0x11, 0x00, 0x00, 0xff, 0xff, 0xd3, 0xe6, 0x37, 0xa1, 0xe0, - 0x04, 0x00, 0x00, + // 734 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x54, 0xcf, 0x4e, 0xe3, 0x46, + 0x18, 0x8f, 0x21, 0x0d, 0x61, 0x12, 0x90, 0x30, 0x09, 0x98, 0xb4, 0xf2, 0x58, 0x3e, 0xa5, 0x52, + 0xe3, 0x28, 0x41, 0x54, 0x25, 0xaa, 0xaa, 0x62, 0xda, 0x03, 0x6a, 0x41, 0xc8, 0x48, 0x1c, 0xaa, + 0x4a, 0xde, 0xb1, 0x33, 0x18, 0x8b, 0x38, 0x63, 0x3c, 0x63, 0x14, 0xf3, 0x04, 0x7b, 0xdc, 0xe3, + 0xde, 0x96, 0x87, 0xe0, 0x0d, 0xf6, 0xb2, 0x47, 0xc4, 0x61, 0xb5, 0x27, 0x6b, 0x15, 0x2e, 0xab, + 0x3d, 0xfa, 0x09, 0x56, 0x1e, 0x3b, 0x21, 0x41, 0xd9, 0x53, 0xe6, 0xfb, 0x7e, 0xff, 0x66, 0xbe, + 0x71, 0x06, 0xc8, 0x36, 0xa1, 0x1e, 0xa1, 0x6d, 0x14, 0xb2, 0xcb, 0xf6, 0x4d, 0xc7, 0xc2, 0x0c, + 0x75, 0x78, 0xa1, 0xf9, 0x01, 0x61, 0x44, 0xdc, 0xcc, 0x70, 0x8d, 0xb7, 0x72, 0xbc, 0x51, 0xcd, + 0x9b, 0x9c, 0xd2, 0xa8, 0x39, 0xc4, 0x21, 0x7c, 0xd9, 0x4e, 0x57, 0x79, 0x77, 0xc7, 0x21, 0xc4, + 0x19, 0xe0, 0x36, 0xaf, 0xac, 0xf0, 0xa2, 0x8d, 0x86, 0x51, 0x06, 0xa9, 0xef, 0x96, 0x40, 0x45, + 0x47, 0x14, 0x1f, 0xd8, 0x36, 0x09, 0x87, 0x4c, 0x94, 0xc0, 0x0a, 0xea, 0xf7, 0x03, 0x4c, 0xa9, + 0x24, 0x28, 0x42, 0x73, 0xd5, 0x98, 0x94, 0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03, 0x02, 0x05, 0x00, 0x00, } func (this *Params) Equal(that interface{}) bool { @@ -306,6 +308,16 @@ func (m *BaseAccount) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.PopIsValid { + i-- + if m.PopIsValid { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x28 + } if m.Sequence != 0 { i = encodeVarintAuth(dAtA, i, uint64(m.Sequence)) i-- @@ -473,6 +485,9 @@ func (m *BaseAccount) Size() (n int) { if m.Sequence != 0 { n += 1 + sovAuth(uint64(m.Sequence)) } + if m.PopIsValid { + n += 2 + } return n } @@ -667,6 +682,26 @@ func (m *BaseAccount) Unmarshal(dAtA []byte) error { break } } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PopIsValid", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAuth + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.PopIsValid = bool(v != 0) default: iNdEx = preIndex skippy, err := skipAuth(dAtA[iNdEx:]) From 2854483862583e5d7382de2c7bbe4ddab70da818 Mon Sep 17 00:00:00 2001 From: kitty Date: Fri, 23 Jul 2021 16:26:39 +0100 Subject: [PATCH 08/10] add bls multsig operations --- crypto/keys/bls12381/bls12381.go | 2 +- crypto/keys/bls12381/multisig.go | 88 +++++++++++++++++++ crypto/keys/bls12381/multisig_test.go | 118 ++++++++++++++++++++++++++ 3 files changed, 207 insertions(+), 1 deletion(-) create mode 100644 crypto/keys/bls12381/multisig.go create mode 100644 crypto/keys/bls12381/multisig_test.go diff --git a/crypto/keys/bls12381/bls12381.go b/crypto/keys/bls12381/bls12381.go index 4806b26685..eab266c3d2 100644 --- a/crypto/keys/bls12381/bls12381.go +++ b/crypto/keys/bls12381/bls12381.go @@ -112,7 +112,7 @@ func GenPrivKey() *PrivKey { return &PrivKey{Key: genPrivKey(crypto.CReader())} } -// genPrivKey generates a new secp256k1 private key using the provided reader. +// genPrivKey generates a new bls12381 private key using the provided reader. func genPrivKey(rand io.Reader) []byte { var ikm [SeedSize]byte _, err := io.ReadFull(rand, ikm[:]) diff --git a/crypto/keys/bls12381/multisig.go b/crypto/keys/bls12381/multisig.go new file mode 100644 index 0000000000..0bd84b8e00 --- /dev/null +++ b/crypto/keys/bls12381/multisig.go @@ -0,0 +1,88 @@ +package bls12381 + +import ( + "encoding/base64" + "fmt" + "os" + + blst "github.com/supranational/blst/bindings/go" +) + +func AggregatePublicKey(pks []*PubKey) *blst.P1Affine { + pubkeys := make([]*blst.P1Affine, len(pks)) + for i, pk := range pks { + pubkeys[i] = new(blst.P1Affine).Deserialize(pk.Key) + if pk == nil { + panic("Failed to deserialize public key") + } + } + + aggregator := new(blst.P1Aggregate) + b := aggregator.Aggregate(pubkeys, false) + if !b { + panic("Failed to aggregate public keys") + } + apk := aggregator.ToAffine() + + return apk +} + +// AggregateSignature combines a set of verified signatures into a single bls signature +func AggregateSignature(sigs [][]byte) []byte { + sigmas := make([]*blst.P2Affine, len(sigs)) + for i, sig := range sigs { + sigmas[i] = new(blst.P2Affine).Uncompress(sig) + if sigmas[i] == nil { + panic("Failed to deserialize signature") + } + } + + aggregator := new(blst.P2Aggregate) + b := aggregator.Aggregate(sigmas, false) + if !b { + panic("Failed to aggregate signatures") + } + aggSigBytes := aggregator.ToAffine().Compress() + return aggSigBytes +} + +// VerifyMultiSignature assumes public key is already validated +func VerifyMultiSignature(msg []byte, sig []byte, pks []*PubKey) bool { + return VerifyAggregateSignature([][]byte{msg}, sig, [][]*PubKey{pks}) +} + +func Unique(msgs [][]byte) bool { + if len(msgs) <= 1 { + return true + } + msgMap := make(map[string]bool, len(msgs)) + for _, msg := range msgs { + s := base64.StdEncoding.EncodeToString(msg) + if _, ok := msgMap[s]; ok { + return false + } + msgMap[s] = true + } + return true +} + +func VerifyAggregateSignature(msgs [][]byte, sig []byte, pkss [][]*PubKey) bool { + //messages must be pairwise distinct + if !Unique(msgs) { + fmt.Fprintf(os.Stdout, "messages must be pairwise distinct") + return false + } + + apks := make([]*blst.P1Affine, len(pkss)) + for i, pks := range pkss { + apks[i] = AggregatePublicKey(pks) + } + + sigma := new(blst.P2Affine).Uncompress(sig) + if sigma == nil { + panic("Failed to deserialize signature") + } + + dst := []byte("BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_") + return sigma.AggregateVerify(true, apks, false, msgs, dst) +} diff --git a/crypto/keys/bls12381/multisig_test.go b/crypto/keys/bls12381/multisig_test.go new file mode 100644 index 0000000000..eb8eaed2a3 --- /dev/null +++ b/crypto/keys/bls12381/multisig_test.go @@ -0,0 +1,118 @@ +package bls12381_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + bls "github.com/cosmos/cosmos-sdk/crypto/keys/bls12381" +) + +func TestBlsMultiSig(t *testing.T) { + total := 5 + pks := make([]*bls.PubKey, total) + sigs := make([][]byte, total) + msg := []byte("hello world") + for i := 0; i < total; i++ { + sk := bls.GenPrivKey() + pk, ok := sk.PubKey().(*bls.PubKey) + require.True(t, ok) + + sig, err := sk.Sign(msg) + require.Nil(t, err) + + pks[i] = pk + sigs[i] = sig + } + + aggSig := bls.AggregateSignature(sigs) + assert.True(t, bls.VerifyMultiSignature(msg, aggSig, pks)) + +} + +func TestBlsAggSig(t *testing.T) { + total := 5 + //sks := make([]*bls.PrivKey, total) + pks := make([][]*bls.PubKey, total) + sigs := make([][]byte, total) + msgs := make([][]byte, total) + for i := 0; i < total; i++ { + msgs[i] = []byte(fmt.Sprintf("message %d", i)) + sk := bls.GenPrivKey() + pk, ok := sk.PubKey().(*bls.PubKey) + require.True(t, ok) + + sig, err := sk.Sign(msgs[i]) + require.Nil(t, err) + + pks[i] = []*bls.PubKey{pk} + sigs[i] = sig + } + + aggSig := bls.AggregateSignature(sigs) + assert.True(t, bls.VerifyAggregateSignature(msgs, aggSig, pks)) + +} + +func benchmarkBlsVerifyMulti(total int, b *testing.B) { + pks := make([]*bls.PubKey, total) + sigs := make([][]byte, total) + msg := []byte("hello world") + for i := 0; i < total; i++ { + sk := bls.GenPrivKey() + pk, ok := sk.PubKey().(*bls.PubKey) + require.True(b, ok) + + sig, err := sk.Sign(msg) + require.Nil(b, err) + + pks[i] = pk + sigs[i] = sig + } + + aggSig := bls.AggregateSignature(sigs) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + bls.VerifyMultiSignature(msg, aggSig, pks) + } +} + +func BenchmarkBlsVerifyMulti8(b *testing.B) { benchmarkBlsVerifyMulti(8, b) } +func BenchmarkBlsVerifyMulti16(b *testing.B) { benchmarkBlsVerifyMulti(16, b) } +func BenchmarkBlsVerifyMulti32(b *testing.B) { benchmarkBlsVerifyMulti(32, b) } +func BenchmarkBlsVerifyMulti64(b *testing.B) { benchmarkBlsVerifyMulti(64, b) } +func BenchmarkBlsVerifyMulti128(b *testing.B) { benchmarkBlsVerifyMulti(128, b) } + +func benchmarkBlsVerifyAgg(total int, b *testing.B) { + pks := make([][]*bls.PubKey, total) + sigs := make([][]byte, total) + msgs := make([][]byte, total) + for i := 0; i < total; i++ { + msgs[i] = []byte(fmt.Sprintf("message %d", i)) + sk := bls.GenPrivKey() + pk, ok := sk.PubKey().(*bls.PubKey) + require.True(b, ok) + + sig, err := sk.Sign(msgs[i]) + require.Nil(b, err) + + pks[i] = []*bls.PubKey{pk} + sigs[i] = sig + } + + aggSig := bls.AggregateSignature(sigs) + b.ResetTimer() + + for i := 0; i < b.N; i++ { + bls.VerifyAggregateSignature(msgs, aggSig, pks) + } +} + +func BenchmarkBlsVerifyAgg8(b *testing.B) { benchmarkBlsVerifyAgg(8, b) } +func BenchmarkBlsVerifyAgg16(b *testing.B) { benchmarkBlsVerifyAgg(16, b) } +func BenchmarkBlsVerifyAgg32(b *testing.B) { benchmarkBlsVerifyAgg(32, b) } +func BenchmarkBlsVerifyAgg64(b *testing.B) { benchmarkBlsVerifyAgg(64, b) } +func BenchmarkBlsVerifyAgg128(b *testing.B) { benchmarkBlsVerifyAgg(128, b) } From 9be8b74882cd567be4616ed4863708a9588f4c04 Mon Sep 17 00:00:00 2001 From: kitty Date: Fri, 23 Jul 2021 16:56:12 +0100 Subject: [PATCH 09/10] fixed golangci-lint error --- crypto/keys/bls12381/multisig.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crypto/keys/bls12381/multisig.go b/crypto/keys/bls12381/multisig.go index 0bd84b8e00..8d549ce70a 100644 --- a/crypto/keys/bls12381/multisig.go +++ b/crypto/keys/bls12381/multisig.go @@ -8,11 +8,11 @@ import ( blst "github.com/supranational/blst/bindings/go" ) -func AggregatePublicKey(pks []*PubKey) *blst.P1Affine { +func aggregatePublicKey(pks []*PubKey) *blst.P1Affine { pubkeys := make([]*blst.P1Affine, len(pks)) for i, pk := range pks { pubkeys[i] = new(blst.P1Affine).Deserialize(pk.Key) - if pk == nil { + if pubkeys[i] == nil { panic("Failed to deserialize public key") } } @@ -67,7 +67,7 @@ func Unique(msgs [][]byte) bool { } func VerifyAggregateSignature(msgs [][]byte, sig []byte, pkss [][]*PubKey) bool { - //messages must be pairwise distinct + // messages must be pairwise distinct if !Unique(msgs) { fmt.Fprintf(os.Stdout, "messages must be pairwise distinct") return false @@ -75,7 +75,7 @@ func VerifyAggregateSignature(msgs [][]byte, sig []byte, pkss [][]*PubKey) bool apks := make([]*blst.P1Affine, len(pkss)) for i, pks := range pkss { - apks[i] = AggregatePublicKey(pks) + apks[i] = aggregatePublicKey(pks) } sigma := new(blst.P2Affine).Uncompress(sig) From 200bf491899755e134ca1cf5128bedd8adb2d7bb Mon Sep 17 00:00:00 2001 From: kitty Date: Mon, 26 Jul 2021 15:02:30 +0100 Subject: [PATCH 10/10] changes after comments --- crypto/keys/bls12381/multisig.go | 48 +++++++++++++++++---------- crypto/keys/bls12381/multisig_test.go | 20 +++++++---- proto/cosmos/auth/v1beta1/auth.proto | 2 +- types/errors/errors.go | 3 ++ x/auth/ante/sigverify.go | 2 +- 5 files changed, 49 insertions(+), 26 deletions(-) diff --git a/crypto/keys/bls12381/multisig.go b/crypto/keys/bls12381/multisig.go index 8d549ce70a..18e499e390 100644 --- a/crypto/keys/bls12381/multisig.go +++ b/crypto/keys/bls12381/multisig.go @@ -3,51 +3,50 @@ package bls12381 import ( "encoding/base64" "fmt" - "os" blst "github.com/supranational/blst/bindings/go" ) -func aggregatePublicKey(pks []*PubKey) *blst.P1Affine { +func aggregatePublicKey(pks []*PubKey) (*blst.P1Affine, error) { pubkeys := make([]*blst.P1Affine, len(pks)) for i, pk := range pks { pubkeys[i] = new(blst.P1Affine).Deserialize(pk.Key) if pubkeys[i] == nil { - panic("Failed to deserialize public key") + return nil, fmt.Errorf("failed to deserialize public key") } } aggregator := new(blst.P1Aggregate) b := aggregator.Aggregate(pubkeys, false) if !b { - panic("Failed to aggregate public keys") + return nil, fmt.Errorf("failed to aggregate public keys") } apk := aggregator.ToAffine() - return apk + return apk, nil } // AggregateSignature combines a set of verified signatures into a single bls signature -func AggregateSignature(sigs [][]byte) []byte { +func AggregateSignature(sigs [][]byte) ([]byte, error) { sigmas := make([]*blst.P2Affine, len(sigs)) for i, sig := range sigs { sigmas[i] = new(blst.P2Affine).Uncompress(sig) if sigmas[i] == nil { - panic("Failed to deserialize signature") + return nil, fmt.Errorf("failed to deserialize the %d-th signature", i) } } aggregator := new(blst.P2Aggregate) b := aggregator.Aggregate(sigmas, false) if !b { - panic("Failed to aggregate signatures") + return nil, fmt.Errorf("failed to aggregate signatures") } aggSigBytes := aggregator.ToAffine().Compress() - return aggSigBytes + return aggSigBytes, nil } // VerifyMultiSignature assumes public key is already validated -func VerifyMultiSignature(msg []byte, sig []byte, pks []*PubKey) bool { +func VerifyMultiSignature(msg []byte, sig []byte, pks []*PubKey) error { return VerifyAggregateSignature([][]byte{msg}, sig, [][]*PubKey{pks}) } @@ -66,23 +65,38 @@ func Unique(msgs [][]byte) bool { return true } -func VerifyAggregateSignature(msgs [][]byte, sig []byte, pkss [][]*PubKey) bool { - // messages must be pairwise distinct +func VerifyAggregateSignature(msgs [][]byte, sig []byte, pkss [][]*PubKey) error { + n := len(msgs) + if n == 0 { + return fmt.Errorf("messages cannot be empty") + } + + if len(pkss) != n { + return fmt.Errorf("the number of messages and public key sets must match") + } + if !Unique(msgs) { - fmt.Fprintf(os.Stdout, "messages must be pairwise distinct") - return false + return fmt.Errorf("messages must be pairwise distinct") } apks := make([]*blst.P1Affine, len(pkss)) for i, pks := range pkss { - apks[i] = aggregatePublicKey(pks) + apk, err := aggregatePublicKey(pks) + if err != nil { + return fmt.Errorf("cannot aggregate public keys: %s", err.Error()) + } + apks[i] = apk } sigma := new(blst.P2Affine).Uncompress(sig) if sigma == nil { - panic("Failed to deserialize signature") + return fmt.Errorf("failed to deserialize signature") } dst := []byte("BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_") - return sigma.AggregateVerify(true, apks, false, msgs, dst) + if !sigma.AggregateVerify(true, apks, false, msgs, dst) { + return fmt.Errorf("failed to verify signature") + } + + return nil } diff --git a/crypto/keys/bls12381/multisig_test.go b/crypto/keys/bls12381/multisig_test.go index eb8eaed2a3..c0024f859b 100644 --- a/crypto/keys/bls12381/multisig_test.go +++ b/crypto/keys/bls12381/multisig_test.go @@ -27,14 +27,15 @@ func TestBlsMultiSig(t *testing.T) { sigs[i] = sig } - aggSig := bls.AggregateSignature(sigs) - assert.True(t, bls.VerifyMultiSignature(msg, aggSig, pks)) + aggSig, err := bls.AggregateSignature(sigs) + require.Nil(t, err) + + assert.Nil(t, bls.VerifyMultiSignature(msg, aggSig, pks)) } func TestBlsAggSig(t *testing.T) { total := 5 - //sks := make([]*bls.PrivKey, total) pks := make([][]*bls.PubKey, total) sigs := make([][]byte, total) msgs := make([][]byte, total) @@ -51,8 +52,10 @@ func TestBlsAggSig(t *testing.T) { sigs[i] = sig } - aggSig := bls.AggregateSignature(sigs) - assert.True(t, bls.VerifyAggregateSignature(msgs, aggSig, pks)) + aggSig, err := bls.AggregateSignature(sigs) + require.Nil(t, err) + + assert.Nil(t, bls.VerifyAggregateSignature(msgs, aggSig, pks)) } @@ -72,7 +75,8 @@ func benchmarkBlsVerifyMulti(total int, b *testing.B) { sigs[i] = sig } - aggSig := bls.AggregateSignature(sigs) + aggSig, err := bls.AggregateSignature(sigs) + require.Nil(b, err) b.ResetTimer() for i := 0; i < b.N; i++ { @@ -103,7 +107,9 @@ func benchmarkBlsVerifyAgg(total int, b *testing.B) { sigs[i] = sig } - aggSig := bls.AggregateSignature(sigs) + aggSig, err := bls.AggregateSignature(sigs) + require.Nil(b, err) + b.ResetTimer() for i := 0; i < b.N; i++ { diff --git a/proto/cosmos/auth/v1beta1/auth.proto b/proto/cosmos/auth/v1beta1/auth.proto index 5b98820258..9be92bd2ce 100644 --- a/proto/cosmos/auth/v1beta1/auth.proto +++ b/proto/cosmos/auth/v1beta1/auth.proto @@ -23,7 +23,7 @@ message BaseAccount { [(gogoproto.jsontag) = "public_key,omitempty", (gogoproto.moretags) = "yaml:\"public_key\""]; uint64 account_number = 3 [(gogoproto.moretags) = "yaml:\"account_number\""]; uint64 sequence = 4; - bool pop_is_valid = 5; + bool pop_is_valid = 5; } // ModuleAccount defines an account for modules that holds coins on a pool. diff --git a/types/errors/errors.go b/types/errors/errors.go index 026f5f569b..909b97f691 100644 --- a/types/errors/errors.go +++ b/types/errors/errors.go @@ -134,6 +134,9 @@ var ( // supported. ErrNotSupported = Register(RootCodespace, 37, "feature not supported") + // ErrInvalidPop to doc + ErrInvalidPop = Register(RootCodespace, 38, "invalid pop for public key") + // ErrPanic is only set when we recover from a panic, so we know to // redact potentially sensitive system info ErrPanic = Register(UndefinedCodespace, 111222, "panic") diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index c5a0d925dd..84de7d391c 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -315,7 +315,7 @@ func (spvd SetPopValidDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate switch pk.(type) { case *bls12381.PubKey, *secp256k1.PubKey, *ed25519.PubKey: if err := acc.SetPopValid(true); err != nil { - panic(err) + return ctx, sdkerrors.Wrap(sdkerrors.ErrInvalidPop, err.Error()) } } }