Skip to content

Commit

Permalink
cherry-pick: sm2
Browse files Browse the repository at this point in the history
  • Loading branch information
sheldon committed Nov 21, 2022
1 parent e5fef13 commit 26cca6e
Show file tree
Hide file tree
Showing 31 changed files with 1,089 additions and 96 deletions.
3 changes: 2 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=sim \
-X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION) \
-X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT) \
-X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" \
-X github.com/tendermint/tendermint/version.TMCoreSemVer=$(TMVERSION)
-X github.com/tendermint/tendermint/version.TMCoreSemVer=$(TMVERSION) \
-X github.com/tendermint/tendermint/crypto/algo.Algo=sm2

ifeq ($(ENABLE_ROCKSDB),true)
BUILD_TAGS += rocksdb_build
Expand Down
4 changes: 2 additions & 2 deletions baseapp/baseapp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1706,14 +1706,14 @@ func TestGRPCQuery(t *testing.T) {
// Test p2p filter queries
func TestP2PQuery(t *testing.T) {
addrPeerFilterOpt := func(bapp *BaseApp) {
bapp.SetAddrPeerFilter(func(addrport string) abci.ResponseQuery {
bapp.SetAddrPeerFilter(func(ctx sdk.Context, addrport string) abci.ResponseQuery {
require.Equal(t, "1.1.1.1:8000", addrport)
return abci.ResponseQuery{Code: uint32(3)}
})
}

idPeerFilterOpt := func(bapp *BaseApp) {
bapp.SetIDPeerFilter(func(id string) abci.ResponseQuery {
bapp.SetIDPeerFilter(func(ctx sdk.Context, id string) abci.ResponseQuery {
require.Equal(t, "testid", id)
return abci.ResponseQuery{Code: uint32(4)}
})
Expand Down
6 changes: 3 additions & 3 deletions baseapp/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,9 @@ func (app *BaseApp) SetEndBlocker(endBlocker sdk.EndBlocker) {
}

func (app *BaseApp) SetAnteHandler(ah sdk.AnteHandler) {
if app.sealed {
panic("SetAnteHandler() on sealed BaseApp")
}
//if app.sealed {
// panic("SetAnteHandler() on sealed BaseApp")
//}

app.anteHandler = ah
}
Expand Down
17 changes: 11 additions & 6 deletions baseapp/p2p.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,18 @@ type peerFilters struct {
}

// FilterPeerByAddrPort filters peers by address/port.
func (app *BaseApp) FilterPeerByAddrPort(info string) abci.ResponseQuery {
func (app *BaseApp) FilterPeerByAddrPort(ctx sdk.Context, info string) abci.ResponseQuery {
if app.addrPeerFilter != nil {
return app.addrPeerFilter(info)
return app.addrPeerFilter(ctx, info)
}

return abci.ResponseQuery{}
}

// FilterPeerByID filters peers by node ID.
func (app *BaseApp) FilterPeerByID(info string) abci.ResponseQuery {
func (app *BaseApp) FilterPeerByID(ctx sdk.Context, info string) abci.ResponseQuery {
if app.idPeerFilter != nil {
return app.idPeerFilter(info)
return app.idPeerFilter(ctx, info)
}

return abci.ResponseQuery{}
Expand All @@ -47,17 +47,22 @@ func handleQueryP2P(app *BaseApp, path []string) abci.ResponseQuery {
)
}

ctx, err := app.createQueryContext(0, false)
if err != nil {
return sdkerrors.QueryResult(err, false)
}

var resp abci.ResponseQuery

cmd, typ, arg := path[1], path[2], path[3]
switch cmd {
case "filter":
switch typ {
case "addr":
resp = app.FilterPeerByAddrPort(arg)
resp = app.FilterPeerByAddrPort(ctx, arg)

case "id":
resp = app.FilterPeerByID(arg)
resp = app.FilterPeerByID(ctx, arg)
}

default:
Expand Down
2 changes: 1 addition & 1 deletion client/keys/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Example:
f.Uint32(flagCoinType, sdk.GetConfig().GetCoinType(), "coin type number for HD derivation")
f.Uint32(flagAccount, 0, "Account number for HD derivation (less than equal 2147483647)")
f.Uint32(flagIndex, 0, "Address index number for HD derivation (less than equal 2147483647)")
f.String(flags.FlagKeyAlgorithm, string(hd.Secp256k1Type), "Key signing algorithm to generate keys for")
f.String(flags.FlagKeyAlgorithm, string(hd.Sm2Type), "Key signing algorithm to generate keys for")

return cmd
}
Expand Down
22 changes: 22 additions & 0 deletions client/tx/legacy.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package tx

import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
Expand Down Expand Up @@ -63,3 +64,24 @@ func CopyTx(tx signing.Tx, builder client.TxBuilder, ignoreSignatureError bool)

return nil
}

// ConvertAndEncodeStdTx encodes the stdTx as a transaction in the format specified by txConfig
func ConvertAndEncodeStdTx(txConfig client.TxConfig, stdTx legacytx.StdTx) ([]byte, error) {
builder := txConfig.NewTxBuilder()

var theTx sdk.Tx

// check if we need a StdTx anyway, in that case don't copy
if _, ok := builder.GetTx().(legacytx.StdTx); ok {
theTx = stdTx
} else {
err := CopyTx(stdTx, builder, false)
if err != nil {
return nil, err
}

theTx = builder.GetTx()
}

return txConfig.TxEncoder()(theTx)
}
5 changes: 5 additions & 0 deletions crypto/codec/amino.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"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"
"github.com/cosmos/cosmos-sdk/crypto/keys/sm2"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
)

Expand All @@ -20,6 +21,8 @@ func RegisterCrypto(cdc *codec.LegacyAmino) {
ed25519.PubKeyName, nil)
cdc.RegisterConcrete(&secp256k1.PubKey{},
secp256k1.PubKeyName, nil)
cdc.RegisterConcrete(&sm2.PubKey{},
sm2.PubKeyName, nil)
cdc.RegisterConcrete(&kmultisig.LegacyAminoPubKey{},
kmultisig.PubKeyAminoRoute, nil)

Expand All @@ -30,4 +33,6 @@ func RegisterCrypto(cdc *codec.LegacyAmino) {
ed25519.PrivKeyName, nil)
cdc.RegisterConcrete(&secp256k1.PrivKey{},
secp256k1.PrivKeyName, nil)
cdc.RegisterConcrete(&sm2.PrivKey{},
sm2.PrivKeyName, nil)
}
3 changes: 3 additions & 0 deletions crypto/codec/proto.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,22 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/keys/multisig"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256r1"
"github.com/cosmos/cosmos-sdk/crypto/keys/sm2"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
)

// RegisterInterfaces registers the sdk.Tx interface.
func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
var pk *cryptotypes.PubKey
registry.RegisterInterface("cosmos.crypto.PubKey", pk)
registry.RegisterImplementations(pk, &sm2.PubKey{})
registry.RegisterImplementations(pk, &ed25519.PubKey{})
registry.RegisterImplementations(pk, &secp256k1.PubKey{})
registry.RegisterImplementations(pk, &multisig.LegacyAminoPubKey{})

var priv *cryptotypes.PrivKey
registry.RegisterInterface("cosmos.crypto.PrivKey", priv)
registry.RegisterImplementations(priv, &sm2.PrivKey{})
registry.RegisterImplementations(priv, &secp256k1.PrivKey{})
registry.RegisterImplementations(priv, &ed25519.PrivKey{}) //nolint
secp256r1.RegisterInterfaces(registry)
Expand Down
11 changes: 11 additions & 0 deletions crypto/codec/tm.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/crypto/keys/sm2"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
Expand All @@ -22,6 +23,10 @@ func FromTmProtoPublicKey(protoPk tmprotocrypto.PublicKey) (cryptotypes.PubKey,
return &secp256k1.PubKey{
Key: protoPk.Secp256K1,
}, nil
case *tmprotocrypto.PublicKey_Sm2:
return &sm2.PubKey{
Key: protoPk.Sm2,
}, nil
default:
return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v from Tendermint public key", protoPk)
}
Expand All @@ -42,6 +47,12 @@ func ToTmProtoPublicKey(pk cryptotypes.PubKey) (tmprotocrypto.PublicKey, error)
Secp256K1: pk.Key,
},
}, nil
case *sm2.PubKey:
return tmprotocrypto.PublicKey{
Sum: &tmprotocrypto.PublicKey_Sm2{
Sm2: pk.Key,
},
}, nil
default:
return tmprotocrypto.PublicKey{}, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v to Tendermint public key", pk)
}
Expand Down
37 changes: 37 additions & 0 deletions crypto/hd/algo.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"github.com/cosmos/go-bip39"

"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/crypto/keys/sm2"
"github.com/cosmos/cosmos-sdk/crypto/types"
)

Expand All @@ -20,11 +21,15 @@ const (
Ed25519Type = PubKeyType("ed25519")
// Sr25519Type represents the Sr25519Type signature system.
Sr25519Type = PubKeyType("sr25519")
// Sm2Type represents the Sm2Type signature system.
Sm2Type = PubKeyType("sm2")
)

// Secp256k1 uses the Bitcoin secp256k1 ECDSA parameters.
var Secp256k1 = secp256k1Algo{}

var Sm2 = sm2Algo{}

type (
DeriveFn func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error)
GenerateFn func(bz []byte) types.PrivKey
Expand Down Expand Up @@ -68,3 +73,35 @@ func (s secp256k1Algo) Generate() GenerateFn {
return &secp256k1.PrivKey{Key: bzArr}
}
}

type sm2Algo struct{}

func (s sm2Algo) Name() PubKeyType {
return Sm2Type
}

// Derive derives and returns the secp256k1 private key for the given seed and HD path.
func (s sm2Algo) 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 sm2 private key from the given bytes.
func (s sm2Algo) Generate() GenerateFn {
return func(bz []byte) types.PrivKey {
var bzArr [sm2.PrivKeySize]byte
copy(bzArr[:], bz)
return &sm2.PrivKey{Key: bzArr[:]}
}
}
4 changes: 2 additions & 2 deletions crypto/keyring/keyring.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,8 @@ func newKeystore(kr keyring.Keyring, cdc codec.Codec, backend string, opts ...Op
// Default options for keybase, these can be overwritten using the
// Option function
options := Options{
SupportedAlgos: SigningAlgoList{hd.Secp256k1},
SupportedAlgosLedger: SigningAlgoList{hd.Secp256k1},
SupportedAlgos: SigningAlgoList{hd.Secp256k1, hd.Sm2},
SupportedAlgosLedger: SigningAlgoList{hd.Secp256k1, hd.Sm2},
}

for _, optionFn := range opts {
Expand Down
Loading

0 comments on commit 26cca6e

Please sign in to comment.