Proto Tx with Any (#7276)

* WIP on protobuf keys

* Use Type() and Bytes() in sr25519 pub key Equals

* Add tests

* Add few more tests

* Update other pub/priv key types Equals

* Fix PrivKey's Sign method

* Rename variables in tests

* Fix infinite recursive calls

* Use tm ed25519 keys

* Add Sign and VerifySignature tests

* Remove ed25519 and sr25519 references

* proto linting

* Add proto crypto file

* Implement some of the new multisig proto type methods

* Add tests for MultisigThresholdPubKey

* Add tests for pubkey pb/amino conversion functions

* Move crypto types.go and register new proto pubkeys

* Add missing pointer ref

* Address review comments

* panic in MultisigThresholdPubKey VerifySignature

* Use internal crypto.PubKey in multisig

* Add tests for MultisigThresholdPubKey VerifyMultisignature

* Only keep LegacyAminoMultisigThresholdPubKey and move to proto keys to v1

* Remove conversion functions and introduce internal PubKey type

* Override Amino marshaling for proto pubkeys

* Merge master

* Make proto-gen

* Start removal of old PubKeyMultisigThreshold references

* Fix tests

* Fix solomachine

* Fix ante handler tests

* Pull latest go-amino

* Remove ed25519

* Remove old secp256k1 PubKey and PrivKey

* Uncomment test case

* Fix linting issues

* More linting

* Revert tests keys values

* Add Amino overrides to proto keys

* Add pubkey test

* Fix tests

* Use threshold isntead of K

* Standardize Type

* Revert standardize types commit

* Fix build

* Fix lint

* Fix lint

* Add comment

* Register crypto.PubKey

* Add empty key in BuildSimTx

* Simplify proto names

* Unpack interfaces for signing desc

* Fix IBC tests?

* Format proto

* Use secp256k1 in ibc

* Fixed merge issues

* Uncomment tests

* Update x/ibc/testing/solomachine.go

* UnpackInterfaces for solomachine types

* Remove old multisig

* Add amino marshal for multisig

* Fix lint

* Correctly register amino

* One test left!

* Remove old struct

* Fix test

* Fix test

* Unpack into tmcrypto

* Remove old threshold pubkey tests

* Fix register amino

* Fix lint

* Use sdk crypto PubKey in multisig UnpackInterfaces

* Potential fix?

* Register LegacyAminoPubKey

* Register our own PubKey

* Register tmcrypto PubKey

* Register both PubKeys

* Register interfaces in test

* Refactor fiels

* Add comments

* Use anil's suggestion

* Add norace back

* Check nil

* Address comments

* FIx lint

* Add tests for solomachine unpack interfaces

* Fix query tx by hash

* Better name in amino register

* Display StdTx instead of proto Tx

* Remove useless check

Co-authored-by: Aaron Craelius <aaronc@users.noreply.github.com>
Co-authored-by: blushi <marie.gauthier63@gmail.com>
Co-authored-by: Alexander Bezobchuk <alexanderbez@users.noreply.github.com>
Co-authored-by: colin axnér <25233464+colin-axner@users.noreply.github.com>
This commit is contained in:
Amaury Martiny
2020-09-21 16:48:28 +00:00
committed by GitHub
co-authored by Aaron Craelius blushi Alexander Bezobchuk colin axnér
parent 535510be1f
commit 7cd25abb87
42 changed files with 584 additions and 619 deletions
-19
View File
@@ -1034,25 +1034,6 @@ func (suite *AnteTestSuite) TestCustomSignatureVerificationGasConsumer() {
false,
sdkerrors.ErrInvalidPubKey,
},
{
"verify that an ed25519 account gets accepted",
func() {
priv1 := ed25519.GenPrivKey()
pub1 := priv1.PubKey()
addr1 := sdk.AccAddress(pub1.Address())
acc1 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1)
suite.Require().NoError(suite.app.BankKeeper.SetBalances(suite.ctx, addr1, sdk.NewCoins(sdk.NewInt64Coin("atom", 150))))
suite.Require().NoError(acc1.SetAccountNumber(1))
suite.app.AccountKeeper.SetAccount(suite.ctx, acc1)
msg := testdata.NewTestMsg(addr1)
privs, accNums, accSeqs = []crypto.PrivKey{priv1}, []uint64{1}, []uint64{0}
msgs = []sdk.Msg{msg}
},
false,
true,
nil,
},
}
for _, tc := range testCases {
+5 -1
View File
@@ -270,7 +270,11 @@ func (suite *AnteTestSuite) TestSigVerification_ExplicitAmino() {
func (suite *AnteTestSuite) TestSigIntegration() {
// generate private keys
privs := []crypto.PrivKey{secp256k1.GenPrivKey(), secp256k1.GenPrivKey(), secp256k1.GenPrivKey()}
privs := []crypto.PrivKey{
secp256k1.GenPrivKey(),
secp256k1.GenPrivKey(),
secp256k1.GenPrivKey(),
}
params := types.DefaultParams()
initialSigCost := params.SigVerifyCostSecp256k1
+24 -12
View File
@@ -47,19 +47,8 @@ func DecodeTxRequestHandlerFn(clientCtx client.Context) http.HandlerFunc {
return
}
txI, err := clientCtx.TxConfig.TxDecoder()(txBytes)
if rest.CheckBadRequestError(w, err) {
return
}
tx, ok := txI.(signing.Tx)
stdTx, ok := convertToStdTx(w, clientCtx, txBytes)
if !ok {
rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("%+v is not backwards compatible with %T", tx, authtypes.StdTx{}))
return
}
stdTx, err := clienttx.ConvertTxToStdTx(clientCtx.LegacyAmino, tx)
if rest.CheckBadRequestError(w, err) {
return
}
@@ -68,3 +57,26 @@ func DecodeTxRequestHandlerFn(clientCtx client.Context) http.HandlerFunc {
rest.PostProcessResponse(w, clientCtx, response)
}
}
// convertToStdTx converts tx proto binary bytes retrieved from Tendermint into
// a StdTx. Returns the StdTx, as well as a flag denoting if the function
// successfully converted or not.
func convertToStdTx(w http.ResponseWriter, clientCtx client.Context, txBytes []byte) (authtypes.StdTx, bool) {
txI, err := clientCtx.TxConfig.TxDecoder()(txBytes)
if rest.CheckBadRequestError(w, err) {
return authtypes.StdTx{}, false
}
tx, ok := txI.(signing.Tx)
if !ok {
rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("%+v is not backwards compatible with %T", tx, authtypes.StdTx{}))
return authtypes.StdTx{}, false
}
stdTx, err := clienttx.ConvertTxToStdTx(clientCtx.LegacyAmino, tx)
if rest.CheckBadRequestError(w, err) {
return authtypes.StdTx{}, false
}
return stdTx, true
}
+10 -2
View File
@@ -53,7 +53,7 @@ func QueryAccountRequestHandlerFn(storeName string, clientCtx client.Context) ht
}
}
// QueryTxsHandlerFn implements a REST handler that searches for transactions.
// QueryTxsRequestHandlerFn implements a REST handler that searches for transactions.
// Genesis transactions are returned if the height parameter is set to zero,
// otherwise the transactions are searched for by events.
func QueryTxsRequestHandlerFn(clientCtx client.Context) http.HandlerFunc {
@@ -128,11 +128,19 @@ func QueryTxRequestHandlerFn(clientCtx client.Context) http.HandlerFunc {
return
}
// We just unmarshalled from Tendermint, we take the proto Tx's raw
// bytes, and convert them into a StdTx to be displayed.
txBytes := output.Tx.Value
stdTx, ok := convertToStdTx(w, clientCtx, txBytes)
if !ok {
return
}
if output.Empty() {
rest.WriteErrorResponse(w, http.StatusNotFound, fmt.Sprintf("no transaction found with hash %s", hashHexStr))
}
rest.PostProcessResponseBare(w, clientCtx, output)
rest.PostProcessResponseBare(w, clientCtx, stdTx)
}
}
+69 -45
View File
@@ -1,25 +1,22 @@
// +build norace
package rest_test
import (
"fmt"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client"
"strings"
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
rest2 "github.com/cosmos/cosmos-sdk/x/auth/client/rest"
"github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/types/rest"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/testutil/network"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client"
rest2 "github.com/cosmos/cosmos-sdk/x/auth/client/rest"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
type IntegrationTestSuite struct {
@@ -33,7 +30,7 @@ func (s *IntegrationTestSuite) SetupSuite() {
s.T().Log("setting up integration test suite")
cfg := network.DefaultConfig()
cfg.NumValidators = 1
cfg.NumValidators = 2
s.cfg = cfg
s.network = network.New(s.T(), cfg)
@@ -109,11 +106,31 @@ func (s *IntegrationTestSuite) TestBroadcastTxRequest() {
s.Require().NotEmpty(txRes.TxHash)
}
func (s *IntegrationTestSuite) TestMultipleSyncBroadcastTxRequests() {
func (s *IntegrationTestSuite) TestQueryTxByHash() {
val0 := s.network.Validators[0]
txConfig := authtypes.StdTxConfig{Cdc: s.cfg.LegacyAmino}
// Create and broadcast a tx.
stdTx := s.createTestStdTx(val0, 1) // Validator's sequence starts at 1.
res, err := s.broadcastReq(stdTx, "block")
s.Require().NoError(err)
var txRes sdk.TxResponse
// NOTE: this uses amino explicitly, don't migrate it!
s.Require().NoError(s.cfg.LegacyAmino.UnmarshalJSON(res, &txRes))
// we just check for a non-empty TxHash here, the actual hash will depend on the underlying tx configuration
s.Require().NotEmpty(txRes.TxHash)
s.network.WaitForNextBlock()
// We now fetch the tx by has on the `/tx/{hash}` route.
txJSON, err := rest.GetRequest(fmt.Sprintf("%s/txs/%s", val0.APIAddress, txRes.TxHash))
s.Require().NoError(err)
// txJSON should contain the whole tx, we just make sure that our custom
// memo is there.
s.Require().True(strings.Contains(string(txJSON), stdTx.Memo))
}
func (s *IntegrationTestSuite) TestMultipleSyncBroadcastTxRequests() {
// First test transaction from validator should have sequence=1 (non-genesis tx)
testCases := []struct {
desc string
@@ -139,35 +156,8 @@ func (s *IntegrationTestSuite) TestMultipleSyncBroadcastTxRequests() {
for _, tc := range testCases {
s.Run(fmt.Sprintf("Case %s", tc.desc), func() {
msg := &types.MsgSend{
val0.Address,
val0.Address,
sdk.Coins{sdk.NewInt64Coin("foo", 100)},
}
// prepare txBuilder with msg
txBuilder := txConfig.NewTxBuilder()
feeAmount := sdk.Coins{sdk.NewInt64Coin(s.cfg.BondDenom, 10)}
gasLimit := testdata.NewTestGasLimit()
txBuilder.SetMsgs(msg)
txBuilder.SetFeeAmount(feeAmount)
txBuilder.SetGasLimit(gasLimit)
// setup txFactory
txFactory := tx.Factory{}
txFactory = txFactory.
WithChainID(val0.ClientCtx.ChainID).
WithKeybase(val0.ClientCtx.Keyring).
WithTxConfig(txConfig).
WithSignMode(signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON).
WithSequence(tc.sequence)
// sign Tx (offline mode so we can manually set sequence number)
err := authclient.SignTx(txFactory, val0.ClientCtx, val0.Moniker, txBuilder, true)
s.Require().NoError(err)
// broadcast test with sync mode, as we want to run CheckTx to verify account sequence is correct
stdTx := txBuilder.GetTx().(authtypes.StdTx)
stdTx := s.createTestStdTx(s.network.Validators[0], tc.sequence)
res, err := s.broadcastReq(stdTx, "sync")
s.Require().NoError(err)
@@ -190,7 +180,41 @@ func (s *IntegrationTestSuite) TestMultipleSyncBroadcastTxRequests() {
}
})
}
}
func (s *IntegrationTestSuite) createTestStdTx(val *network.Validator, sequence uint64) authtypes.StdTx {
txConfig := authtypes.StdTxConfig{Cdc: s.cfg.LegacyAmino}
msg := &types.MsgSend{
FromAddress: val.Address,
ToAddress: val.Address,
Amount: sdk.Coins{sdk.NewInt64Coin(fmt.Sprintf("%stoken", val.Moniker), 100)},
}
// prepare txBuilder with msg
txBuilder := txConfig.NewTxBuilder()
feeAmount := sdk.Coins{sdk.NewInt64Coin(s.cfg.BondDenom, 10)}
gasLimit := testdata.NewTestGasLimit()
txBuilder.SetMsgs(msg)
txBuilder.SetFeeAmount(feeAmount)
txBuilder.SetGasLimit(gasLimit)
txBuilder.SetMemo("foobar")
// setup txFactory
txFactory := tx.Factory{}.
WithChainID(val.ClientCtx.ChainID).
WithKeybase(val.ClientCtx.Keyring).
WithTxConfig(txConfig).
WithSignMode(signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON).
WithSequence(sequence)
// sign Tx (offline mode so we can manually set sequence number)
err := authclient.SignTx(txFactory, val.ClientCtx, val.Moniker, txBuilder, true)
s.Require().NoError(err)
stdTx := txBuilder.GetTx().(authtypes.StdTx)
return stdTx
}
func (s *IntegrationTestSuite) broadcastReq(stdTx authtypes.StdTx, mode string) ([]byte, error) {
+29 -30
View File
@@ -1,13 +1,15 @@
package tx
import (
"fmt"
"github.com/gogo/protobuf/proto"
"github.com/tendermint/tendermint/crypto"
"github.com/cosmos/cosmos-sdk/client"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
"github.com/cosmos/cosmos-sdk/x/auth/ante"
@@ -27,12 +29,6 @@ type wrapper struct {
// from the client using TxRaw if the tx was decoded from the wire
authInfoBz []byte
// pubKeys represents the cached crypto.PubKey's that were set either from tx decoding
// or decoded from AuthInfo when GetPubKey's was called
pubKeys []crypto.PubKey
pubkeyCodec types.PublicKeyCodec
txBodyHasUnknownNonCriticals bool
}
@@ -52,7 +48,7 @@ type ExtensionOptionsTxBuilder interface {
SetNonCriticalExtensionOptions(...*codectypes.Any)
}
func newBuilder(pubkeyCodec types.PublicKeyCodec) *wrapper {
func newBuilder() *wrapper {
return &wrapper{
tx: &tx.Tx{
Body: &tx.TxBody{},
@@ -60,7 +56,6 @@ func newBuilder(pubkeyCodec types.PublicKeyCodec) *wrapper {
Fee: &tx.Fee{},
},
},
pubkeyCodec: pubkeyCodec,
}
}
@@ -109,25 +104,23 @@ func (w *wrapper) GetSigners() []sdk.AccAddress {
}
func (w *wrapper) GetPubKeys() []crypto.PubKey {
if w.pubKeys == nil {
signerInfos := w.tx.AuthInfo.SignerInfos
pubKeys := make([]crypto.PubKey, len(signerInfos))
signerInfos := w.tx.AuthInfo.SignerInfos
pks := make([]crypto.PubKey, len(signerInfos))
for i, si := range signerInfos {
var err error
pk := si.PublicKey
if pk != nil {
pubKeys[i], err = w.pubkeyCodec.Decode(si.PublicKey)
if err != nil {
panic(err)
}
}
for i, si := range signerInfos {
// NOTE: it is okay to leave this nil if there is no PubKey in the SignerInfo.
// PubKey's can be left unset in SignerInfo.
if si.PublicKey == nil {
continue
}
w.pubKeys = pubKeys
pk, ok := si.PublicKey.GetCachedValue().(crypto.PubKey)
if ok {
pks[i] = pk
}
}
return w.pubKeys
return pks
}
func (w *wrapper) GetGas() uint64 {
@@ -250,12 +243,12 @@ func (w *wrapper) SetSignatures(signatures ...signing.SignatureV2) error {
for i, sig := range signatures {
var modeInfo *tx.ModeInfo
modeInfo, rawSigs[i] = SignatureDataToModeInfoAndSig(sig.Data)
pk, err := w.pubkeyCodec.Encode(sig.PubKey)
any, err := PubKeyToAny(sig.PubKey)
if err != nil {
return err
}
signerInfos[i] = &tx.SignerInfo{
PublicKey: pk,
PublicKey: any,
ModeInfo: modeInfo,
Sequence: sig.Sequence,
}
@@ -271,8 +264,6 @@ func (w *wrapper) setSignerInfos(infos []*tx.SignerInfo) {
w.tx.AuthInfo.SignerInfos = infos
// set authInfoBz to nil because the cached authInfoBz no longer matches tx.AuthInfo
w.authInfoBz = nil
// set cached pubKeys to nil because they no longer match tx.AuthInfo
w.pubKeys = nil
}
func (w *wrapper) setSignatures(sigs [][]byte) {
@@ -291,10 +282,9 @@ func (w *wrapper) AsAny() *codectypes.Any {
}
// WrapTx creates a TxBuilder wrapper around a tx.Tx proto message.
func WrapTx(protoTx *tx.Tx, pubkeyCodec types.PublicKeyCodec) client.TxBuilder {
func WrapTx(protoTx *tx.Tx) client.TxBuilder {
return &wrapper{
tx: protoTx,
pubkeyCodec: pubkeyCodec,
tx: protoTx,
}
}
@@ -315,3 +305,12 @@ func (w *wrapper) SetNonCriticalExtensionOptions(extOpts ...*codectypes.Any) {
w.tx.Body.NonCriticalExtensionOptions = extOpts
w.bodyBz = nil
}
// PubKeyToAny converts a crypto.PubKey to a proto Any.
func PubKeyToAny(key crypto.PubKey) (*codectypes.Any, error) {
protoMsg, ok := key.(proto.Message)
if !ok {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidPubKey, fmt.Sprintf("can't proto encode %T", protoMsg))
}
return codectypes.NewAnyWithValue(protoMsg)
}
+5 -8
View File
@@ -8,7 +8,6 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/legacy"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/std"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
@@ -20,20 +19,18 @@ func TestTxBuilder(t *testing.T) {
_, pubkey, addr := testdata.KeyTestPubAddr()
marshaler := codec.NewProtoCodec(codectypes.NewInterfaceRegistry())
txBuilder := newBuilder(std.DefaultPublicKeyCodec{})
cdc := std.DefaultPublicKeyCodec{}
txBuilder := newBuilder()
memo := "sometestmemo"
msgs := []sdk.Msg{testdata.NewTestMsg(addr)}
accSeq := uint64(2) // Arbitrary account sequence
pk, err := cdc.Encode(pubkey)
any, err := PubKeyToAny(pubkey)
require.NoError(t, err)
var signerInfo []*txtypes.SignerInfo
signerInfo = append(signerInfo, &txtypes.SignerInfo{
PublicKey: pk,
PublicKey: any,
ModeInfo: &txtypes.ModeInfo{
Sum: &txtypes.ModeInfo_Single_{
Single: &txtypes.ModeInfo_Single{
@@ -111,7 +108,7 @@ func TestTxBuilder(t *testing.T) {
require.Equal(t, 1, len(txBuilder.GetPubKeys()))
require.Equal(t, legacy.Cdc.MustMarshalBinaryBare(pubkey), legacy.Cdc.MustMarshalBinaryBare(txBuilder.GetPubKeys()[0]))
any, err := codectypes.NewAnyWithValue(testdata.NewTestMsg())
any, err = codectypes.NewAnyWithValue(testdata.NewTestMsg())
require.NoError(t, err)
txBuilder.SetExtensionOptions(any)
require.Equal(t, []*codectypes.Any{any}, txBuilder.GetExtensionOptions())
@@ -137,7 +134,7 @@ func TestBuilderValidateBasic(t *testing.T) {
// require to fail validation upon invalid fee
badFeeAmount := testdata.NewTestFeeAmount()
badFeeAmount[0].Amount = sdk.NewInt(-5)
txBuilder := newBuilder(std.DefaultPublicKeyCodec{})
txBuilder := newBuilder()
var sig1, sig2 signing.SignatureV2
sig1 = signing.SignatureV2{
+5 -8
View File
@@ -8,13 +8,11 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/signing"
)
type config struct {
pubkeyCodec types.PublicKeyCodec
handler signing.SignModeHandler
decoder sdk.TxDecoder
encoder sdk.TxEncoder
@@ -23,22 +21,21 @@ type config struct {
protoCodec *codec.ProtoCodec
}
// NewTxConfig returns a new protobuf TxConfig using the provided ProtoCodec, PublicKeyCodec and sign modes. The
// NewTxConfig returns a new protobuf TxConfig using the provided ProtoCodec and sign modes. The
// first enabled sign mode will become the default sign mode.
func NewTxConfig(protoCodec *codec.ProtoCodec, pubkeyCodec types.PublicKeyCodec, enabledSignModes []signingtypes.SignMode) client.TxConfig {
func NewTxConfig(protoCodec *codec.ProtoCodec, enabledSignModes []signingtypes.SignMode) client.TxConfig {
return &config{
pubkeyCodec: pubkeyCodec,
handler: makeSignModeHandler(enabledSignModes),
decoder: DefaultTxDecoder(protoCodec, pubkeyCodec),
decoder: DefaultTxDecoder(protoCodec),
encoder: DefaultTxEncoder(),
jsonDecoder: DefaultJSONTxDecoder(protoCodec, pubkeyCodec),
jsonDecoder: DefaultJSONTxDecoder(protoCodec),
jsonEncoder: DefaultJSONTxEncoder(),
protoCodec: protoCodec,
}
}
func (g config) NewTxBuilder() client.TxBuilder {
return newBuilder(g.pubkeyCodec)
return newBuilder()
}
// WrapTxBuilder returns a builder from provided transaction
+5 -7
View File
@@ -3,22 +3,20 @@ package tx
import (
"testing"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/std"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/testutil"
)
func TestGenerator(t *testing.T) {
interfaceRegistry := codectypes.NewInterfaceRegistry()
std.RegisterInterfaces(interfaceRegistry)
interfaceRegistry.RegisterImplementations((*sdk.Msg)(nil), &testdata.TestMsg{})
marshaler := codec.NewProtoCodec(interfaceRegistry)
pubKeyCodec := std.DefaultPublicKeyCodec{}
suite.Run(t, testutil.NewTxConfigTestSuite(NewTxConfig(marshaler, pubKeyCodec, DefaultSignModes)))
protoCodec := codec.NewProtoCodec(interfaceRegistry)
suite.Run(t, testutil.NewTxConfigTestSuite(NewTxConfig(protoCodec, DefaultSignModes)))
}
+5 -39
View File
@@ -1,18 +1,15 @@
package tx
import (
"github.com/tendermint/tendermint/crypto"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/unknownproto"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/tx"
)
// DefaultTxDecoder returns a default protobuf TxDecoder using the provided Marshaler and PublicKeyCodec
func DefaultTxDecoder(cdc *codec.ProtoCodec, keyCodec cryptotypes.PublicKeyCodec) sdk.TxDecoder {
// DefaultTxDecoder returns a default protobuf TxDecoder using the provided Marshaler.
func DefaultTxDecoder(cdc *codec.ProtoCodec) sdk.TxDecoder {
return func(txBytes []byte) (sdk.Tx, error) {
var raw tx.TxRaw
@@ -59,24 +56,17 @@ func DefaultTxDecoder(cdc *codec.ProtoCodec, keyCodec cryptotypes.PublicKeyCodec
Signatures: raw.Signatures,
}
pks, err := extractPubKeys(theTx, keyCodec)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error())
}
return &wrapper{
tx: theTx,
bodyBz: raw.BodyBytes,
authInfoBz: raw.AuthInfoBytes,
pubKeys: pks,
pubkeyCodec: keyCodec,
txBodyHasUnknownNonCriticals: txBodyHasUnknownNonCriticals,
}, nil
}
}
// DefaultTxDecoder returns a default protobuf JSON TxDecoder using the provided Marshaler and PublicKeyCodec
func DefaultJSONTxDecoder(cdc *codec.ProtoCodec, keyCodec cryptotypes.PublicKeyCodec) sdk.TxDecoder {
// DefaultJSONTxDecoder returns a default protobuf JSON TxDecoder using the provided Marshaler.
func DefaultJSONTxDecoder(cdc *codec.ProtoCodec) sdk.TxDecoder {
return func(txBytes []byte) (sdk.Tx, error) {
var theTx tx.Tx
err := cdc.UnmarshalJSON(txBytes, &theTx)
@@ -84,32 +74,8 @@ func DefaultJSONTxDecoder(cdc *codec.ProtoCodec, keyCodec cryptotypes.PublicKeyC
return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error())
}
pks, err := extractPubKeys(&theTx, keyCodec)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error())
}
return &wrapper{
tx: &theTx,
pubKeys: pks,
pubkeyCodec: keyCodec,
tx: &theTx,
}, nil
}
}
func extractPubKeys(tx *tx.Tx, keyCodec cryptotypes.PublicKeyCodec) ([]crypto.PubKey, error) {
if tx.AuthInfo == nil {
return []crypto.PubKey{}, nil
}
signerInfos := tx.AuthInfo.SignerInfos
pks := make([]crypto.PubKey, len(signerInfos))
for i, si := range signerInfos {
pk, err := keyCodec.Decode(si.PublicKey)
if err != nil {
return nil, err
}
pks[i] = pk
}
return pks, nil
}
+3 -5
View File
@@ -8,7 +8,6 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/std"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
@@ -21,21 +20,20 @@ func TestDirectModeHandler(t *testing.T) {
interfaceRegistry := codectypes.NewInterfaceRegistry()
interfaceRegistry.RegisterImplementations((*sdk.Msg)(nil), &testdata.TestMsg{})
marshaler := codec.NewProtoCodec(interfaceRegistry)
pubKeyCdc := std.DefaultPublicKeyCodec{}
txConfig := NewTxConfig(marshaler, pubKeyCdc, []signingtypes.SignMode{signingtypes.SignMode_SIGN_MODE_DIRECT})
txConfig := NewTxConfig(marshaler, []signingtypes.SignMode{signingtypes.SignMode_SIGN_MODE_DIRECT})
txBuilder := txConfig.NewTxBuilder()
memo := "sometestmemo"
msgs := []sdk.Msg{testdata.NewTestMsg(addr)}
accSeq := uint64(2) // Arbitrary account sequence
pk, err := pubKeyCdc.Encode(pubkey)
any, err := PubKeyToAny(pubkey)
require.NoError(t, err)
var signerInfo []*txtypes.SignerInfo
signerInfo = append(signerInfo, &txtypes.SignerInfo{
PublicKey: pk,
PublicKey: any,
ModeInfo: &txtypes.ModeInfo{
Sum: &txtypes.ModeInfo_Single_{
Single: &txtypes.ModeInfo_Single{
+4 -7
View File
@@ -14,7 +14,6 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/std"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
)
@@ -22,11 +21,10 @@ import (
func TestDefaultTxDecoderError(t *testing.T) {
registry := codectypes.NewInterfaceRegistry()
cdc := codec.NewProtoCodec(registry)
pubKeyCdc := std.DefaultPublicKeyCodec{}
encoder := DefaultTxEncoder()
decoder := DefaultTxDecoder(cdc, pubKeyCdc)
decoder := DefaultTxDecoder(cdc)
builder := newBuilder(pubKeyCdc)
builder := newBuilder()
err := builder.SetMsgs(testdata.NewTestMsg())
require.NoError(t, err)
@@ -44,8 +42,7 @@ func TestDefaultTxDecoderError(t *testing.T) {
func TestUnknownFields(t *testing.T) {
registry := codectypes.NewInterfaceRegistry()
cdc := codec.NewProtoCodec(registry)
pubKeyCdc := std.DefaultPublicKeyCodec{}
decoder := DefaultTxDecoder(cdc, pubKeyCdc)
decoder := DefaultTxDecoder(cdc)
tests := []struct {
name string
@@ -128,7 +125,7 @@ func TestUnknownFields(t *testing.T) {
if tt.shouldAminoErr != "" {
handler := signModeLegacyAminoJSONHandler{}
decoder := DefaultTxDecoder(codec.NewProtoCodec(codectypes.NewInterfaceRegistry()), std.DefaultPublicKeyCodec{})
decoder := DefaultTxDecoder(codec.NewProtoCodec(codectypes.NewInterfaceRegistry()))
theTx, err := decoder(txBz)
require.NoError(t, err)
_, err = handler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, signing.SignerData{}, theTx)
+3 -4
View File
@@ -6,7 +6,6 @@ import (
"github.com/stretchr/testify/require"
cdctypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/std"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing"
@@ -34,7 +33,7 @@ func buildTx(t *testing.T, bldr *wrapper) {
}
func TestLegacyAminoJSONHandler_GetSignBytes(t *testing.T) {
bldr := newBuilder(std.DefaultPublicKeyCodec{})
bldr := newBuilder()
buildTx(t, bldr)
tx := bldr.GetTx()
@@ -65,7 +64,7 @@ func TestLegacyAminoJSONHandler_GetSignBytes(t *testing.T) {
require.Error(t, err)
// expect error with extension options
bldr = newBuilder(std.DefaultPublicKeyCodec{})
bldr = newBuilder()
buildTx(t, bldr)
any, err := cdctypes.NewAnyWithValue(testdata.NewTestMsg())
require.NoError(t, err)
@@ -75,7 +74,7 @@ func TestLegacyAminoJSONHandler_GetSignBytes(t *testing.T) {
require.Error(t, err)
// expect error with non-critical extension options
bldr = newBuilder(std.DefaultPublicKeyCodec{})
bldr = newBuilder()
buildTx(t, bldr)
bldr.tx.Body.NonCriticalExtensionOptions = []*cdctypes.Any{any}
tx = bldr.GetTx()
+6 -8
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/tendermint/tendermint/crypto"
"github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/types/tx"
@@ -109,15 +110,15 @@ func (g config) MarshalSignatureJSON(sigs []signing.SignatureV2) ([]byte, error)
descs := make([]*signing.SignatureDescriptor, len(sigs))
for i, sig := range sigs {
publicKey, err := g.pubkeyCodec.Encode(sig.PubKey)
descData := signing.SignatureDataToProto(sig.Data)
any, err := PubKeyToAny(sig.PubKey)
if err != nil {
return nil, err
}
descData := signing.SignatureDataToProto(sig.Data)
descs[i] = &signing.SignatureDescriptor{
PublicKey: publicKey,
PublicKey: any,
Data: descData,
}
}
@@ -136,10 +137,7 @@ func (g config) UnmarshalSignatureJSON(bz []byte) ([]signing.SignatureV2, error)
sigs := make([]signing.SignatureV2, len(sigDescs.Signatures))
for i, desc := range sigDescs.Signatures {
pubKey, err := g.pubkeyCodec.Decode(desc.PublicKey)
if err != nil {
return nil, err
}
pubKey, _ := desc.PublicKey.GetCachedValue().(crypto.PubKey)
data := signing.SignatureDataFromProto(desc.Data)